diff --git a/.gitignore b/.gitignore index 7d472ff011d76be0cbea04137c02d673b0ab2962..4fd748879c6b1a51ead28c365dff7c4822492e41 100644 --- a/.gitignore +++ b/.gitignore @@ -7,3 +7,4 @@ bin/ target/ .idea/ *.iml +**/.DS_Store diff --git a/pom.xml b/pom.xml index 688fc86c3c2b28cad76a0842c3fe7276e2cd9ab2..79a6c16780a42e4a156951d517e3fd255c25083b 100644 --- a/pom.xml +++ b/pom.xml @@ -1,67 +1,62 @@ <?xml version="1.0" encoding="UTF-8"?> -<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> - <modelVersion>4.0.0</modelVersion> +<project xmlns="http://maven.apache.org/POM/4.0.0" + xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> + <modelVersion>4.0.0</modelVersion> - <parent> - <groupId>org.bioimageanalysis.icy</groupId> - <artifactId>pom-icy</artifactId> - <version>2.1.3</version> - </parent> + <parent> + <groupId>org.bioimageanalysis.icy</groupId> + <artifactId>pom-icy</artifactId> + <version>2.2.0</version> + </parent> - <artifactId>script-editor</artifactId> - <version>1.18.0</version> + <artifactId>script-editor</artifactId> + <version>1.19.0</version> - <packaging>jar</packaging> + <packaging>jar</packaging> - <name>Script Editor</name> - <description> + <name>Script Editor</name> + <description> Script Editor plugin for Icy, support Javascript and Python script languages. </description> - <dependencies> + <dependencies> <dependency> <groupId>org.bioimageanalysis.icy</groupId> - <artifactId>icy-kernel</artifactId> - <version>2.4.3</version> + <artifactId>protocols</artifactId> </dependency> - <dependency> - <groupId>org.bioimageanalysis.icy</groupId> - <artifactId>protocols</artifactId> - </dependency> - <dependency> - <groupId>org.bioimageanalysis.icy</groupId> - <artifactId>javadocparser</artifactId> - </dependency> - <dependency> - <groupId>org.bioimageanalysis.icy</groupId> - <artifactId>autocomplete</artifactId> - </dependency> - <dependency> - <groupId>org.bioimageanalysis.icy</groupId> - <artifactId>rsyntaxtextarea</artifactId> - </dependency> - <dependency> - <groupId>org.bioimageanalysis.icy</groupId> - <artifactId>nashorn</artifactId> - <version>15.3.0</version> - </dependency> - <dependency> - <groupId>org.bioimageanalysis.icy</groupId> - <artifactId>rhino</artifactId> - </dependency> - <dependency> - <groupId>org.bioimageanalysis.icy</groupId> - <artifactId>jython</artifactId> - <version>2.8.1</version> - </dependency> - </dependencies> + <dependency> + <groupId>org.bioimageanalysis.icy</groupId> + <artifactId>javadocparser</artifactId> + </dependency> + <dependency> + <groupId>org.bioimageanalysis.icy</groupId> + <artifactId>autocomplete</artifactId> + </dependency> + <dependency> + <groupId>org.bioimageanalysis.icy</groupId> + <artifactId>rsyntaxtextarea</artifactId> + </dependency> + <dependency> + <groupId>org.bioimageanalysis.icy</groupId> + <artifactId>nashorn</artifactId> + </dependency> + <dependency> + <groupId>org.bioimageanalysis.icy</groupId> + <artifactId>rhino</artifactId> + </dependency> + <dependency> + <groupId>org.bioimageanalysis.icy</groupId> + <artifactId>jython</artifactId> + </dependency> + </dependencies> - <repositories> - <repository> - <id>icy</id> - <url>https://icy-nexus.pasteur.fr/repository/Icy/</url> - </repository> - </repositories> + <repositories> + <repository> + <id>icy</id> + <url>https://icy-nexus.pasteur.fr/repository/Icy/</url> + </repository> + </repositories> </project> \ No newline at end of file diff --git a/src/main/java/plugins/tprovoost/scripteditor/completion/IcyAutoCompletion.java b/src/main/java/plugins/tprovoost/scripteditor/completion/IcyAutoCompletion.java index 0516169f7ed86447a7e4c258b39b66d4ca682466..22ec6199f11728f1f92d05e9a9ee0619c2dcdacd 100644 --- a/src/main/java/plugins/tprovoost/scripteditor/completion/IcyAutoCompletion.java +++ b/src/main/java/plugins/tprovoost/scripteditor/completion/IcyAutoCompletion.java @@ -5,16 +5,13 @@ import javax.swing.text.JTextComponent; import org.fife.ui.autocomplete.AutoCompletion; import org.fife.ui.autocomplete.CompletionProvider; -public abstract class IcyAutoCompletion extends AutoCompletion -{ +public abstract class IcyAutoCompletion extends AutoCompletion { - public IcyAutoCompletion(CompletionProvider provider) - { + public IcyAutoCompletion(final CompletionProvider provider) { super(provider); } - public boolean packageExists(String neededPackage) - { + public boolean packageExists(final String neededPackage) { return getTextComponent().getText().contains(neededPackage); } @@ -22,13 +19,10 @@ public abstract class IcyAutoCompletion extends AutoCompletion /** * Add an import into the textcomponent if necessary. - * - * @param tc - * the text component - * @param neededClass - * the class to be added - * @param isClass - * is is a class or a package ? + * + * @param tc the text component + * @param neededClass the class to be added + * @param isClass is is a class or a package ? * @return the added import name */ public abstract String addImport(JTextComponent tc, String neededClass, boolean isClass); diff --git a/src/main/java/plugins/tprovoost/scripteditor/completion/IcyCompletionCellRenderer.java b/src/main/java/plugins/tprovoost/scripteditor/completion/IcyCompletionCellRenderer.java index edd24d44c96d8df752627b63c7ee486500b47f4e..32035a82bcaf63a803a938c2a096e6f2702286d6 100644 --- a/src/main/java/plugins/tprovoost/scripteditor/completion/IcyCompletionCellRenderer.java +++ b/src/main/java/plugins/tprovoost/scripteditor/completion/IcyCompletionCellRenderer.java @@ -19,93 +19,82 @@ import plugins.tprovoost.scripteditor.completion.types.NewInstanceCompletion; import plugins.tprovoost.scripteditor.completion.types.ScriptFunctionCompletion; public class IcyCompletionCellRenderer extends CompletionCellRenderer { - - /** */ - private static final long serialVersionUID = 1L; - - // images - public static final BufferedImage IMAGE_STATIC = ImageUtil - .load(PluginLoader.getResourceAsStream("plugins/tprovoost/scripteditor/resources/icons/static_co.gif")); - - public static final BufferedImage IMAGE_METHOD = ImageUtil - .load(PluginLoader.getResourceAsStream("plugins/tprovoost/scripteditor/resources/icons/methpub_obj.gif")); - - public static final BufferedImage IMAGE_DEPRECATED = ImageUtil - .load(PluginLoader.getResourceAsStream("plugins/tprovoost/scripteditor/resources/icons/deprecated.gif")); - - // icons - public static final ImageIcon ICON_METHOD = new ImageIcon(IMAGE_METHOD); - - public static final ImageIcon ICON_VARIABLES = new ImageIcon(ImageUtil.load( - PluginLoader.getResourceAsStream("plugins/tprovoost/scripteditor/resources/icons/field_public_obj.gif"))); - - public static final ImageIcon ICON_OTHER = new ImageIcon(ImageUtil - .load(PluginLoader.getResourceAsStream("plugins/tprovoost/scripteditor/resources/icons/constant_co.gif"))); - - public static final ImageIcon ICON_CLASS = new ImageIcon(ImageUtil - .load(PluginLoader.getResourceAsStream("plugins/tprovoost/scripteditor/resources/icons/class_obj.gif"))); - - public static final ImageIcon ICON_INSTERFACE = new ImageIcon(ImageUtil - .load(PluginLoader.getResourceAsStream("plugins/tprovoost/scripteditor/resources/icons/int_obj.gif"))); - - @Override - protected void prepareForFunctionCompletion(@SuppressWarnings("rawtypes") JList list, FunctionCompletion fc, - int index, boolean selected, boolean hasFocus) { - if (fc instanceof ScriptFunctionCompletion) { - ImageIcon icon = ICON_METHOD; - BufferedImage img = null; - if (((ScriptFunctionCompletion) fc).isStatic()) { - BufferedImage func2 = ImageUtil.getCopy(IMAGE_METHOD); - func2.getGraphics().drawImage(IMAGE_STATIC, 0, 0, null); - img = func2; - } - if (((ScriptFunctionCompletion) fc).getMethod().getAnnotation(Deprecated.class) != null) { - if (img == null) - img = ImageUtil.getCopy(IMAGE_METHOD); - img.getGraphics().drawImage(IMAGE_DEPRECATED, 0, 0, null); - } - if (img != null) - setIcon(new ImageIcon(img)); - else - setIcon(icon); - } else if (fc instanceof NewInstanceCompletion) { - setIcon(ICON_CLASS); - } else - setIcon(ICON_METHOD); - super.prepareForFunctionCompletion(list, fc, index, selected, hasFocus); - } - - @Override - protected void prepareForVariableCompletion(@SuppressWarnings("rawtypes") JList list, VariableCompletion vc, - int index, boolean selected, boolean hasFocus) { - ImageIcon icon; - if (vc instanceof BasicJavaClassCompletion) { - Class<?> javaClass = ((BasicJavaClassCompletion) vc).getJavaClass(); - if (javaClass.isInterface()) - icon = ICON_INSTERFACE; - else - icon = ICON_CLASS; - - // test deprecation - if (javaClass.getAnnotation(Deprecated.class) != null) { - Image img = ImageUtil.getCopy(icon.getImage()); - img.getGraphics().drawImage(IMAGE_DEPRECATED, 0, 0, null); - setIcon(new ImageIcon(img)); - } else - setIcon(icon); - } else { - icon = ICON_VARIABLES; - setIcon(icon); - } - - super.prepareForVariableCompletion(list, vc, index, selected, hasFocus); - } - - @Override - protected void prepareForOtherCompletion(@SuppressWarnings("rawtypes") JList list, Completion c, int index, - boolean selected, boolean hasFocus) { - setIcon(ICON_OTHER); - super.prepareForOtherCompletion(list, c, index, selected, hasFocus); - } + // images + public static final BufferedImage IMAGE_STATIC = ImageUtil.load(PluginLoader.getResourceAsStream("plugins/tprovoost/scripteditor/resources/icons/static_co.gif")); + + public static final BufferedImage IMAGE_METHOD = ImageUtil.load(PluginLoader.getResourceAsStream("plugins/tprovoost/scripteditor/resources/icons/methpub_obj.gif")); + + public static final BufferedImage IMAGE_DEPRECATED = ImageUtil.load(PluginLoader.getResourceAsStream("plugins/tprovoost/scripteditor/resources/icons/deprecated.gif")); + + // icons + public static final ImageIcon ICON_METHOD = new ImageIcon(IMAGE_METHOD); + + public static final ImageIcon ICON_VARIABLES = new ImageIcon(ImageUtil.load(PluginLoader.getResourceAsStream("plugins/tprovoost/scripteditor/resources/icons/field_public_obj.gif"))); + + public static final ImageIcon ICON_OTHER = new ImageIcon(ImageUtil.load(PluginLoader.getResourceAsStream("plugins/tprovoost/scripteditor/resources/icons/constant_co.gif"))); + + public static final ImageIcon ICON_CLASS = new ImageIcon(ImageUtil.load(PluginLoader.getResourceAsStream("plugins/tprovoost/scripteditor/resources/icons/class_obj.gif"))); + + public static final ImageIcon ICON_INSTERFACE = new ImageIcon(ImageUtil.load(PluginLoader.getResourceAsStream("plugins/tprovoost/scripteditor/resources/icons/int_obj.gif"))); + + @Override + protected void prepareForFunctionCompletion(final JList<?> list, final FunctionCompletion fc, final int index, final boolean selected, final boolean hasFocus) { + if (fc instanceof ScriptFunctionCompletion) { + BufferedImage img = null; + if (((ScriptFunctionCompletion) fc).isStatic()) { + final BufferedImage func2 = ImageUtil.getCopy(IMAGE_METHOD); + func2.getGraphics().drawImage(IMAGE_STATIC, 0, 0, null); + img = func2; + } + if (((ScriptFunctionCompletion) fc).getMethod().getAnnotation(Deprecated.class) != null) { + if (img == null) + img = ImageUtil.getCopy(IMAGE_METHOD); + img.getGraphics().drawImage(IMAGE_DEPRECATED, 0, 0, null); + } + if (img != null) + setIcon(new ImageIcon(img)); + else + setIcon(ICON_METHOD); + } + else if (fc instanceof NewInstanceCompletion) { + setIcon(ICON_CLASS); + } + else + setIcon(ICON_METHOD); + super.prepareForFunctionCompletion(list, fc, index, selected, hasFocus); + } + + @Override + protected void prepareForVariableCompletion(final JList<?> list, final VariableCompletion vc, final int index, final boolean selected, final boolean hasFocus) { + final ImageIcon icon; + if (vc instanceof BasicJavaClassCompletion) { + final Class<?> javaClass = ((BasicJavaClassCompletion) vc).getJavaClass(); + if (javaClass.isInterface()) + icon = ICON_INSTERFACE; + else + icon = ICON_CLASS; + + // test deprecation + if (javaClass.getAnnotation(Deprecated.class) != null) { + final Image img = ImageUtil.getCopy(icon.getImage()); + img.getGraphics().drawImage(IMAGE_DEPRECATED, 0, 0, null); + setIcon(new ImageIcon(img)); + } + else + setIcon(icon); + } + else { + icon = ICON_VARIABLES; + setIcon(icon); + } + + super.prepareForVariableCompletion(list, vc, index, selected, hasFocus); + } + + @Override + protected void prepareForOtherCompletion(final JList<?> list, final Completion c, final int index, final boolean selected, final boolean hasFocus) { + setIcon(ICON_OTHER); + super.prepareForOtherCompletion(list, c, index, selected, hasFocus); + } } diff --git a/src/main/java/plugins/tprovoost/scripteditor/completion/IcyCompletionProvider.java b/src/main/java/plugins/tprovoost/scripteditor/completion/IcyCompletionProvider.java index 696de8a8dc3a0641cbd7b5baf01d144afe4f5323..ce3e4e8c2b9b64364cb68434c97f7cb23decd766 100644 --- a/src/main/java/plugins/tprovoost/scripteditor/completion/IcyCompletionProvider.java +++ b/src/main/java/plugins/tprovoost/scripteditor/completion/IcyCompletionProvider.java @@ -26,6 +26,7 @@ import javax.swing.text.Document; import javax.swing.text.Element; import javax.swing.text.JTextComponent; +import icy.system.IcyExceptionHandler; import org.fife.ui.autocomplete.BasicCompletion; import org.fife.ui.autocomplete.Completion; import org.fife.ui.autocomplete.DefaultCompletionProvider; @@ -34,84 +35,69 @@ import org.fife.ui.autocomplete.ParameterizedCompletion.Parameter; import org.fife.ui.autocomplete.Util; import org.fife.ui.autocomplete.VariableCompletion; -import icy.gui.frame.progress.ProgressFrame; import icy.plugin.PluginLoader; import icy.util.ClassUtil; import icy.util.StringUtil; import plugins.tprovoost.scripteditor.completion.types.BasicJavaClassCompletion; -import plugins.tprovoost.scripteditor.completion.types.JavaFunctionCompletion; import plugins.tprovoost.scripteditor.completion.types.NewInstanceCompletion; import plugins.tprovoost.scripteditor.completion.types.ScriptFunctionCompletion; import plugins.tprovoost.scripteditor.completion.types.ScriptFunctionCompletion.BindingFunction; import plugins.tprovoost.scripteditor.scriptinghandlers.IcyFunctionBlock; -import plugins.tprovoost.scripteditor.scriptinghandlers.ScriptEngine; import plugins.tprovoost.scripteditor.scriptinghandlers.ScriptEngineHandler; import plugins.tprovoost.scripteditor.scriptinghandlers.ScriptingHandler; import plugins.tprovoost.scripteditor.scriptinghandlers.VariableType; -public class IcyCompletionProvider extends DefaultCompletionProvider -{ +public class IcyCompletionProvider extends DefaultCompletionProvider { protected ScriptingHandler handler; protected boolean advanced = true; - private static Comparator<Completion> comparatorFull = new Comparator<Completion>() - { - @Override - public int compare(Completion c1, Completion c2) - { - int compare = ((Integer) c2.getRelevance()).compareTo(c1.getRelevance()); - if (compare == 0) - { - return c1.getInputText().compareTo(c2.getInputText()); - } - return compare; + private static final Comparator<Completion> comparatorFull = (c1, c2) -> { + int compare = Integer.compare(c2.getRelevance(), c1.getRelevance()); + if (compare == 0) { + return c1.getInputText().compareTo(c2.getInputText()); } + return compare; }; - public void setHandler(ScriptingHandler handler) - { + public void setHandler(final ScriptingHandler handler) { this.handler = handler; } - public void installMethods(ArrayList<Method> methods) - { - for (final Method method : methods) - { - Class<?> clazz = method.getDeclaringClass(); + public void installMethods(final ArrayList<Method> methods) { + for (final Method method : methods) { + final Class<?> clazz = method.getDeclaringClass(); // make sure the method is public and annotated - int modifiers = method.getModifiers(); + final int modifiers = method.getModifiers(); if (!Modifier.isPublic(modifiers)) continue; // is it an annotated with BindingFunction? - BindingFunction blockFunction = method.getAnnotation(BindingFunction.class); + final BindingFunction blockFunction = method.getAnnotation(BindingFunction.class); if (blockFunction == null) continue; // Generate the function for the provider - ArrayList<Parameter> fParams = new ArrayList<Parameter>(); - Class<?>[] paramTypes = method.getParameterTypes(); + final ArrayList<Parameter> fParams = new ArrayList<>(); + final Class<?>[] paramTypes = method.getParameterTypes(); // get the parameters - String params = ""; - String functionName = blockFunction.value(); + StringBuilder params = new StringBuilder(); + final String functionName = blockFunction.value(); // get the parameters - for (int i = 0; i < paramTypes.length; ++i) - { + for (int i = 0; i < paramTypes.length; ++i) { fParams.add(new Parameter(getType(paramTypes[i], true), "arg" + i)); - params += ",arg" + i; + params.append(",arg").append(i); } if (params.length() > 0) - params = params.substring(1); + params = new StringBuilder(params.substring(1)); // the object for the provider - ScriptFunctionCompletion sfc; + final ScriptFunctionCompletion sfc; if (Modifier.isStatic(method.getModifiers())) sfc = new ScriptFunctionCompletion(this, functionName, method); else sfc = new ScriptFunctionCompletion(this, method.getName(), method); sfc.setDefinedIn(clazz.getName().replace('$', '.')); - if (method.getAnnotation(Deprecated.class) != null) - { + if (method.getAnnotation(Deprecated.class) != null) { sfc.setShortDescription("deprecated"); } sfc.setParams(fParams); @@ -129,295 +115,87 @@ public class IcyCompletionProvider extends DefaultCompletionProvider } } - /** - * @param engine - * {@link ScriptEngine} - * @param frame - * progress frame - */ - @Deprecated - public void findAllMethods(ScriptEngine engine, ProgressFrame frame) - { - - ScriptEngineHandler engineHandler = ScriptEngineHandler.getEngineHandler(engine); - HashMap<String, VariableType> listFunction = engineHandler.getEngineFunctions(); - HashMap<Class<?>, ArrayList<ScriptFunctionCompletion>> engineTypesMethod = engineHandler.getEngineTypesMethod(); - - ArrayList<String> clazzes; - - try - { - clazzes = getClassNamesFromPackage("icy"); - } - catch (IOException e1) - { - e1.printStackTrace(); - return; - } - if (frame != null) - frame.setLength(clazzes.size()); - Collections.sort(clazzes); - for (int idxClass = 0; idxClass < clazzes.size(); ++idxClass) - { - if (frame != null) - frame.setPosition(idxClass); - String className = clazzes.get(idxClass).replace('/', '.'); - try - { - // the current class - Class<?> clazz = Class.forName(className); - - // get all methods - Method[] methods = clazz.getMethods(); - - // iterate through each - for (final Method method : methods) - { - ArrayList<Parameter> fParams = new ArrayList<Parameter>(); - - Class<?>[] paramTypes = method.getParameterTypes(); - - // get the parameters - for (int i = 0; i < paramTypes.length; ++i) - { - fParams.add(new Parameter(getType(paramTypes[i], true), "arg" + i)); - } - - ScriptFunctionCompletion sfc = new ScriptFunctionCompletion(this, method.getName(), method); - sfc.setDefinedIn(clazz.getName().replace('$', '.')); - sfc.setParams(fParams); - BindingFunction blockFunction = method.getAnnotation(BindingFunction.class); - if (blockFunction == null) - sfc.setRelevance(2); - else - sfc.setRelevance(4); - addCompletion(sfc); - if (getCompletionByInputText(clazz.getName()) == null) - addCompletion(new BasicJavaClassCompletion(this, clazz)); - - if (listFunction != null) - { - Class<?> returnType = method.getReturnType(); - if (VariableType.isGeneric(returnType)) - listFunction.put(sfc.getMethodCall().substring("packages.".length()), new VariableType( - returnType, VariableType.getType(method.getGenericReturnType().toString()))); - else - listFunction.put(sfc.getMethodCall().substring("packages.".length()), - new VariableType(returnType)); - } - if (engineTypesMethod != null) - { - ArrayList<ScriptFunctionCompletion> methodsExisting = engineTypesMethod.get(clazz); - if (methodsExisting == null) - methodsExisting = new ArrayList<ScriptFunctionCompletion>(); - methodsExisting.add(sfc); - engineTypesMethod.put(clazz, methodsExisting); - } - } - } - catch (ClassNotFoundException e) - { - } - } + @Override + public List<Completion> getCompletions(final JTextComponent comp) { + final List<Completion> originalList = getCompletionsImpl(comp); + final List<Completion> toReturn = new ArrayList<>(); - } + //final List<Completion> inScriptVariables = new ArrayList<>(); + //final List<Completion> inScriptBasic = new ArrayList<>(); + final List<Completion> inScriptFunctions = new ArrayList<>(); + final List<Completion> variables = new ArrayList<>(); + final List<Completion> basic = new ArrayList<>(); + final List<Completion> functions = new ArrayList<>(); - @Override - public List<Completion> getCompletions(JTextComponent comp) - { - List<Completion> originalList = getCompletionsImpl(comp); - List<Completion> toReturn = new ArrayList<Completion>(); - - List<Completion> inScriptVariables = new ArrayList<Completion>(); - List<Completion> inScriptBasic = new ArrayList<Completion>(); - List<Completion> inScriptFunctions = new ArrayList<Completion>(); - List<Completion> variables = new ArrayList<Completion>(); - List<Completion> basic = new ArrayList<Completion>(); - List<Completion> functions = new ArrayList<Completion>(); - - // String enteredText = getAlreadyEnteredText(comp); - - for (Completion c : new ArrayList<Completion>(originalList)) - { - String rText = c.getReplacementText(); - // int previousDotIdx = enteredText.lastIndexOf('.') + 1; - // if (previousDotIdx < 0) - // previousDotIdx = 0; - // int nextDotIdx = rText.indexOf('.', previousDotIdx); - int previousDotIdx = 0; - int nextDotIdx = -1; - - if (c instanceof FunctionCompletion) - { + // FIXME: 07/04/2023 Need rework, unnecessary if-else bloc with fixed params value + for (final Completion c : new ArrayList<>(originalList)) { + if (c instanceof FunctionCompletion) { // the completion is a function. - if (previousDotIdx == 0 && nextDotIdx == -1) - { - if (!isFunctionAlreadyDeclared((FunctionCompletion) c, functions)) - functions.add(c); - } - else - { - String res; - if (nextDotIdx == -1) - { - res = rText.substring(previousDotIdx); - FunctionCompletion co = (FunctionCompletion) c; - - FunctionCompletion coDuplicate; - if (co instanceof JavaFunctionCompletion) - { - if (co instanceof ScriptFunctionCompletion) - { - coDuplicate = new ScriptFunctionCompletion(c.getProvider(), co.getName(), - ((ScriptFunctionCompletion) co).getMethod()); - } - else if (co instanceof NewInstanceCompletion) - { - coDuplicate = new NewInstanceCompletion(c.getProvider(), co.getName(), - ((NewInstanceCompletion) co).getConstructor()); - } - else - { - coDuplicate = null; - System.out.println("Unsupported JavaFunctionCompletion Type."); - } - if (((JavaFunctionCompletion) co).isPopulateDone()) - { - coDuplicate.setSummary(co.getSummary()); - } - } - else - { - coDuplicate = new FunctionCompletion(c.getProvider(), res, co.getType()); - coDuplicate.setSummary(co.getSummary()); - } - coDuplicate.setShortDescription(co.getShortDescription()); - coDuplicate.setReturnValueDescription(co.getReturnValueDescription()); - coDuplicate.setDefinedIn(co.getDefinedIn()); - coDuplicate.setRelevance(co.getRelevance()); - List<Parameter> parameters = new ArrayList<Parameter>(); - for (int i = 0; i < co.getParamCount(); ++i) - parameters.add(co.getParam(i)); - if (c instanceof ScriptFunctionCompletion) - inScriptFunctions.add(coDuplicate); - else - { - if (!isFunctionAlreadyDeclared(coDuplicate, functions)) - functions.add(coDuplicate); - } - } - else - { - res = rText.substring(previousDotIdx, nextDotIdx); - BasicCompletion c2 = duplicateBasicCompletion((BasicCompletion) c, res); - if (!exists(c2, basic)) - basic.add(c2); - } - } + if (c instanceof ScriptFunctionCompletion && !isFunctionAlreadyDeclared((ScriptFunctionCompletion) c, inScriptFunctions)) + inScriptFunctions.add(c); + else if (!isFunctionAlreadyDeclared((FunctionCompletion) c, functions)) + functions.add(c); + originalList.remove(c); } - else if (c instanceof VariableCompletion) - { + else if (c instanceof VariableCompletion) { + + // the completion is a variable + + variables.add(c); - if (previousDotIdx == 0 && nextDotIdx == -1) - { - if (c instanceof ScriptFunctionCompletion) - inScriptVariables.add(c); - else - variables.add(c); - } - else - { - String res; - if (nextDotIdx == -1) - { - res = rText.substring(previousDotIdx); - VariableCompletion co = (VariableCompletion) c; - VariableCompletion c2 = new VariableCompletion(co.getProvider(), res, co.getType()); - c2.setDefinedIn(co.getDefinedIn()); - c2.setShortDescription(co.getShortDescription()); - c2.setSummary(co.getSummary()); - c2.setRelevance(co.getRelevance()); - if (!isFunctionAlreadyDeclared((FunctionCompletion) c2, variables)) - variables.add(c2); - } - else - { - res = rText.substring(previousDotIdx, nextDotIdx); - BasicCompletion c2 = duplicateBasicCompletion((BasicCompletion) c, res); - if (!isFunctionAlreadyDeclared((FunctionCompletion) c2, basic)) - basic.add(c2); - } - } originalList.remove(c); } - else if (c instanceof BasicCompletion) - { + else if (c instanceof BasicCompletion) { // the completion is something else - if (previousDotIdx == 0 && nextDotIdx == -1) - { - basic.add(c); - } - else - { - String res = nextDotIdx == -1 ? rText.substring(previousDotIdx) - : rText.substring(previousDotIdx, nextDotIdx); - BasicCompletion c2 = duplicateBasicCompletion((BasicCompletion) c, res); - if (!exists(c2, basic)) - basic.add(c2); - } + + basic.add(c); + originalList.remove(c); } } - toReturn.addAll(inScriptVariables); + + //toReturn.addAll(inScriptVariables); toReturn.addAll(inScriptFunctions); - toReturn.addAll(inScriptBasic); + //toReturn.addAll(inScriptBasic); toReturn.addAll(variables); toReturn.addAll(functions); toReturn.addAll(basic); toReturn.addAll(originalList); - Collections.sort(toReturn, comparatorFull); + toReturn.sort(comparatorFull); + return toReturn; } @Override - protected boolean isValidChar(char ch) - { + protected boolean isValidChar(final char ch) { return super.isValidChar(ch) || ch == '\"'; } - protected boolean isValidCharStrict(char ch) - { + protected boolean isValidCharStrict(final char ch) { return isValidCharStrict(ch, false); } - protected boolean isValidCharStrict(char ch, boolean weirdChars) - { + protected boolean isValidCharStrict(final char ch, final boolean weirdChars) { if (weirdChars) - return super.isValidChar(ch) || ch == '.' || ch == '(' || ch == ')' || ch == ',' || ch == '\"' || ch == '[' - || ch == ']'; + return super.isValidChar(ch) || ch == '.' || ch == '(' || ch == ')' || ch == ',' || ch == '\"' || ch == '[' || ch == ']'; else return super.isValidChar(ch) || ch == '.' || ch == '[' || ch == ']'; } /** * Returns is a completion c exists in the given list of completions. - * - * @param c - * {@link Completion} object - * @param list - * list of {@link Completion} objects to look in + * + * @param c {@link Completion} object + * @param list list of {@link Completion} objects to look in * @return <code>true</code> if specified {@link Completion} object is found in the list */ - public static boolean exists(Completion c, List<Completion> list) - { + public static boolean exists(final Completion c, final List<Completion> list) { boolean found = false; - for (Completion ctmp : list) - { - if (ctmp.getReplacementText().contentEquals(c.getReplacementText())) - { + for (final Completion ctmp : list) { + if (ctmp.getReplacementText().contentEquals(c.getReplacementText())) { found = true; break; } @@ -425,25 +203,19 @@ public class IcyCompletionProvider extends DefaultCompletionProvider return found; } - public static boolean isFunctionAlreadyDeclared(FunctionCompletion fc, List<Completion> completions) - { + public static boolean isFunctionAlreadyDeclared(final FunctionCompletion fc, final List<Completion> completions) { if (completions.isEmpty()) return false; boolean alreadyDeclared = false; - for (int i = 0; i < completions.size() && !alreadyDeclared; ++i) - { - Completion c = completions.get(i); - if (fc.getReplacementText().contentEquals(c.getReplacementText())) - { - if (c instanceof FunctionCompletion) - { - FunctionCompletion fctmp = (FunctionCompletion) c; - if (fctmp.getParamCount() == fc.getParamCount()) - { + for (int i = 0; i < completions.size() && !alreadyDeclared; ++i) { + final Completion c = completions.get(i); + if (fc.getReplacementText().contentEquals(c.getReplacementText())) { + if (c instanceof FunctionCompletion) { + final FunctionCompletion fctmp = (FunctionCompletion) c; + if (fctmp.getParamCount() == fc.getParamCount()) { boolean different = false; - for (int paramIdx = 0; paramIdx < fctmp.getParamCount(); ++paramIdx) - { - if (!different && fctmp.getParam(paramIdx).getType() != fc.getParam(paramIdx).getType()) + for (int paramIdx = 0; paramIdx < fctmp.getParamCount(); ++paramIdx) { + if (!different && !fctmp.getParam(paramIdx).getType().equals(fc.getParam(paramIdx).getType())) different = true; } if (!different) @@ -455,113 +227,93 @@ public class IcyCompletionProvider extends DefaultCompletionProvider return alreadyDeclared; } - public BasicCompletion duplicateBasicCompletion(BasicCompletion c, String res) - { - BasicCompletion co = (BasicCompletion) c; - BasicCompletion c2; - if (co instanceof BasicJavaClassCompletion) - { - BasicJavaClassCompletion basicJavaCO = (BasicJavaClassCompletion) co; + public BasicCompletion duplicateBasicCompletion(final BasicCompletion c, final String res) { + final BasicCompletion c2; + if (c instanceof BasicJavaClassCompletion) { + final BasicJavaClassCompletion basicJavaCO = (BasicJavaClassCompletion) c; c2 = new BasicJavaClassCompletion(c.getProvider(), basicJavaCO.getJavaClass()); if (basicJavaCO.isParsingDone()) - c2.setSummary(co.getSummary()); + c2.setSummary(c.getSummary()); } - else - { + else { c2 = new BasicCompletion(c.getProvider(), res); - c2.setSummary(co.getSummary()); + c2.setSummary(c.getSummary()); } - c2.setRelevance(co.getRelevance()); + c2.setRelevance(c.getRelevance()); return c2; } - /** - * {@inheritDoc} - */ - protected List<Completion> getCompletionsImpl(JTextComponent comp) - { + @Override + protected List<Completion> getCompletionsImpl(final JTextComponent comp) { // return completions; - List<Completion> retVal = new ArrayList<Completion>(); + final List<Completion> retVal = new ArrayList<>(); String text = getAlreadyEnteredTextWithFunc(comp); int lastIdx = text.lastIndexOf('.'); - ScriptEngineHandler engineHandler = ScriptEngineHandler.getLastEngineHandler(); - HashMap<String, VariableType> engineVariables = ScriptEngineHandler.getLastEngineHandler().getEngineVariables(); + final ScriptEngineHandler engineHandler = ScriptEngineHandler.getLastEngineHandler(); + final HashMap<String, VariableType> engineVariables = ScriptEngineHandler.getLastEngineHandler().getEngineVariables(); // Cannot work directly because returns null on the provider. - HashMap<Class<?>, ArrayList<ScriptFunctionCompletion>> engineTypesMethod = engineHandler.getEngineTypesMethod(); - HashMap<Integer, IcyFunctionBlock> localFunctions; + final HashMap<Class<?>, ArrayList<ScriptFunctionCompletion>> engineTypesMethod = engineHandler.getEngineTypesMethod(); + final HashMap<Integer, IcyFunctionBlock> localFunctions; if (handler != null) localFunctions = handler.getBlockFunctions(); else - localFunctions = new HashMap<Integer, IcyFunctionBlock>(); + localFunctions = new HashMap<>(); - if (text != null) - { + if (text != null) { // test if inside parenthesis - if (text.contains("(")) - { - String text2 = String.copyValueOf(text.toCharArray()); + if (text.contains("(")) { + final String text2 = String.copyValueOf(text.toCharArray()); int idx; int i = 0; int pOpen = 0; int pClose = 0; - while (i < text2.length() - 1 && (idx = text2.indexOf('(', i)) != -1) - { + while (i < text2.length() - 1 && (idx = text2.indexOf('(', i)) != -1) { ++pOpen; i += idx + 1; } i = 0; - while (i < text2.length() - 1 && (idx = text2.indexOf(')', i)) != -1) - { + while (i < text2.length() - 1 && (idx = text2.indexOf(')', i)) != -1) { ++pClose; i += idx + 1; } - int ppCount = pOpen - pClose; - if (ppCount > 0) - { + final int ppCount = pOpen - pClose; + if (ppCount > 0) { text = text2.substring(text2.lastIndexOf('(') + 1); lastIdx = text.lastIndexOf('.'); } } - boolean containsNew = text.contains("new "); - if (containsNew) - { + + final boolean containsNew = text.contains("new "); + if (containsNew) { text = text.substring("new ".length()); // add the classes - if (text.length() > 0 && Character.isUpperCase(text.charAt(0))) - { - ArrayList<String> classes = ScriptEngineHandler.getAllClasses(); - for (String s : classes) - { + if (text.length() > 0 && Character.isUpperCase(text.charAt(0))) { + final ArrayList<String> classes = ScriptEngineHandler.getAllClasses(); + for (final String s : classes) { String nameFinal = ClassUtil.getSimpleClassName(s); - int idxD = nameFinal.indexOf('$'); - if (idxD != -1) - { - nameFinal = nameFinal.substring(idxD + 1, nameFinal.length()); + final int idxD = nameFinal.indexOf('$'); + if (idxD != -1) { + nameFinal = nameFinal.substring(idxD + 1); } - if (nameFinal.toLowerCase().startsWith(text.toLowerCase())) - { - try - { - Class<?> clazz = ClassUtil.findClass(s); + if (nameFinal.toLowerCase().startsWith(text.toLowerCase())) { + try { + final Class<?> clazz = ClassUtil.findClass(s); if (Modifier.isStatic(clazz.getModifiers())) continue; - for (Constructor<?> c : clazz.getConstructors()) - { - int mod = c.getModifiers(); - if (Modifier.isPublic(mod)) - { - NewInstanceCompletion fc = new NewInstanceCompletion(this, nameFinal, c); + for (final Constructor<?> c : clazz.getConstructors()) { + final int mod = c.getModifiers(); + if (Modifier.isPublic(mod)) { + final NewInstanceCompletion fc = new NewInstanceCompletion(this, nameFinal, c); fc.setRelevance(ScriptingHandler.RELEVANCE_HIGH); // TODO relevance assignment = type / expression = void fc.setDefinedIn(clazz.toString().replace('$', '.')); - ArrayList<Parameter> params = new ArrayList<Parameter>(); + final ArrayList<Parameter> params = new ArrayList<>(); int i = 0; - for (Class<?> clazzParam : c.getParameterTypes()) - { + for (final Class<?> clazzParam : c.getParameterTypes()) { params.add(new Parameter(getType(clazzParam, true), "arg" + i)); ++i; } @@ -570,45 +322,38 @@ public class IcyCompletionProvider extends DefaultCompletionProvider } } } - catch (ClassNotFoundException e) - { + catch (final ClassNotFoundException e) { + IcyExceptionHandler.showErrorMessage(e, true); } } } } } - else if (text.isEmpty() || lastIdx == -1) - { + else if (text.isEmpty() || lastIdx == -1) { doClassicCompletion(text, retVal); } - else - { + else { // ----------------- // Generate classes // ----------------- - if (text.startsWith("Packages.")) - { - String clazzWanted = text.substring("Packages.".length()); - ArrayList<String> classes = ScriptEngineHandler.getAllClasses(); - for (String s : classes) - { + if (text.startsWith("Packages.")) { + final String clazzWanted = text.substring("Packages.".length()); + final ArrayList<String> classes = ScriptEngineHandler.getAllClasses(); + for (String s : classes) { s = s.replace('$', '.'); - if (s.toLowerCase().startsWith(clazzWanted.toLowerCase())) - { - int startOffset = clazzWanted.lastIndexOf('.'); - int endOffset; - BasicCompletion c; - if (startOffset != -1) - { + if (s.toLowerCase().startsWith(clazzWanted.toLowerCase())) { + final int startOffset = clazzWanted.lastIndexOf('.'); + final int endOffset; + final BasicCompletion c; + if (startOffset != -1) { endOffset = s.indexOf('.', startOffset + 1); if (endOffset != -1) c = new BasicCompletion(this, s.substring(startOffset + 1, endOffset)); else - c = new BasicCompletion(this, s.substring(startOffset + 1, s.length())); + c = new BasicCompletion(this, s.substring(startOffset + 1)); } - else - { - endOffset = s.indexOf('.', 0); + else { + endOffset = s.indexOf('.'); if (endOffset != -1) c = new BasicCompletion(this, s.substring(0, endOffset)); else @@ -620,42 +365,35 @@ public class IcyCompletionProvider extends DefaultCompletionProvider } } } - if (handler != null) - { - String command; - if (lastIdx != -1) - { + + if (handler != null) { + final String command; + if (lastIdx != -1) { command = text.substring(0, lastIdx); if (lastIdx <= text.length() - 1) // dot is before the // last - text = text.substring(lastIdx + 1, text.length()); + text = text.substring(lastIdx + 1); } else command = text; - ArrayList<ScriptFunctionCompletion> methods = null; + ArrayList<ScriptFunctionCompletion> methods; // is the command a classname ? Class<?> clazz = handler.resolveClassDeclaration(command.replace('.', '$')); - if (clazz != null) - { + if (clazz != null) { // ---------------------------- // STATIC ACCESS // ---------------------------- - if (containsNew) - { + if (containsNew) { populateWithConstructors(clazz, retVal); } - else if ((methods = engineTypesMethod.get(clazz)) != null && !advanced) - { - for (ScriptFunctionCompletion complete : methods) - { - if (complete.isStatic() && (text.isEmpty() - || complete.getName().toLowerCase().startsWith(text.toLowerCase()))) + else if ((methods = engineTypesMethod.get(clazz)) != null && !advanced) { + for (final ScriptFunctionCompletion complete : methods) { + if (complete.isStatic() && (text.isEmpty() || complete.getName().toLowerCase().startsWith(text.toLowerCase()))) retVal.add(generateSFCCopy(complete, true)); } } - else - { + else { populateClassTypes(new VariableType(clazz), text, retVal, true); } } @@ -663,17 +401,13 @@ public class IcyCompletionProvider extends DefaultCompletionProvider // check in the local variables if it is a variable // if it is : propose depending on the variable type VariableType type = handler.getVariableDeclaration(command); - if ((type != null && type.getClazz() != null) - || ((type = engineVariables.get(command)) != null && type.getClazz() != null)) - { + if ((type != null && type.getClazz() != null) || ((type = engineVariables.get(command)) != null && type.getClazz() != null)) { // ---------------------------- // VARIABLE ACCESS // ---------------------------- methods = engineTypesMethod.get(clazz); - if (methods != null && !advanced) - { - for (ScriptFunctionCompletion complete : methods) - { + if (methods != null && !advanced) { + for (final ScriptFunctionCompletion complete : methods) { if (!complete.getName().toLowerCase().startsWith(text.toLowerCase())) continue; if (complete.isStatic()) @@ -684,30 +418,25 @@ public class IcyCompletionProvider extends DefaultCompletionProvider retVal.add(generateSFCCopy(complete)); } } - else - { + else { populateClassTypes(type, text, retVal); } } - else - { + else { // ---------------------------- // FUNCTION ACCESS // ---------------------------- // if not : look the type of the function (if declared). - int startOffset = getStartOffset(comp) - 1; + final int startOffset = getStartOffset(comp) - 1; // System.out.println("offset:" + startOffset); // for (Integer i : localFunctions.keySet()) // System.out.println(i); - IcyFunctionBlock fb = localFunctions.get(startOffset); - if (fb != null) - { + final IcyFunctionBlock fb = localFunctions.get(startOffset); + if (fb != null) { clazz = fb.getReturnType().getClazz(); methods = engineTypesMethod.get(clazz); - if (methods != null && !advanced) - { - for (ScriptFunctionCompletion complete : methods) - { + if (methods != null && !advanced) { + for (final ScriptFunctionCompletion complete : methods) { if (complete.isStatic()) complete.setRelevance(ScriptingHandler.RELEVANCE_LOW); else if (!complete.isStatic()) @@ -717,16 +446,14 @@ public class IcyCompletionProvider extends DefaultCompletionProvider retVal.add(generateSFCCopy(complete)); } } - else - { + else { Type t = null; if (fb.getMethod() != null) t = fb.getMethod().getGenericReturnType(); populateClassTypes(fb.getReturnType(), t, text, retVal, false); } } - else - { + else { // Import feature. // doClassicCompletion(command, retVal, true); } @@ -737,36 +464,31 @@ public class IcyCompletionProvider extends DefaultCompletionProvider return retVal; } - protected void populateWithConstructors(Class<?> clazz, List<Completion> retVal) - { + protected void populateWithConstructors(final Class<?> clazz, final List<Completion> retVal) { if (!Modifier.isPublic(clazz.getModifiers())) return; - String name; + final String name; if (clazz.isArray()) name = clazz.getCanonicalName(); else name = clazz.getName(); - for (Constructor<?> c : clazz.getConstructors()) - { - int mod = c.getModifiers(); - if (Modifier.isPublic(mod)) - { - NewInstanceCompletion fc = new NewInstanceCompletion(this, name, c); + for (final Constructor<?> c : clazz.getConstructors()) { + final int mod = c.getModifiers(); + if (Modifier.isPublic(mod)) { + final NewInstanceCompletion fc = new NewInstanceCompletion(this, name, c); fc.setRelevance(ScriptingHandler.RELEVANCE_HIGH); // TODO relevance assignment = type / expr = void fc.setDefinedIn(clazz.toString().replace('$', '.')); - ArrayList<Parameter> params = new ArrayList<Parameter>(); + final ArrayList<Parameter> params = new ArrayList<>(); int i = 0; - for (Class<?> clazzParam : c.getParameterTypes()) - { + for (final Class<?> clazzParam : c.getParameterTypes()) { params.add(new Parameter(getType(clazzParam, true), "arg" + i)); ++i; } - if (c.getAnnotation(Deprecated.class) != null) - { + if (c.getAnnotation(Deprecated.class) != null) { fc.setSummary("Deprecated"); fc.setShortDescription("Deprecated"); } @@ -776,91 +498,74 @@ public class IcyCompletionProvider extends DefaultCompletionProvider } } - protected void populateClassTypes(VariableType type, String text, List<Completion> retVal) - { + protected void populateClassTypes(final VariableType type, final String text, final List<Completion> retVal) { populateClassTypes(type, null, text, retVal, false); } - protected void populateClassTypes(VariableType type, String text, List<Completion> retVal, boolean staticOnly) - { + protected void populateClassTypes(final VariableType type, final String text, final List<Completion> retVal, final boolean staticOnly) { populateClassTypes(type, null, text, retVal, staticOnly); } - protected void populateClassTypes(VariableType type2, Type t, String text, List<Completion> retVal, - boolean staticOnly) - { - Class<?> type = type2.getClazz(); - if (type == null) - { + protected void populateClassTypes(final VariableType type2, final Type t, final String text, final List<Completion> retVal, final boolean staticOnly) { + final Class<?> type = type2.getClazz(); + if (type == null) { return; } if (!Modifier.isPublic(type.getModifiers())) return; - ArrayList<Completion> listFields = new ArrayList<Completion>(); - ArrayList<Completion> listMethods = new ArrayList<Completion>(); - ArrayList<Completion> listClasses = new ArrayList<Completion>(); - ArrayList<Completion> listEnums = new ArrayList<Completion>(); - for (Field f : type.getFields()) - { - String name = f.getName(); + final ArrayList<Completion> listFields = new ArrayList<>(); + final ArrayList<Completion> listMethods = new ArrayList<>(); + final ArrayList<Completion> listClasses = new ArrayList<>(); + final ArrayList<Completion> listEnums = new ArrayList<>(); + for (final Field f : type.getFields()) { + final String name = f.getName(); if (!name.toLowerCase().startsWith(text.toLowerCase())) continue; - int mod = f.getModifiers(); - if (Modifier.isPublic(mod)) - { - if (!staticOnly) - { - VariableCompletion vc = new VariableCompletion(this, name, getType(f.getType(), true)); + final int mod = f.getModifiers(); + if (Modifier.isPublic(mod)) { + if (!staticOnly) { + final VariableCompletion vc = new VariableCompletion(this, name, getType(f.getType(), true)); if (Modifier.isStatic(mod)) vc.setRelevance(ScriptingHandler.RELEVANCE_LOW); else vc.setRelevance(ScriptingHandler.RELEVANCE_HIGH); listFields.add(vc); } - else if (Modifier.isStatic(mod)) - { - VariableCompletion vc = new VariableCompletion(this, name, getType(f.getType(), true)); + else if (Modifier.isStatic(mod)) { + final VariableCompletion vc = new VariableCompletion(this, name, getType(f.getType(), true)); vc.setRelevance(ScriptingHandler.RELEVANCE_HIGH); - if (f.getAnnotation(Deprecated.class) != null) - { + if (f.getAnnotation(Deprecated.class) != null) { vc.setSummary("deprecated"); } listFields.add(vc); } } } - for (Class<?> c : type.getClasses()) - { - if (Modifier.isPublic(c.getModifiers()) && c.getSimpleName().toLowerCase().startsWith(text.toLowerCase())) - { - BasicJavaClassCompletion jcc = new BasicJavaClassCompletion(this, c); + for (final Class<?> c : type.getClasses()) { + if (Modifier.isPublic(c.getModifiers()) && c.getSimpleName().toLowerCase().startsWith(text.toLowerCase())) { + final BasicJavaClassCompletion jcc = new BasicJavaClassCompletion(this, c); jcc.setRelevance(ScriptingHandler.RELEVANCE_MIN); if (!exists(jcc, retVal)) listClasses.add(jcc); } } - if (type.isArray()) - { - VariableCompletion vc = new VariableCompletion(this, "length", int.class.getName()); + if (type.isArray()) { + final VariableCompletion vc = new VariableCompletion(this, "length", int.class.getName()); vc.setRelevance(ScriptingHandler.RELEVANCE_HIGH); listFields.add(vc); } - for (Method m : type.getMethods()) - { + for (final Method m : type.getMethods()) { if (!m.getName().toLowerCase().startsWith(text.toLowerCase())) continue; - int mod = m.getModifiers(); + final int mod = m.getModifiers(); // if (!Modifier.isPublic(mod)) // continue; - if (!staticOnly) - { - ScriptFunctionCompletion fc; - if (Pattern.matches("(\\[*)E", m.getGenericReturnType().toString())) - { + if (!staticOnly) { + final ScriptFunctionCompletion fc; + if (Pattern.matches("(\\[*)E", m.getGenericReturnType().toString())) { fc = new ScriptFunctionCompletion(this, m.getName(), m, type2); } - else - { + else { fc = new ScriptFunctionCompletion(this, m.getName(), m); } if (Modifier.isStatic(mod)) @@ -870,45 +575,38 @@ public class IcyCompletionProvider extends DefaultCompletionProvider // TODO relevance assignment = type / expr = void fc.setDefinedIn(type.toString().replace('$', '.')); - ArrayList<Parameter> params = new ArrayList<Parameter>(); + final ArrayList<Parameter> params = new ArrayList<>(); int i = 0; - for (Class<?> clazzParam : m.getParameterTypes()) - { + for (final Class<?> clazzParam : m.getParameterTypes()) { params.add(new Parameter(getType(clazzParam, true), "arg" + i)); ++i; } fc.setParams(params); - if (m.getAnnotation(Deprecated.class) != null) - { + if (m.getAnnotation(Deprecated.class) != null) { fc.setSummary("deprecated"); fc.setShortDescription("Deprecated"); } listMethods.add(fc); } - else if (Modifier.isStatic(mod)) - { - ScriptFunctionCompletion fc; - if (Pattern.matches("(\\[*)E", m.getGenericReturnType().toString())) - { + else if (Modifier.isStatic(mod)) { + final ScriptFunctionCompletion fc; + if (Pattern.matches("(\\[*)E", m.getGenericReturnType().toString())) { fc = new ScriptFunctionCompletion(this, m.getName(), m, type2); } - else - { + else { fc = new ScriptFunctionCompletion(this, m.getName(), m); } fc.setRelevance(ScriptingHandler.RELEVANCE_HIGH); // TODO relevance assignment = type / expr = void fc.setDefinedIn(type.toString().replace('$', '.')); - ArrayList<Parameter> params = new ArrayList<Parameter>(); + final ArrayList<Parameter> params = new ArrayList<>(); int i = 0; - for (Class<?> clazzParam : m.getParameterTypes()) - { + for (final Class<?> clazzParam : m.getParameterTypes()) { params.add(new Parameter(getType(clazzParam, true), "arg" + i)); ++i; } - if (m.getAnnotation(Deprecated.class) != null) - { + if (m.getAnnotation(Deprecated.class) != null) { fc.setSummary("deprecated"); fc.setShortDescription("Deprecated"); } @@ -922,60 +620,49 @@ public class IcyCompletionProvider extends DefaultCompletionProvider retVal.addAll(listEnums); } - protected Completion generateSFCCopy(ScriptFunctionCompletion complete, boolean b) - { - Method method = complete.getMethod(); - String shortDescript = complete.getShortDescription(); + protected Completion generateSFCCopy(final ScriptFunctionCompletion complete, final boolean b) { + final Method method = complete.getMethod(); + final String shortDescript = complete.getShortDescription(); - ScriptFunctionCompletion sfcCopy = new ScriptFunctionCompletion(this, method.getName(), method); + final ScriptFunctionCompletion sfcCopy = new ScriptFunctionCompletion(this, method.getName(), method); sfcCopy.setDefinedIn(complete.getDefinedIn()); sfcCopy.setRelevance(complete.getRelevance()); sfcCopy.setReturnValueDescription(method.getReturnType().toString()); if (shortDescript != null) sfcCopy.setShortDescription(shortDescript); - ArrayList<Parameter> params = new ArrayList<Parameter>(); + final ArrayList<Parameter> params = new ArrayList<>(); for (int i = 0; i < complete.getParamCount(); ++i) params.add(complete.getParam(i)); sfcCopy.setParams(params); return sfcCopy; } - protected Completion generateSFCCopy(ScriptFunctionCompletion complete) - { + protected Completion generateSFCCopy(final ScriptFunctionCompletion complete) { return generateSFCCopy(complete, false); } - protected void doClassicCompletion(String text, List<Completion> retVal) - { + protected void doClassicCompletion(final String text, final List<Completion> retVal) { doClassicCompletion(text, retVal, false); } - @SuppressWarnings("unchecked") - protected void doClassicCompletion(String text, List<Completion> retVal, boolean importOnly) - { + protected void doClassicCompletion(final String text, final List<Completion> retVal, final boolean importOnly) { // add the classes - if (text.length() > 0 && Character.isUpperCase(text.charAt(0))) - { - ArrayList<String> classes = ScriptEngineHandler.getAllClasses(); - for (String s : classes) - { - try - { - Class<?> clazz = ClassUtil.findClass(s); - if (Modifier.isPublic(clazz.getModifiers())) - { + if (text.length() > 0 && Character.isUpperCase(text.charAt(0))) { + final ArrayList<String> classes = ScriptEngineHandler.getAllClasses(); + for (final String s : classes) { + try { + final Class<?> clazz = ClassUtil.findClass(s); + if (Modifier.isPublic(clazz.getModifiers())) { String nameFinal = ClassUtil.getSimpleClassName(s); - int idxDollar = nameFinal.indexOf('$'); - if (idxDollar != -1) - { + final int idxDollar = nameFinal.indexOf('$'); + if (idxDollar != -1) { nameFinal = nameFinal.substring(idxDollar + 1); // continue; } - String desc = null; - if (nameFinal.toLowerCase().startsWith(text.toLowerCase())) - { - BasicJavaClassCompletion c = new BasicJavaClassCompletion(this, clazz, importOnly); + final String desc = null; + if (nameFinal.toLowerCase().startsWith(text.toLowerCase())) { + final BasicJavaClassCompletion c = new BasicJavaClassCompletion(this, clazz, importOnly); c.setShortDescription(desc == null ? "" : desc); c.setRelevance(ScriptingHandler.RELEVANCE_MIN); c.setDefinedIn(s.replace('$', '.')); @@ -983,40 +670,34 @@ public class IcyCompletionProvider extends DefaultCompletionProvider } } } - catch (ClassNotFoundException e) - { + catch (final ClassNotFoundException e) { + IcyExceptionHandler.showErrorMessage(e, true); } } } // nothing worked, display normal int index = Collections.binarySearch(completions, text, comparator); - if (index < 0) - { // No exact match + if (index < 0) { // No exact match index = -index - 1; } - else - { + else { // If there are several overloads for the function being // completed, Collections.binarySearch() will // return the index of one of those overloads, but we must // return all of them, so search backward until we find the // first one. int pos = index - 1; - while (pos > 0 && comparator.compare(completions.get(pos), text) == 0) - { - retVal.add((Completion) completions.get(pos)); + while (pos > 0 && comparator.compare(completions.get(pos), text) == 0) { + retVal.add(completions.get(pos)); pos--; } } - while (index < completions.size()) - { - Completion c = (Completion) completions.get(index); - if (Util.startsWithIgnoreCase(c.getInputText(), text)) - { - if (c instanceof ScriptFunctionCompletion) - { + while (index < completions.size()) { + final Completion c = completions.get(index); + if (Util.startsWithIgnoreCase(c.getInputText(), text)) { + if (c instanceof ScriptFunctionCompletion) { if (((ScriptFunctionCompletion) c).isStatic()) retVal.add(c); } @@ -1024,39 +705,34 @@ public class IcyCompletionProvider extends DefaultCompletionProvider retVal.add(c); index++; } - else - { + else { break; } } } @Override - public String getAlreadyEnteredText(JTextComponent comp) - { + public String getAlreadyEnteredText(final JTextComponent comp) { // used only for insertion of text - Document doc = comp.getDocument(); + final Document doc = comp.getDocument(); - int dot = comp.getCaretPosition(); - Element root = doc.getDefaultRootElement(); - int index = root.getElementIndex(dot); - Element elem = root.getElement(index); + final int dot = comp.getCaretPosition(); + final Element root = doc.getDefaultRootElement(); + final int index = root.getElementIndex(dot); + final Element elem = root.getElement(index); int start = elem.getStartOffset(); int len = dot - start; - try - { + try { doc.getText(start, len, seg); } - catch (BadLocationException ble) - { + catch (final BadLocationException ble) { ble.printStackTrace(); return EMPTY_STRING; } - int segEnd = seg.offset + len; + final int segEnd = seg.offset + len; start = segEnd - 1; - while (start >= seg.offset && isValidChar(seg.array[start])) - { + while (start >= seg.offset && isValidChar(seg.array[start])) { start--; } start++; @@ -1065,73 +741,63 @@ public class IcyCompletionProvider extends DefaultCompletionProvider return len == 0 ? EMPTY_STRING : new String(seg.array, start, len); } - public String getAlreadyEnteredTextWithFunc(JTextComponent comp) - { + public String getAlreadyEnteredTextWithFunc(final JTextComponent comp) { - Document doc = comp.getDocument(); + final Document doc = comp.getDocument(); - int dot = comp.getCaretPosition(); - Element root = doc.getDefaultRootElement(); - int index = root.getElementIndex(dot); - Element elem = root.getElement(index); + final int dot = comp.getCaretPosition(); + final Element root = doc.getDefaultRootElement(); + final int index = root.getElementIndex(dot); + final Element elem = root.getElement(index); int start = elem.getStartOffset(); int len = dot - start; - try - { + try { doc.getText(start, len, seg); } - catch (BadLocationException ble) - { + catch (final BadLocationException ble) { ble.printStackTrace(); return EMPTY_STRING; } - int segEnd = seg.offset + len; + final int segEnd = seg.offset + len; start = segEnd - 1; - while (start >= seg.offset && isValidCharStrict(seg.array[start], start != segEnd - 1) - && (start != segEnd - 1 || seg.array[start] != ',')) - { + while (start >= seg.offset && isValidCharStrict(seg.array[start], start != segEnd - 1) && (start != segEnd - 1 || seg.array[start] != ',')) { start--; } - if (start >= seg.offset + 3 && seg.toString().contains("new")) - { + if (start >= seg.offset + 3 && seg.toString().contains("new")) { if (seg.array[start] == ' ' && seg.array[start - 1] == 'w' && seg.array[start - 2] == 'e' - && seg.array[start - 3] == 'n') - { + && seg.array[start - 3] == 'n') { start -= 4; } } start++; len = segEnd - start; - return len == 0 ? EMPTY_STRING : new String(seg.array, start, len); + //return len == 0 ? EMPTY_STRING : new String(seg.array, start, len); + return len == 0 ? "" : new String(seg.array, start, len); } - public int getStartOffset(JTextComponent comp) - { + public int getStartOffset(final JTextComponent comp) { - Document doc = comp.getDocument(); + final Document doc = comp.getDocument(); - int dot = comp.getCaretPosition(); - Element root = doc.getDefaultRootElement(); - int index = root.getElementIndex(dot); - Element elem = root.getElement(index); + final int dot = comp.getCaretPosition(); + final Element root = doc.getDefaultRootElement(); + final int index = root.getElementIndex(dot); + final Element elem = root.getElement(index); int start = elem.getStartOffset(); - int len = dot - start; - try - { + final int len = dot - start; + try { doc.getText(start, len, seg); } - catch (BadLocationException ble) - { + catch (final BadLocationException ble) { ble.printStackTrace(); return -1; } - int segEnd = seg.offset + len; + final int segEnd = seg.offset + len; start = segEnd - 1; - while (start >= seg.offset && isValidChar(seg.array[start])) - { + while (start >= seg.offset && isValidChar(seg.array[start])) { start--; } start++; @@ -1140,39 +806,32 @@ public class IcyCompletionProvider extends DefaultCompletionProvider } /** - * @param clazz - * the class the get the type from - * @param simpleName - * if we want the simple name of the class + * @param clazz the class the get the type from + * @param simpleName if we want the simple name of the class * @return the class name */ - public static String getType(Class<?> clazz, boolean simpleName) - { - if (simpleName) - { + public static String getType(final Class<?> clazz, final boolean simpleName) { + if (simpleName) { if (clazz.isArray()) return clazz.getCanonicalName(); return clazz.getSimpleName(); } - else - { + else { if (clazz.isPrimitive()) return clazz.getSimpleName(); return clazz.getName(); } } - public ArrayList<String> getClassNamesFromPackage(String packageName) throws IOException - { - ClassLoader classLoader = PluginLoader.getLoader(); - URL packageURL; - ArrayList<String> names = new ArrayList<String>(); + public ArrayList<String> getClassNamesFromPackage(String packageName) throws IOException { + final ClassLoader classLoader = PluginLoader.getLoader(); + final URL packageURL; + final ArrayList<String> names = new ArrayList<>(); packageName = packageName.replace(".", "/"); packageURL = classLoader.getResource(packageName); - if (packageURL.getProtocol().equals("jar")) - { + if (packageURL != null && packageURL.getProtocol().equals("jar")) { String jarFileName; // build jar file name, then loop through zipped entries @@ -1183,75 +842,57 @@ public class IcyCompletionProvider extends DefaultCompletionProvider // loop through files in classpath } - else - { - File folder = new File(packageURL.getFile()); - File[] contenuti = folder.listFiles(); + else if (packageURL != null) { + final File folder = new File(packageURL.getFile()); + final File[] contenuti = folder.listFiles(); String entryName; - for (File actual : contenuti) - { - entryName = actual.getName(); - entryName = entryName.substring(0, entryName.lastIndexOf('.')); - names.add(entryName); + if (contenuti != null) { + for (final File actual : contenuti) { + entryName = actual.getName(); + entryName = entryName.substring(0, entryName.lastIndexOf('.')); + names.add(entryName); + } } } return names; } - private ArrayList<String> getNames(String jarFileName, String packageName) throws IOException - { + private ArrayList<String> getNames(final String jarFileName, final String packageName) throws IOException { - Enumeration<JarEntry> jarEntries; + final Enumeration<JarEntry> jarEntries; String entryName; - ArrayList<String> toReturn = new ArrayList<String>(); - JarFile jf = null; - try - { - jf = new JarFile(jarFileName); + final ArrayList<String> toReturn = new ArrayList<>(); + try (final JarFile jf = new JarFile(jarFileName)) { jarEntries = jf.entries(); - while (jarEntries.hasMoreElements()) - { + while (jarEntries.hasMoreElements()) { entryName = jarEntries.nextElement().getName(); - if (entryName.startsWith(packageName) && entryName.length() > packageName.length() + 5) - { - Pattern p = Pattern.compile("((\\w|\\.|\\\\|/)+)(|\\$[a-zA-Z0-9]*[a-zA-Z]).class"); - Matcher m = p.matcher(entryName); - if (m.matches()) - { + if (entryName.startsWith(packageName) && entryName.length() > packageName.length() + 5) { + final Pattern p = Pattern.compile("((\\w|\\.|\\\\|/)+)(|\\$[a-zA-Z0-9]*[a-zA-Z]).class"); + final Matcher m = p.matcher(entryName); + if (m.matches()) { entryName = m.group(1) + m.group(3); toReturn.add(entryName); } } } } - finally - { - if (jf != null) - jf.close(); - } return toReturn; } - public void installDefaultCompletions(String language) - { - // no laguage defined ? --> exit + public void installDefaultCompletions(final String language) { + // no language defined ? --> exit if (StringUtil.isEmpty(language)) return; - - InputStream in = getClass().getClassLoader().getResourceAsStream( - "plugins/tprovoost/scripteditor/resources/lang/" + language.toLowerCase() + ".xml"); - try - { - if (in != null) - { + + final InputStream in = getClass().getClassLoader().getResourceAsStream("plugins/tprovoost/scripteditor/resources/lang/" + language.toLowerCase() + ".xml"); + try { + if (in != null) { loadFromXML(in); in.close(); } else - System.out.println("File not found: " + "plugins/tprovoost/scripteditor/resources/lang/" - + language.toLowerCase() + ".xml"); + System.out.println("File not found: " + "plugins/tprovoost/scripteditor/resources/lang/" + language.toLowerCase() + ".xml"); } - catch (IOException ioe) - { + catch (final IOException ioe) { ioe.printStackTrace(); } } diff --git a/src/main/java/plugins/tprovoost/scripteditor/completion/IcyCompletionProviderPython.java b/src/main/java/plugins/tprovoost/scripteditor/completion/IcyCompletionProviderPython.java index b0a520b6ed15ce9b4b0a1e5a79f6ae21bb706c33..2fdcec9140522dcac375200f7b14e706b1dccf55 100644 --- a/src/main/java/plugins/tprovoost/scripteditor/completion/IcyCompletionProviderPython.java +++ b/src/main/java/plugins/tprovoost/scripteditor/completion/IcyCompletionProviderPython.java @@ -1,10 +1,10 @@ package plugins.tprovoost.scripteditor.completion; +import icy.system.IcyExceptionHandler; import icy.util.ClassUtil; import java.io.BufferedReader; import java.io.File; -import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.lang.reflect.Constructor; @@ -30,288 +30,255 @@ import plugins.tprovoost.scripteditor.scriptinghandlers.ScriptingHandler; import plugins.tprovoost.scripteditor.scriptinghandlers.VariableType; import plugins.tprovoost.scripteditor.scriptinghandlers.py.PythonScriptingHandler; -public class IcyCompletionProviderPython extends IcyCompletionProvider -{ +public class IcyCompletionProviderPython extends IcyCompletionProvider { - @Override - protected List<Completion> getCompletionsImpl(JTextComponent comp) - { - // return completions; - List<Completion> retVal = new ArrayList<Completion>(); - String text = getAlreadyEnteredTextWithFunc(comp); - int lastIdx = text.lastIndexOf('.'); + @Override + protected List<Completion> getCompletionsImpl(final JTextComponent comp) { + // return completions; + final List<Completion> retVal = new ArrayList<>(); + String text = getAlreadyEnteredTextWithFunc(comp); + int lastIdx = text.lastIndexOf('.'); - ScriptEngineHandler engineHandler = ScriptEngineHandler.getLastEngineHandler(); - HashMap<String, VariableType> engineVariables = ScriptEngineHandler.getLastEngineHandler().getEngineVariables(); + final ScriptEngineHandler engineHandler = ScriptEngineHandler.getLastEngineHandler(); + final HashMap<String, VariableType> engineVariables = ScriptEngineHandler.getLastEngineHandler().getEngineVariables(); - // Cannot work directly because returns null on the provider. - HashMap<Class<?>, ArrayList<ScriptFunctionCompletion>> engineTypesMethod = engineHandler.getEngineTypesMethod(); - HashMap<Integer, IcyFunctionBlock> localFunctions; - if (handler != null) - localFunctions = handler.getBlockFunctions(); - else - localFunctions = new HashMap<Integer, IcyFunctionBlock>(); + // Cannot work directly because returns null on the provider. + final HashMap<Class<?>, ArrayList<ScriptFunctionCompletion>> engineTypesMethod = engineHandler.getEngineTypesMethod(); + final HashMap<Integer, IcyFunctionBlock> localFunctions; + if (handler != null) + localFunctions = handler.getBlockFunctions(); + else + localFunctions = new HashMap<>(); - if (text != null) - { - // test if inside parenthesis - if (text.contains("(")) - { - String text2 = String.copyValueOf(text.toCharArray()); - int idx; - int i = 0; - int pOpen = 0; - int pClose = 0; - while (i < text2.length() - 1 && (idx = text2.indexOf('(', i)) != -1) - { - ++pOpen; - i += idx + 1; - } - i = 0; - while (i < text2.length() - 1 && (idx = text2.indexOf(')', i)) != -1) - { - ++pClose; - i += idx + 1; - } - int ppCount = pOpen - pClose; - if (ppCount > 0) - { - text = text2.substring(text2.lastIndexOf('(') + 1); - lastIdx = text.lastIndexOf('.'); - } - } - boolean containsNew = text.contains("new "); - if (containsNew) - { - text = text.substring("new ".length()); - // add the classes - if (text.length() > 0 && Character.isUpperCase(text.charAt(0))) - { - ArrayList<String> classes = ScriptEngineHandler.getAllClasses(); - for (String s : classes) - { - String nameFinal = ClassUtil.getSimpleClassName(s); - int idxD = nameFinal.indexOf('$'); - if (idxD != -1) - { - nameFinal = nameFinal.substring(idxD + 1, nameFinal.length()); - } - if (nameFinal.toLowerCase().startsWith(text.toLowerCase())) - { - try - { - Class<?> clazz = ClassUtil.findClass(s); - if (Modifier.isStatic(clazz.getModifiers())) - continue; - for (Constructor<?> c : clazz.getConstructors()) - { - int mod = c.getModifiers(); - if (Modifier.isPublic(mod)) - { - NewInstanceCompletion fc = new NewInstanceCompletion(this, nameFinal, c); - fc.setRelevance(ScriptingHandler.RELEVANCE_HIGH); + if (text != null) { + // test if inside parenthesis + if (text.contains("(")) { + final String text2 = String.copyValueOf(text.toCharArray()); + int idx; + int i = 0; + int pOpen = 0; + int pClose = 0; + while (i < text2.length() - 1 && (idx = text2.indexOf('(', i)) != -1) { + ++pOpen; + i += idx + 1; + } + i = 0; + while (i < text2.length() - 1 && (idx = text2.indexOf(')', i)) != -1) { + ++pClose; + i += idx + 1; + } + final int ppCount = pOpen - pClose; + if (ppCount > 0) { + text = text2.substring(text2.lastIndexOf('(') + 1); + lastIdx = text.lastIndexOf('.'); + } + } + final boolean containsNew = text.contains("new "); + if (containsNew) { + text = text.substring("new ".length()); + // add the classes + if (text.length() > 0 && Character.isUpperCase(text.charAt(0))) { + final ArrayList<String> classes = ScriptEngineHandler.getAllClasses(); + for (final String s : classes) { + String nameFinal = ClassUtil.getSimpleClassName(s); + final int idxD = nameFinal.indexOf('$'); + if (idxD != -1) { + nameFinal = nameFinal.substring(idxD + 1); + } + if (nameFinal.toLowerCase().startsWith(text.toLowerCase())) { + try { + final Class<?> clazz = ClassUtil.findClass(s); + if (Modifier.isStatic(clazz.getModifiers())) + continue; + for (final Constructor<?> c : clazz.getConstructors()) { + final int mod = c.getModifiers(); + if (Modifier.isPublic(mod)) { + final NewInstanceCompletion fc = new NewInstanceCompletion(this, nameFinal, c); + fc.setRelevance(ScriptingHandler.RELEVANCE_HIGH); - // TODO relevance assignment = type / - // expression = void - fc.setDefinedIn(clazz.toString().replace('$', '.')); - ArrayList<Parameter> params = new ArrayList<Parameter>(); - int i = 0; - for (Class<?> clazzParam : c.getParameterTypes()) - { - params.add(new Parameter(getType(clazzParam, true), "arg" + i)); - ++i; - } - fc.setParams(params); - retVal.add(fc); - } - } - } catch (ClassNotFoundException e) - { - } - } - } - } - } else if (text.isEmpty() || lastIdx == -1) - { - doClassicCompletion(text, retVal); - } else - { - // ----------------- - // Generate classes - // ----------------- - if (text.startsWith("Packages.")) - { - String clazzWanted = text.substring("Packages.".length()); - ArrayList<String> classes = ScriptEngineHandler.getAllClasses(); - for (String s : classes) - { - s = s.replace('$', '.'); - if (s.toLowerCase().startsWith(clazzWanted.toLowerCase())) - { - int startOffset = clazzWanted.lastIndexOf('.'); - int endOffset; - BasicCompletion c; - if (startOffset != -1) - { - endOffset = s.indexOf('.', startOffset + 1); - if (endOffset != -1) - c = new BasicCompletion(this, s.substring(startOffset + 1, endOffset)); - else - c = new BasicCompletion(this, s.substring(startOffset + 1, s.length())); - } else - { - endOffset = s.indexOf('.', 0); - if (endOffset != -1) - c = new BasicCompletion(this, s.substring(0, endOffset)); - else - c = new BasicCompletion(this, s); - } - c.setRelevance(ScriptingHandler.RELEVANCE_MIN); - if (!exists(c, retVal)) - retVal.add(c); - } - } - } - if (handler != null) - { - String command; - if (lastIdx != -1) - { - command = text.substring(0, lastIdx); - if (lastIdx <= text.length() - 1) // dot is before the - // last - text = text.substring(lastIdx + 1, text.length()); - } else - command = text; - ArrayList<ScriptFunctionCompletion> methods = null; + // TODO relevance assignment = type / + // expression = void + fc.setDefinedIn(clazz.toString().replace('$', '.')); + final ArrayList<Parameter> params = new ArrayList<>(); + int i = 0; + for (final Class<?> clazzParam : c.getParameterTypes()) { + params.add(new Parameter(getType(clazzParam, true), "arg" + i)); + ++i; + } + fc.setParams(params); + retVal.add(fc); + } + } + } + catch (final ClassNotFoundException e) { + IcyExceptionHandler.showErrorMessage(e, true); + } + } + } + } + } + else if (text.isEmpty() || lastIdx == -1) { + doClassicCompletion(text, retVal); + } + else { + // ----------------- + // Generate classes + // ----------------- + if (text.startsWith("Packages.")) { + final String clazzWanted = text.substring("Packages.".length()); + final ArrayList<String> classes = ScriptEngineHandler.getAllClasses(); + for (String s : classes) { + s = s.replace('$', '.'); + if (s.toLowerCase().startsWith(clazzWanted.toLowerCase())) { + final int startOffset = clazzWanted.lastIndexOf('.'); + final int endOffset; + final BasicCompletion c; + if (startOffset != -1) { + endOffset = s.indexOf('.', startOffset + 1); + if (endOffset != -1) + c = new BasicCompletion(this, s.substring(startOffset + 1, endOffset)); + else + c = new BasicCompletion(this, s.substring(startOffset + 1)); + } + else { + endOffset = s.indexOf('.'); + if (endOffset != -1) + c = new BasicCompletion(this, s.substring(0, endOffset)); + else + c = new BasicCompletion(this, s); + } + c.setRelevance(ScriptingHandler.RELEVANCE_MIN); + if (!exists(c, retVal)) + retVal.add(c); + } + } + } + if (handler != null) { + final String command; + if (lastIdx != -1) { + command = text.substring(0, lastIdx); + if (lastIdx <= text.length() - 1) // dot is before the + // last + text = text.substring(lastIdx + 1); + } + else + command = text; + ArrayList<ScriptFunctionCompletion> methods; - // is the command a classname ? - Class<?> clazz = handler.resolveClassDeclaration(command.replace('.', '$')); - if (clazz != null) - { - // ---------------------------- - // STATIC ACCESS - // ---------------------------- - if (containsNew) - { - populateWithConstructors(clazz, retVal); - } else if ((methods = engineTypesMethod.get(clazz)) != null && !advanced) - { - for (ScriptFunctionCompletion complete : methods) - { - if (complete.isStatic() && (text.isEmpty() || complete.getName().toLowerCase().startsWith(text.toLowerCase()))) - retVal.add(generateSFCCopy(complete, true)); - } - } else - { - populateClassTypes(new VariableType(clazz), text, retVal, true); - } - } + // is the command a classname ? + Class<?> clazz = handler.resolveClassDeclaration(command.replace('.', '$')); + if (clazz != null) { + // ---------------------------- + // STATIC ACCESS + // ---------------------------- + if (containsNew) { + populateWithConstructors(clazz, retVal); + } + else if ((methods = engineTypesMethod.get(clazz)) != null && !advanced) { + for (final ScriptFunctionCompletion complete : methods) { + if (complete.isStatic() && (text.isEmpty() || complete.getName().toLowerCase().startsWith(text.toLowerCase()))) + retVal.add(generateSFCCopy(complete, true)); + } + } + else { + populateClassTypes(new VariableType(clazz), text, retVal, true); + } + } - // check in the local variables if it is a variable - // if it is : propose depending on the variable type - VariableType type = handler.getVariableDeclaration(command); - if ((type != null && type.getClazz() != null) || ((type = engineVariables.get(command)) != null && type.getClazz() != null)) - { - // ---------------------------- - // VARIABLE ACCESS - // ---------------------------- - methods = engineTypesMethod.get(clazz); - if (methods != null && !advanced) - { - for (ScriptFunctionCompletion complete : methods) - { - if (!complete.getName().toLowerCase().startsWith(text.toLowerCase())) - continue; - if (complete.isStatic()) - complete.setRelevance(ScriptingHandler.RELEVANCE_LOW); - else if (!complete.isStatic()) - complete.setRelevance(ScriptingHandler.RELEVANCE_HIGH); - if (text.isEmpty() || complete.getName().toLowerCase().startsWith(text.toLowerCase())) - retVal.add(generateSFCCopy(complete)); - } - } else - { - populateClassTypes(type, text, retVal); - } - } - File f = ((PythonScriptingHandler) handler).getModules().get(command); - if (f != null) - { - // TODO - try - { - BufferedReader br = new BufferedReader(new FileReader(f)); - String textModule = ""; - String line; - while ((line = br.readLine()) != null) - textModule += line + "\n"; + // check in the local variables if it is a variable + // if it is : propose depending on the variable type + VariableType type = handler.getVariableDeclaration(command); + if ((type != null && type.getClazz() != null) || ((type = engineVariables.get(command)) != null && type.getClazz() != null)) { + // ---------------------------- + // VARIABLE ACCESS + // ---------------------------- + methods = engineTypesMethod.get(clazz); + if (methods != null && !advanced) { + for (final ScriptFunctionCompletion complete : methods) { + if (!complete.getName().toLowerCase().startsWith(text.toLowerCase())) + continue; + if (complete.isStatic()) + complete.setRelevance(ScriptingHandler.RELEVANCE_LOW); + else if (!complete.isStatic()) + complete.setRelevance(ScriptingHandler.RELEVANCE_HIGH); + if (text.isEmpty() || complete.getName().toLowerCase().startsWith(text.toLowerCase())) + retVal.add(generateSFCCopy(complete)); + } + } + else { + populateClassTypes(type, text, retVal); + } + } + final File f = ((PythonScriptingHandler) handler).getModules().get(command); + if (f != null) { + // TODO + try { + final BufferedReader br = new BufferedReader(new FileReader(f)); + final StringBuilder textModule = new StringBuilder(); + String line; + while ((line = br.readLine()) != null) + textModule.append(line).append("\n"); - RSyntaxTextArea textArea = new RSyntaxTextArea(); - textArea.setText(textModule); + final RSyntaxTextArea textArea = new RSyntaxTextArea(); + textArea.setText(textModule.toString()); - PythonScriptingHandler handlerModule = new PythonScriptingHandler(null, textArea, null, false); - handlerModule.setVarInterpretation(true); - handlerModule.setStrict(false); - handlerModule.interpret(false); - HashMap<String, VariableType> localFuncts = handlerModule.getLocalFunctions(); + final PythonScriptingHandler handlerModule = new PythonScriptingHandler(null, textArea, null, false); + handlerModule.setVarInterpretation(true); + handlerModule.setStrict(false); + handlerModule.interpret(false); + final HashMap<String, VariableType> localFuncts = handlerModule.getLocalFunctions(); - for (String s : localFuncts.keySet()) - { - type = localFuncts.get(s); - FunctionCompletion fc = new FunctionCompletion(this, s, type == null ? "" : type.toString()); - fc.setDefinedIn(command); - retVal.add(fc); - } - br.close(); - } catch (FileNotFoundException e) - { - } catch (IOException e) - { - } + for (final String s : localFuncts.keySet()) { + type = localFuncts.get(s); + final FunctionCompletion fc = new FunctionCompletion(this, s, type == null ? "" : type.toString()); + fc.setDefinedIn(command); + retVal.add(fc); + } + br.close(); + } + catch (final IOException e) { + IcyExceptionHandler.showErrorMessage(e, true); + } - } else - { - // ---------------------------- - // FUNCTION ACCESS - // ---------------------------- - // if not : look the type of the function (if declared). - int startOffset = getStartOffset(comp) - 1; - // System.out.println("offset:" + startOffset); - // for (Integer i : localFunctions.keySet()) - // System.out.println(i); - IcyFunctionBlock fb = localFunctions.get(startOffset); - if (fb != null) - { - clazz = fb.getReturnType().getClazz(); - methods = engineTypesMethod.get(clazz); - if (methods != null && !advanced) - { - for (ScriptFunctionCompletion complete : methods) - { - if (complete.isStatic()) - complete.setRelevance(ScriptingHandler.RELEVANCE_LOW); - else if (!complete.isStatic()) - complete.setRelevance(ScriptingHandler.RELEVANCE_HIGH); - if (text.isEmpty() || complete.getName().toLowerCase().startsWith(text.toLowerCase())) - retVal.add(generateSFCCopy(complete)); - } - } else - { - Type t = null; - if (fb.getMethod() != null) - t = fb.getMethod().getGenericReturnType(); - populateClassTypes(fb.getReturnType(), t, text, retVal, false); - } - } else - { - // Import feature. - // doClassicCompletion(command, retVal, true); - } - } - } - } - } - return retVal; - } + } + else { + // ---------------------------- + // FUNCTION ACCESS + // ---------------------------- + // if not : look the type of the function (if declared). + final int startOffset = getStartOffset(comp) - 1; + // System.out.println("offset:" + startOffset); + // for (Integer i : localFunctions.keySet()) + // System.out.println(i); + final IcyFunctionBlock fb = localFunctions.get(startOffset); + if (fb != null) { + clazz = fb.getReturnType().getClazz(); + methods = engineTypesMethod.get(clazz); + if (methods != null && !advanced) { + for (final ScriptFunctionCompletion complete : methods) { + if (complete.isStatic()) + complete.setRelevance(ScriptingHandler.RELEVANCE_LOW); + else if (!complete.isStatic()) + complete.setRelevance(ScriptingHandler.RELEVANCE_HIGH); + if (text.isEmpty() || complete.getName().toLowerCase().startsWith(text.toLowerCase())) + retVal.add(generateSFCCopy(complete)); + } + } + else { + Type t = null; + if (fb.getMethod() != null) + t = fb.getMethod().getGenericReturnType(); + populateClassTypes(fb.getReturnType(), t, text, retVal, false); + } + } + else { + // Import feature. + // doClassicCompletion(command, retVal, true); + } + } + } + } + } + return retVal; + } } diff --git a/src/main/java/plugins/tprovoost/scripteditor/completion/JSAutoCompletion.java b/src/main/java/plugins/tprovoost/scripteditor/completion/JSAutoCompletion.java index 9503193c013e0a784e531d110330ef929596d7f8..ea5010d428600fe4355f254f81ef9eb15e86dccd 100644 --- a/src/main/java/plugins/tprovoost/scripteditor/completion/JSAutoCompletion.java +++ b/src/main/java/plugins/tprovoost/scripteditor/completion/JSAutoCompletion.java @@ -12,59 +12,53 @@ import plugins.tprovoost.scripteditor.completion.types.BasicJavaClassCompletion; import plugins.tprovoost.scripteditor.completion.types.NewInstanceCompletion; import plugins.tprovoost.scripteditor.completion.types.ScriptFunctionCompletion; -public class JSAutoCompletion extends IcyAutoCompletion -{ +public class JSAutoCompletion extends IcyAutoCompletion { - public JSAutoCompletion(CompletionProvider provider) - { + public JSAutoCompletion(final CompletionProvider provider) { super(provider); } @Override - protected void insertCompletion(Completion c, boolean typedParamListStartChar) - { - - if (c instanceof ScriptFunctionCompletion) - { - // get position before insertion - // JTextComponent tc = getTextComponent(); - // ScriptFunctionCompletion sfc = ((ScriptFunctionCompletion) c); - // - // // get method added - // Method m = sfc.getMethod(); - // if (m != null) - // { - // String neededClass = m.getDeclaringClass().getName(); - - // test eventual needed importClasses - // if (sfc.isStatic() && !classAlreadyImported(neededClass)) - // { - // int caretPos = tc.getCaretPosition(); - // - // // import the needed class + movement - // caretPos += addImport(tc, neededClass, true).length(); - // - // // put the caret in the right position - // tc.getCaret().setDot(caretPos); - // } - // } - } - else if (c instanceof BasicJavaClassCompletion) - { + protected void insertCompletion(final Completion c, final boolean typedParamListStartChar) { + + //if (c instanceof ScriptFunctionCompletion) { + // get position before insertion + // JTextComponent tc = getTextComponent(); + // ScriptFunctionCompletion sfc = ((ScriptFunctionCompletion) c); + // + // // get method added + // Method m = sfc.getMethod(); + // if (m != null) + // { + // String neededClass = m.getDeclaringClass().getName(); + + // test eventual needed importClasses + // if (sfc.isStatic() && !classAlreadyImported(neededClass)) + // { + // int caretPos = tc.getCaretPosition(); + // + // // import the needed class + movement + // caretPos += addImport(tc, neededClass, true).length(); + // + // // put the caret in the right position + // tc.getCaret().setDot(caretPos); + // } + // } + //} + //else if (c instanceof BasicJavaClassCompletion) { + if (c instanceof BasicJavaClassCompletion) { // get the current text - JTextComponent tc = getTextComponent(); + final JTextComponent tc = getTextComponent(); // get the caret position int caretPos = tc.getCaretPosition(); - Class<?> clazz = ((BasicJavaClassCompletion) c).getJavaClass(); + final Class<?> clazz = ((BasicJavaClassCompletion) c).getJavaClass(); String neededClass = clazz.getName(); - if (clazz.isMemberClass()) - { + if (clazz.isMemberClass()) { neededClass = ClassUtil.getBaseClassName(neededClass); } - if (!classAlreadyImported(neededClass)) - { + if (!classAlreadyImported(neededClass)) { // import the needed class + movement caretPos += addImport(tc, neededClass, true).length(); @@ -72,20 +66,18 @@ public class JSAutoCompletion extends IcyAutoCompletion tc.getCaret().setDot(caretPos); } } - else if (c instanceof NewInstanceCompletion) - { + else if (c instanceof NewInstanceCompletion) { // get the current text - JTextComponent tc = getTextComponent(); + final JTextComponent tc = getTextComponent(); // get the caret position int caretPos = tc.getCaretPosition(); // class to import - Class<?> clazz = ((NewInstanceCompletion) c).getConstructor().getDeclaringClass(); - String neededClass = clazz.getName(); + final Class<?> clazz = ((NewInstanceCompletion) c).getConstructor().getDeclaringClass(); + final String neededClass = clazz.getName(); - if (!classAlreadyImported(neededClass)) - { + if (!classAlreadyImported(neededClass)) { // import the needed class + movement caretPos += addImport(tc, neededClass, true).length(); @@ -98,20 +90,16 @@ public class JSAutoCompletion extends IcyAutoCompletion } @Override - protected String getReplacementText(Completion c, Document doc, int start, int len) - { + protected String getReplacementText(final Completion c, final Document doc, final int start, final int len) { String toReturn = super.getReplacementText(c, doc, start, len); - if (c instanceof ScriptFunctionCompletion) - { - ScriptFunctionCompletion fc = (ScriptFunctionCompletion) c; + if (c instanceof ScriptFunctionCompletion) { + final ScriptFunctionCompletion fc = (ScriptFunctionCompletion) c; String textBefore = ""; - if (!fc.isStatic()) - { - CompletionProvider provider = getCompletionProvider(); - if (provider instanceof IcyCompletionProvider) - { + if (!fc.isStatic()) { + final CompletionProvider provider = getCompletionProvider(); + if (provider instanceof IcyCompletionProvider) { textBefore = provider.getAlreadyEnteredText(getTextComponent()); - int lastIdx = textBefore.lastIndexOf('.'); + final int lastIdx = textBefore.lastIndexOf('.'); if (lastIdx != -1) textBefore = textBefore.substring(0, lastIdx + 1); else @@ -120,67 +108,58 @@ public class JSAutoCompletion extends IcyAutoCompletion toReturn = textBefore + fc.getMethod().getName(); } } - else if (c instanceof BasicJavaClassCompletion) - { - Class<?> clazz = ((BasicJavaClassCompletion) c).getJavaClass(); + else if (c instanceof BasicJavaClassCompletion) { + final Class<?> clazz = ((BasicJavaClassCompletion) c).getJavaClass(); String textBefore = ""; - CompletionProvider provider = getCompletionProvider(); - if (provider instanceof IcyCompletionProvider) - { + final CompletionProvider provider = getCompletionProvider(); + if (provider instanceof IcyCompletionProvider) { textBefore = ((IcyCompletionProvider) provider).getAlreadyEnteredTextWithFunc(getTextComponent()); - int lastIdx = textBefore.lastIndexOf('.'); + final int lastIdx = textBefore.lastIndexOf('.'); if (lastIdx != -1) textBefore = textBefore.substring(0, lastIdx); else textBefore = ""; } - if (textBefore == "") - { + if (textBefore.equals("")) { toReturn = clazz.getName(); toReturn = ClassUtil.getSimpleClassName(toReturn).replace('$', '.'); } - else - { + else { toReturn = clazz.getSimpleName(); } } return toReturn; } - public String addImport(JTextComponent tc, String neededClass, boolean isClass) - { - String resultingImport; + @Override + public String addImport(final JTextComponent tc, final String neededClass, final boolean isClass) { + final String resultingImport; if (isClass) resultingImport = "importClass(Packages." + neededClass + ")\n"; else resultingImport = "importPackage(Packages." + ClassUtil.getPackageName(neededClass) + ")\n"; - if (!tc.getText().contains(resultingImport)) - { - // FIXME: add after the last import insteand of beginning of file. + if (!tc.getText().contains(resultingImport)) { + // FIXME: add after the last import instead of beginning of file. tc.setText(resultingImport + tc.getText()); } return resultingImport; } - public String addBaseClass(JTextComponent tc, String neededBaseClass) - { + public String addBaseClass(final JTextComponent tc, final String neededBaseClass) { return neededBaseClass; } @Override - public boolean classAlreadyImported(String neededClass) - { - String text = getTextComponent().getText(); + public boolean classAlreadyImported(final String neededClass) { + final String text = getTextComponent().getText(); // test if contains the class or if contains the importPackage enclosing // the class if (neededClass.startsWith("java.") || neededClass.startsWith("javax.")) - return text.contains("importClass(" + neededClass + ")") - || text.contains("importPackage(" + ClassUtil.getPackageName(neededClass) + ")"); - return text.contains("importClass(Packages." + neededClass + ")") - || text.contains("importPackage(Packages." + ClassUtil.getPackageName(neededClass) + ")"); + return text.contains("importClass(" + neededClass + ")") || text.contains("importPackage(" + ClassUtil.getPackageName(neededClass) + ")"); + return text.contains("importClass(Packages." + neededClass + ")") || text.contains("importPackage(Packages." + ClassUtil.getPackageName(neededClass) + ")"); } } diff --git a/src/main/java/plugins/tprovoost/scripteditor/completion/PythonAutoCompletion.java b/src/main/java/plugins/tprovoost/scripteditor/completion/PythonAutoCompletion.java index 00bb5b14a228fdbe17c08f407fe042b3c1f755da..b4b0ca408286c9459886b8fbe78e7058773b32d7 100644 --- a/src/main/java/plugins/tprovoost/scripteditor/completion/PythonAutoCompletion.java +++ b/src/main/java/plugins/tprovoost/scripteditor/completion/PythonAutoCompletion.java @@ -15,29 +15,23 @@ import plugins.tprovoost.scripteditor.completion.types.BasicJavaClassCompletion; import plugins.tprovoost.scripteditor.completion.types.NewInstanceCompletion; import plugins.tprovoost.scripteditor.completion.types.ScriptFunctionCompletion; -public class PythonAutoCompletion extends IcyAutoCompletion -{ +public class PythonAutoCompletion extends IcyAutoCompletion { - public PythonAutoCompletion(CompletionProvider provider) - { + public PythonAutoCompletion(final CompletionProvider provider) { super(provider); } @Override - protected String getReplacementText(Completion c, Document doc, int start, int len) - { + protected String getReplacementText(final Completion c, final Document doc, final int start, final int len) { String toReturn = super.getReplacementText(c, doc, start, len); - if (c instanceof ScriptFunctionCompletion) - { - ScriptFunctionCompletion fc = (ScriptFunctionCompletion) c; + if (c instanceof ScriptFunctionCompletion) { + final ScriptFunctionCompletion fc = (ScriptFunctionCompletion) c; String textBefore = ""; - if (!fc.isStatic()) - { - CompletionProvider provider = getCompletionProvider(); - if (provider instanceof IcyCompletionProvider) - { + if (!fc.isStatic()) { + final CompletionProvider provider = getCompletionProvider(); + if (provider instanceof IcyCompletionProvider) { textBefore = provider.getAlreadyEnteredText(getTextComponent()); - int lastIdx = textBefore.lastIndexOf('.'); + final int lastIdx = textBefore.lastIndexOf('.'); if (lastIdx != -1) textBefore = textBefore.substring(0, lastIdx + 1); else @@ -46,28 +40,24 @@ public class PythonAutoCompletion extends IcyAutoCompletion toReturn = textBefore + fc.getMethod().getName(); } } - else if (c instanceof BasicJavaClassCompletion) - { - Class<?> clazz = ((BasicJavaClassCompletion) c).getJavaClass(); + else if (c instanceof BasicJavaClassCompletion) { + final Class<?> clazz = ((BasicJavaClassCompletion) c).getJavaClass(); String textBefore = ""; - CompletionProvider provider = getCompletionProvider(); - if (provider instanceof IcyCompletionProvider) - { + final CompletionProvider provider = getCompletionProvider(); + if (provider instanceof IcyCompletionProvider) { textBefore = ((IcyCompletionProvider) provider).getAlreadyEnteredTextWithFunc(getTextComponent()); - int lastIdx = textBefore.lastIndexOf('.'); + final int lastIdx = textBefore.lastIndexOf('.'); if (lastIdx != -1) textBefore = textBefore.substring(0, lastIdx); else textBefore = ""; } - if (textBefore == "") - { + if (textBefore.equals("")) { toReturn = clazz.getName(); toReturn = ClassUtil.getSimpleClassName(toReturn).replace('$', '.'); } - else - { + else { toReturn = clazz.getSimpleName(); } } @@ -75,24 +65,20 @@ public class PythonAutoCompletion extends IcyAutoCompletion } @Override - protected void insertCompletion(Completion c, boolean typedParamListStartChar) - { - if (c instanceof BasicJavaClassCompletion) - { + protected void insertCompletion(final Completion c, final boolean typedParamListStartChar) { + if (c instanceof BasicJavaClassCompletion) { // get the current text - JTextComponent tc = getTextComponent(); + final JTextComponent tc = getTextComponent(); // get the caret position int caretPos = tc.getCaretPosition(); - Class<?> clazz = ((BasicJavaClassCompletion) c).getJavaClass(); + final Class<?> clazz = ((BasicJavaClassCompletion) c).getJavaClass(); String neededClass = clazz.getName(); - if (clazz.isMemberClass()) - { + if (clazz.isMemberClass()) { neededClass = ClassUtil.getBaseClassName(neededClass); } - if (!classAlreadyImported(neededClass)) - { + if (!classAlreadyImported(neededClass)) { // import the needed class + movement caretPos += addImport(tc, neededClass, true).length(); @@ -100,20 +86,18 @@ public class PythonAutoCompletion extends IcyAutoCompletion tc.getCaret().setDot(caretPos); } } - else if (c instanceof NewInstanceCompletion) - { + else if (c instanceof NewInstanceCompletion) { // get the current text - JTextComponent tc = getTextComponent(); + final JTextComponent tc = getTextComponent(); // get the caret position int caretPos = tc.getCaretPosition(); // class to import - Class<?> clazz = ((NewInstanceCompletion) c).getConstructor().getDeclaringClass(); - String neededClass = clazz.getName(); + final Class<?> clazz = ((NewInstanceCompletion) c).getConstructor().getDeclaringClass(); + final String neededClass = clazz.getName(); - if (!classAlreadyImported(neededClass)) - { + if (!classAlreadyImported(neededClass)) { // import the needed class + movement caretPos += addImport(tc, neededClass, true).length(); @@ -125,21 +109,19 @@ public class PythonAutoCompletion extends IcyAutoCompletion super.insertCompletion(c, typedParamListStartChar); } - public String addImport(JTextComponent tc, String neededClass, boolean isClass) - { + @Override + public String addImport(final JTextComponent tc, final String neededClass, final boolean isClass) { String resultingImport = ""; - String packageName = ClassUtil.getPackageName(neededClass); - if (!packageName.isEmpty()) - { + final String packageName = ClassUtil.getPackageName(neededClass); + if (!packageName.isEmpty()) { if (!isClass) return resultingImport; resultingImport += "from " + packageName + " "; } if (isClass) resultingImport += "import " + ClassUtil.getSimpleClassName(neededClass); - else - { - int lastIdxDot = packageName.lastIndexOf('.'); + else { + final int lastIdxDot = packageName.lastIndexOf('.'); if (lastIdxDot != -1) resultingImport += "as " + packageName.substring(lastIdxDot); else @@ -153,19 +135,18 @@ public class PythonAutoCompletion extends IcyAutoCompletion } @Override - public boolean classAlreadyImported(String neededClass) - { - String text = getTextComponent().getText(); + public boolean classAlreadyImported(final String neededClass) { + final String text = getTextComponent().getText(); // test if contains the class or if contains the importPackage enclosing // the class - Pattern p = Pattern.compile("from\\s" + ClassUtil.getPackageName(neededClass) + "\\simport\\s" + ClassUtil.getSimpleClassName(neededClass)); - Matcher m = p.matcher(text); + final Pattern p = Pattern.compile("from\\s" + ClassUtil.getPackageName(neededClass) + "\\simport\\s" + ClassUtil.getSimpleClassName(neededClass)); + final Matcher m = p.matcher(text); if (m.find()) { return true; } // Do more tests? - + // Not found by default. return false; } diff --git a/src/main/java/plugins/tprovoost/scripteditor/completion/types/BasicJavaClassCompletion.java b/src/main/java/plugins/tprovoost/scripteditor/completion/types/BasicJavaClassCompletion.java index 6aff6d91d4795c4b4df58f2e32ebf96fd278a6e9..0f0db40fd8d3d7c88887d7384f17f17523d1202b 100644 --- a/src/main/java/plugins/tprovoost/scripteditor/completion/types/BasicJavaClassCompletion.java +++ b/src/main/java/plugins/tprovoost/scripteditor/completion/types/BasicJavaClassCompletion.java @@ -18,75 +18,62 @@ import japa.parser.ast.body.JavadocComment; import plugins.tprovoost.scripteditor.javasource.ClassSource; import plugins.tprovoost.scripteditor.javasource.JarAccess; -public class BasicJavaClassCompletion extends VariableCompletion -{ - private static HashMap<Class<?>, String> cache = new HashMap<Class<?>, String>(); - private Class<?> clazz; - private boolean importOnly; +public class BasicJavaClassCompletion extends VariableCompletion { + private static final HashMap<Class<?>, String> cache = new HashMap<>(); + private final Class<?> clazz; + private final boolean importOnly; private boolean parsingDone = false; - public BasicJavaClassCompletion(CompletionProvider provider, Class<?> clazz) - { + public BasicJavaClassCompletion(final CompletionProvider provider, final Class<?> clazz) { this(provider, clazz, false); } - public BasicJavaClassCompletion(CompletionProvider provider, Class<?> clazz, boolean importOnly) - { + public BasicJavaClassCompletion(final CompletionProvider provider, final Class<?> clazz, final boolean importOnly) { super(provider, clazz.getSimpleName(), clazz.getSimpleName()); this.clazz = clazz; this.importOnly = importOnly; } - public Class<?> getJavaClass() - { + public Class<?> getJavaClass() { return clazz; } - public boolean isParsingDone() - { + public boolean isParsingDone() { return parsingDone; } - public boolean isAbstract() - { + public boolean isAbstract() { return Modifier.isAbstract(clazz.getModifiers()); } @Override - public String getSummary() - { + public String getSummary() { String summaryCache = cache.get(clazz); // return super.getSummary(); - if (!parsingDone) - { - if (summaryCache == null) - { + if (!parsingDone) { + if (summaryCache == null) { final ClassSource cs = ClassSource.getClassSource(clazz); - if (!cs.isClassOrInterfacesSet()) - { + if (!cs.isClassOrInterfacesSet()) { cs.populateClassesOrInterfaces(); } - ClassOrInterfaceDeclaration coi = cs.getClassOrInterfaces().get(clazz.getName()); - if (coi != null && coi.getJavaDoc() != null) - { - JavadocComment comment = coi.getJavaDoc(); - if (comment != null) - { + final ClassOrInterfaceDeclaration coi = cs.getClassOrInterfaces().get(clazz.getName()); + if (coi != null && coi.getJavaDoc() != null) { + final JavadocComment comment = coi.getJavaDoc(); + if (!comment.getContent().isEmpty()) { String content = comment.getContent(); content = ClassSource.docCommentToHtml("/**" + content + "*/"); summaryCache = content; } } else - { summaryCache = ""; - } + cache.put(clazz, summaryCache); } parsingDone = true; super.setSummary(summaryCache); } - StringBuilder sb = new StringBuilder(); + final StringBuilder sb = new StringBuilder(); addDefinitionString(sb); possiblyAddDescription(sb); possiblyAddDefinedIn(sb); @@ -95,48 +82,42 @@ public class BasicJavaClassCompletion extends VariableCompletion return sb.toString(); } - private void possiblyAddSource(StringBuilder sb) - { - InputStream is = JarAccess.getJavaSourceInputStream(clazz); + private void possiblyAddSource(final StringBuilder sb) { + final InputStream is = JarAccess.getJavaSourceInputStream(clazz); if (is != null) sb.append("<hr><a href=\"SourceCodeLink\">View Source</a>"); // TODO: Localize me } @Override - public String getShortDescription() - { + public String getShortDescription() { if (parsingDone && cache.get(clazz) != null) return cache.get(clazz); return super.getDefinitionString(); } @Override - public String getAlreadyEntered(JTextComponent comp) - { + public String getAlreadyEntered(final JTextComponent comp) { // return super.getAlreadyEntered(comp); - Document doc = comp.getDocument(); - Segment seg = new Segment(); + final Document doc = comp.getDocument(); + final Segment seg = new Segment(); - int dot = comp.getCaretPosition(); - Element root = doc.getDefaultRootElement(); - int index = root.getElementIndex(dot); - Element elem = root.getElement(index); + final int dot = comp.getCaretPosition(); + final Element root = doc.getDefaultRootElement(); + final int index = root.getElementIndex(dot); + final Element elem = root.getElement(index); int start = elem.getStartOffset(); int len = dot - start; - try - { + try { doc.getText(start, len, seg); } - catch (BadLocationException ble) - { + catch (final BadLocationException ble) { ble.printStackTrace(); return ""; } - int segEnd = seg.offset + len; + final int segEnd = seg.offset + len; start = segEnd - 1; - while (start >= seg.offset && isValidChar(seg.array[start])) - { + while (start >= seg.offset && isValidChar(seg.array[start])) { start--; } start++; @@ -145,13 +126,11 @@ public class BasicJavaClassCompletion extends VariableCompletion return len == 0 ? "" : new String(seg.array, start, len); } - private boolean isValidChar(char ch) - { + private boolean isValidChar(final char ch) { return Character.isLetterOrDigit(ch) || ch == '_' || ch == '\"'; } - public boolean importOnly() - { + public boolean importOnly() { return importOnly; } diff --git a/src/main/java/plugins/tprovoost/scripteditor/completion/types/JavaFunctionCompletion.java b/src/main/java/plugins/tprovoost/scripteditor/completion/types/JavaFunctionCompletion.java index ec46d422f9c18875ac76a1fb1b74d643880785a2..7caffafe10b118066032e6fcd202cc9f0ca00454 100644 --- a/src/main/java/plugins/tprovoost/scripteditor/completion/types/JavaFunctionCompletion.java +++ b/src/main/java/plugins/tprovoost/scripteditor/completion/types/JavaFunctionCompletion.java @@ -5,25 +5,21 @@ import java.util.HashMap; import org.fife.ui.autocomplete.CompletionProvider; import org.fife.ui.autocomplete.FunctionCompletion; -public class JavaFunctionCompletion extends FunctionCompletion -{ - protected static HashMap<String, String> cacheSummary = new HashMap<String, String>(); +public class JavaFunctionCompletion extends FunctionCompletion { + protected static HashMap<String, String> cacheSummary = new HashMap<>(); protected String summary; protected boolean isParseDone; - public JavaFunctionCompletion(CompletionProvider provider, String name, String returnType) - { + public JavaFunctionCompletion(final CompletionProvider provider, final String name, final String returnType) { super(provider, name, returnType); } - public boolean isPopulateDone() - { + public boolean isPopulateDone() { return isParseDone; } @Override - public String getShortDescription() - { + public String getShortDescription() { if (summary != null) return summary; return super.getShortDescription(); diff --git a/src/main/java/plugins/tprovoost/scripteditor/completion/types/NewInstanceCompletion.java b/src/main/java/plugins/tprovoost/scripteditor/completion/types/NewInstanceCompletion.java index 7459f45a19e8dcb71ac3d9f36e4332ff8b126a44..e9a17c459bb9e038583be5b9d5488b4e6fca0f13 100644 --- a/src/main/java/plugins/tprovoost/scripteditor/completion/types/NewInstanceCompletion.java +++ b/src/main/java/plugins/tprovoost/scripteditor/completion/types/NewInstanceCompletion.java @@ -17,6 +17,7 @@ import javax.swing.text.Element; import javax.swing.text.JTextComponent; import javax.swing.text.Segment; +import icy.system.IcyExceptionHandler; import org.fife.ui.autocomplete.CompletionProvider; import japa.parser.ast.body.ConstructorDeclaration; @@ -24,24 +25,20 @@ import japa.parser.ast.body.JavadocComment; import plugins.tprovoost.scripteditor.javasource.ClassSource; import plugins.tprovoost.scripteditor.javasource.JarAccess; -public class NewInstanceCompletion extends JavaFunctionCompletion -{ - private static HashMap<String, ConstructorDeclaration> cacheConsDecl = new HashMap<String, ConstructorDeclaration>(); - private static HashMap<String, List<Parameter>> cacheParams = new HashMap<String, List<Parameter>>(); +public class NewInstanceCompletion extends JavaFunctionCompletion { + private static final HashMap<String, ConstructorDeclaration> cacheConsDecl = new HashMap<>(); + private static final HashMap<String, List<Parameter>> cacheParams = new HashMap<>(); - private Constructor<?> constructor; - private boolean isStatic; + private final Constructor<?> constructor; private boolean isParseDone = false; @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.METHOD) - public @interface BindingFunction - { + public @interface BindingFunction { String value(); } - public NewInstanceCompletion(CompletionProvider provider, String name, Constructor<?> constructor) - { + public NewInstanceCompletion(final CompletionProvider provider, final String name, final Constructor<?> constructor) { super(provider, name, constructor.getDeclaringClass().getName()); this.constructor = constructor; } @@ -49,31 +46,26 @@ public class NewInstanceCompletion extends JavaFunctionCompletion /** * @return the correct function call in java. */ - public String getMethodCall() - { - ConstructorDeclaration constDecl = cacheConsDecl.get(constructor.toGenericString()); - String parametersAsString = ""; - if (constDecl != null) - { - List<japa.parser.ast.body.Parameter> params = constDecl.getParameters(); - for (int i = 0; i < params.size(); ++i) - { - japa.parser.ast.body.Parameter p = params.get(i); + public String getMethodCall() { + final ConstructorDeclaration constDecl = cacheConsDecl.get(constructor.toGenericString()); + final StringBuilder parametersAsString = new StringBuilder(); + if (constDecl != null) { + final List<japa.parser.ast.body.Parameter> params = constDecl.getParameters(); + for (int i = 0; i < params.size(); ++i) { + final japa.parser.ast.body.Parameter p = params.get(i); if (i != 0) - parametersAsString += " ," + p.getType() + " " + p.getId().getName(); + parametersAsString.append(" ,").append(p.getType()).append(" ").append(p.getId().getName()); else - parametersAsString += p.getType() + " " + p.getId().getName(); + parametersAsString.append(p.getType()).append(" ").append(p.getId().getName()); } } - else - { - Class<?>[] paramTypes = constructor.getParameterTypes(); - for (int i = 0; i < paramTypes.length; ++i) - { + else { + final Class<?>[] paramTypes = constructor.getParameterTypes(); + for (int i = 0; i < paramTypes.length; ++i) { if (i != 0) - parametersAsString += " ,arg" + i; + parametersAsString.append(" ,arg").append(i); else - parametersAsString += "arg" + i; + parametersAsString.append("arg").append(i); } } return "Packages." + constructor.getDeclaringClass().getName() + "." + constructor.getName() + "(" @@ -83,8 +75,7 @@ public class NewInstanceCompletion extends JavaFunctionCompletion /** * @return if the function should be accessed in a static way. */ - public boolean isStatic() - { + public boolean isStatic() { if (constructor != null) return Modifier.isStatic(constructor.getModifiers()); return false; @@ -93,9 +84,8 @@ public class NewInstanceCompletion extends JavaFunctionCompletion /** * @return the origin class */ - public Class<?> getOriginatingClass() - { - if (isStatic) + public Class<?> getOriginatingClass() { + if (isStatic()) return null; return constructor.getDeclaringClass(); } @@ -103,46 +93,40 @@ public class NewInstanceCompletion extends JavaFunctionCompletion /** * @return the constructor */ - public Constructor<?> getConstructor() - { + public Constructor<?> getConstructor() { return constructor; } @Override - public boolean equals(Object arg0) - { + public boolean equals(final Object arg0) { if (!(arg0 instanceof NewInstanceCompletion)) return false; return ((NewInstanceCompletion) arg0).getName().contentEquals(getName()); } @Override - public String getAlreadyEntered(JTextComponent comp) - { + public String getAlreadyEntered(final JTextComponent comp) { // return super.getAlreadyEntered(comp); - Document doc = comp.getDocument(); - Segment seg = new Segment(); + final Document doc = comp.getDocument(); + final Segment seg = new Segment(); - int dot = comp.getCaretPosition(); - Element root = doc.getDefaultRootElement(); - int index = root.getElementIndex(dot); - Element elem = root.getElement(index); + final int dot = comp.getCaretPosition(); + final Element root = doc.getDefaultRootElement(); + final int index = root.getElementIndex(dot); + final Element elem = root.getElement(index); int start = elem.getStartOffset(); int len = dot - start; - try - { + try { doc.getText(start, len, seg); } - catch (BadLocationException ble) - { + catch (final BadLocationException ble) { ble.printStackTrace(); return ""; } - int segEnd = seg.offset + len; + final int segEnd = seg.offset + len; start = segEnd - 1; - while (start >= seg.offset && isValidChar(seg.array[start])) - { + while (start >= seg.offset && isValidChar(seg.array[start])) { start--; } start++; @@ -151,39 +135,32 @@ public class NewInstanceCompletion extends JavaFunctionCompletion return len == 0 ? "" : new String(seg.array, start, len); } - private boolean isValidChar(char ch) - { + private boolean isValidChar(final char ch) { return Character.isLetterOrDigit(ch) || ch == '_' || ch == '\"'; } @Override - public Parameter getParam(int index) - { - List<Parameter> params = cacheParams.get(constructor.toGenericString()); - if (params != null) - { + public Parameter getParam(final int index) { + final List<Parameter> params = cacheParams.get(constructor.toGenericString()); + if (params != null) { return params.get(index); } - if (!isParseDone) - { + if (!isParseDone) { populate(); } return super.getParam(index); } @Override - public String getSummary() - { + public String getSummary() { summary = cacheSummary.get(constructor.toGenericString()); - if (!isParseDone) - { + if (!isParseDone) { if (summary == null) populate(); } - StringBuilder sb = new StringBuilder(); + final StringBuilder sb = new StringBuilder(); addDefinitionString(sb); - if (!possiblyAddDescription(sb)) - { + if (!possiblyAddDescription(sb)) { sb.append("<br><br><br>"); } addParameters(sb); @@ -193,65 +170,52 @@ public class NewInstanceCompletion extends JavaFunctionCompletion return sb.toString(); } - private void populate() - { + private void populate() { ConstructorDeclaration dc = cacheConsDecl.get(constructor.toGenericString()); - if (dc == null) - { + if (dc == null) { Class<?> currentClass = constructor.getDeclaringClass(); - while (dc == null && currentClass != null) - { - try - { - Constructor<?> c = currentClass.getDeclaredConstructor(constructor.getParameterTypes()); + while (dc == null && currentClass != null) { + try { + final Constructor<?> c = currentClass.getDeclaredConstructor(constructor.getParameterTypes()); final ClassSource cs = ClassSource.getClassSource(currentClass); - if (!cs.isConstructorsSet()) - { + if (!cs.isConstructorsSet()) { cs.populateConstructors(); } dc = cs.getConstructors().get(c.toGenericString()); } - catch (SecurityException e) - { - } - catch (NoSuchMethodException e) - { + catch (final SecurityException | NoSuchMethodException e) { + IcyExceptionHandler.showErrorMessage(e, true); } currentClass = currentClass.getSuperclass(); } } - if (dc != null) - { - JavadocComment comment = dc.getJavaDoc(); - if (comment != null) - { + if (dc != null) { + final JavadocComment comment = dc.getJavaDoc(); + if (comment != null) { String content = comment.getContent(); content = ClassSource.docCommentToHtml("/**" + content + "*/"); summary = content; } - HashMap<String, String> paramsHash = ClassSource.getParameters(summary); + final HashMap<String, String> paramsHash = ClassSource.getParameters(summary); - if (paramsHash.size() > 0 && summary != null) - { - int idx = summary.indexOf(ClassSource.PARAM_PATTERN); - int idxEnd = summary.indexOf("</p>", idx); + if (paramsHash.size() > 0 && summary != null) { + final int idx = summary.indexOf(ClassSource.PARAM_PATTERN); + final int idxEnd = summary.indexOf("</p>", idx); summary = summary.substring(0, idx) + summary.substring(idxEnd + "</p>".length()); } // putting back the right parameters. - ArrayList<Parameter> params = new ArrayList<Parameter>(); - List<japa.parser.ast.body.Parameter> list = dc.getParameters(); - int size = getParamCount(); - if (list != null && list.size() == size) - { - for (int i = 0; i < getParamCount(); ++i) - { - japa.parser.ast.body.Parameter sourceParam = list.get(i); - String name = sourceParam.getId().getName(); - Parameter param = new Parameter(sourceParam.getType(), name); + final ArrayList<Parameter> params = new ArrayList<>(); + final List<japa.parser.ast.body.Parameter> list = dc.getParameters(); + final int size = getParamCount(); + if (list != null && list.size() == size) { + for (int i = 0; i < getParamCount(); ++i) { + final japa.parser.ast.body.Parameter sourceParam = list.get(i); + final String name = sourceParam.getId().getName(); + final Parameter param = new Parameter(sourceParam.getType(), name); params.add(param); - String desc = paramsHash.get(name); + final String desc = paramsHash.get(name); if (desc != null) param.setDescription(desc); } @@ -260,16 +224,14 @@ public class NewInstanceCompletion extends JavaFunctionCompletion } cacheSummary.put(constructor.toGenericString(), summary); } - else - { + else { summary = ""; } isParseDone = true; } - private void possiblyAddSource(StringBuilder sb) - { - InputStream is = JarAccess.getJavaSourceInputStream(constructor.getDeclaringClass()); + private void possiblyAddSource(final StringBuilder sb) { + final InputStream is = JarAccess.getJavaSourceInputStream(constructor.getDeclaringClass()); if (is != null) sb.append("<hr><a href=\"SourceCodeLink\">View Source</a>"); } diff --git a/src/main/java/plugins/tprovoost/scripteditor/completion/types/PythonModuleCompletion.java b/src/main/java/plugins/tprovoost/scripteditor/completion/types/PythonModuleCompletion.java index 87269eded65868c0cde05719fa20d5b3604f1442..d5c87cfab6ff7d863fa9e6da3cdb2155c973a0b0 100644 --- a/src/main/java/plugins/tprovoost/scripteditor/completion/types/PythonModuleCompletion.java +++ b/src/main/java/plugins/tprovoost/scripteditor/completion/types/PythonModuleCompletion.java @@ -3,12 +3,10 @@ package plugins.tprovoost.scripteditor.completion.types; import org.fife.ui.autocomplete.BasicCompletion; import org.fife.ui.autocomplete.CompletionProvider; -public class PythonModuleCompletion extends BasicCompletion -{ +public class PythonModuleCompletion extends BasicCompletion { - public PythonModuleCompletion(CompletionProvider provider, String replacementText) - { - super(provider, replacementText); - } + public PythonModuleCompletion(final CompletionProvider provider, final String replacementText) { + super(provider, replacementText); + } } diff --git a/src/main/java/plugins/tprovoost/scripteditor/completion/types/ScriptFunctionCompletion.java b/src/main/java/plugins/tprovoost/scripteditor/completion/types/ScriptFunctionCompletion.java index e531a662164716e4c98923a7dad9d2e5e46a3e20..806c62b276d4f5680434ab5fd075e7e7789fd25b 100644 --- a/src/main/java/plugins/tprovoost/scripteditor/completion/types/ScriptFunctionCompletion.java +++ b/src/main/java/plugins/tprovoost/scripteditor/completion/types/ScriptFunctionCompletion.java @@ -17,6 +17,7 @@ import javax.swing.text.Element; import javax.swing.text.JTextComponent; import javax.swing.text.Segment; +import icy.system.IcyExceptionHandler; import org.fife.ui.autocomplete.CompletionProvider; import japa.parser.ast.body.JavadocComment; @@ -25,30 +26,29 @@ import plugins.tprovoost.scripteditor.javasource.ClassSource; import plugins.tprovoost.scripteditor.javasource.JarAccess; import plugins.tprovoost.scripteditor.scriptinghandlers.VariableType; -public class ScriptFunctionCompletion extends JavaFunctionCompletion -{ - private static HashMap<String, MethodDeclaration> cacheMetDecl = new HashMap<String, MethodDeclaration>(); - private static HashMap<String, List<Parameter>> cacheParams = new HashMap<String, List<Parameter>>(); +public class ScriptFunctionCompletion extends JavaFunctionCompletion { + private static final HashMap<String, MethodDeclaration> cacheMetDecl = new HashMap<>(); + private static final HashMap<String, List<Parameter>> cacheParams = new HashMap<>(); - private Method method; - private boolean isStatic; + private final Method method; @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.METHOD) - public @interface BindingFunction - { + public @interface BindingFunction { String value(); } - public ScriptFunctionCompletion(CompletionProvider provider, String name, Method method) - { - super(provider, name, method.getReturnType().isArray() ? method.getReturnType().getCanonicalName() - : method.getReturnType().getName()); + public ScriptFunctionCompletion(final CompletionProvider provider, final String name, final Method method) { + super( + provider, + name, + (method.getReturnType().isArray()) ? + method.getReturnType().getCanonicalName() : method.getReturnType().getName() + ); this.method = method; } - public ScriptFunctionCompletion(CompletionProvider provider, String name, Method method, VariableType type) - { + public ScriptFunctionCompletion(final CompletionProvider provider, final String name, final Method method, final VariableType type) { super(provider, name, type.getType()); this.method = method; } @@ -56,42 +56,35 @@ public class ScriptFunctionCompletion extends JavaFunctionCompletion /** * @return the correct function call in java. */ - public String getMethodCall() - { - String parametersAsString = ""; - MethodDeclaration methodDecl = cacheMetDecl.get(method.toGenericString()); - if (methodDecl != null) - { - List<japa.parser.ast.body.Parameter> params = methodDecl.getParameters(); - for (int i = 0; i < params.size(); ++i) - { - japa.parser.ast.body.Parameter p = params.get(i); + public String getMethodCall() { + final StringBuilder parametersAsString = new StringBuilder(); + final MethodDeclaration methodDecl = cacheMetDecl.get(method.toGenericString()); + if (methodDecl != null) { + final List<japa.parser.ast.body.Parameter> params = methodDecl.getParameters(); + for (int i = 0; i < params.size(); ++i) { + final japa.parser.ast.body.Parameter p = params.get(i); if (i != 0) - parametersAsString += " ," + p.getType() + " " + p.getId().getName(); + parametersAsString.append(" ,").append(p.getType()).append(" ").append(p.getId().getName()); else - parametersAsString += p.getType() + " " + p.getId().getName(); + parametersAsString.append(p.getType()).append(" ").append(p.getId().getName()); } } - else - { - Class<?>[] paramTypes = method.getParameterTypes(); - for (int i = 0; i < paramTypes.length; ++i) - { + else { + final Class<?>[] paramTypes = method.getParameterTypes(); + for (int i = 0; i < paramTypes.length; ++i) { if (i != 0) - parametersAsString += " ,arg" + i; + parametersAsString.append(" ,arg").append(i); else - parametersAsString += "arg" + i; + parametersAsString.append("arg").append(i); } } - return "Packages." + method.getDeclaringClass().getName() + "." + method.getName() + "(" + parametersAsString - + ");"; + return "Packages." + method.getDeclaringClass().getName() + "." + method.getName() + "(" + parametersAsString + ");"; } /** * @return if the function should be accessed in a static way. */ - public boolean isStatic() - { + public boolean isStatic() { if (method != null) return Modifier.isStatic(method.getModifiers()); return false; @@ -100,53 +93,46 @@ public class ScriptFunctionCompletion extends JavaFunctionCompletion /** * @return the origin class */ - public Class<?> getOriginatingClass() - { - if (isStatic) + public Class<?> getOriginatingClass() { + if (isStatic()) return null; return method.getDeclaringClass(); } - public Method getMethod() - { + public Method getMethod() { return method; } @Override - public boolean equals(Object arg0) - { + public boolean equals(final Object arg0) { if (!(arg0 instanceof ScriptFunctionCompletion)) return false; return ((ScriptFunctionCompletion) arg0).getName().contentEquals(getName()); } @Override - public String getAlreadyEntered(JTextComponent comp) - { + public String getAlreadyEntered(final JTextComponent comp) { // return super.getAlreadyEntered(comp); - Document doc = comp.getDocument(); - Segment seg = new Segment(); + final Document doc = comp.getDocument(); + final Segment seg = new Segment(); - int dot = comp.getCaretPosition(); - Element root = doc.getDefaultRootElement(); - int index = root.getElementIndex(dot); - Element elem = root.getElement(index); + final int dot = comp.getCaretPosition(); + final Element root = doc.getDefaultRootElement(); + final int index = root.getElementIndex(dot); + final Element elem = root.getElement(index); int start = elem.getStartOffset(); int len = dot - start; - try - { + try { doc.getText(start, len, seg); } - catch (BadLocationException ble) - { + catch (final BadLocationException ble) { ble.printStackTrace(); return ""; } - int segEnd = seg.offset + len; + final int segEnd = seg.offset + len; start = segEnd - 1; - while (start >= seg.offset && isValidChar(seg.array[start])) - { + while (start >= seg.offset && isValidChar(seg.array[start])) { start--; } start++; @@ -155,148 +141,122 @@ public class ScriptFunctionCompletion extends JavaFunctionCompletion return len == 0 ? "" : new String(seg.array, start, len); } - private boolean isValidChar(char ch) - { + private boolean isValidChar(final char ch) { return Character.isLetterOrDigit(ch) || ch == '_' || ch == '\"'; } @Override - public Parameter getParam(int index) - { - List<Parameter> params = cacheParams.get(method.toGenericString()); - if (params != null) - { + public Parameter getParam(final int index) { + final List<Parameter> params = cacheParams.get(method.toGenericString()); + if (params != null) { return params.get(index); } - if (!isParseDone) - { + if (!isParseDone) { populate(); } return super.getParam(index); } @Override - public String getSummary() - { + public String getSummary() { summary = cacheSummary.get(method.toGenericString()); - if (!isParseDone) - { + if (!isParseDone) { if (summary == null) populate(); } - StringBuilder sb = new StringBuilder(); + final StringBuilder sb = new StringBuilder(); addDefinitionString(sb); - if (!possiblyAddDescription(sb)) - { + if (!possiblyAddDescription(sb)) { sb.append("<br><br><br>"); } addParameters(sb); possiblyAddDefinedIn(sb); possiblyAddSource(sb); sb.append("</html>"); - String sumResult = sb.toString(); - return sumResult; + return sb.toString(); } @Override - protected void addParameters(StringBuilder sb) - { - int paramCount = getParamCount(); - if (paramCount > 0) - { + protected void addParameters(final StringBuilder sb) { + final int paramCount = getParamCount(); + if (paramCount > 0) { sb.append("<b>Parameters:</b><br>"); sb.append("<center><table width='90%'><tr><td>"); - for (int i = 0; i < paramCount; i++) - { - Parameter param = getParam(i); + for (int i = 0; i < paramCount; i++) { + final Parameter param = getParam(i); sb.append("<b>"); sb.append(param.getName() != null ? param.getName() : param.getType()); sb.append(" : </b><br> "); - String desc = param.getDescription(); - if (desc != null) - { + final String desc = param.getDescription(); + if (desc != null) { sb.append(desc); } sb.append("<br>"); } sb.append("</td></tr></table></center><br><br>"); } - String returnValDesc = getReturnValueDescription(); - if (returnValDesc != null) - { + final String returnValDesc = getReturnValueDescription(); + if (returnValDesc != null) { sb.append("<b>Returns:</b><br><center><table width='90%'><tr><td>"); sb.append(returnValDesc); sb.append("</td></tr></table></center><br><br>"); } } - private void possiblyAddSource(StringBuilder sb) - { - InputStream is = JarAccess.getJavaSourceInputStream(method.getDeclaringClass()); + private void possiblyAddSource(final StringBuilder sb) { + final InputStream is = JarAccess.getJavaSourceInputStream(method.getDeclaringClass()); if (is != null) sb.append("<hr><a href=\"SourceCodeLink\">View Source</a>"); } - protected void populate() - { + protected void populate() { MethodDeclaration md = cacheMetDecl.get(method.toGenericString()); - if (md == null) - { + if (md == null) { Class<?> currentClass = method.getDeclaringClass(); - while (md == null && currentClass != null) - { - try - { - Method m = currentClass.getDeclaredMethod(this.method.getName(), this.method.getParameterTypes()); + while (md == null && currentClass != null) { + try { + final Method m = currentClass.getDeclaredMethod(this.method.getName(), this.method.getParameterTypes()); final ClassSource cs = ClassSource.getClassSource(currentClass); - if (!cs.isMethodsSet()) - { + if (!cs.isMethodsSet()) { cs.populateMethods(); } md = cs.getMethods().get(m.toGenericString()); } - catch (SecurityException e) - { - } - catch (NoSuchMethodException e) - { + catch (final SecurityException | NoSuchMethodException e) { + System.err.println("plugins.tprovoost.scripteditor.completion.types.ScriptFunctionCompletion.populate()"); + IcyExceptionHandler.showErrorMessage(e, false); } currentClass = currentClass.getSuperclass(); } } - if (md != null) - { - JavadocComment comment = md.getJavaDoc(); - if (comment != null) - { + if (md != null) { + final JavadocComment comment = md.getJavaDoc(); + if (comment != null) { String content = comment.getContent(); content = ClassSource.docCommentToHtml("/**" + content + "*/"); summary = content; } - HashMap<String, String> paramsHash = ClassSource.getParameters(summary); + final HashMap<String, String> paramsHash = ClassSource.getParameters(summary); // Removes parameters from Doc since they are going to be handled in this. - if (paramsHash.size() > 0 && summary != null) - { - int idx = summary.indexOf(ClassSource.PARAM_PATTERN); - int idxEnd = summary.indexOf("</p>", idx); + if (paramsHash.size() > 0 && summary != null) { + final int idx = summary.indexOf(ClassSource.PARAM_PATTERN); + final int idxEnd = summary.indexOf("</p>", idx); summary = summary.substring(0, idx) + summary.substring(idxEnd + "</p>".length()); } // putting back the right parameters. - ArrayList<Parameter> params = new ArrayList<Parameter>(); - List<japa.parser.ast.body.Parameter> list = md.getParameters(); - int size = getParamCount(); - if (list != null && list.size() == size) - { - for (int i = 0; i < getParamCount(); ++i) - { - japa.parser.ast.body.Parameter sourceParam = list.get(i); - String name = sourceParam.getId().getName(); - Parameter param = new Parameter(sourceParam.getType(), name); + final ArrayList<Parameter> params = new ArrayList<>(); + final List<japa.parser.ast.body.Parameter> list = md.getParameters(); + final int size = getParamCount(); + if (list != null && list.size() == size) { + for (int i = 0; i < getParamCount(); ++i) { + final japa.parser.ast.body.Parameter sourceParam = list.get(i); + final String name = sourceParam.getId().getName(); + final Parameter param = new Parameter(sourceParam.getType(), name); params.add(param); - String desc = paramsHash.get(name); + final String desc = paramsHash.get(name); if (desc != null) param.setDescription(desc); } @@ -305,8 +265,7 @@ public class ScriptFunctionCompletion extends JavaFunctionCompletion } cacheSummary.put(method.toGenericString(), summary); } - else - { + else { summary = ""; } isParseDone = true; diff --git a/src/main/java/plugins/tprovoost/scripteditor/gui/CommandPanel.java b/src/main/java/plugins/tprovoost/scripteditor/gui/CommandPanel.java index 2a6ad91430dfa357ef12743bba5cdae0b7ea1d99..66441cc8eccc7dd5663f1a39a74b4433f01d338c 100644 --- a/src/main/java/plugins/tprovoost/scripteditor/gui/CommandPanel.java +++ b/src/main/java/plugins/tprovoost/scripteditor/gui/CommandPanel.java @@ -6,9 +6,9 @@ import java.awt.event.ActionListener; import java.awt.event.ItemListener; import java.awt.image.BufferedImage; import java.util.ArrayList; +import java.util.Vector; import javax.script.ScriptEngineFactory; -import javax.script.ScriptEngineManager; import javax.swing.BorderFactory; import javax.swing.Box; import javax.swing.BoxLayout; @@ -29,68 +29,28 @@ import plugins.tprovoost.scripteditor.scriptinghandlers.ScriptEngineHandler; /** * This panel creates the tools needed to choose the language (for each * language) and run the code. - * + * * @author Thomas Provoost */ -class CommandPanel extends JPanel -{ - - /** */ - private static final long serialVersionUID = 1L; - - private static final BufferedImage imgPlayback2 = ImageUtil.load(PluginLoader - .getResourceAsStream("plugins/tprovoost/scripteditor/resources/icons/playback_erase_play_alpha.png")); +class CommandPanel extends JPanel { + private static final BufferedImage imgPlayback2 = ImageUtil.load(PluginLoader.getResourceAsStream("plugins/tprovoost/scripteditor/resources/icons/playback_erase_play_alpha.png")); private static final int STRUT_SIZE = 4; - private JComboBox comboLanguages; - - private JMenuItem btnRun; - private JMenuItem btnRunNew2; - private JSplitButton btnSplitRun; - private JButton btnStop; - - private ActionListener runInNewListener = new ActionListener() - { - - @Override - public void actionPerformed(ActionEvent e) - { - if (!lastIsNew) - { - lastIsNew = true; - btnSplitRun.setIcon(new IcyIcon("playback_play", 16)); - btnSplitRun - .setToolTipText("Creates a new context and run the script. The previous context will be lost."); - btnSplitRun.repaint(); - } - } - }; + private final JComboBox<String> comboLanguages; - private ActionListener runInSameListener = new ActionListener() - { + private final JMenuItem btnRun; + private final JMenuItem btnRunNew2; + private final JSplitButton btnSplitRun; + private final JButton btnStop; - @Override - public void actionPerformed(ActionEvent e) - { - if (lastIsNew) - { - lastIsNew = false; - btnSplitRun.setIcon(new IcyIcon(imgPlayback2, 16)); - btnSplitRun.setToolTipText("All variables in the bindings are re-usable."); - btnSplitRun.repaint(); - } - } - }; protected boolean lastIsNew = true; - public CommandPanel() - { + public CommandPanel() { this("JavaScript"); } - public CommandPanel(String language) - { + public CommandPanel(final String language) { // final JButton btnBuild = new JButton("Verify"); btnRun = new JMenuItem("Run in Current Context", new IcyIcon(imgPlayback2, 16)); btnRun.setToolTipText("All variables in the bindings are re-usable."); @@ -100,10 +60,9 @@ class CommandPanel extends JPanel btnSplitRun.setToolTipText("Creates a new context and run the script. The previous context will be lost."); btnRunNew2 = new JMenuItem("Run in New Context", new IcyIcon("playback_play", 16)); - btnRunNew2.setToolTipText( - "Creates a new context and run the script. The previous context and its bindings will be lost."); + btnRunNew2.setToolTipText("Creates a new context and run the script. The previous context and its bindings will be lost."); - JPopupMenu popupRun = new JPopupMenu(); + final JPopupMenu popupRun = new JPopupMenu(); popupRun.add(btnRunNew2); popupRun.add(btnRun); btnSplitRun.setPopupMenu(popupRun); @@ -115,35 +74,45 @@ class CommandPanel extends JPanel setLayout(new BoxLayout(this, BoxLayout.X_AXIS)); setBorder(BorderFactory.createEmptyBorder(2, 0, 2, 0)); - ArrayList<String> values = new ArrayList<String>(); - for (ScriptEngineFactory factory : ScriptEngineHandler.getEngineManager().getEngineFactories()) - { + final ArrayList<String> values = new ArrayList<>(); + for (final ScriptEngineFactory factory : ScriptEngineHandler.getEngineManager().getEngineFactories()) { values.add(ScriptEngineHandler.getLanguageName(factory)); } - comboLanguages = new JComboBox(values.toArray(new String[values.size()])); + comboLanguages = new JComboBox<>(new Vector<>(values)); comboLanguages.setSelectedItem(language); comboLanguages.setMaximumSize(comboLanguages.getPreferredSize()); - btnRun.addActionListener(runInSameListener); + btnRun.addActionListener(e -> { + if (lastIsNew) { + lastIsNew = false; + btnSplitRun.setIcon(new IcyIcon(imgPlayback2, 16)); + btnSplitRun.setToolTipText("All variables in the bindings are re-usable."); + btnSplitRun.repaint(); + } + }); - btnSplitRun.addSplitButtonActionListener(new SplitButtonActionListener() - { + btnSplitRun.addSplitButtonActionListener(new SplitButtonActionListener() { @Override - public void splitButtonClicked(ActionEvent e) - { + public void splitButtonClicked(final ActionEvent e) { } @Override - public void buttonClicked(ActionEvent e) - { + public void buttonClicked(final ActionEvent e) { if (lastIsNew) btnRunNew2.doClick(); else btnRun.doClick(); } }); - btnRunNew2.addActionListener(runInNewListener); + btnRunNew2.addActionListener(e -> { + if (!lastIsNew) { + lastIsNew = true; + btnSplitRun.setIcon(new IcyIcon("playback_play", 16)); + btnSplitRun.setToolTipText("Creates a new context and run the script. The previous context will be lost."); + btnSplitRun.repaint(); + } + }); add(new JLabel("Lang: ")); add(comboLanguages); @@ -154,66 +123,53 @@ class CommandPanel extends JPanel add(Box.createHorizontalGlue()); } - public void setRunButtonsEnabled(boolean b) - { + public void setRunButtonsEnabled(final boolean b) { btnRun.setEnabled(b); btnSplitRun.setEnabled(b); } - public void setStopButtonEnabled(boolean b) - { + public void setStopButtonEnabled(final boolean b) { btnRun.setEnabled(!b); btnSplitRun.setEnabled(!b); btnStop.setEnabled(b); } - public void addLanguageListener(ItemListener listener) - { + public void addLanguageListener(final ItemListener listener) { comboLanguages.addItemListener(listener); } - public void removeLanguageListener(ItemListener listener) - { + public void removeLanguageListener(final ItemListener listener) { comboLanguages.removeItemListener(listener); } /** - * Get the current selected language in the combobox. - * - * @return + * @return the current selected language in the combobox. */ - public String getLanguage() - { + public String getLanguage() { return (String) comboLanguages.getSelectedItem(); } - public void removeRunInSameListener(ActionListener listener) - { + public void removeRunInSameListener(final ActionListener listener) { btnRun.removeActionListener(listener); } - public void removeRunInNewListener(ActionListener listener) - { + public void removeRunInNewListener(final ActionListener listener) { btnRunNew2.removeActionListener(listener); } - public void addRunInSameListener(ActionListener listener) - { + public void addRunInSameListener(final ActionListener listener) { btnRun.addActionListener(listener); } - public void addRunInNewListener(ActionListener listener) - { + public void addRunInNewListener(final ActionListener listener) { btnRunNew2.addActionListener(listener); } - public void addStopListener(ActionListener listener) - { + public void addStopListener(final ActionListener listener) { btnStop.addActionListener(listener); } - public void removeStopListener(ActionListener listener) - { + public void removeStopListener(final ActionListener listener) { btnStop.removeActionListener(listener); } } diff --git a/src/main/java/plugins/tprovoost/scripteditor/gui/ConsoleOutput.java b/src/main/java/plugins/tprovoost/scripteditor/gui/ConsoleOutput.java index fe2b76b53653f599558f7146a5dfd31468ff5c7d..9e4ec3a013e7983fb5905c5e51a4988a73581e89 100644 --- a/src/main/java/plugins/tprovoost/scripteditor/gui/ConsoleOutput.java +++ b/src/main/java/plugins/tprovoost/scripteditor/gui/ConsoleOutput.java @@ -4,14 +4,10 @@ import java.awt.BorderLayout; import java.awt.Color; import java.awt.Dimension; import java.awt.Rectangle; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; import java.awt.event.AdjustmentEvent; import java.awt.event.AdjustmentListener; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; -import java.awt.event.MouseWheelEvent; -import java.awt.event.MouseWheelListener; import javax.swing.BorderFactory; import javax.swing.BoundedRangeModel; @@ -28,157 +24,125 @@ import javax.swing.text.Document; import javax.swing.text.Style; import javax.swing.text.StyleConstants; +import icy.system.IcyExceptionHandler; import icy.util.EventUtil; -@SuppressWarnings("serial") public class ConsoleOutput extends JPanel { - protected boolean scrollLocked; - final JTextPane textPane; - private JScrollPane scrollpane; - - ConsoleOutput() - { - setLayout(new BorderLayout()); - - textPane = new JTextPane(); - textPane.setEditable(false); - // not a good idea to fix the FONT ! + protected boolean scrollLocked; + final JTextPane textPane; + + ConsoleOutput() { + setLayout(new BorderLayout()); + + textPane = new JTextPane(); + textPane.setEditable(false); + // not a good idea to fix the FONT ! // textPane.setFont(new Font("sansserif", Font.PLAIN, 12)); - textPane.setBorder(BorderFactory.createBevelBorder(BevelBorder.LOWERED)); - - // HANDLE RIGHT CLICK POPUP MENU - textPane.addMouseListener(new MouseAdapter() - { - @Override - public void mouseClicked(MouseEvent e) - { - if (EventUtil.isRightMouseButton(e)) - { - JPopupMenu popup = new JPopupMenu(); - JMenuItem itemCopy = new JMenuItem("Copy"); - itemCopy.addActionListener(new ActionListener() - { - - @Override - public void actionPerformed(ActionEvent e) - { - textPane.copy(); - } - }); - popup.add(itemCopy); - popup.show(textPane, e.getX(), e.getY()); - e.consume(); - } - } - }); - - // by default the JTextPane will autoscroll everytime something is modified - // in the document. So in our case it would always autoscroll to the bottom - // of the console. We want to disable that and do the scrolling at our discretion. - class NonSrollingCaret extends DefaultCaret { - public void adjustVisibility(Rectangle rec) {} - } - textPane.setCaret(new NonSrollingCaret()); - - // Create the scrollpane around the output - scrollpane = new JScrollPane(textPane); - scrollpane.setBorder(BorderFactory.createEmptyBorder(2, 0, 2, 0)); - scrollpane.setAutoscrolls(true); - scrollpane.setPreferredSize(new Dimension(400, 200)); - add(scrollpane); - - final JScrollBar scrollbar = scrollpane.getVerticalScrollBar(); - - // Listener for the scrollbar, to achieve auto-scroll or scroll-lock - // depending on the position of the scrollbar - scrollbar.addAdjustmentListener(new AdjustmentListener() - { - final BoundedRangeModel brm = scrollbar.getModel(); - - @Override - public void adjustmentValueChanged(AdjustmentEvent e) - { - if (scrollbar.getValueIsAdjusting()) - { - boolean atBottom = (scrollbar.getValue() + scrollbar.getVisibleAmount() == scrollbar.getMaximum()); - if (atBottom) - setScrollLocked(false); - else - setScrollLocked(true); - } - if (!isScrollLocked() && !textPane.getText().isEmpty()) - { - brm.setValue(brm.getMaximum()); - } - } - - }); - - scrollpane.addMouseWheelListener(new MouseWheelListener() - { - - @Override - public void mouseWheelMoved(MouseWheelEvent e) - { - boolean atBottom = (scrollbar.getValue() + scrollbar.getVisibleAmount() == scrollbar.getMaximum()); - if (atBottom && e.getWheelRotation() >= 0) - { - // we are at bottom and asking to go down => we should disable the auto-scroll lock - // and let the console auto-scroll - setScrollLocked(false); - } - else - setScrollLocked(true); - } - }); - } - - private synchronized boolean isScrollLocked() - { - return scrollLocked; - } - - private synchronized void setScrollLocked(boolean scrollLocked) - { - this.scrollLocked = scrollLocked; - } - - public JTextPane getTextPane() { - return textPane; - } - - public void append(String s) { - Document doc = textPane.getDocument(); - try - { - Style style = textPane.getStyle("normal"); - if (style == null) - style = textPane.addStyle("normal", null); - doc.insertString(doc.getLength(), s, style); - } catch (BadLocationException e2) - { - } - } - - public void clear() { - textPane.setText(""); - } - - public void appendError(String s) { - Document doc = textPane.getDocument(); - try - { - Style style = textPane.getStyle("error"); - if (style == null) - { - style = textPane.addStyle("error", null); - StyleConstants.setForeground(style, Color.red); - } - doc.insertString(doc.getLength(), s, style); - } - catch (BadLocationException e) - { - } - } + textPane.setBorder(BorderFactory.createBevelBorder(BevelBorder.LOWERED)); + + // HANDLE RIGHT CLICK POPUP MENU + textPane.addMouseListener(new MouseAdapter() { + @Override + public void mouseClicked(final MouseEvent e) { + if (EventUtil.isRightMouseButton(e)) { + final JPopupMenu popup = new JPopupMenu(); + final JMenuItem itemCopy = new JMenuItem("Copy"); + itemCopy.addActionListener(e1 -> textPane.copy()); + popup.add(itemCopy); + popup.show(textPane, e.getX(), e.getY()); + e.consume(); + } + } + }); + + // by default the JTextPane will autoscroll everytime something is modified + // in the document. So in our case it would always autoscroll to the bottom + // of the console. We want to disable that and do the scrolling at our discretion. + class NonSrollingCaret extends DefaultCaret { + @Override + public void adjustVisibility(final Rectangle rec) { + } + } + textPane.setCaret(new NonSrollingCaret()); + + // Create the scrollpane around the output + final JScrollPane scrollpane = new JScrollPane(textPane); + scrollpane.setBorder(BorderFactory.createEmptyBorder(2, 0, 2, 0)); + scrollpane.setAutoscrolls(true); + scrollpane.setPreferredSize(new Dimension(400, 200)); + add(scrollpane); + + final JScrollBar scrollbar = scrollpane.getVerticalScrollBar(); + + // Listener for the scrollbar, to achieve auto-scroll or scroll-lock + // depending on the position of the scrollbar + scrollbar.addAdjustmentListener(new AdjustmentListener() { + final BoundedRangeModel brm = scrollbar.getModel(); + + @Override + public void adjustmentValueChanged(final AdjustmentEvent e) { + if (scrollbar.getValueIsAdjusting()) { + final boolean atBottom = (scrollbar.getValue() + scrollbar.getVisibleAmount() == scrollbar.getMaximum()); + setScrollLocked(!atBottom); + } + if (!isScrollLocked() && !textPane.getText().isEmpty()) { + brm.setValue(brm.getMaximum()); + } + } + + }); + + scrollpane.addMouseWheelListener(e -> { + final boolean atBottom = (scrollbar.getValue() + scrollbar.getVisibleAmount() == scrollbar.getMaximum()); + + // we are at bottom and asking to go down => we should disable the auto-scroll lock + // and let the console auto-scroll + setScrollLocked(!(atBottom && e.getWheelRotation() >= 0)); + }); + } + + private synchronized boolean isScrollLocked() { + return scrollLocked; + } + + private synchronized void setScrollLocked(final boolean scrollLocked) { + this.scrollLocked = scrollLocked; + } + + public JTextPane getTextPane() { + return textPane; + } + + public void append(final String s) { + final Document doc = textPane.getDocument(); + try { + Style style = textPane.getStyle("normal"); + if (style == null) + style = textPane.addStyle("normal", null); + doc.insertString(doc.getLength(), s, style); + } + catch (final BadLocationException e) { + IcyExceptionHandler.showErrorMessage(e, true); + } + } + + public void clear() { + textPane.setText(""); + } + + public void appendError(final String s) { + final Document doc = textPane.getDocument(); + try { + Style style = textPane.getStyle("error"); + if (style == null) { + style = textPane.addStyle("error", null); + StyleConstants.setForeground(style, Color.red); + } + doc.insertString(doc.getLength(), s, style); + } + catch (final BadLocationException e) { + IcyExceptionHandler.showErrorMessage(e, true); + } + } } diff --git a/src/main/java/plugins/tprovoost/scripteditor/gui/FindAndReplaceDialog.java b/src/main/java/plugins/tprovoost/scripteditor/gui/FindAndReplaceDialog.java index ff464f5575f61adc2301fd50aefe199dc2ccf11f..002d291b26edee28113772a06a8d25a5c882ec04 100644 --- a/src/main/java/plugins/tprovoost/scripteditor/gui/FindAndReplaceDialog.java +++ b/src/main/java/plugins/tprovoost/scripteditor/gui/FindAndReplaceDialog.java @@ -33,41 +33,34 @@ import org.fife.ui.rtextarea.SearchContext; import org.fife.ui.rtextarea.SearchEngine; import org.fife.ui.rtextarea.SearchResult; -public class FindAndReplaceDialog extends JDialog implements ActionListener -{ - /** - * - */ - private static final long serialVersionUID = 1L; +public class FindAndReplaceDialog extends JDialog implements ActionListener { private static FindAndReplaceDialog singleton; - private JTextField searchField, replaceField; - private JCheckBox matchCase, wholeWord, regex; - private JButton btnFind, btnReplace, btnReplaceFind, btnReplaceAll, btnClose; + private final JTextField searchField, replaceField; + private final JCheckBox matchCase, wholeWord, regex; + private final JButton btnFind, btnReplace, btnReplaceFind, btnReplaceAll; private ScriptingEditor editor; - private JRadioButton radioForward; - private JRadioButton rdbtnBackward; + private final JRadioButton radioForward; - private FindAndReplaceDialog(Frame parent) - { + private FindAndReplaceDialog(final Frame parent) { super(parent); - JPanel panelMain = new JPanel(); + final JPanel panelMain = new JPanel(); panelMain.setBorder(new EmptyBorder(8, 8, 8, 8)); setContentPane(panelMain); setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE); panelMain.setLayout(new BorderLayout(0, 0)); - JPanel panelTop = new JPanel(); + final JPanel panelTop = new JPanel(); panelMain.add(panelTop, BorderLayout.NORTH); panelTop.setLayout(new BoxLayout(panelTop, BoxLayout.Y_AXIS)); - JPanel panelFind = new JPanel(); + final JPanel panelFind = new JPanel(); panelTop.add(panelFind); panelFind.setBorder(new EmptyBorder(4, 4, 4, 4)); panelFind.setLayout(new BoxLayout(panelFind, BoxLayout.X_AXIS)); - JLabel lblFind = new JLabel("Find:"); + final JLabel lblFind = new JLabel("Find:"); panelFind.add(lblFind); panelFind.add(Box.createHorizontalStrut(61)); @@ -76,12 +69,12 @@ public class FindAndReplaceDialog extends JDialog implements ActionListener panelFind.add(searchField); searchField.setColumns(10); - JPanel panelReplace = new JPanel(); + final JPanel panelReplace = new JPanel(); panelTop.add(panelReplace); panelReplace.setBorder(new EmptyBorder(4, 4, 4, 4)); panelReplace.setLayout(new BoxLayout(panelReplace, BoxLayout.X_AXIS)); - JLabel lblReplace = new JLabel("Replace with:"); + final JLabel lblReplace = new JLabel("Replace with:"); panelReplace.add(lblReplace); panelReplace.add(Box.createHorizontalStrut(20)); @@ -90,16 +83,15 @@ public class FindAndReplaceDialog extends JDialog implements ActionListener replaceField.setColumns(10); panelReplace.add(replaceField); - JPanel panelDirection = new JPanel(); + final JPanel panelDirection = new JPanel(); panelTop.add(panelDirection); - panelDirection - .setBorder(new TitledBorder(null, "Direction", TitledBorder.LEADING, TitledBorder.TOP, null, null)); + panelDirection.setBorder(new TitledBorder(null, "Direction", TitledBorder.LEADING, TitledBorder.TOP, null, null)); panelDirection.setLayout(new BoxLayout(panelDirection, BoxLayout.X_AXIS)); - ButtonGroup group = new ButtonGroup(); + final ButtonGroup group = new ButtonGroup(); radioForward = new JRadioButton("Forward"); radioForward.setSelected(true); - rdbtnBackward = new JRadioButton("Backward"); + final JRadioButton rdbtnBackward = new JRadioButton("Backward"); group.add(radioForward); group.add(rdbtnBackward); @@ -107,13 +99,12 @@ public class FindAndReplaceDialog extends JDialog implements ActionListener panelDirection.add(rdbtnBackward); panelDirection.add(Box.createHorizontalGlue()); - JPanel panelOptions = new JPanel(); + final JPanel panelOptions = new JPanel(); panelTop.add(panelOptions); - panelOptions.setBorder(new TitledBorder(UIManager.getBorder("TitledBorder.border"), "Options", - TitledBorder.LEADING, TitledBorder.TOP, null, null)); + panelOptions.setBorder(new TitledBorder(UIManager.getBorder("TitledBorder.border"), "Options", TitledBorder.LEADING, TitledBorder.TOP, null, null)); panelOptions.setLayout(new GridLayout(0, 1, 0, 0)); - JPanel panel = new JPanel(); + final JPanel panel = new JPanel(); panel.setBorder(new EmptyBorder(2, 2, 2, 2)); panelOptions.add(panel); panel.setLayout(new BoxLayout(panel, BoxLayout.X_AXIS)); @@ -124,7 +115,7 @@ public class FindAndReplaceDialog extends JDialog implements ActionListener wholeWord = new JCheckBox("Whole word"); panel.add(wholeWord); - JPanel panel_1 = new JPanel(); + final JPanel panel_1 = new JPanel(); panel_1.setBorder(new EmptyBorder(2, 2, 2, 2)); panelOptions.add(panel_1); panel_1.setLayout(new BoxLayout(panel_1, BoxLayout.X_AXIS)); @@ -132,13 +123,13 @@ public class FindAndReplaceDialog extends JDialog implements ActionListener regex = new JCheckBox("Regular expressions"); panel_1.add(regex); - JPanel panelSouth = new JPanel(); + final JPanel panelSouth = new JPanel(); panelMain.add(panelSouth, BorderLayout.SOUTH); panelSouth.setLayout(new BoxLayout(panelSouth, BoxLayout.X_AXIS)); panelSouth.add(Box.createHorizontalGlue()); - JPanel panelButtons = new JPanel(); + final JPanel panelButtons = new JPanel(); panelSouth.add(panelButtons); panelButtons.setLayout(new GridLayout(0, 2, 0, 0)); @@ -154,19 +145,11 @@ public class FindAndReplaceDialog extends JDialog implements ActionListener btnReplaceAll = new JButton("Replace All"); panelButtons.add(btnReplaceAll); - JLabel lblFiller = new JLabel(""); + final JLabel lblFiller = new JLabel(""); panelButtons.add(lblFiller); - btnClose = new JButton("Close"); - btnClose.addActionListener(new ActionListener() - { - - @Override - public void actionPerformed(ActionEvent e) - { - dispose(); - } - }); + final JButton btnClose = new JButton("Close"); + btnClose.addActionListener(e -> dispose()); panelButtons.add(btnClose); setTitle("Find/Replace"); @@ -174,68 +157,55 @@ public class FindAndReplaceDialog extends JDialog implements ActionListener pack(); setLocationRelativeTo(parent); - // -------------- - // ACTIONS - // --------------- btnFind.addActionListener(this); btnReplace.addActionListener(this); btnReplaceAll.addActionListener(this); btnReplaceFind.addActionListener(this); panelMain.getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0), "escape"); - panelMain.getActionMap().put("escape", new AbstractAction() - { - private static final long serialVersionUID = 1L; - + panelMain.getActionMap().put("escape", new AbstractAction() { @Override - public void actionPerformed(ActionEvent e) - { + public void actionPerformed(final ActionEvent e) { dispose(); singleton = null; } }); } - protected RSyntaxTextArea getTextArea() - { - if (editor != null) - { - Component comp = editor.getTabbedPane().getSelectedComponent(); - if (comp instanceof ScriptingPanel) - { + protected RSyntaxTextArea getTextArea() { + if (editor != null) { + final Component comp = editor.getTabbedPane().getSelectedComponent(); + if (comp instanceof ScriptingPanel) { return ((ScriptingPanel) comp).getTextArea(); } } return null; } - public static void showDialog(ScriptingEditor editor) - { - FindAndReplaceDialog dialog = getInstance(); + public static void showDialog(final ScriptingEditor editor) { + final FindAndReplaceDialog dialog = getInstance(); dialog.editor = editor; - RSyntaxTextArea textArea = dialog.getTextArea(); + final RSyntaxTextArea textArea = dialog.getTextArea(); if (textArea != null) dialog.searchField.setText(textArea.getSelectedText()); dialog.searchField.selectAll(); dialog.setVisible(true); } - private static FindAndReplaceDialog getInstance() - { + private static FindAndReplaceDialog getInstance() { if (singleton == null) singleton = new FindAndReplaceDialog(Icy.getMainInterface().getMainFrame()); return singleton; } - public void actionPerformed(ActionEvent e) - { - Object source = e.getSource(); - String text = searchField.getText(); + @Override + public void actionPerformed(final ActionEvent e) { + final Object source = e.getSource(); + final String text = searchField.getText(); if (text.length() == 0) return; - RSyntaxTextArea textArea = getTextArea(); - if (textArea == null) - { + final RSyntaxTextArea textArea = getTextArea(); + if (textArea == null) { MessageDialog.showDialog("No text to search in."); return; } @@ -243,36 +213,32 @@ public class FindAndReplaceDialog extends JDialog implements ActionListener findOrReplace(false); else if (source == btnReplace) findOrReplace(true); - else if (source == btnReplaceFind) - { + else if (source == btnReplaceFind) { findOrReplace(true); findOrReplace(false); } - else if (source == btnReplaceAll) - { - SearchContext cx = new SearchContext(text); + else if (source == btnReplaceAll) { + final SearchContext cx = new SearchContext(text); cx.setRegularExpression(regex.isSelected()); cx.setReplaceWith(replaceField.getText()); cx.setMatchCase(matchCase.isSelected()); cx.setWholeWord(wholeWord.isSelected()); - SearchResult result = SearchEngine.replaceAll(textArea, cx); + final SearchResult result = SearchEngine.replaceAll(textArea, cx); JOptionPane.showMessageDialog(this, result.getCount() + " replacements made!"); } } - public boolean findOrReplace(boolean replace) - { + public boolean findOrReplace(final boolean replace) { return findOrReplace(replace, radioForward.isSelected()); } - public boolean findOrReplace(boolean replace, boolean forward) - { + public boolean findOrReplace(final boolean replace, final boolean forward) { if (searchOrReplaceFromHere(replace, forward)) return true; - RSyntaxTextArea textArea = getTextArea(); + final RSyntaxTextArea textArea = getTextArea(); if (textArea == null) return false; - int caret = textArea.getCaretPosition(); + final int caret = textArea.getCaretPosition(); textArea.setCaretPosition(forward ? 0 : textArea.getDocument().getLength()); if (searchOrReplaceFromHere(replace, forward)) return true; @@ -281,39 +247,29 @@ public class FindAndReplaceDialog extends JDialog implements ActionListener return false; } - protected boolean searchOrReplaceFromHere(boolean replace) - { - return searchOrReplaceFromHere(radioForward.isSelected()); - } - - protected boolean searchOrReplaceFromHere(boolean replace, boolean forward) - { - SearchContext cx = new SearchContext(searchField.getText()); + protected boolean searchOrReplaceFromHere(final boolean replace, final boolean forward) { + final SearchContext cx = new SearchContext(searchField.getText()); cx.setRegularExpression(regex.isSelected()); cx.setReplaceWith(replaceField.getText()); cx.setMatchCase(matchCase.isSelected()); cx.setSearchForward(forward); cx.setWholeWord(wholeWord.isSelected()); - if (replace) - { + if (replace) { return SearchEngine.replace(getTextArea(), cx).wasFound(); } return SearchEngine.find(getTextArea(), cx).wasFound(); } - public boolean isReplace() - { + public boolean isReplace() { return btnReplace.isEnabled(); } /** * Sets the content of the search field. - * - * @param pattern - * The new content of the search field. + * + * @param pattern The new content of the search field. */ - public void setSearchPattern(String pattern) - { + public void setSearchPattern(final String pattern) { searchField.setText(pattern); } } diff --git a/src/main/java/plugins/tprovoost/scripteditor/gui/JSplitButton.java b/src/main/java/plugins/tprovoost/scripteditor/gui/JSplitButton.java index 8b40a87da75e872217fa4c0714c6e525f891b97d..aad86c4962e5159b747405601e633831a91b5635 100644 --- a/src/main/java/plugins/tprovoost/scripteditor/gui/JSplitButton.java +++ b/src/main/java/plugins/tprovoost/scripteditor/gui/JSplitButton.java @@ -42,20 +42,13 @@ import plugins.tprovoost.scripteditor.gui.action.SplitButtonActionListener; * nice.My email naveedmurtuza[at]gmail.com<br> * <br> * P.S. The fireXXX methods has been directly plagarized from JDK source code, and yes even the - * javadocs..;)<br> + * javadocs<br> * <br> * The border bug in metal L&F is now fixed. Thanks to Herve Guillaume. - * + * * @author Naveed Quadri */ -public class JSplitButton extends JButton implements MouseMotionListener, MouseListener, ActionListener, Serializable -{ - - /** - * - */ - private static final long serialVersionUID = 1L; - +public class JSplitButton extends JButton implements MouseMotionListener, MouseListener, ActionListener, Serializable { private int separatorSpacing = 4; private int splitWidth = 22; private int arrowSize = 8; @@ -70,14 +63,11 @@ public class JSplitButton extends JButton implements MouseMotionListener, MouseL /** * Creates a button with initial text and an icon. - * - * @param text - * the text of the button - * @param icon - * the Icon image to display on the button + * + * @param text the text of the button + * @param icon the Icon image to display on the button */ - public JSplitButton(String text, Icon icon) - { + public JSplitButton(final String text, final Icon icon) { super(text, icon); addMouseMotionListener(this); addMouseListener(this); @@ -86,62 +76,53 @@ public class JSplitButton extends JButton implements MouseMotionListener, MouseL /** * Creates a button with text. - * - * @param text - * the text of the button + * + * @param text the text of the button */ - public JSplitButton(String text) - { + public JSplitButton(final String text) { this(text, null); } /** * Creates a button with an icon. - * - * @param icon - * the Icon image to display on the button + * + * @param icon the Icon image to display on the button */ - public JSplitButton(Icon icon) - { + public JSplitButton(final Icon icon) { this(null, icon); } /** * Creates a button with no set text or icon. */ - public JSplitButton() - { + public JSplitButton() { this(null, null); } /** * Returns the JPopupMenu if set, null otherwise. - * + * * @return JPopupMenu */ - public JPopupMenu getPopupMenu() - { + public JPopupMenu getPopupMenu() { return popupMenu; } /** * Sets the JPopupMenu to be displayed, when the split part of the button is clicked. - * - * @param popupMenu - * the popup menu to set + * + * @param popupMenu the popup menu to set */ - public void setPopupMenu(JPopupMenu popupMenu) - { + public void setPopupMenu(final JPopupMenu popupMenu) { this.popupMenu = popupMenu; image = null; // to repaint the arrow image } /** * @return the separatorSpacing. Separator spacing is the space above and below the separator - * (the line drawn when you hover your mouse over the split part of the button). + * (the line drawn when you hover your mouse over the split part of the button). */ - public int getSeparatorSpacing() - { + public int getSeparatorSpacing() { return separatorSpacing; } @@ -149,52 +130,44 @@ public class JSplitButton extends JButton implements MouseMotionListener, MouseL * Sets the separatorSpacing.<br> * Separator spacing is the space above and below the separator * (the line drawn when you hover your mouse over the split part of the button). - * - * @param separatorSpacing - * the space between the separator and the content + * + * @param separatorSpacing the space between the separator and the content */ - public void setSeparatorSpacing(int separatorSpacing) - { + public void setSeparatorSpacing(final int separatorSpacing) { this.separatorSpacing = separatorSpacing; } /** * Show the dropdown menu, if attached, even if the button part is clicked. - * + * * @return true if alwaysDropdown, false otherwise. */ - public boolean isAlwaysDropDown() - { + public boolean isAlwaysDropDown() { return alwaysDropDown; } /** * Show the dropdown menu, if attached, even if the button part is clicked. - * - * @param alwaysDropDown - * true to show the attached dropdown even if the button part is clicked, false otherwise + * + * @param alwaysDropDown true to show the attached dropdown even if the button part is clicked, false otherwise */ - public void setAlwaysDropDown(boolean alwaysDropDown) - { + public void setAlwaysDropDown(final boolean alwaysDropDown) { this.alwaysDropDown = alwaysDropDown; } /** * @return the color of the arrow. */ - public Color getArrowColor() - { + public Color getArrowColor() { return arrowColor; } /** * Set the arrow color. - * - * @param arrowColor - * color to set + * + * @param arrowColor color to set */ - public void setArrowColor(Color arrowColor) - { + public void setArrowColor(final Color arrowColor) { this.arrowColor = arrowColor; image = null; // to repaint the image with the new color } @@ -202,130 +175,108 @@ public class JSplitButton extends JButton implements MouseMotionListener, MouseL /** * @return disabledArrowColor color of the arrow if no popup attached. */ - public Color getDisabledArrowColor() - { + public Color getDisabledArrowColor() { return disabledArrowColor; } /** * sets the disabled arrow color - * - * @param disabledArrowColor - * color of the arrow if no popup attached. + * + * @param disabledArrowColor color of the arrow if no popup attached. */ - public void setDisabledArrowColor(Color disabledArrowColor) - { + public void setDisabledArrowColor(final Color disabledArrowColor) { this.disabledArrowColor = disabledArrowColor; image = null; // to repaint the image with the new color } /** * @return the split width.<br> - * The Split width is the width of the split part of the button. + * The Split width is the width of the split part of the button. */ - public int getSplitWidth() - { + public int getSplitWidth() { return splitWidth; } /** * Sets the split width.<br> * the Split width is the width of the split part of the button. - * - * @param splitWidth - * the width to set + * + * @param splitWidth the width to set */ - public void setSplitWidth(int splitWidth) - { + public void setSplitWidth(final int splitWidth) { this.splitWidth = splitWidth; } /** * @return size of the arrow */ - public int getArrowSize() - { + public int getArrowSize() { return arrowSize; } /** * sets the size of the arrow - * - * @param arrowSize - * size to set + * + * @param arrowSize size to set */ - public void setArrowSize(int arrowSize) - { + public void setArrowSize(final int arrowSize) { this.arrowSize = arrowSize; image = null; // to repaint the image with the new size } /** - * @return the image to be drawn in the split part. If no is set, a new image is created with the triangle. + * @return the image to be drawn in the split part. If no image is set, a new image is created with the triangle. */ - public Image getImage() - { - if (image != null) - { - return image; - } - else - { - Graphics2D g = null; + public Image getImage() { + if (image == null) { + Graphics2D g; BufferedImage img = new BufferedImage(arrowSize, arrowSize, BufferedImage.TYPE_INT_RGB); - g = (Graphics2D) img.createGraphics(); + g = img.createGraphics(); g.setColor(Color.WHITE); g.fillRect(0, 0, img.getWidth(), img.getHeight()); g.setColor(popupMenu != null ? arrowColor : disabledArrowColor); // this creates a triangle facing right > - g.fillPolygon(new int[] {0, 0, arrowSize / 2}, new int[] {0, arrowSize, arrowSize / 2}, 3); + g.fillPolygon(new int[]{0, 0, arrowSize / 2}, new int[]{0, arrowSize, arrowSize / 2}, 3); g.dispose(); // rotate it to face downwards img = rotate(img, 90); - BufferedImage dimg = new BufferedImage(img.getWidth(), img.getHeight(), BufferedImage.TYPE_INT_ARGB); - g = (Graphics2D) dimg.createGraphics(); + final BufferedImage dimg = new BufferedImage(img.getWidth(), img.getHeight(), BufferedImage.TYPE_INT_ARGB); + g = dimg.createGraphics(); g.setComposite(AlphaComposite.Src); g.drawImage(img, null, 0, 0); g.dispose(); - for (int i = 0; i < dimg.getHeight(); i++) - { - for (int j = 0; j < dimg.getWidth(); j++) - { - if (dimg.getRGB(j, i) == Color.WHITE.getRGB()) - { + for (int i = 0; i < dimg.getHeight(); i++) { + for (int j = 0; j < dimg.getWidth(); j++) { + if (dimg.getRGB(j, i) == Color.WHITE.getRGB()) { dimg.setRGB(j, i, 0x8F1C1C); } } } image = Toolkit.getDefaultToolkit().createImage(dimg.getSource()); - return image; } + return image; } /** * Sets the image to draw instead of the triangle. - * - * @param image - * the image to set + * + * @param image the image to set */ - public void setImage(Image image) - { + public void setImage(final Image image) { this.image = image; } @Override - protected void paintComponent(Graphics g) - { + protected void paintComponent(final Graphics g) { super.paintComponent(g); - Color oldColor = g.getColor(); + final Color oldColor = g.getColor(); splitRectangle = new Rectangle(getWidth() - splitWidth, 0, splitWidth, getHeight()); g.translate(splitRectangle.x, splitRectangle.y); - int mh = getHeight() / 2; - int mw = splitWidth / 2; + final int mh = getHeight() / 2; + final int mw = splitWidth / 2; g.drawImage(getImage(), mw - arrowSize / 2, mh + 2 - arrowSize / 2, null); - if (onSplit && !alwaysDropDown && popupMenu != null) - { + if (onSplit && !alwaysDropDown && popupMenu != null) { g.setColor(UIManager.getLookAndFeelDefaults().getColor("Button.background")); g.drawLine(1, separatorSpacing + 2, 1, getHeight() - separatorSpacing - 2); g.setColor(UIManager.getLookAndFeelDefaults().getColor("Button.shadow")); @@ -337,32 +288,27 @@ public class JSplitButton extends JButton implements MouseMotionListener, MouseL /** * Rotates the given image with the specified angle. - * - * @param img - * image to rotate - * @param angle - * angle of rotation + * + * @param img image to rotate + * @param angle angle of rotation * @return rotated image */ - private BufferedImage rotate(BufferedImage img, int angle) - { - int w = img.getWidth(); - int h = img.getHeight(); - BufferedImage dimg = new BufferedImage(w, h, img.getType()); - Graphics2D g = dimg.createGraphics(); - g.rotate(Math.toRadians(angle), w / 2, h / 2); + private BufferedImage rotate(final BufferedImage img, final int angle) { + final int w = img.getWidth(); + final int h = img.getHeight(); + final BufferedImage dimg = new BufferedImage(w, h, img.getType()); + final Graphics2D g = dimg.createGraphics(); + g.rotate(Math.toRadians(angle), w / 2d, h / 2d); g.drawImage(img, null, 0, 0); return dimg; } /** * Adds an <code>SplitButtonActionListener</code> to the button. - * - * @param l - * the <code>ActionListener</code> to be added + * + * @param l the <code>ActionListener</code> to be added */ - public void addSplitButtonActionListener(SplitButtonActionListener l) - { + public void addSplitButtonActionListener(final SplitButtonActionListener l) { listenerList.add(SplitButtonActionListener.class, l); } @@ -370,117 +316,83 @@ public class JSplitButton extends JButton implements MouseMotionListener, MouseL * Removes an <code>SplitButtonActionListener</code> from the button. * If the listener is the currently set <code>Action</code> for the button, then the * <code>Action</code> is set to <code>null</code>. - * - * @param l - * the listener to be removed + * + * @param l the listener to be removed */ - public void removeSplitButtonActionListener(SplitButtonActionListener l) - { - if ((l != null) && (getAction() == l)) - { - setAction(null); - } - else - { - listenerList.remove(SplitButtonActionListener.class, l); - } + public void removeSplitButtonActionListener(final SplitButtonActionListener l) { + listenerList.remove(SplitButtonActionListener.class, l); } @Override - public void mouseMoved(MouseEvent e) - { - if (splitRectangle.contains(e.getPoint())) - { - onSplit = true; - } - else - { - onSplit = false; - } + public void mouseMoved(final MouseEvent e) { + onSplit = splitRectangle.contains(e.getPoint()); repaint(splitRectangle); } @Override - public void actionPerformed(ActionEvent e) - { - if (popupMenu == null) - { + public void actionPerformed(final ActionEvent e) { + if (popupMenu == null) { fireButtonClicked(e); } - else if (alwaysDropDown) - { + else if (alwaysDropDown) { popupMenu.show(this, 0, getHeight()); fireButtonClicked(e); } - else if (onSplit) - { + else if (onSplit) { popupMenu.show(this, 0, getHeight()); fireSplitbuttonClicked(e); } - else - { + else { fireButtonClicked(e); } } @Override - public void mouseExited(MouseEvent e) - { + public void mouseExited(final MouseEvent e) { onSplit = false; repaint(splitRectangle); } @Override - public void mouseDragged(MouseEvent e) - { + public void mouseDragged(final MouseEvent e) { } @Override - public void mouseClicked(MouseEvent e) - { + public void mouseClicked(final MouseEvent e) { } @Override - public void mousePressed(MouseEvent e) - { + public void mousePressed(final MouseEvent e) { } @Override - public void mouseReleased(MouseEvent e) - { + public void mouseReleased(final MouseEvent e) { } @Override - public void mouseEntered(MouseEvent e) - { + public void mouseEntered(final MouseEvent e) { } /** * Notifies all listeners that have registered interest for * notification on this event type. The event instance * is lazily created using the <code>event</code> parameter. - * - * @param event - * the <code>ActionEvent</code> object + * + * @param event the <code>ActionEvent</code> object * @see EventListenerList */ - private void fireButtonClicked(ActionEvent event) - { + private void fireButtonClicked(final ActionEvent event) { // Guaranteed to return a non-null array - Object[] listeners = listenerList.getListenerList(); + final Object[] listeners = listenerList.getListenerList(); ActionEvent e = null; // Process the listeners last to first, notifying // those that are interested in this event - for (int i = listeners.length - 2; i >= 0; i -= 2) - { - if (listeners[i] == SplitButtonActionListener.class) - { + for (int i = listeners.length - 2; i >= 0; i -= 2) { + if (listeners[i] == SplitButtonActionListener.class) { // Lazily create the event: - if (e == null) - { + if (e == null) { String actionCommand = event.getActionCommand(); - if (actionCommand == null) - { + if (actionCommand == null) { actionCommand = getActionCommand(); } e = new ActionEvent(JSplitButton.this, ActionEvent.ACTION_PERFORMED, actionCommand, event.getWhen(), @@ -495,28 +407,22 @@ public class JSplitButton extends JButton implements MouseMotionListener, MouseL * Notifies all listeners that have registered interest for * notification on this event type. The event instance * is lazily created using the <code>event</code> parameter. - * - * @param event - * the <code>ActionEvent</code> object + * + * @param event the <code>ActionEvent</code> object * @see EventListenerList */ - private void fireSplitbuttonClicked(ActionEvent event) - { + private void fireSplitbuttonClicked(final ActionEvent event) { // Guaranteed to return a non-null array - Object[] listeners = listenerList.getListenerList(); + final Object[] listeners = listenerList.getListenerList(); ActionEvent e = null; // Process the listeners last to first, notifying // those that are interested in this event - for (int i = listeners.length - 2; i >= 0; i -= 2) - { - if (listeners[i] == SplitButtonActionListener.class) - { + for (int i = listeners.length - 2; i >= 0; i -= 2) { + if (listeners[i] == SplitButtonActionListener.class) { // Lazily create the event: - if (e == null) - { + if (e == null) { String actionCommand = event.getActionCommand(); - if (actionCommand == null) - { + if (actionCommand == null) { actionCommand = getActionCommand(); } e = new ActionEvent(JSplitButton.this, ActionEvent.ACTION_PERFORMED, actionCommand, event.getWhen(), diff --git a/src/main/java/plugins/tprovoost/scripteditor/gui/Preferences.java b/src/main/java/plugins/tprovoost/scripteditor/gui/Preferences.java index 644e6c03bbeaaeb7202c04a04f740293dda8fefc..50006552f07c345ba34998306d9dfc1c85ca7d06 100644 --- a/src/main/java/plugins/tprovoost/scripteditor/gui/Preferences.java +++ b/src/main/java/plugins/tprovoost/scripteditor/gui/Preferences.java @@ -4,12 +4,10 @@ import icy.preferences.GeneralPreferences; import icy.preferences.PluginsPreferences; import icy.preferences.XMLPreferences; -public class Preferences -{ - private static Preferences singleton = new Preferences(); +public class Preferences { + private static final Preferences singleton = new Preferences(); - private XMLPreferences prefs = PluginsPreferences.getPreferences().node( - "plugins.tprovoost.scripteditor.main.ScriptEditorPlugin"); + private final XMLPreferences prefs = PluginsPreferences.getPreferences().node("plugins.tprovoost.scripteditor.main.ScriptEditorPlugin"); // private PreferencesTableModel tableModel; // private final String PREF_VAR_INTERPRET = "varinterp"; @@ -33,62 +31,51 @@ public class Preferences // private boolean advanced; private boolean fullAutocomplete; - private Preferences() - { + private Preferences() { loadPrefs(); } - public static Preferences getPreferences() - { + public static Preferences getPreferences() { return singleton; } - public boolean isFullAutoCompleteEnabled() - { + public boolean isFullAutoCompleteEnabled() { return fullAutocomplete; } - public boolean isVarInterpretationEnabled() - { + public boolean isVarInterpretationEnabled() { // return varInterp; return true; } - public boolean isOverrideEnabled() - { + public boolean isOverrideEnabled() { // return override; return true; } - public boolean isAutoBuildEnabled() - { + public boolean isAutoBuildEnabled() { // return autoVerif; return true; } - public boolean isStrictModeEnabled() - { + public boolean isStrictModeEnabled() { // return strict; return false; } - public boolean isAutoClearOutputEnabled() - { + public boolean isAutoClearOutputEnabled() { return autoClearOutput; } - public boolean isSoftTabsEnabled() - { + public boolean isSoftTabsEnabled() { return soft; } - public int indentSpacesCount() - { + public int indentSpacesCount() { return tabWidth; } - public int getFontSize() - { + public int getFontSize() { return fontSize; } @@ -135,8 +122,7 @@ public class Preferences // } // } - public void savePrefs() - { + public void savePrefs() { // prefs.putBoolean(PREF_VAR_INTERPRET, isVarInterpretationEnabled()); // prefs.putBoolean(PREF_OVERRIDE, isOverrideEnabled()); // prefs.putBoolean(PREF_VERIF, isAutoBuildEnabled()); @@ -148,8 +134,7 @@ public class Preferences prefs.putInt(PREF_FONT_SIZE, getFontSize()); } - public void loadPrefs() - { + public void loadPrefs() { // varInterp = prefs.getBoolean(PREF_VAR_INTERPRET, Boolean.TRUE); // override = prefs.getBoolean(PREF_OVERRIDE, Boolean.TRUE); // autoVerif = prefs.getBoolean(PREF_VERIF, Boolean.TRUE); @@ -161,28 +146,23 @@ public class Preferences fontSize = prefs.getInt(PREF_FONT_SIZE, GeneralPreferences.getGuiFontSize()); } - public void setFullAutoCompleteEnabled(boolean enabled) - { + public void setFullAutoCompleteEnabled(final boolean enabled) { fullAutocomplete = enabled; } - public void setAutoClearOutputEnabled(boolean enabled) - { + public void setAutoClearOutputEnabled(final boolean enabled) { autoClearOutput = enabled; } - public void setSoftTabsEnabled(boolean enabled) - { + public void setSoftTabsEnabled(final boolean enabled) { soft = enabled; } - public void setTabWidth(int tabWidth) - { + public void setTabWidth(final int tabWidth) { this.tabWidth = tabWidth; } - public void setFontSize(int value) - { + public void setFontSize(final int value) { fontSize = value; } diff --git a/src/main/java/plugins/tprovoost/scripteditor/gui/PreferencesListener.java b/src/main/java/plugins/tprovoost/scripteditor/gui/PreferencesListener.java index 9db58ede3a7a6e09db7819f824ba23061351be25..87f2d621c9dcad228bbb4ac20d0d547c6b093612 100644 --- a/src/main/java/plugins/tprovoost/scripteditor/gui/PreferencesListener.java +++ b/src/main/java/plugins/tprovoost/scripteditor/gui/PreferencesListener.java @@ -3,5 +3,5 @@ package plugins.tprovoost.scripteditor.gui; import java.util.EventListener; interface PreferencesListener extends EventListener { - void preferencesChanged(); + void preferencesChanged(); } \ No newline at end of file diff --git a/src/main/java/plugins/tprovoost/scripteditor/gui/PreferencesWindow.java b/src/main/java/plugins/tprovoost/scripteditor/gui/PreferencesWindow.java index 7bf8efa52f51dc22aa04f24ca10b7eb273f06c40..28aeb149530fb946e92f89e27804abc0cf192d0d 100644 --- a/src/main/java/plugins/tprovoost/scripteditor/gui/PreferencesWindow.java +++ b/src/main/java/plugins/tprovoost/scripteditor/gui/PreferencesWindow.java @@ -7,8 +7,6 @@ import java.awt.BorderLayout; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.Insets; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; import javax.swing.JButton; import javax.swing.JCheckBox; @@ -20,11 +18,10 @@ import javax.swing.SwingConstants; import javax.swing.border.EmptyBorder; import javax.swing.event.EventListenerList; -public class PreferencesWindow extends IcyFrame -{ - private static PreferencesWindow singleton = new PreferencesWindow(); +public class PreferencesWindow extends IcyFrame { + private static final PreferencesWindow singleton = new PreferencesWindow(); - private Preferences preferences = Preferences.getPreferences(); + private final Preferences preferences = Preferences.getPreferences(); private JSpinner spinFontSize; private JSpinner tfSpacesTab; @@ -32,54 +29,51 @@ public class PreferencesWindow extends IcyFrame private JCheckBox cboxAutoClearOutput; private JCheckBox cboxFullAutocomplete; - private PreferencesWindow() - { + private PreferencesWindow() { super("Script Editor Preferences", true, true, false, true); - + setContentPane(createGUI()); } - public static PreferencesWindow getPreferencesWindow() - { + public static PreferencesWindow getPreferencesWindow() { return singleton; } - private JPanel createGUI() - { - JPanel toReturn = new JPanel(); + private JPanel createGUI() { + final JPanel toReturn = new JPanel(); toReturn.setBorder(new EmptyBorder(4, 4, 4, 4)); toReturn.setLayout(new BorderLayout(0, 0)); - JLabel lblPreferences = new JLabel("<html><h2>Preferences</h2></html>"); + final JLabel lblPreferences = new JLabel("<html><h2>Preferences</h2></html>"); lblPreferences.setHorizontalAlignment(SwingConstants.CENTER); toReturn.add(lblPreferences, BorderLayout.NORTH); - JPanel panelCenter = new JPanel(); + final JPanel panelCenter = new JPanel(); toReturn.add(panelCenter, BorderLayout.CENTER); - GridBagLayout gbl_panel_1 = new GridBagLayout(); - gbl_panel_1.columnWidths = new int[] {0, 0, 0}; - gbl_panel_1.rowHeights = new int[] {0, 0, 0, 0, 0, 0}; - gbl_panel_1.columnWeights = new double[] {1.0, 0.0, Double.MIN_VALUE}; - gbl_panel_1.rowWeights = new double[] {0.0, 0.0, 0.0, 0.0, 0.0, Double.MIN_VALUE}; + final GridBagLayout gbl_panel_1 = new GridBagLayout(); + gbl_panel_1.columnWidths = new int[]{0, 0, 0}; + gbl_panel_1.rowHeights = new int[]{0, 0, 0, 0, 0, 0}; + gbl_panel_1.columnWeights = new double[]{1.0, 0.0, Double.MIN_VALUE}; + gbl_panel_1.rowWeights = new double[]{0.0, 0.0, 0.0, 0.0, 0.0, Double.MIN_VALUE}; panelCenter.setLayout(gbl_panel_1); - JLabel lblFullAutocomplete = new JLabel("Enable 'auto complete' after any character typed"); - GridBagConstraints gbc_lblFullAutocomplete = new GridBagConstraints(); + final JLabel lblFullAutocomplete = new JLabel("Enable 'auto complete' after any character typed"); + final GridBagConstraints gbc_lblFullAutocomplete = new GridBagConstraints(); gbc_lblFullAutocomplete.anchor = GridBagConstraints.WEST; gbc_lblFullAutocomplete.insets = new Insets(0, 0, 5, 5); gbc_lblFullAutocomplete.gridx = 0; gbc_lblFullAutocomplete.gridy = 0; panelCenter.add(lblFullAutocomplete, gbc_lblFullAutocomplete); cboxFullAutocomplete = new JCheckBox(""); - GridBagConstraints gbc_cboxFullAutocomplete = new GridBagConstraints(); + final GridBagConstraints gbc_cboxFullAutocomplete = new GridBagConstraints(); gbc_cboxFullAutocomplete.anchor = GridBagConstraints.WEST; gbc_cboxFullAutocomplete.insets = new Insets(0, 0, 5, 0); gbc_cboxFullAutocomplete.gridx = 1; gbc_cboxFullAutocomplete.gridy = 0; panelCenter.add(cboxFullAutocomplete, gbc_cboxFullAutocomplete); - JLabel lblAutoClearOutput = new JLabel("Always clear the output when run is clicked"); - GridBagConstraints gbc_lblAutoClearOutput = new GridBagConstraints(); + final JLabel lblAutoClearOutput = new JLabel("Always clear the output when run is clicked"); + final GridBagConstraints gbc_lblAutoClearOutput = new GridBagConstraints(); gbc_lblAutoClearOutput.anchor = GridBagConstraints.WEST; gbc_lblAutoClearOutput.insets = new Insets(0, 0, 5, 5); gbc_lblAutoClearOutput.gridx = 0; @@ -87,16 +81,16 @@ public class PreferencesWindow extends IcyFrame panelCenter.add(lblAutoClearOutput, gbc_lblAutoClearOutput); cboxAutoClearOutput = new JCheckBox(""); - GridBagConstraints gbc_cboxAutoClearOutput = new GridBagConstraints(); + final GridBagConstraints gbc_cboxAutoClearOutput = new GridBagConstraints(); gbc_cboxAutoClearOutput.anchor = GridBagConstraints.WEST; gbc_cboxAutoClearOutput.insets = new Insets(0, 0, 5, 0); gbc_cboxAutoClearOutput.gridx = 1; gbc_cboxAutoClearOutput.gridy = 1; panelCenter.add(cboxAutoClearOutput, gbc_cboxAutoClearOutput); - JLabel lblSoft = new JLabel("Use Soft tabs"); + final JLabel lblSoft = new JLabel("Use Soft tabs"); lblSoft.setToolTipText("Auto-expand tabs to spaces"); - GridBagConstraints gbc_lblSoft = new GridBagConstraints(); + final GridBagConstraints gbc_lblSoft = new GridBagConstraints(); gbc_lblSoft.anchor = GridBagConstraints.WEST; gbc_lblSoft.insets = new Insets(0, 0, 5, 5); gbc_lblSoft.gridx = 0; @@ -104,15 +98,15 @@ public class PreferencesWindow extends IcyFrame panelCenter.add(lblSoft, gbc_lblSoft); cboxSoft = new JCheckBox(""); - GridBagConstraints gbc_cboxSoft = new GridBagConstraints(); + final GridBagConstraints gbc_cboxSoft = new GridBagConstraints(); gbc_cboxSoft.anchor = GridBagConstraints.WEST; gbc_cboxSoft.insets = new Insets(0, 0, 5, 0); gbc_cboxSoft.gridx = 1; gbc_cboxSoft.gridy = 2; panelCenter.add(cboxSoft, gbc_cboxSoft); - JLabel lblSpacesTab = new JLabel("Tab width"); - GridBagConstraints gbc_lblSpacesTab = new GridBagConstraints(); + final JLabel lblSpacesTab = new JLabel("Tab width"); + final GridBagConstraints gbc_lblSpacesTab = new GridBagConstraints(); gbc_lblSpacesTab.anchor = GridBagConstraints.WEST; gbc_lblSpacesTab.insets = new Insets(0, 0, 5, 5); gbc_lblSpacesTab.gridx = 0; @@ -121,87 +115,68 @@ public class PreferencesWindow extends IcyFrame tfSpacesTab = new JSpinner(); tfSpacesTab.setModel(new SpinnerNumberModel(4, 1, 10, 1)); - GridBagConstraints gbc_tfSpacesTab = new GridBagConstraints(); + final GridBagConstraints gbc_tfSpacesTab = new GridBagConstraints(); gbc_tfSpacesTab.fill = GridBagConstraints.HORIZONTAL; gbc_tfSpacesTab.insets = new Insets(0, 0, 5, 0); gbc_tfSpacesTab.gridx = 1; gbc_tfSpacesTab.gridy = 3; panelCenter.add(tfSpacesTab, gbc_tfSpacesTab); - JLabel lblFontSize = new JLabel("Font size"); - GridBagConstraints gbc_lblFontSize = new GridBagConstraints(); + final JLabel lblFontSize = new JLabel("Font size"); + final GridBagConstraints gbc_lblFontSize = new GridBagConstraints(); gbc_lblFontSize.anchor = GridBagConstraints.WEST; gbc_lblFontSize.insets = new Insets(0, 0, 0, 5); gbc_lblFontSize.gridx = 0; gbc_lblFontSize.gridy = 4; panelCenter.add(lblFontSize, gbc_lblFontSize); spinFontSize = new JSpinner(new SpinnerNumberModel(GeneralPreferences.getGuiFontSize(), 4, 30, 1)); - GridBagConstraints gbc_spinFontSize = new GridBagConstraints(); + final GridBagConstraints gbc_spinFontSize = new GridBagConstraints(); gbc_spinFontSize.fill = GridBagConstraints.HORIZONTAL; gbc_spinFontSize.gridx = 1; gbc_spinFontSize.gridy = 4; panelCenter.add(spinFontSize, gbc_spinFontSize); - JPanel panelButton = new JPanel(); + final JPanel panelButton = new JPanel(); toReturn.add(panelButton, BorderLayout.SOUTH); - GridBagLayout gbl_panelButton = new GridBagLayout(); - gbl_panelButton.columnWidths = new int[] {131, 59, 45, 65, 0}; - gbl_panelButton.rowHeights = new int[] {23, 0}; - gbl_panelButton.columnWeights = new double[] {1.0, 0.0, 0.0, 0.0, Double.MIN_VALUE}; - gbl_panelButton.rowWeights = new double[] {0.0, Double.MIN_VALUE}; + final GridBagLayout gbl_panelButton = new GridBagLayout(); + gbl_panelButton.columnWidths = new int[]{131, 59, 45, 65, 0}; + gbl_panelButton.rowHeights = new int[]{23, 0}; + gbl_panelButton.columnWeights = new double[]{1.0, 0.0, 0.0, 0.0, Double.MIN_VALUE}; + gbl_panelButton.rowWeights = new double[]{0.0, Double.MIN_VALUE}; panelButton.setLayout(gbl_panelButton); - JButton btnApply = new JButton("Apply"); - GridBagConstraints gbc_btnApply = new GridBagConstraints(); + final JButton btnApply = new JButton("Apply"); + final GridBagConstraints gbc_btnApply = new GridBagConstraints(); gbc_btnApply.anchor = GridBagConstraints.NORTH; gbc_btnApply.insets = new Insets(0, 0, 0, 5); gbc_btnApply.gridx = 1; gbc_btnApply.gridy = 0; panelButton.add(btnApply, gbc_btnApply); - btnApply.addActionListener(new ActionListener() - { - @Override - public void actionPerformed(ActionEvent e) - { - applyPreferences(); - } - }); + btnApply.addActionListener(e -> applyPreferences()); - JButton btnOk = new JButton("Ok"); - GridBagConstraints gbc_btnOk = new GridBagConstraints(); + final JButton btnOk = new JButton("Ok"); + final GridBagConstraints gbc_btnOk = new GridBagConstraints(); gbc_btnOk.anchor = GridBagConstraints.NORTH; gbc_btnOk.insets = new Insets(0, 0, 0, 5); gbc_btnOk.gridx = 2; gbc_btnOk.gridy = 0; panelButton.add(btnOk, gbc_btnOk); - btnOk.addActionListener(new ActionListener() - { - - @Override - public void actionPerformed(ActionEvent e) - { - applyPreferences(); - close(); - } + btnOk.addActionListener(e -> { + applyPreferences(); + close(); }); - JButton btnCancel = new JButton("Cancel"); - GridBagConstraints gbc_btnCancel = new GridBagConstraints(); + final JButton btnCancel = new JButton("Cancel"); + final GridBagConstraints gbc_btnCancel = new GridBagConstraints(); gbc_btnCancel.anchor = GridBagConstraints.NORTH; gbc_btnCancel.gridx = 3; gbc_btnCancel.gridy = 0; panelButton.add(btnCancel, gbc_btnCancel); - btnCancel.addActionListener(new ActionListener() - { - - @Override - public void actionPerformed(ActionEvent e) - { - // restore the values - initGUI(); - // do not save and do not tell listeners - close(); - } + btnCancel.addActionListener(e -> { + // restore the values + initGUI(); + // do not save and do not tell listeners + close(); }); initGUI(); @@ -209,8 +184,7 @@ public class PreferencesWindow extends IcyFrame return toReturn; } - void initGUI() - { + void initGUI() { // cboxVarInterp.setSelected(preferences.isVarInterpretationEnabled()); // cboxOverride.setSelected(preferences.isOverrideEnabled()); // cboxAutoVerif.setSelected(preferences.isAutoBuildEnabled()); @@ -222,8 +196,7 @@ public class PreferencesWindow extends IcyFrame spinFontSize.setValue(Integer.valueOf(preferences.getFontSize())); } - void applyPreferences() - { + void applyPreferences() { preferences.setFullAutoCompleteEnabled(cboxFullAutocomplete.isSelected()); preferences.setAutoClearOutputEnabled(cboxAutoClearOutput.isSelected()); preferences.setSoftTabsEnabled(cboxSoft.isSelected()); @@ -236,26 +209,21 @@ public class PreferencesWindow extends IcyFrame private final EventListenerList listeners = new EventListenerList(); - public void addPreferencesListener(PreferencesListener listener) - { + public void addPreferencesListener(final PreferencesListener listener) { listeners.add(PreferencesListener.class, listener); } - public void removePreferencesListener(PreferencesListener listener) - { + public void removePreferencesListener(final PreferencesListener listener) { listeners.remove(PreferencesListener.class, listener); } - protected void firePreferencesChanged() - { - for (PreferencesListener listener : getPreferencesListeners()) - { + protected void firePreferencesChanged() { + for (final PreferencesListener listener : getPreferencesListeners()) { listener.preferencesChanged(); } } - public PreferencesListener[] getPreferencesListeners() - { + public PreferencesListener[] getPreferencesListeners() { return listeners.getListeners(PreferencesListener.class); } } diff --git a/src/main/java/plugins/tprovoost/scripteditor/gui/RecentFiles.java b/src/main/java/plugins/tprovoost/scripteditor/gui/RecentFiles.java index 4e7ce31e57789f163ad1f29d12dccab188a28e45..73dc2c182735b48e5917e07d3871feff0f51d745 100644 --- a/src/main/java/plugins/tprovoost/scripteditor/gui/RecentFiles.java +++ b/src/main/java/plugins/tprovoost/scripteditor/gui/RecentFiles.java @@ -7,75 +7,67 @@ import java.io.File; import java.util.ArrayList; public class RecentFiles { - private ArrayList<String> previousFiles = new ArrayList<String>(); - - // remember up to MAX_RECENT_FILES files - private final int MAX_RECENT_FILES = 20; - - XMLPreferences recentFilesPref; - - RecentFiles(XMLPreferences prefs) - { - this.recentFilesPref = prefs.node("recentFiles"); - } - - void add(File file) - { - add(file.getAbsolutePath()); - } - - void add(String fileName) - { - // remove the file if it is present - previousFiles.remove(fileName); - - // insert the new file at the top of the list - previousFiles.add(0, fileName); - - // trim the list - if (previousFiles.size() > MAX_RECENT_FILES) - { - // remove the oldest - previousFiles.remove(previousFiles.size()-1); - } - } - - /** - * Save the recent files to the XML file. - * Note that IcyPreferences.save() should be - * called explicitly after this. - */ - void save() - { - // remove previous settings - // Note: I do not use recentFilesPref.removeChildren() because it leaves blank lines - // in the XML file - XMLUtil.removeAllChildren(recentFilesPref.getXMLNode()); - - int i = 0; - for (String fileName:previousFiles) - { - XMLPreferences key = recentFilesPref.node("entry" + i); - key.put("file0", fileName); - i += 1; - } - } + private final ArrayList<String> previousFiles = new ArrayList<>(); - /** - * Load the recent files from the XML file. - */ - void load() - { - previousFiles.clear(); - - for (XMLPreferences key : recentFilesPref.getChildren()) - { - String fileName = key.get("file0", ""); - previousFiles.add(fileName); - } - } + // remember up to MAX_RECENT_FILES files + private static final int MAX_RECENT_FILES = 20; - public ArrayList<String> getFiles() { - return previousFiles; - } + XMLPreferences recentFilesPref; + + RecentFiles(final XMLPreferences prefs) { + this.recentFilesPref = prefs.node("recentFiles"); + } + + void add(final File file) { + add(file.getAbsolutePath()); + } + + void add(final String fileName) { + // remove the file if it is present + previousFiles.remove(fileName); + + // insert the new file at the top of the list + previousFiles.add(0, fileName); + + // trim the list + if (previousFiles.size() > MAX_RECENT_FILES) { + // remove the oldest + previousFiles.remove(previousFiles.size() - 1); + } + } + + /** + * Save the recent files to the XML file. + * Note that IcyPreferences.save() should be + * called explicitly after this. + */ + void save() { + // remove previous settings + // Note: I do not use recentFilesPref.removeChildren() because it leaves blank lines + // in the XML file + XMLUtil.removeAllChildren(recentFilesPref.getXMLNode()); + + int i = 0; + for (final String fileName : previousFiles) { + final XMLPreferences key = recentFilesPref.node("entry" + i); + key.put("file0", fileName); + i += 1; + } + } + + /** + * Load the recent files from the XML file. + */ + void load() { + previousFiles.clear(); + + for (final XMLPreferences key : recentFilesPref.getChildren()) { + final String fileName = key.get("file0", ""); + previousFiles.add(fileName); + } + } + + public ArrayList<String> getFiles() { + return previousFiles; + } } diff --git a/src/main/java/plugins/tprovoost/scripteditor/gui/ScriptingEditor.java b/src/main/java/plugins/tprovoost/scripteditor/gui/ScriptingEditor.java index 52d9df96d5e8029d2f80ddcec32f57a1f78598df..9149422e505d84683479d7d013f467c491166c38 100644 --- a/src/main/java/plugins/tprovoost/scripteditor/gui/ScriptingEditor.java +++ b/src/main/java/plugins/tprovoost/scripteditor/gui/ScriptingEditor.java @@ -30,13 +30,9 @@ import javax.swing.JSplitPane; import javax.swing.JTabbedPane; import javax.swing.KeyStroke; import javax.swing.WindowConstants; -import javax.swing.event.ChangeEvent; -import javax.swing.event.ChangeListener; -import javax.swing.event.HyperlinkEvent; import javax.swing.event.HyperlinkEvent.EventType; import javax.swing.event.HyperlinkListener; -import icy.common.listener.AcceptListener; import icy.file.FileUtil; import icy.file.Loader; import icy.gui.frame.IcyFrame; @@ -52,7 +48,7 @@ import icy.preferences.PluginsPreferences; import icy.preferences.XMLPreferences; import icy.resource.icon.IcyIcon; import icy.system.FileDrop; -import icy.system.SystemUtil; +import icy.system.IcyExceptionHandler; import icy.system.thread.ThreadUtil; import icy.util.XMLUtil; import plugins.tprovoost.scripteditor.gui.ScriptingPanel.SavedAsListener; @@ -64,28 +60,25 @@ import plugins.tprovoost.scripteditor.scriptinghandlers.ScriptEngineHandler; /** * Main GUI of the class - * + * * @author tprovoost */ -public class ScriptingEditor extends IcyFrame implements ActionListener -{ +public class ScriptingEditor extends IcyFrame implements ActionListener { // Scripting Panels JTabbedPane tabbedPane; - private JPanel addPanePanel; + private final JPanel addPanePanel; // Console - private ConsoleOutput consoleOutput; + private final ConsoleOutput consoleOutput; private Scriptingconsole console; private JButton btnClearConsole; // Preferences and recent files private JMenu menuOpenRecent; static String currentDirectoryPath = ""; - private static final int ctrlMask = SystemUtil.getMenuCtrlMask(); private static final String STRING_LAST_DIRECTORY = "lastDirectory"; - private XMLPreferences prefs = PluginsPreferences.getPreferences() - .node("plugins.tprovoost.scripteditor.main.ScriptEditorPlugin"); + private final XMLPreferences prefs = PluginsPreferences.getPreferences().node("plugins.tprovoost.scripteditor.main.ScriptEditorPlugin"); private final RecentFiles recentFiles = new RecentFiles(prefs); @@ -95,20 +88,16 @@ public class ScriptingEditor extends IcyFrame implements ActionListener private static final boolean IS_PYTHON_INSTALLED = ScriptEngineHandler.getEngineManager().getEngineByExtension("py") != null; private static final String PREF_IDX = "idxTab"; - private IcyFrameListener frameListener = new IcyFrameAdapter() - { + private final IcyFrameListener frameListener = new IcyFrameAdapter() { @Override - public void icyFrameClosing(IcyFrameEvent e) - { - if (IcyFrame.getAllFrames(ScriptingEditor.class).size() == 1) - { + public void icyFrameClosing(final IcyFrameEvent e) { + if (IcyFrame.getAllFrames(ScriptingEditor.class).size() == 1) { ScriptEngineHandler.clearEngines(); final BindingsScriptFrame scriptFrame = BindingsScriptFrame.getInstance(); // can be released at this point - if (scriptFrame != null) - { + if (scriptFrame != null) { // close the bindings frame and release the reference to the engine scriptFrame.setVisible(false); scriptFrame.setEngine(null); @@ -125,152 +114,95 @@ public class ScriptingEditor extends IcyFrame implements ActionListener } }; - // listener called when Icy exits, asking for user confirmation - private AcceptListener acceptlistener = new AcceptListener() - { - @Override - public boolean accept(Object source) - { - // close all the tabs, asking the user confirmation - // do not save tab state while closing (would break the saved state) - saveStateEnabled = false; - boolean canClose = closeAll(); - saveStateEnabled = true; - return canClose; - } - }; - // listener called when a child ScriptingPanel saves a new file - private SavedAsListener savedAsListener = new SavedAsListener() - { - - @Override - public void savedAs(File f) - { - addRecentFile(f); - } - }; + private final SavedAsListener savedAsListener = this::addRecentFile; // listener called when a child ScriptingPanel wants its title to be changed - private TitleChangedListener titleChangedListener = new TitleChangedListener() - { + private final TitleChangedListener titleChangedListener = new TitleChangedListener() { @Override - public void titleChanged(ScriptingPanel panel, String title) - { - int idx = tabbedPane.indexOfComponent(panel); - if (idx != -1) - { + public void titleChanged(final ScriptingPanel panel, final String title) { + final int idx = tabbedPane.indexOfComponent(panel); + if (idx != -1) { tabbedPane.setTitleAt(idx, title); - Component c = tabbedPane.getTabComponentAt(idx); + final Component c = tabbedPane.getTabComponentAt(idx); if (c instanceof JComponent) - ((JComponent) c).revalidate(); + c.revalidate(); else c.repaint(); } } }; - private FileDrop.FileDropListener fileDropListener = new FileDrop.FileDropListener() - { - - @Override - public void filesDropped(File[] files) - { - for (File f : files) - if (f.getName().endsWith(".js") || f.getName().endsWith(".py")) - try - { - openFile(f); - } - catch (IOException e) - { - } - else - Loader.load(f.toString(), true); - } - }; - - private HyperlinkListener hyperlinkListener = new HyperlinkListener() - { - - @Override - public void hyperlinkUpdate(HyperlinkEvent e) - { - if (e.getEventType() == EventType.ACTIVATED) - { - URL url = e.getURL(); - String res = url == null ? e.getDescription() : url.getFile(); - try - { - openFile(new File(res)); + private final FileDrop.FileDropListener fileDropListener = files -> { + for (File f : files) + if (f.getName().endsWith(".js") || f.getName().endsWith(".py")) + try { + openFile(f); } - catch (IOException e1) - { + catch (IOException e) { + IcyExceptionHandler.showErrorMessage(e, true); } + else + Loader.load(f.toString(), true); + }; + + private final HyperlinkListener hyperlinkListener = e -> { + if (e.getEventType() == EventType.ACTIVATED) { + URL url = e.getURL(); + String res = url == null ? e.getDescription() : url.getFile(); + try { + openFile(new File(res)); + } + catch (IOException ex) { + IcyExceptionHandler.showErrorMessage(ex, true); } } }; // listen to changes of language in a child panel - public ItemListener languageListener = new ItemListener() - { - - @Override - public void itemStateChanged(ItemEvent e) - { - if (e.getStateChange() == ItemEvent.SELECTED) - { - String language = (String) e.getItem(); - changeConsoleLanguage(language); - } + public ItemListener languageListener = e -> { + if (e.getStateChange() == ItemEvent.SELECTED) { + String language = (String) e.getItem(); + changeConsoleLanguage(language); } }; - private JPanel panelSouth; + private final JPanel panelSouth; - public ScriptingEditor() - { + public ScriptingEditor() { super("Script Editor", true, true, true, true); setJMenuBar(createJMenuBar()); - JPanel mainPanel = new JPanel(new BorderLayout()); + final JPanel mainPanel = new JPanel(new BorderLayout()); tabbedPane = new JTabbedPane(); tabbedPane.setTabLayoutPolicy(JTabbedPane.SCROLL_TAB_LAYOUT); - tabbedPane.addChangeListener(new ChangeListener() - { - @Override - public void stateChanged(ChangeEvent arg0) - { - Component comp = tabbedPane.getSelectedComponent(); - if (!(comp instanceof ScriptingPanel)) - { - createNewPane(); - return; - } + tabbedPane.addChangeListener(event -> { + final Component comp = tabbedPane.getSelectedComponent(); + if (!(comp instanceof ScriptingPanel)) { + createNewPane(); + return; + } - ScriptingPanel panel = (ScriptingPanel) comp; + final ScriptingPanel panel = (ScriptingPanel) comp; - // save the editor state to be able to restore the currently-opened tab - saveEditorState(); + // save the editor state to be able to restore the currently-opened tab + saveEditorState(); - // update the console language according to the selected panel - changeConsoleLanguage(panel.getLanguage()); + // update the console language according to the selected panel + changeConsoleLanguage(panel.getLanguage()); - // update the editor title with the absolute path of the selected tab - File f = panel.getSaveFile(); - String s; - if (f != null) - { - s = f.getAbsolutePath(); - } - else - { - s = panel.getPanelName(); - } - setTitle("Script Editor - " + s); + // update the editor title with the absolute path of the selected tab + final File f = panel.getSaveFile(); + final String s; + if (f != null) { + s = f.getAbsolutePath(); + } + else { + s = panel.getPanelName(); } + setTitle("Script Editor - " + s); }); new FileDrop(getExternalFrame(), fileDropListener); @@ -288,13 +220,13 @@ public class ScriptingEditor extends IcyFrame implements ActionListener btnClearConsole = new JButton("Clear"); btnClearConsole.addActionListener(ScriptingEditor.this); - JPanel bottomPanel = new JPanel(new BorderLayout()); + final JPanel bottomPanel = new JPanel(new BorderLayout()); bottomPanel.add(consoleOutput, BorderLayout.CENTER); panelSouth = new JPanel(new BorderLayout()); bottomPanel.add(panelSouth, BorderLayout.SOUTH); - JSplitPane split = new JSplitPane(JSplitPane.VERTICAL_SPLIT, tabbedPane, bottomPanel); + final JSplitPane split = new JSplitPane(JSplitPane.VERTICAL_SPLIT, tabbedPane, bottomPanel); split.setDividerLocation(0.75d); split.setResizeWeight(0.75d); split.setOneTouchExpandable(true); @@ -308,7 +240,14 @@ public class ScriptingEditor extends IcyFrame implements ActionListener // --------------------- // exit listener - Icy.getMainInterface().addCanExitListener(acceptlistener); + Icy.getMainInterface().addCanExitListener(o -> { + // close all the tabs, asking the user confirmation + // do not save tab state while closing (would break the saved state) + saveStateEnabled = false; + final boolean canClose = closeAll(); + saveStateEnabled = true; + return canClose; + }); restoreEditorState(); } @@ -316,96 +255,79 @@ public class ScriptingEditor extends IcyFrame implements ActionListener /** * @return the tabbedPane. */ - public JTabbedPane getTabbedPane() - { + public JTabbedPane getTabbedPane() { return tabbedPane; } - void restoreEditorState() - { + void restoreEditorState() { currentDirectoryPath = prefs.get(STRING_LAST_DIRECTORY, ""); // load preferences final XMLPreferences openedFiles = prefs.node("openedFiles"); - final ArrayList<String> toOpen = new ArrayList<String>(); - for (XMLPreferences key : openedFiles.getChildren()) - { - String fileName = key.get("file0", ""); + final ArrayList<String> toOpen = new ArrayList<>(); + for (final XMLPreferences key : openedFiles.getChildren()) { + final String fileName = key.get("file0", ""); toOpen.add(fileName); } recentFiles.load(); updateRecentFilesMenu(); - if (toOpen.isEmpty()) - { + if (toOpen.isEmpty()) { // No files to reopen, let's create by default a Javascript panel named "Untitled" // This will also create and add a console createNewPane(); } - ThreadUtil.invokeLater(new Runnable() - { - - @Override - public void run() - { - // disable the state saving (would break the state) - saveStateEnabled = false; - for (String s : toOpen) - { - try - { - // open the file, do not save editor state - openFile(new File(s)); - } - catch (IOException e1) - { - } + ThreadUtil.invokeLater(() -> { + // disable the state saving (would break the state) + saveStateEnabled = false; + for (final String s : toOpen) { + try { + // open the file, do not save editor state + openFile(new File(s)); } - int idx = openedFiles.getInt(PREF_IDX, 0); - // the maximum possible index is the tab count minus two - // because we must count the '+' tab and the offset of one - // between the count and the index - int maxIdx = tabbedPane.getTabCount() - 2; - if (idx <= maxIdx) - { - tabbedPane.setSelectedIndex(idx); + catch (final IOException e) { + IcyExceptionHandler.showErrorMessage(e, true); } - // re-enable the state saving - saveStateEnabled = true; } + final int idx = openedFiles.getInt(PREF_IDX, 0); + // the maximum possible index is the tab count minus two + // because we must count the '+' tab and the offset of one + // between the count and the index + final int maxIdx = tabbedPane.getTabCount() - 2; + if (idx <= maxIdx) { + tabbedPane.setSelectedIndex(idx); + } + // re-enable the state saving + saveStateEnabled = true; }); } /** * Save the editor state (opened files, selected tab) to the disk */ - private void saveEditorState() - { + private void saveEditorState() { // do nothing when disabled if (!saveStateEnabled) return; - int idx = tabbedPane.getSelectedIndex(); + final int idx = tabbedPane.getSelectedIndex(); // Saving state of the opened files. - XMLPreferences openedFiles = prefs.node("openedFiles"); + final XMLPreferences openedFiles = prefs.node("openedFiles"); // remove previous settings // Note: I do not use openedFiles.removeChildren() because it leaves blank lines // in the XML file XMLUtil.removeAllChildren(openedFiles.getXMLNode()); - for (int i = 0; i < tabbedPane.getTabCount() - 1; ++i) - { - Component c = tabbedPane.getComponentAt(i); - if (c instanceof ScriptingPanel) - { - File f = ((ScriptingPanel) c).getSaveFile(); - if (f != null) - { - XMLPreferences key = openedFiles.node("entry" + i); + for (int i = 0; i < tabbedPane.getTabCount() - 1; ++i) { + final Component c = tabbedPane.getComponentAt(i); + if (c instanceof ScriptingPanel) { + final File f = ((ScriptingPanel) c).getSaveFile(); + if (f != null) { + final XMLPreferences key = openedFiles.node("entry" + i); key.put("file0", f.getAbsolutePath()); } } @@ -419,14 +341,12 @@ public class ScriptingEditor extends IcyFrame implements ActionListener /** * Close all tabs by dispatching the closing to each tab. - * + * * @return Returns if success in closing. False means the user decided to - * cancel the closing. + * cancel the closing. */ - private boolean closeAll() - { - if (getInternalFrame().getDefaultCloseOperation() == WindowConstants.DO_NOTHING_ON_CLOSE) - { + private boolean closeAll() { + if (getInternalFrame().getDefaultCloseOperation() == WindowConstants.DO_NOTHING_ON_CLOSE) { if (!closeAllTabs()) return false; @@ -436,25 +356,22 @@ public class ScriptingEditor extends IcyFrame implements ActionListener return true; } - public ScriptingPanel createNewPane() - { + public ScriptingPanel createNewPane() { return createNewPane("Untitled"); } /** * Creates a new Scripting Pane in the JTabbedPane and returns it. <br> * Automatically removes the "+" tab and re-add it after the panel. - * - * @param name - * file path + * + * @param name file path * @return the Script panel * @see #createNewPane() * @see #openFile(File) */ - public ScriptingPanel createNewPane(String name) - { - ScriptingPanel panelCreated; - String ext = FileUtil.getFileExtension(name, false); + public ScriptingPanel createNewPane(final String name) { + final ScriptingPanel panelCreated; + final String ext = FileUtil.getFileExtension(name, false); if (ext.contentEquals("py")) panelCreated = new ScriptingPanel(name, "Python", consoleOutput); else @@ -481,7 +398,7 @@ public class ScriptingEditor extends IcyFrame implements ActionListener tabbedPane.addTab("+", new JLabel()); tabbedPane.setTabComponentAt(idx + 1, addPanePanel); tabbedPane.setSelectedIndex(tabbedPane.getTabCount() - 2); - Insets i = addPanePanel.getInsets(); + final Insets i = addPanePanel.getInsets(); i.bottom = 0; i.left = 0; i.right = 0; @@ -491,38 +408,32 @@ public class ScriptingEditor extends IcyFrame implements ActionListener /** * Open the file f into the editor as a new tab. - * - * @param f - * the file to open - * @throws IOException - * if an error occurred while opening the file + * + * @param f the file to open + * @throws IOException if an error occurred while opening the file */ - public void openFile(File f) throws IOException - { + public void openFile(final File f) throws IOException { if (!f.exists()) return; - String filename = f.getName(); + final String filename = f.getName(); boolean exists = false; for (int i = 0; i < tabbedPane.getTabCount(); ++i) - if (tabbedPane.getTitleAt(i).contentEquals(filename)) - { + if (tabbedPane.getTitleAt(i).contentEquals(filename)) { tabbedPane.setSelectedIndex(i); exists = true; } - if (exists) - { + if (exists) { return; } - ScriptingPanel panel = createNewPane(filename); + final ScriptingPanel panel = createNewPane(filename); panel.openFile(f); addRecentFile(f); removeUntitledFirstPane(); saveEditorState(); } - private void removeUntitledFirstPane() - { + private void removeUntitledFirstPane() { // the user has chosen to open a file, // while the editor only has the default "Untitled" file opened. // remove that pane if it is really empty @@ -533,49 +444,34 @@ public class ScriptingEditor extends IcyFrame implements ActionListener if (tabbedPane.getTabCount() <= 2) return; - ScriptingPanel panel = (ScriptingPanel) tabbedPane.getComponentAt(0); - if (tabbedPane.getTitleAt(0).contentEquals("Untitled") && panel.getTextArea().getText().isEmpty() - && !panel.isDirty()) - { + final ScriptingPanel panel = (ScriptingPanel) tabbedPane.getComponentAt(0); + if (tabbedPane.getTitleAt(0).contentEquals("Untitled") && panel.getTextArea().getText().isEmpty() && !panel.isDirty()) { closeTab(0); } } - private void updateRecentFilesMenu() - { + private void updateRecentFilesMenu() { menuOpenRecent.removeAll(); - for (int i = 0; i < recentFiles.getFiles().size(); ++i) - { - String path = recentFiles.getFiles().get(i); - JMenuItem item = createRecentFileItem(path); - if (item != null) - { + for (int i = 0; i < recentFiles.getFiles().size(); ++i) { + final String path = recentFiles.getFiles().get(i); + final JMenuItem item = createRecentFileItem(path); + if (item != null) { menuOpenRecent.add(item); } } } - private JMenuItem createRecentFileItem(String filename) - { + private JMenuItem createRecentFileItem(final String filename) { final File f = new File(filename); JMenuItem toReturn = null; - if (f.exists()) - { + if (f.exists()) { toReturn = new JMenuItem(f.getName() + " - " + f.getParent()); - toReturn.addActionListener(new ActionListener() - { - - @Override - public void actionPerformed(ActionEvent e) - { - try - { - openFile(f); - } - catch (IOException e1) - { - e1.printStackTrace(); - } + toReturn.addActionListener(e -> { + try { + openFile(f); + } + catch (final IOException e1) { + e1.printStackTrace(); } }); } @@ -584,17 +480,13 @@ public class ScriptingEditor extends IcyFrame implements ActionListener /** * Open the file name into the editor as a new tab. - * - * @param tabName - * the name of the new tab - * @param stream - * the {@link InputStream} containing the script content - * @throws IOException - * if an error occurred while opening the file + * + * @param tabName the name of the new tab + * @param stream the {@link InputStream} containing the script content + * @throws IOException if an error occurred while opening the file */ - public void openStream(String tabName, InputStream stream) throws IOException - { - ScriptingPanel panel = createNewPane(tabName); + public void openStream(final String tabName, final InputStream stream) throws IOException { + final ScriptingPanel panel = createNewPane(tabName); panel.openStream(stream); removeUntitledFirstPane(); saveEditorState(); @@ -602,31 +494,26 @@ public class ScriptingEditor extends IcyFrame implements ActionListener /** * Displays a JFileChoose and let the user choose its file, then open it. - * + * * @see ScriptingEditor#openFile(File) */ - public void showOpenFileDialog() - { - JFileChooser fc; - if (currentDirectoryPath == "") + public void showOpenFileDialog() { + final JFileChooser fc; + if (currentDirectoryPath.equals("")) fc = new JFileChooser(); else fc = new JFileChooser(currentDirectoryPath); fc.setMultiSelectionEnabled(true); - if (fc.showOpenDialog(getFrame()) == JFileChooser.APPROVE_OPTION) - { - File[] files = fc.getSelectedFiles(); - for (File f : files) - { - String path = FileUtil.getDirectory(f.getAbsolutePath()); + if (fc.showOpenDialog(getFrame()) == JFileChooser.APPROVE_OPTION) { + final File[] files = fc.getSelectedFiles(); + for (final File f : files) { + final String path = FileUtil.getDirectory(f.getAbsolutePath()); currentDirectoryPath = path; prefs.put(STRING_LAST_DIRECTORY, path); - try - { + try { openFile(f); } - catch (IOException e) - { + catch (final IOException e) { new FailedAnnounceFrame(f.getName() + " is not a valid file"); } } @@ -636,268 +523,164 @@ public class ScriptingEditor extends IcyFrame implements ActionListener /** * @return the new created JMenuBar of the {@link ScriptingEditor}. */ - private JMenuBar createJMenuBar() - { - JMenuBar toReturn = new JMenuBar(); + private JMenuBar createJMenuBar() { + final JMenuBar toReturn = new JMenuBar(); // MENU FILE - JMenu menuFile = new JMenu("File"); - JMenuItem menuNew = new JMenuItem("New"); - menuNew.addActionListener(new ActionListener() - { - - @Override - public void actionPerformed(ActionEvent e) - { - createNewPane("Untitled"); - } - }); + final JMenu menuFile = new JMenu("File"); + final JMenuItem menuNew = new JMenuItem("New"); + menuNew.addActionListener(e -> createNewPane("Untitled")); menuFile.add(menuNew); - menuNew.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_N, ctrlMask)); + menuNew.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_N, InputEvent.CTRL_DOWN_MASK)); - JMenuItem menuOpen = new JMenuItem("Open..."); - menuOpen.addActionListener(new ActionListener() - { - - @Override - public void actionPerformed(ActionEvent e) - { - showOpenFileDialog(); - } - }); - menuOpen.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_O, ctrlMask)); + final JMenuItem menuOpen = new JMenuItem("Open..."); + menuOpen.addActionListener(e -> showOpenFileDialog()); + menuOpen.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_O, InputEvent.CTRL_DOWN_MASK)); menuOpen.setDisplayedMnemonicIndex(0); menuFile.add(menuOpen); menuOpenRecent = new JMenu("Open Recent"); menuFile.add(menuOpenRecent); - JMenuItem menuSave = new JMenuItem("Save"); - menuSave.addActionListener(new ActionListener() - { - @Override - public void actionPerformed(ActionEvent e) - { - Component comp = tabbedPane.getSelectedComponent(); - if (comp instanceof ScriptingPanel) - { - ScriptingPanel panel = ((ScriptingPanel) comp); - if (panel.isDirty()) - { - if (panel.getSaveFile() == null) - { - panel.showSaveFileDialog(currentDirectoryPath); - } - else - { - panel.saveFile(); - } + final JMenuItem menuSave = new JMenuItem("Save"); + menuSave.addActionListener(e -> { + final Component comp = tabbedPane.getSelectedComponent(); + if (comp instanceof ScriptingPanel) { + final ScriptingPanel panel = ((ScriptingPanel) comp); + if (panel.isDirty()) { + if (panel.getSaveFile() == null) { + panel.showSaveFileDialog(currentDirectoryPath); + } + else { + panel.saveFile(); } } } }); - menuSave.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_S, ctrlMask)); + menuSave.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_S, InputEvent.CTRL_DOWN_MASK)); menuFile.add(menuSave); - JMenuItem menuSaveAs = new JMenuItem("Save As..."); - menuSaveAs.addActionListener(new ActionListener() - { - - @Override - public void actionPerformed(ActionEvent e) - { - Component comp = tabbedPane.getSelectedComponent(); - if (comp instanceof ScriptingPanel) - { - ((ScriptingPanel) comp).showSaveFileDialog(currentDirectoryPath); - } + final JMenuItem menuSaveAs = new JMenuItem("Save As..."); + menuSaveAs.addActionListener(e -> { + final Component comp = tabbedPane.getSelectedComponent(); + if (comp instanceof ScriptingPanel) { + ((ScriptingPanel) comp).showSaveFileDialog(currentDirectoryPath); } }); - menuSaveAs.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_S, ctrlMask | InputEvent.SHIFT_DOWN_MASK)); + menuSaveAs.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_S, InputEvent.CTRL_DOWN_MASK | InputEvent.SHIFT_DOWN_MASK)); menuFile.add(menuSaveAs); menuFile.add(new JSeparator()); - JMenuItem menuClose = new JMenuItem("Close Tab"); - menuClose.addActionListener(new ActionListener() - { - - @Override - public void actionPerformed(ActionEvent e) - { - int i = tabbedPane.getSelectedIndex(); - if (i >= 0 && i < tabbedPane.getTabCount() - 1) - { - closeTab(i); - } + final JMenuItem menuClose = new JMenuItem("Close Tab"); + menuClose.addActionListener(e -> { + final int i = tabbedPane.getSelectedIndex(); + if (i >= 0 && i < tabbedPane.getTabCount() - 1) { + closeTab(i); } }); - menuClose.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_W, ctrlMask)); + menuClose.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_W, InputEvent.CTRL_DOWN_MASK)); menuFile.add(menuClose); - JMenuItem menuCloseAll = new JMenuItem("Close All Tabs"); - menuCloseAll.addActionListener(new ActionListener() - { - - @Override - public void actionPerformed(ActionEvent e) - { - closeAllTabs(); - } - }); + final JMenuItem menuCloseAll = new JMenuItem("Close All Tabs"); + menuCloseAll.addActionListener(e -> closeAllTabs()); menuFile.add(menuCloseAll); - JMenuItem menuCloseAllOthers = new JMenuItem("Close Other Tabs"); - menuCloseAllOthers.addActionListener(new ActionListener() - { - - @Override - public void actionPerformed(ActionEvent e) - { - int idx = tabbedPane.getSelectedIndex(); - int N = tabbedPane.getTabCount() - 1; - - ArrayList<Integer> tabsToClose = new ArrayList<Integer>(); - for (int i = 0; i < N; i++) - tabsToClose.add(i); - tabsToClose.remove(idx); - - // remove tabs in reverse order to not change the tab indexes on the way - ListIterator<Integer> iterator = tabsToClose.listIterator(tabsToClose.size()); - while (iterator.hasPrevious()) - { - if (!closeTab(iterator.previous())) - break; - } + final JMenuItem menuCloseAllOthers = new JMenuItem("Close Other Tabs"); + menuCloseAllOthers.addActionListener(e -> { + final int idx = tabbedPane.getSelectedIndex(); + final int N = tabbedPane.getTabCount() - 1; + + final ArrayList<Integer> tabsToClose = new ArrayList<>(); + for (int i = 0; i < N; i++) + tabsToClose.add(i); + tabsToClose.remove(idx); + + // remove tabs in reverse order to not change the tab indexes on the way + final ListIterator<Integer> iterator = tabsToClose.listIterator(tabsToClose.size()); + while (iterator.hasPrevious()) { + if (!closeTab(iterator.previous())) + break; } }); menuFile.add(menuCloseAllOthers); // MENU EDIT - JMenu menuEdit = new JMenu("Edit"); - JMenuItem menuUndo = new JMenuItem("Undo"); - menuUndo.addActionListener(new ActionListener() - { - - @Override - public void actionPerformed(ActionEvent e) - { - Component comp = tabbedPane.getTabComponentAt(0); - if (!(comp instanceof ScriptingPanel)) - return; - ScriptingPanel panel = (ScriptingPanel) comp; - panel.getTextArea().getActionForKeyStroke(KeyStroke.getKeyStroke(KeyEvent.VK_Z, ctrlMask)) - .actionPerformed(e); - } + final JMenu menuEdit = new JMenu("Edit"); + final JMenuItem menuUndo = new JMenuItem("Undo"); + menuUndo.addActionListener(e -> { + final Component comp = tabbedPane.getTabComponentAt(0); + if (!(comp instanceof ScriptingPanel)) + return; + final ScriptingPanel panel = (ScriptingPanel) comp; + panel.getTextArea().getActionForKeyStroke(KeyStroke.getKeyStroke(KeyEvent.VK_Z, InputEvent.CTRL_DOWN_MASK)) + .actionPerformed(e); }); - menuUndo.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_Z, ctrlMask)); + menuUndo.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_Z, InputEvent.CTRL_DOWN_MASK)); menuEdit.add(menuUndo); - JMenuItem menuRedo = new JMenuItem("Redo"); - menuRedo.addActionListener(new ActionListener() - { - - @Override - public void actionPerformed(ActionEvent e) - { - Component comp = tabbedPane.getTabComponentAt(0); - if (!(comp instanceof ScriptingPanel)) - return; - ScriptingPanel panel = (ScriptingPanel) comp; - panel.getTextArea().getActionForKeyStroke(KeyStroke.getKeyStroke(KeyEvent.VK_Y, ctrlMask)) - .actionPerformed(e); - } + final JMenuItem menuRedo = new JMenuItem("Redo"); + menuRedo.addActionListener(e -> { + final Component comp = tabbedPane.getTabComponentAt(0); + if (!(comp instanceof ScriptingPanel)) + return; + final ScriptingPanel panel = (ScriptingPanel) comp; + panel.getTextArea().getActionForKeyStroke(KeyStroke.getKeyStroke(KeyEvent.VK_Y, InputEvent.CTRL_DOWN_MASK)) + .actionPerformed(e); }); - menuRedo.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_Y, ctrlMask)); + menuRedo.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_Y, InputEvent.CTRL_DOWN_MASK)); menuEdit.add(menuRedo); menuEdit.add(new JSeparator()); - JMenuItem menuFormat = new JMenuItem("Format"); - menuFormat.addActionListener(new ActionListener() - { - - @Override - public void actionPerformed(ActionEvent e) - { - Component c = tabbedPane.getSelectedComponent(); - if (c instanceof ScriptingPanel) - { - ScriptingPanel panel = ((ScriptingPanel) c); - panel.format(); - } + final JMenuItem menuFormat = new JMenuItem("Format"); + menuFormat.addActionListener(e -> { + final Component c = tabbedPane.getSelectedComponent(); + if (c instanceof ScriptingPanel) { + final ScriptingPanel panel = ((ScriptingPanel) c); + panel.format(); } }); - menuFormat.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_F, ctrlMask | InputEvent.SHIFT_DOWN_MASK)); + menuFormat.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_F, InputEvent.CTRL_DOWN_MASK | InputEvent.SHIFT_DOWN_MASK)); menuEdit.add(menuFormat); - JMenuItem menuAutoImport = new JMenuItem("Auto-Import"); - menuAutoImport.addActionListener(new ActionListener() - { - - @Override - public void actionPerformed(ActionEvent e) - { - // TODO - // parse the text, look for an Unknown - // if it starts by a Capital letter, try to load it - // if multiple choices, do nothing for now - Component c = tabbedPane.getSelectedComponent(); - if (c instanceof ScriptingPanel) - { - ScriptingPanel panel = ((ScriptingPanel) c); - panel.getScriptHandler().autoImport(); - } + final JMenuItem menuAutoImport = new JMenuItem("Auto-Import"); + menuAutoImport.addActionListener(e -> { + // TODO + // parse the text, look for an Unknown + // if it starts by a Capital letter, try to load it + // if multiple choices, do nothing for now + final Component c = tabbedPane.getSelectedComponent(); + if (c instanceof ScriptingPanel) { + final ScriptingPanel panel = ((ScriptingPanel) c); + panel.getScriptHandler().autoImport(); } }); menuEdit.add(menuAutoImport); menuEdit.add(new JSeparator()); // FIND FEATURE - JMenuItem menuFind = new JMenuItem("Find"); - menuFind.addActionListener(new ActionListener() - { - - @Override - public void actionPerformed(ActionEvent e) - { - displayFindReplace(); - } - }); - menuFind.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_F, ctrlMask)); + final JMenuItem menuFind = new JMenuItem("Find"); + menuFind.addActionListener(e -> displayFindReplace()); + menuFind.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_F, InputEvent.CTRL_DOWN_MASK)); // menuFind.setEnabled(false); menuEdit.add(menuFind); // REPLACE FEATURE - JMenuItem menuReplace = new JMenuItem("Replace"); - menuReplace.addActionListener(new ActionListener() - { - - @Override - public void actionPerformed(ActionEvent e) - { - displayFindReplace(); - } - }); - menuReplace.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_H, ctrlMask)); + final JMenuItem menuReplace = new JMenuItem("Replace"); + menuReplace.addActionListener(e -> displayFindReplace()); + menuReplace.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_H, InputEvent.CTRL_DOWN_MASK)); // menuReplace.setEnabled(false); menuEdit.add(menuReplace); // GOTO LINE FEATURE - JMenuItem menuGotoLine = new JMenuItem("Go to Line..."); - menuGotoLine.addActionListener(new ActionListener() - { - - @Override - public void actionPerformed(ActionEvent e) - { - Component c = tabbedPane.getSelectedComponent(); - if (c instanceof ScriptingPanel) - { - ((ScriptingPanel) c).displayGotoLine(); - } + final JMenuItem menuGotoLine = new JMenuItem("Go to Line..."); + menuGotoLine.addActionListener(e -> { + final Component c = tabbedPane.getSelectedComponent(); + if (c instanceof ScriptingPanel) { + ((ScriptingPanel) c).displayGotoLine(); } }); - menuGotoLine.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_L, ctrlMask)); + menuGotoLine.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_L, InputEvent.CTRL_DOWN_MASK)); menuEdit.add(menuGotoLine); // JMenu menuTools = new JMenu("Tools"); @@ -905,50 +688,28 @@ public class ScriptingEditor extends IcyFrame implements ActionListener // menuTools.add(menuFindClass); // MENU TEMPLATES - JMenu menuTemplate = new JMenu("Templates"); + final JMenu menuTemplate = new JMenu("Templates"); populateMenuTemplate(menuTemplate); - JMenu menuOptions = new JMenu("Options"); - JMenuItem menuPreferences = new JMenuItem("Preferences"); - menuPreferences.addActionListener(new ActionListener() - { - @Override - public void actionPerformed(ActionEvent e) - { - final PreferencesWindow prefs = PreferencesWindow.getPreferencesWindow(); - prefs.addToDesktopPane(); - prefs.setVisible(true); - } + final JMenu menuOptions = new JMenu("Options"); + final JMenuItem menuPreferences = new JMenuItem("Preferences"); + menuPreferences.addActionListener(e -> { + final PreferencesWindow prefs = PreferencesWindow.getPreferencesWindow(); + prefs.addToDesktopPane(); + prefs.setVisible(true); }); menuOptions.add(menuPreferences); - JMenuItem menuBindingsFrame = new JMenuItem("Bindings Frame"); - menuBindingsFrame.addActionListener(new ActionListener() - { - - @Override - public void actionPerformed(ActionEvent e) - { - BindingsScriptFrame frame = BindingsScriptFrame.getInstance(); - frame.update(); - if (frame.isVisible()) - frame.setVisible(false); - else - frame.setVisible(true); - } + final JMenuItem menuBindingsFrame = new JMenuItem("Bindings Frame"); + menuBindingsFrame.addActionListener(e -> { + final BindingsScriptFrame frame = BindingsScriptFrame.getInstance(); + frame.update(); + frame.setVisible(!frame.isVisible()); }); menuOptions.add(menuBindingsFrame); - JMenuItem menuHelp = new JMenuItem("Help (online)"); - menuHelp.addActionListener(new ActionListener() - { - - @Override - public void actionPerformed(ActionEvent arg0) - { - NetworkUtil.openBrowser("http://icy.bioimageanalysis.org/plugin/Script_Editor#documentation"); - } - }); + final JMenuItem menuHelp = new JMenuItem("Help (online)"); + menuHelp.addActionListener(arg0 -> NetworkUtil.openBrowser("https://icy.bioimageanalysis.org/plugin/script-editor/")); menuOptions.add(menuHelp); toReturn.add(menuFile); @@ -965,8 +726,7 @@ public class ScriptingEditor extends IcyFrame implements ActionListener return toReturn; } - public void displayFindReplace() - { + public void displayFindReplace() { FindAndReplaceDialog.showDialog(this); } @@ -976,19 +736,16 @@ public class ScriptingEditor extends IcyFrame implements ActionListener * * @return false if the operation is cancelled. */ - private boolean closeAllTabs() - { + private boolean closeAllTabs() { boolean ok = true; // number of files opened - int N = tabbedPane.getTabCount() - 1; + final int N = tabbedPane.getTabCount() - 1; // close all tabs // Note: do not use a while loop on getTabCount() here, it could loop // indefinitely in case of a coding error involving the '+' tab... - for (int i = 0; i < N; i++) - { - if (!closeTab(0)) - { + for (int i = 0; i < N; i++) { + if (!closeTab(0)) { ok = false; break; } @@ -997,41 +754,32 @@ public class ScriptingEditor extends IcyFrame implements ActionListener return ok; } - protected boolean closeTab(final int i) - { - Component c = tabbedPane.getTabComponentAt(i); + protected boolean closeTab(final int i) { + final Component c = tabbedPane.getTabComponentAt(i); - if (c instanceof TabComponentButton) - { - ScriptingPanel panel = ((TabComponentButton) c).getPanel(); - boolean ok = panel.close(); + if (c instanceof TabComponentButton) { + final ScriptingPanel panel = ((TabComponentButton) c).getPanel(); + final boolean ok = panel.close(); - if (ok) - { + if (ok) { panel.removeSavedAsListener(savedAsListener); panel.removeTitleChangedListener(titleChangedListener); panel.removeFileDropListeners(); panel.removeHyperlinkListener(hyperlinkListener); panel.removeLanguageListener(languageListener); - ThreadUtil.invokeLater(new Runnable() - { - @Override - public void run() - { - if (i == tabbedPane.getSelectedIndex() && i >= (tabbedPane.getTabCount() - 2)) - { - // We are closing the last tab. - // The next one is the virtual tab used a "plus" button to open a new tab. - // We want to avoid selecting that tab artificially, - // so go to the previous one. - tabbedPane.setSelectedIndex(i - 1); - } - - // remove the tab - if (i != -1) - tabbedPane.remove(i); + ThreadUtil.invokeLater(() -> { + if (i == tabbedPane.getSelectedIndex() && i >= (tabbedPane.getTabCount() - 2)) { + // We are closing the last tab. + // The next one is the virtual tab used a "plus" button to open a new tab. + // We want to avoid selecting that tab artificially, + // so go to the previous one. + tabbedPane.setSelectedIndex(i - 1); } + + // remove the tab + if (i != -1) + tabbedPane.remove(i); }); saveEditorState(); @@ -1043,56 +791,32 @@ public class ScriptingEditor extends IcyFrame implements ActionListener return true; } - protected boolean closeTab(TabComponentButton tabComponent) - { - int i = tabbedPane.indexOfTabComponent(tabComponent); + protected boolean closeTab(final TabComponentButton tabComponent) { + final int i = tabbedPane.indexOfTabComponent(tabComponent); return closeTab(i); } /** * Hard coded function populating the templates. May change to an automatic * parsing of files. - * + * * @param menuTemplate */ - private void populateMenuTemplate(JMenu menuTemplate) - { - JMenu menuTemplateJS = new JMenu("JavaScript"); - JMenuItem itemJSDuplicateSequence = new JMenuItem("Duplicate Sequence"); - - itemJSDuplicateSequence.addActionListener(new ActionListener() - { - @Override - public void actionPerformed(ActionEvent e) - { - openJSTemplate("duplicateSequence.js"); - } - }); + private void populateMenuTemplate(final JMenu menuTemplate) { + final JMenu menuTemplateJS = new JMenu("JavaScript"); + final JMenuItem itemJSDuplicateSequence = new JMenuItem("Duplicate Sequence"); + + itemJSDuplicateSequence.addActionListener(e -> openJSTemplate("duplicateSequence.js")); menuTemplateJS.add(itemJSDuplicateSequence); - JMenuItem itemThreshold = new JMenuItem("Threshold"); - itemThreshold.addActionListener(new ActionListener() - { - @Override - public void actionPerformed(ActionEvent e) - { - openJSTemplate("threshold.js"); - } - }); + final JMenuItem itemThreshold = new JMenuItem("Threshold"); + itemThreshold.addActionListener(e -> openJSTemplate("threshold.js")); menuTemplateJS.add(itemThreshold); - JMenu menuTemplatePython = new JMenu("Python"); - JMenuItem itemPythonDuplicateSequence = new JMenuItem("Duplicate Sequence"); - - itemPythonDuplicateSequence.addActionListener(new ActionListener() - { + final JMenu menuTemplatePython = new JMenu("Python"); + final JMenuItem itemPythonDuplicateSequence = new JMenuItem("Duplicate Sequence"); - @Override - public void actionPerformed(ActionEvent e) - { - openPythonTemplate("duplicateSequence.py"); - } - }); + itemPythonDuplicateSequence.addActionListener(e -> openPythonTemplate("duplicateSequence.py")); menuTemplatePython.add(itemPythonDuplicateSequence); // add JS templates. @@ -1101,52 +825,43 @@ public class ScriptingEditor extends IcyFrame implements ActionListener menuTemplate.add(menuTemplatePython); } - private void openJSTemplate(String templateName) - { + private void openJSTemplate(final String templateName) { openTemplate("js", templateName); } - private void openPythonTemplate(String templateName) - { + private void openPythonTemplate(final String templateName) { openTemplate("python", templateName); } /** * Open a template file contained in * plugins/tprovoost/scripteditor/templates/" + type + "/" + templateName - * + * * @param type * @param templateName */ - private void openTemplate(String type, String templateName) - { - String current = new File(".").getAbsolutePath(); - current = current.substring(0, current.length() - 1); - try - { - InputStream is = PluginLoader.getResourceAsStream( - "plugins/tprovoost/scripteditor/resources/templates/" + type + "/" + templateName); + private void openTemplate(final String type, final String templateName) { + //String current = new File(".").getAbsolutePath(); + //current = current.substring(0, current.length() - 1); + try { + final InputStream is = PluginLoader.getResourceAsStream("plugins/tprovoost/scripteditor/resources/templates/" + type + "/" + templateName); openStream(templateName, is); } - catch (IOException e1) - { + catch (final IOException e) { + IcyExceptionHandler.showErrorMessage(e, true); } } - public String getCurrentDirectory() - { + public String getCurrentDirectory() { return currentDirectoryPath; } - public void changeConsoleLanguage(String language) - { + public void changeConsoleLanguage(final String language) { // the Console uses the same engine but another script handler - if (language.contentEquals("Python")) - { + if (language.contentEquals("Python")) { console = new PythonScriptingconsole(); } - else - { + else { console = new Scriptingconsole(); } @@ -1158,8 +873,7 @@ public class ScriptingEditor extends IcyFrame implements ActionListener // not a good idea to fix the FONT // console.setFont(consoleOutput.getTextPane().getFont()); - if (panelSouth != null) - { + if (panelSouth != null) { panelSouth.removeAll(); panelSouth.add(console, BorderLayout.CENTER); panelSouth.add(btnClearConsole, BorderLayout.EAST); @@ -1168,31 +882,26 @@ public class ScriptingEditor extends IcyFrame implements ActionListener } @Override - public void actionPerformed(ActionEvent e) - { - if (e.getSource() == btnClearConsole) - { + public void actionPerformed(final ActionEvent e) { + if (e.getSource() == btnClearConsole) { if (console != null) console.clear(); } } - public void addRecentFile(File f) - { + public void addRecentFile(final File f) { recentFiles.add(f); updateRecentFilesMenu(); } - public static String getDefaultFolder() - { + public static String getDefaultFolder() { return ""; } /** * @return the consoleOutput */ - public ConsoleOutput getConsoleOutput() - { + public ConsoleOutput getConsoleOutput() { return consoleOutput; } } \ No newline at end of file diff --git a/src/main/java/plugins/tprovoost/scripteditor/gui/ScriptingPanel.java b/src/main/java/plugins/tprovoost/scripteditor/gui/ScriptingPanel.java index 78e155372cc818d52f45a8aed2e1063d4e335f43..126fc03c5e8b47c7973bd856663df03f237ccae5 100644 --- a/src/main/java/plugins/tprovoost/scripteditor/gui/ScriptingPanel.java +++ b/src/main/java/plugins/tprovoost/scripteditor/gui/ScriptingPanel.java @@ -1,7 +1,6 @@ package plugins.tprovoost.scripteditor.gui; import java.awt.BorderLayout; -import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.ItemEvent; import java.awt.event.ItemListener; @@ -26,14 +25,11 @@ import javax.swing.JTextArea; import javax.swing.event.DocumentEvent; import javax.swing.event.DocumentListener; import javax.swing.event.EventListenerList; -import javax.swing.event.HyperlinkEvent; import javax.swing.event.HyperlinkListener; import javax.swing.filechooser.FileNameExtensionFilter; import javax.swing.text.BadLocationException; -import org.fife.ui.autocomplete.Completion; -import org.fife.ui.autocomplete.DescWindowCallback; -import org.fife.ui.autocomplete.ExternalURLHandler; +import icy.system.IcyExceptionHandler; import org.fife.ui.rsyntaxtextarea.RSyntaxTextArea; import org.fife.ui.rsyntaxtextarea.SyntaxConstants; import org.fife.ui.rsyntaxtextarea.Theme; @@ -74,48 +70,45 @@ import plugins.tprovoost.scripteditor.scriptinghandlers.ScriptingHandler; import plugins.tprovoost.scripteditor.scriptinghandlers.js.JSScriptingHandlerRhino; import plugins.tprovoost.scripteditor.scriptinghandlers.py.PythonScriptingHandler; -// import plugins.tprovoost.scripteditor.main.scriptinghandlers.JSScriptingHandler7; - -public class ScriptingPanel extends JPanel implements ScriptListener -{ - /** */ - private static final long serialVersionUID = 1L; - +public class ScriptingPanel extends JPanel implements ScriptListener { private ScriptingHandler scriptHandler; - private RSyntaxTextArea textArea; - private RTextScrollPane pane; - private CommandPanel options; + private final RSyntaxTextArea textArea; + private final RTextScrollPane pane; + private final CommandPanel options; private String panelName; private String saveFileString = ""; - /** Default file used to save the content into */ + /** + * Default file used to save the content into + */ private File saveFile = null; - /** Provider used for auto-completion. */ + /** + * Provider used for auto-completion. + */ private IcyCompletionProvider provider; - /** Auto-completion system. Uses provider item. */ + /** + * Auto-completion system. Uses provider item. + */ private IcyAutoCompletion ac; - private ConsoleOutput consoleOutput; // may be null ! - private boolean integrated; + private final ConsoleOutput consoleOutput; // may be null ! + private final boolean integrated; /** * This listener is called when there are changes applied in the preferences * window. It applies the preferences to the opened ScriptingPanels. */ - private PreferencesListener applyPrefsListener = new PreferencesListener() - { + private final PreferencesListener applyPrefsListener = new PreferencesListener() { @Override - public void preferencesChanged() - { - Preferences preferences = Preferences.getPreferences(); + public void preferencesChanged() { + final Preferences preferences = Preferences.getPreferences(); textArea.setTabsEmulated(preferences.isSoftTabsEnabled()); textArea.setTabSize(preferences.indentSpacesCount()); textArea.setFont(FontUtil.setSize(textArea.getFont(), preferences.getFontSize())); - if (consoleOutput != null) - { + if (consoleOutput != null) { consoleOutput.textPane .setFont(FontUtil.setSize(consoleOutput.textPane.getFont(), preferences.getFontSize())); } @@ -123,57 +116,24 @@ public class ScriptingPanel extends JPanel implements ScriptListener }; // listen to changes of language in a child panel - private ItemListener languageListener = new ItemListener() - { - - @Override - public void itemStateChanged(ItemEvent e) - { - if (e.getStateChange() == ItemEvent.SELECTED) - { - String language = (String) e.getItem(); - installLanguage(language); - } + private final ItemListener languageListener = e -> { + if (e.getStateChange() == ItemEvent.SELECTED) { + String language = (String) e.getItem(); + installLanguage(language); } }; - private ActionListener runInNewListener = new ActionListener() - { - - @Override - public void actionPerformed(ActionEvent e) - { - runInNew(); - } - }; + private final ActionListener runInNewListener = e -> runInNew(); - private ActionListener runInSameListener = new ActionListener() - { - - @Override - public void actionPerformed(ActionEvent e) - { - runInSame(); - } - }; + private final ActionListener runInSameListener = e -> runInSame(); - private ActionListener stopListener = new ActionListener() - { + private final ActionListener stopListener = e -> stopScript(); - @Override - public void actionPerformed(ActionEvent e) - { - stopScript(); - } - }; - - public ScriptingPanel(String name, String language) - { + public ScriptingPanel(final String name, final String language) { this(name, language, true, null); } - public ScriptingPanel(String name, String language, ConsoleOutput consoleOutput) - { + public ScriptingPanel(final String name, final String language, final ConsoleOutput consoleOutput) { this(name, language, false, consoleOutput); } @@ -181,18 +141,13 @@ public class ScriptingPanel extends JPanel implements ScriptListener * Creates a panel for scripting, using an {@link RSyntaxTextArea} for the text * and {@link Gutter} to display line numbers and errors. Error is shown in the * output window as a {@link JTextArea} in a {@link JScrollPane}. - * - * @param name - * panel name - * @param language - * panel name - * @param integrated - * integrated state - * @param consoleOutput - * the output console used for this panel + * + * @param name panel name + * @param language panel name + * @param integrated integrated state + * @param consoleOutput the output console used for this panel */ - public ScriptingPanel(String name, String language, boolean integrated, ConsoleOutput consoleOutput) - { + public ScriptingPanel(final String name, final String language, final boolean integrated, final ConsoleOutput consoleOutput) { this.panelName = name; this.integrated = integrated; this.consoleOutput = consoleOutput; @@ -213,34 +168,20 @@ public class ScriptingPanel extends JPanel implements ScriptListener textArea.setPaintMatchedBracketPair(true); textArea.setPaintTabLines(true); textArea.setTabsEmulated(false); - textArea.addHyperlinkListener(new HyperlinkListener() - { - - @Override - public void hyperlinkUpdate(HyperlinkEvent e) - { - NetworkUtil.openBrowser(e.getURL()); - } - - }); - textArea.getDocument().addDocumentListener(new DocumentListener() - { - + textArea.addHyperlinkListener(e -> NetworkUtil.openBrowser(e.getURL())); + textArea.getDocument().addDocumentListener(new DocumentListener() { @Override - public void removeUpdate(DocumentEvent arg0) - { + public void removeUpdate(final DocumentEvent e) { updateTitle(); } @Override - public void insertUpdate(DocumentEvent arg0) - { + public void insertUpdate(final DocumentEvent e) { updateTitle(); } @Override - public void changedUpdate(DocumentEvent arg0) - { + public void changedUpdate(final DocumentEvent e) { // this is fired when the style changes // ignore } @@ -271,78 +212,61 @@ public class ScriptingPanel extends JPanel implements ScriptListener /** * @return the provider */ - public IcyCompletionProvider getProvider() - { + public IcyCompletionProvider getProvider() { return provider; } /** * Setter for the provider. - * - * @param provider - * provider + * + * @param provider provider */ - public void setProvider(IcyCompletionProvider provider) - { + public void setProvider(final IcyCompletionProvider provider) { this.provider = provider; } - public RSyntaxTextArea getTextArea() - { + public RSyntaxTextArea getTextArea() { return textArea; } - public RTextScrollPane getPane() - { + public RTextScrollPane getPane() { return pane; } - public String getPanelName() - { + public String getPanelName() { return panelName; } - public void setSyntax(String syntaxType) - { + public void setSyntax(final String syntaxType) { textArea.setSyntaxEditingStyle(syntaxType); } /** * Install the wanted theme. - * - * @param s - * theme name + * + * @param s theme name */ - public void setTheme(String s) - { - try - { - Theme t = Theme.load(PluginLoader.getLoader() - .getResourceAsStream("plugins/tprovoost/scripteditor/resources/themes/" + s + ".xml")); + public void setTheme(final String s) { + try { + final Theme t = Theme.load(PluginLoader.getLoader().getResourceAsStream("plugins/tprovoost/scripteditor/resources/themes/" + s + ".xml")); t.apply(textArea); } - catch (IOException e) - { + catch (final IOException e) { System.out.println("Couldn't load theme"); } } /** * Save the data into the file f. - * - * @param f - * file where to save data + * + * @param f file where to save data * @return success state */ - public boolean saveFileAs(File f) - { - if (f != null) - { - BufferedWriter writer = null; - try - { - String s = textArea.getText(); - writer = new BufferedWriter(new FileWriter(f)); + public boolean saveFileAs(final File f) { + if (f != null) { + try { + final String s = textArea.getText(); + final BufferedWriter writer = new BufferedWriter(new FileWriter(f)); writer.write(s); writer.close(); saveFile = f; @@ -353,8 +277,7 @@ public class ScriptingPanel extends JPanel implements ScriptListener fireSavedAs(f); return true; } - catch (IOException e) - { + catch (final IOException e) { new FailedAnnounceFrame(e.getLocalizedMessage()); return false; } @@ -364,60 +287,49 @@ public class ScriptingPanel extends JPanel implements ScriptListener // listener used to propagate the "Saved As" action up to the editor // without making the ScriptingPanel dependent on the editor - public static interface SavedAsListener extends EventListener - { + public interface SavedAsListener extends EventListener { void savedAs(File f); } private final EventListenerList savedAslisteners = new EventListenerList(); - public void addSavedAsListener(SavedAsListener listener) - { + public void addSavedAsListener(final SavedAsListener listener) { savedAslisteners.add(SavedAsListener.class, listener); } - public void removeSavedAsListener(SavedAsListener listener) - { + public void removeSavedAsListener(final SavedAsListener listener) { savedAslisteners.remove(SavedAsListener.class, listener); } - protected void fireSavedAs(File f) - { - for (SavedAsListener listener : getSavedAsListeners()) - { + protected void fireSavedAs(final File f) { + for (final SavedAsListener listener : getSavedAsListeners()) { listener.savedAs(f); } } - public SavedAsListener[] getSavedAsListeners() - { + public SavedAsListener[] getSavedAsListeners() { return savedAslisteners.getListeners(SavedAsListener.class); } /** * Save the file is dirty. Returns true if success or not dirty. - * + * * @return success state */ - public boolean saveFile() - { + public boolean saveFile() { if (!isDirty()) return true; - if (saveFile != null) - { - BufferedWriter writer = null; - try - { - String s = textArea.getText(); - writer = new BufferedWriter(new FileWriter(saveFile)); + if (saveFile != null) { + try { + final String s = textArea.getText(); + final BufferedWriter writer = new BufferedWriter(new FileWriter(saveFile)); writer.write(s); writer.close(); saveFileString = s; updateTitle(); return true; } - catch (IOException e) - { + catch (final IOException e) { new FailedAnnounceFrame(e.getLocalizedMessage()); return false; } @@ -427,58 +339,47 @@ public class ScriptingPanel extends JPanel implements ScriptListener /** * Displays a JFileChoose and let the user choose its file, then open it. - * - * @param currentDirectoryPath - * current directory + * + * @param currentDirectoryPath current directory * @return <code>true</code> if the operation succeed * @see ScriptingEditor#openFile(File) */ - public boolean showSaveFileDialog(String currentDirectoryPath) - { + public boolean showSaveFileDialog(final String currentDirectoryPath) { return showSaveFileDialog(currentDirectoryPath, panelName); } /** * Displays a JFileChoose and let the user choose its file, then open it. - * - * @param currentDirectoryPath - * current directory - * @param defaultName - * default file name + * + * @param currentDirectoryPath current directory + * @param defaultName default file name * @return <code>true</code> if the operation succeed * @see ScriptingEditor#openFile(File) */ - public boolean showSaveFileDialog(String currentDirectoryPath, String defaultName) - { + public boolean showSaveFileDialog(final String currentDirectoryPath, final String defaultName) { final JFileChooser fc; - if (currentDirectoryPath == "") + if (currentDirectoryPath.equals("")) fc = new JFileChooser(); else fc = new JFileChooser(currentDirectoryPath); - if (getLanguage().contentEquals("JavaScript")) - { + if (getLanguage().contentEquals("JavaScript")) { fc.setFileFilter(new FileNameExtensionFilter("Javascript files", "js")); } - else if (getLanguage().contentEquals("Python")) - { + else if (getLanguage().contentEquals("Python")) { fc.setFileFilter(new FileNameExtensionFilter("Python files", "py")); } - fc.addKeyListener(new KeyAdapter() - { + fc.addKeyListener(new KeyAdapter() { @Override - public void keyPressed(KeyEvent e) - { + public void keyPressed(final KeyEvent e) { fc.accept(fc.getSelectedFile()); fc.removeKeyListener(this); } }); if (!defaultName.isEmpty()) fc.setSelectedFile(new File(defaultName)); - if (fc.showSaveDialog(Icy.getMainInterface().getMainFrame()) == JFileChooser.APPROVE_OPTION) - { + if (fc.showSaveDialog(Icy.getMainInterface().getMainFrame()) == JFileChooser.APPROVE_OPTION) { File file = fc.getSelectedFile(); - if (FileUtil.getFileExtension(file.getAbsolutePath(), false).isEmpty()) - { + if (FileUtil.getFileExtension(file.getAbsolutePath(), false).isEmpty()) { file = addExtension(file); } return saveFileAs(file); @@ -486,14 +387,11 @@ public class ScriptingPanel extends JPanel implements ScriptListener return false; } - private File addExtension(File file) - { - if (getLanguage().contentEquals("JavaScript")) - { + private File addExtension(final File file) { + if (getLanguage().contentEquals("JavaScript")) { return new File(file.getAbsolutePath() + ".js"); } - else if (getLanguage().contentEquals("Python")) - { + else if (getLanguage().contentEquals("Python")) { return new File(file.getAbsolutePath() + ".py"); } return file; @@ -501,39 +399,32 @@ public class ScriptingPanel extends JPanel implements ScriptListener // listener used to propagate the "Saved As" action up to the editor // without making the ScriptingPanel dependent on the editor - public static interface TitleChangedListener extends EventListener - { + public interface TitleChangedListener extends EventListener { void titleChanged(ScriptingPanel panel, String title); } private final EventListenerList titleChangedListeners = new EventListenerList(); - public void addTitleChangedListener(TitleChangedListener listener) - { + public void addTitleChangedListener(final TitleChangedListener listener) { titleChangedListeners.add(TitleChangedListener.class, listener); } - public void removeTitleChangedListener(TitleChangedListener listener) - { + public void removeTitleChangedListener(final TitleChangedListener listener) { titleChangedListeners.remove(TitleChangedListener.class, listener); } - protected void fireTitleChanged(String title) - { - for (TitleChangedListener listener : getTitleChangedListeners()) - { + protected void fireTitleChanged(final String title) { + for (final TitleChangedListener listener : getTitleChangedListeners()) { listener.titleChanged(this, title); } } - public TitleChangedListener[] getTitleChangedListeners() - { + public TitleChangedListener[] getTitleChangedListeners() { return titleChangedListeners.getListeners(TitleChangedListener.class); } - private void updateTitle() - { - String title; + private void updateTitle() { + final String title; if (isDirty()) title = panelName + "*"; else @@ -545,14 +436,11 @@ public class ScriptingPanel extends JPanel implements ScriptListener * Try to close this ScriptingPanel. The user will be asked whether to save the * files if they are modified. If the operation is not cancelled, the listeners * are removed. - * - * @param defaultSaveDirectory - * Default directory used if a file need to be saved + * * @return false is the close operation is cancelled */ - boolean close() - { - boolean canClose; + boolean close() { + final boolean canClose; if (isDirty()) canClose = ConfirmDialog.confirm( @@ -560,8 +448,7 @@ public class ScriptingPanel extends JPanel implements ScriptListener else canClose = true; - if (canClose) - { + if (canClose) { cleanup(); PreferencesWindow.getPreferencesWindow().removePreferencesListener(applyPrefsListener); options.removeLanguageListener(languageListener); @@ -577,19 +464,16 @@ public class ScriptingPanel extends JPanel implements ScriptListener /** * Removes the script listeners, release completion objects... */ - void cleanup() - { + void cleanup() { // Autocompletion is done with the following item - if (scriptHandler != null) - { + if (scriptHandler != null) { scriptHandler.stopThreads(); scriptHandler.removeScriptListener(this); textArea.removeKeyListener(scriptHandler); PluginRepositoryLoader.removeListener(scriptHandler); } - if (ac != null) - { + if (ac != null) { ac.uninstall(); } } @@ -597,84 +481,44 @@ public class ScriptingPanel extends JPanel implements ScriptListener /** * Install the wanted language in the text area: creates the provider and its * default auto-complete words. - * - * @param language - * javascript / ruby / python / etc. + * + * @param language javascript / ruby / python / etc. */ - public synchronized void installLanguage(final String language) - { + public synchronized void installLanguage(final String language) { final Preferences preferences = Preferences.getPreferences(); cleanup(); - + // the provider provides the results when hitting Ctrl + Space. - if (provider == null) - { - if (StringUtil.equals(language, "Python")) - { + if (provider == null) { + if (StringUtil.equals(language, "Python")) { provider = new IcyCompletionProviderPython(); } - else - { + else { provider = new IcyCompletionProvider(); } - boolean autoActivate = preferences.isFullAutoCompleteEnabled(); + final boolean autoActivate = preferences.isFullAutoCompleteEnabled(); provider.setAutoActivationRules(autoActivate, "."); - ThreadUtil.invokeLater(new Runnable() - { - - @Override - public void run() - { - provider.setListCellRenderer(new IcyCompletionCellRenderer()); - } - }); + ThreadUtil.invokeLater(() -> provider.setListCellRenderer(new IcyCompletionCellRenderer())); } provider.clear(); // set the syntax - if (StringUtil.equals(language, "JavaScript")) - { + if (StringUtil.equals(language, "JavaScript")) { // setSyntax(SyntaxConstants.SYNTAX_STYLE_JAVA); setSyntax(SyntaxConstants.SYNTAX_STYLE_JAVASCRIPT); ac = new JSAutoCompletion(provider); - ThreadUtil.invokeLater(new Runnable() - { - - @Override - public void run() - { - options.setRunButtonsEnabled(true); - } - }); + ThreadUtil.invokeLater(() -> options.setRunButtonsEnabled(true)); } - else if (StringUtil.equals(language, "Python")) - { + else if (StringUtil.equals(language, "Python")) { setSyntax(SyntaxConstants.SYNTAX_STYLE_PYTHON); ac = new PythonAutoCompletion(provider); - ThreadUtil.invokeLater(new Runnable() - { - - @Override - public void run() - { - options.setRunButtonsEnabled(true); - } - }); + ThreadUtil.invokeLater(() -> options.setRunButtonsEnabled(true)); } - else - { + else { setSyntax(SyntaxConstants.SYNTAX_STYLE_NONE); new AnnounceFrame("This language is not yet supported."); - ThreadUtil.invokeLater(new Runnable() - { - - @Override - public void run() - { - options.setRunButtonsEnabled(false); - } - }); + ThreadUtil.invokeLater(() -> options.setRunButtonsEnabled(false)); return; } @@ -688,123 +532,98 @@ public class ScriptingPanel extends JPanel implements ScriptListener ac.setAutoActivationEnabled(true); ac.setAutoActivationDelay(500); ac.setShowDescWindow(true); - ac.setExternalURLHandler(new ExternalURLHandler() - { - @Override - public void urlClicked(HyperlinkEvent e, Completion c, DescWindowCallback callback) - { - if (e.getDescription().contentEquals("SourceCodeLink")) - { - Class<?> clazz = null; - if (c instanceof BasicJavaClassCompletion) - { - clazz = ((BasicJavaClassCompletion) c).getJavaClass(); - openSource(clazz); - } - else if (c instanceof ScriptFunctionCompletion) - { - ScriptFunctionCompletion sfc = (ScriptFunctionCompletion) c; - Method m = sfc.getMethod(); - clazz = m.getDeclaringClass(); - final ClassSource cs = ClassSource.getClassSource(clazz); - MethodDeclaration md = cs.getMethods().get(m.toGenericString()); - openSource(clazz, md.getBeginLine() - 1, md.getEndLine() - 1); - } - else if (c instanceof NewInstanceCompletion) - { - Constructor<?> cons = ((NewInstanceCompletion) c).getConstructor(); - clazz = cons.getDeclaringClass(); - final ClassSource cs = ClassSource.getClassSource(clazz); - ConstructorDeclaration cd = cs.getConstructors().get(cons.toGenericString()); - if (cd != null) - openSource(clazz, cd.getBeginLine() - 1, cd.getEndLine() - 1); - else - System.out.println(clazz); - } + ac.setExternalURLHandler((e, c, callback) -> { + if (e.getDescription().contentEquals("SourceCodeLink")) { + if (c instanceof BasicJavaClassCompletion) { + openSource(((BasicJavaClassCompletion) c).getJavaClass()); } - else - { - System.out.println("Click:" + e.getDescription()); - // callback.showSummaryFor(new BasicJavaCl, ""); + else if (c instanceof ScriptFunctionCompletion) { + final ScriptFunctionCompletion sfc = (ScriptFunctionCompletion) c; + final Method m = sfc.getMethod(); + final Class<?> clazz = m.getDeclaringClass(); + final ClassSource cs = ClassSource.getClassSource(clazz); + final MethodDeclaration md = cs.getMethods().get(m.toGenericString()); + openSource(clazz, md.getBeginLine() - 1, md.getEndLine() - 1); } + else if (c instanceof NewInstanceCompletion) { + final Constructor<?> cons = ((NewInstanceCompletion) c).getConstructor(); + final Class<?> clazz = cons.getDeclaringClass(); + final ClassSource cs = ClassSource.getClassSource(clazz); + final ConstructorDeclaration cd = cs.getConstructors().get(cons.toGenericString()); + if (cd != null) + openSource(clazz, cd.getBeginLine() - 1, cd.getEndLine() - 1); + else + System.out.println(clazz); + } + } + else { + System.out.println("Click:" + e.getDescription()); + // callback.showSummaryFor(new BasicJavaCl, ""); } }); - ThreadUtil.invokeLater(new Runnable() - { - @Override - public void run() - { - // add the scripting handler, which handles the compilation - // and the parsing of the code for advanced features. - if (StringUtil.equals(language, "JavaScript")) - { - // if - // (System.getProperty("java.version").startsWith("1.6.")) { - scriptHandler = new JSScriptingHandlerRhino(provider, textArea, pane.getGutter(), true); - // } else { - // scriptHandler = new JSScriptingHandlerSimple(provider, - // textArea, - // pane.getGutter(), true); - // } - } - else if (StringUtil.equals(language, "Python")) - { - scriptHandler = new PythonScriptingHandler(provider, textArea, pane.getGutter(), true); - } - else - { - scriptHandler = null; - } - - if (scriptHandler != null) - { - if (!integrated && consoleOutput != null) - scriptHandler.setOutput(consoleOutput); - - scriptHandler.addScriptListener(ScriptingPanel.this); - scriptHandler.setVarInterpretation(preferences.isVarInterpretationEnabled()); - scriptHandler.setStrict(preferences.isStrictModeEnabled()); - scriptHandler.setForceRun(preferences.isOverrideEnabled()); - // scriptHandler.interpret(false); - provider.setHandler(scriptHandler); - textArea.addKeyListener(scriptHandler); - PluginRepositoryLoader.addListener(scriptHandler); - - BindingsScriptFrame frame = BindingsScriptFrame.getInstance(); - frame.setEngine(scriptHandler.getEngine()); - } - rebuildGUI(); - textArea.requestFocus(); + ThreadUtil.invokeLater(() -> { + // add the scripting handler, which handles the compilation + // and the parsing of the code for advanced features. + if (StringUtil.equals(language, "JavaScript")) { + // if + // (System.getProperty("java.version").startsWith("1.6.")) { + scriptHandler = new JSScriptingHandlerRhino(provider, textArea, pane.getGutter(), true); + // } else { + // scriptHandler = new JSScriptingHandlerSimple(provider, + // textArea, + // pane.getGutter(), true); + // } + } + else if (StringUtil.equals(language, "Python")) { + scriptHandler = new PythonScriptingHandler(provider, textArea, pane.getGutter(), true); + } + else { + scriptHandler = null; + } + + if (scriptHandler != null) { + if (!integrated && consoleOutput != null) + scriptHandler.setOutput(consoleOutput); + + scriptHandler.addScriptListener(ScriptingPanel.this); + scriptHandler.setVarInterpretation(preferences.isVarInterpretationEnabled()); + scriptHandler.setStrict(preferences.isStrictModeEnabled()); + scriptHandler.setForceRun(preferences.isOverrideEnabled()); + // scriptHandler.interpret(false); + provider.setHandler(scriptHandler); + textArea.addKeyListener(scriptHandler); + PluginRepositoryLoader.addListener(scriptHandler); + + final BindingsScriptFrame frame = BindingsScriptFrame.getInstance(); + frame.setEngine(scriptHandler.getEngine()); } + rebuildGUI(); + textArea.requestFocus(); }); } - public void openSource(Class<?> clazz) - { + public void openSource(final Class<?> clazz) { openSource(clazz, 0, 0); } - public void openSource(Class<?> clazz, int lineBegin, int lineEnd) - { - InputStream jar = JarAccess.getJavaSourceInputStream(clazz); - if (jar != null) - { + public void openSource(final Class<?> clazz, final int lineBegin, final int lineEnd) { + final InputStream jar = JarAccess.getJavaSourceInputStream(clazz); + if (jar != null) { String res = null; - try - { - byte b[] = new byte[jar.available()]; + try { + final byte[] b = new byte[jar.available()]; jar.read(b); res = new String(b); } - catch (IOException e1) - { + catch (final IOException e) { + IcyExceptionHandler.showErrorMessage(e, true); } if (res == null) return; // creates the dialog - IcyFrame frame = new IcyFrame("Source code of: [" + clazz.getName() + "]", true, true, true, true); - JPanel panel = new JPanel(new BorderLayout()); + final IcyFrame frame = new IcyFrame("Source code of: [" + clazz.getName() + "]", true, true, true, true); + final JPanel panel = new JPanel(new BorderLayout()); // Generation of the RSyntaxTextArea final RSyntaxTextArea sourceTextArea = new RSyntaxTextArea(200, 200); @@ -823,18 +642,16 @@ public class ScriptingPanel extends JPanel implements ScriptListener sourceTextArea.setTabsEmulated(false); // Change the theme to Eclipse - try - { - Theme t = Theme.load(PluginLoader.getLoader() - .getResourceAsStream("plugins/tprovoost/scripteditor/resources/themes/eclipse.xml")); + try { + final Theme t = Theme.load(PluginLoader.getLoader().getResourceAsStream("plugins/tprovoost/scripteditor/resources/themes/eclipse.xml")); t.apply(sourceTextArea); } - catch (IOException e2) - { + catch (final IOException e) { + IcyExceptionHandler.showErrorMessage(e, true); } // Add the RSyntaxTextArea to a scroll pane - RTextScrollPane paneSource = new RTextScrollPane(sourceTextArea); + final RTextScrollPane paneSource = new RTextScrollPane(sourceTextArea); panel.add(paneSource); frame.setContentPane(panel); frame.setSize(720, 640); @@ -844,25 +661,18 @@ public class ScriptingPanel extends JPanel implements ScriptListener // Put the cursor at the right place int posCaretBegin = 0; int posCaretEnd = 0; - try - { + try { posCaretBegin = sourceTextArea.getLineStartOffset(lineBegin); posCaretEnd = sourceTextArea.getLineStartOffset(lineEnd); } - catch (BadLocationException e) - { + catch (final BadLocationException e) { + IcyExceptionHandler.showErrorMessage(e, true); } sourceTextArea.getCaret().setDot(posCaretEnd); final int begin = posCaretBegin; - ThreadUtil.bgRun(new Runnable() - { - - @Override - public void run() - { - ThreadUtil.sleep(100); - sourceTextArea.getCaret().setDot(begin); - } + ThreadUtil.bgRun(() -> { + ThreadUtil.sleep(100); + sourceTextArea.getCaret().setDot(begin); }); } } @@ -870,45 +680,39 @@ public class ScriptingPanel extends JPanel implements ScriptListener /** * @return the handler. */ - public ScriptingHandler getScriptHandler() - { + public ScriptingHandler getScriptHandler() { return scriptHandler; } /** * Setter for the handler. Should only be used for reference to the same script * handler in different panels. For instance with the {@link Javascript} block. - * - * @param scriptHandler - * the {@link ScriptingHandler} + * + * @param scriptHandler the {@link ScriptingHandler} */ - public void setScriptHandler(ScriptingHandler scriptHandler) - { + public void setScriptHandler(final ScriptingHandler scriptHandler) { this.scriptHandler = scriptHandler; } /** * @return the default save location. */ - public File getSaveFile() - { + public File getSaveFile() { return saveFile; } /** * @return if the file has been modified since its last save. */ - public boolean isDirty() - { - String currentText = textArea.getText(); + public boolean isDirty() { + final String currentText = textArea.getText(); return (saveFile == null && !currentText.isEmpty()) || !saveFileString.contentEquals(currentText); } /** * Rebuild the whole GUI. */ - private void rebuildGUI() - { + private void rebuildGUI() { removeAll(); add(pane); @@ -919,110 +723,85 @@ public class ScriptingPanel extends JPanel implements ScriptListener /** * Sets the text in the textArea. - * - * @param text - * the text to set + * + * @param text the text to set */ - public void setText(String text) - { + public void setText(final String text) { textArea.setText(text); } /** * @return the current selected language in the combobox. */ - public String getLanguage() - { - return (String) options.getLanguage(); + public String getLanguage() { + return options.getLanguage(); } /** * Load the content of the file into the textArea. Also updates the * {@link #saveFile()} and {@link #saveFileAs(File)} variables, used to know if * the text is dirty. - * - * @param f - * the file to load the code from. - * @throws IOException - * If the file could not be opened or read, an exception is raised. + * + * @param f the file to load the code from. + * @throws IOException If the file could not be opened or read, an exception is raised. * @see #isDirty() */ - public void openFile(File f) throws IOException - { - BufferedReader reader = new BufferedReader(new FileReader(f)); - String all = ""; + public void openFile(final File f) throws IOException { + final BufferedReader reader = new BufferedReader(new FileReader(f)); + final StringBuilder all = new StringBuilder(); String line; - while ((line = reader.readLine()) != null) - { - all += (line + "\n"); + while ((line = reader.readLine()) != null) { + all.append(line).append("\n"); } saveFile = f; - saveFileString = all; - textArea.setText(all); + saveFileString = all.toString(); + textArea.setText(all.toString()); scriptHandler.setFileName(f.getAbsolutePath()); reader.close(); } - public void openStream(InputStream stream) throws IOException - { - byte[] data = new byte[stream.available()]; + public void openStream(final InputStream stream) throws IOException { + final byte[] data = new byte[stream.available()]; stream.read(data); - String s = ""; - for (byte b : data) - s += (char) b; - textArea.setText(s); + final StringBuilder s = new StringBuilder(); + for (final byte b : data) + s.append((char) b); + textArea.setText(s.toString()); stream.close(); - ThreadUtil.bgRun(new Runnable() - { - - @Override - public void run() - { - while (scriptHandler == null) - ThreadUtil.sleep(1000); - scriptHandler.autoDownloadPlugins(); - } + ThreadUtil.bgRun(() -> { + while (scriptHandler == null) + ThreadUtil.sleep(1000L); + scriptHandler.autoDownloadPlugins(); }); } @Override - public void evaluationStarted() - { + public void evaluationStarted() { } @Override - public void evaluationOver() - { - ThreadUtil.invokeLater(new Runnable() - { - - @Override - public void run() - { - options.setStopButtonEnabled(false); - } - }); + public void evaluationOver() { + ThreadUtil.invokeLater(() -> options.setStopButtonEnabled(false)); } /** * Displays a modal dialog to go to a specific line. */ - public void displayGotoLine() - { - int min = 1; - int max = textArea.getLineCount(); - String res = JOptionPane.showInputDialog(Icy.getMainInterface().getMainFrame(), - "Enter line number (" + min + "," + max + ")", "Go to Line", JOptionPane.QUESTION_MESSAGE); - try - { - int line = Integer.parseInt(res); + public void displayGotoLine() { + final int min = 1; + final int max = textArea.getLineCount(); + final String res = JOptionPane.showInputDialog( + Icy.getMainInterface().getMainFrame(), + "Enter line number (" + min + "," + max + ")", + "Go to Line", + JOptionPane.QUESTION_MESSAGE + ); + try { + final int line = Integer.parseInt(res); textArea.setCaretPosition(textArea.getLineStartOffset(line - 1)); } - catch (NumberFormatException e) - { - } - catch (BadLocationException e) - { + catch (final NumberFormatException | BadLocationException e) { + IcyExceptionHandler.showErrorMessage(e, true); } } @@ -1030,19 +809,16 @@ public class ScriptingPanel extends JPanel implements ScriptListener * Format the text in this panel. Do a space/tab conversion according to the * preferences, and perform a language-specific beautification. */ - public void format() - { + public void format() { // getScriptHandler().organizeImports(); // do the tab-to-space (or space-to-tab) conversion - Preferences preferences = Preferences.getPreferences(); - RSyntaxTextArea textArea = getTextArea(); - if (preferences.isSoftTabsEnabled()) - { + final Preferences preferences = Preferences.getPreferences(); + final RSyntaxTextArea textArea = getTextArea(); + if (preferences.isSoftTabsEnabled()) { textArea.convertTabsToSpaces(); } - else - { + else { textArea.convertSpacesToTabs(); } @@ -1050,76 +826,55 @@ public class ScriptingPanel extends JPanel implements ScriptListener getScriptHandler().format(); } - public void addFileDropListener(FileDropListener fileDropListener) - { + public void addFileDropListener(final FileDropListener fileDropListener) { new FileDrop(textArea, fileDropListener); } - public void removeFileDropListeners() - { + public void removeFileDropListeners() { FileDrop.remove(textArea); } - public void addHyperlinkListener(HyperlinkListener listener) - { - ((RSyntaxTextArea) textArea).addHyperlinkListener(listener); + public void addHyperlinkListener(final HyperlinkListener listener) { + textArea.addHyperlinkListener(listener); } - public void removeHyperlinkListener(HyperlinkListener listener) - { - ((RSyntaxTextArea) textArea).removeHyperlinkListener(listener); + public void removeHyperlinkListener(final HyperlinkListener listener) { + textArea.removeHyperlinkListener(listener); } - public void addLanguageListener(ItemListener listener) - { + public void addLanguageListener(final ItemListener listener) { options.addLanguageListener(listener); } - public void removeLanguageListener(ItemListener listener) - { + public void removeLanguageListener(final ItemListener listener) { options.removeLanguageListener(listener); } - protected void runInNew() - { + protected void runInNew() { runScript(true); } - protected void runInSame() - { + protected void runInSame() { runScript(false); } - protected void runScript(boolean newEngine) - { + protected void runScript(final boolean newEngine) { if (scriptHandler == null) return; - if (!integrated) - { - if (isDirty()) - { - if (saveFile != null) - { + if (!integrated) { + if (isDirty()) { + if (saveFile != null) { saveFile(); } } } - Preferences preferences = Preferences.getPreferences(); + final Preferences preferences = Preferences.getPreferences(); - ThreadUtil.invokeLater(new Runnable() - { + ThreadUtil.invokeLater(() -> options.setStopButtonEnabled(true)); - @Override - public void run() - { - options.setStopButtonEnabled(true); - } - }); - - if (!integrated) - { + if (!integrated) { scriptHandler.setNewEngine(newEngine); scriptHandler.setForceRun(preferences.isOverrideEnabled()); scriptHandler.setStrict(preferences.isStrictModeEnabled()); @@ -1128,13 +883,11 @@ public class ScriptingPanel extends JPanel implements ScriptListener } } - protected void stopScript() - { + protected void stopScript() { if (scriptHandler == null) return; - if (scriptHandler.isRunning()) - { + if (scriptHandler.isRunning()) { scriptHandler.killScript(); } } diff --git a/src/main/java/plugins/tprovoost/scripteditor/gui/TabComponentButton.java b/src/main/java/plugins/tprovoost/scripteditor/gui/TabComponentButton.java index 126b1ce605db1ce335d2d20c9600d1f696e2a68d..2157ea547681ee6374abfdfaa2172b6764c802a5 100644 --- a/src/main/java/plugins/tprovoost/scripteditor/gui/TabComponentButton.java +++ b/src/main/java/plugins/tprovoost/scripteditor/gui/TabComponentButton.java @@ -27,38 +27,28 @@ import javax.swing.plaf.basic.BasicButtonUI; * Component to be used as tabComponent; Contains a JLabel to show the text and * a JButton to close the tab it belongs to */ -public class TabComponentButton extends JPanel -{ - /** */ - private static final long serialVersionUID = 1L; +public class TabComponentButton extends JPanel { private final ScriptingPanel panel; private final ScriptingEditor editor; - public TabComponentButton(ScriptingEditor scriptingEditor, final ScriptingPanel panelCreated) - { + public TabComponentButton(final ScriptingEditor scriptingEditor, final ScriptingPanel panelCreated) { // unset default FlowLayout' gaps super(new FlowLayout(FlowLayout.LEFT, 0, 0)); - if (panelCreated == null) - { + if (panelCreated == null) { throw new NullPointerException("TabbedPane is null"); } this.panel = panelCreated; this.editor = scriptingEditor; - + setOpaque(false); // make JLabel read titles from JTabbedPane - JLabel label = new JLabel() - { - /** */ - private static final long serialVersionUID = 1L; - - public String getText() - { - JTabbedPane pane = editor.getTabbedPane(); - int i = pane.indexOfTabComponent(TabComponentButton.this); - if (i != -1) - { + final JLabel label = new JLabel() { + @Override + public String getText() { + final JTabbedPane pane = editor.getTabbedPane(); + final int i = pane.indexOfTabComponent(TabComponentButton.this); + if (i != -1) { return pane.getTitleAt(i); } return ""; @@ -69,7 +59,7 @@ public class TabComponentButton extends JPanel // add more space between the label and the button label.setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 5)); // tab button - JButton button = new TabButton(); + final JButton button = new TabButton(); add(button); // add more space to the top of the component setBorder(BorderFactory.createEmptyBorder(2, 0, 0, 0)); @@ -77,14 +67,9 @@ public class TabComponentButton extends JPanel // addMouseListener(this); } - private class TabButton extends JButton implements ActionListener - { - /** */ - private static final long serialVersionUID = 1L; - - public TabButton() - { - int size = 17; + private class TabButton extends JButton implements ActionListener { + public TabButton() { + final int size = 17; setPreferredSize(new Dimension(size, size)); setToolTipText("Close this tab"); // Make the button looks the same for all Laf's @@ -103,84 +88,76 @@ public class TabComponentButton extends JPanel addActionListener(this); } - public void actionPerformed(ActionEvent e) - { + @Override + public void actionPerformed(final ActionEvent e) { deletePane(); } // we don't want to update UI for this button - public void updateUI() - { - } + @Override + public void updateUI() {} // paint the cross - protected void paintComponent(Graphics g) - { + @Override + protected void paintComponent(final Graphics g) { super.paintComponent(g); - Graphics2D g2 = (Graphics2D) g.create(); + final Graphics2D g2 = (Graphics2D) g.create(); // shift the image for pressed buttons - if (getModel().isPressed()) - { + if (getModel().isPressed()) { g2.translate(1, 1); } g2.setStroke(new BasicStroke(2)); g2.setColor(Color.BLACK); - if (getModel().isRollover()) - { + if (getModel().isRollover()) { g2.setColor(Color.MAGENTA); } - int delta = 6; + final int delta = 6; g2.drawLine(delta, delta, getWidth() - delta - 1, getHeight() - delta - 1); g2.drawLine(getWidth() - delta - 1, delta, delta, getHeight() - delta - 1); g2.dispose(); } } - private final MouseListener buttonMouseListener = new MouseAdapter() - { - public void mouseEntered(MouseEvent e) - { - Component component = e.getComponent(); - if (component instanceof AbstractButton) - { - AbstractButton button = (AbstractButton) component; + private final MouseListener buttonMouseListener = new MouseAdapter() { + @Override + public void mouseEntered(final MouseEvent e) { + final Component component = e.getComponent(); + if (component instanceof AbstractButton) { + final AbstractButton button = (AbstractButton) component; button.setBorderPainted(true); } } - public void mouseExited(MouseEvent e) - { - Component component = e.getComponent(); - if (component instanceof AbstractButton) - { - AbstractButton button = (AbstractButton) component; + @Override + public void mouseExited(final MouseEvent e) { + final Component component = e.getComponent(); + if (component instanceof AbstractButton) { + final AbstractButton button = (AbstractButton) component; button.setBorderPainted(false); } } - public void mouseClicked(MouseEvent e) - { - if (EventUtil.isMiddleMouseButton(e)) - { + @Override + public void mouseClicked(final MouseEvent e) { + if (EventUtil.isMiddleMouseButton(e)) { deletePane(); e.consume(); } else super.mouseClicked(e); - }; + } }; /** * Remove this pane from the {@link JTabbedPane}. - * + * * @return false if the user has cancelled the operation */ - public boolean deletePane() - { + public boolean deletePane() { return editor.closeTab(this); } - public ScriptingPanel getPanel() { - return panel; - } + public ScriptingPanel getPanel() { + return panel; + } } \ No newline at end of file diff --git a/src/main/java/plugins/tprovoost/scripteditor/gui/action/SplitButtonActionListener.java b/src/main/java/plugins/tprovoost/scripteditor/gui/action/SplitButtonActionListener.java index ad6bda973dc0c0aa55b24c6d32723914cd0ccf01..641419a6e7942af685fcda0d71d19a86c5dc4e68 100644 --- a/src/main/java/plugins/tprovoost/scripteditor/gui/action/SplitButtonActionListener.java +++ b/src/main/java/plugins/tprovoost/scripteditor/gui/action/SplitButtonActionListener.java @@ -12,26 +12,22 @@ import java.util.EventListener; * occurs, that object's <code>buttonClicked</code> or <code>splitButtonClicked</code> * method is invoked. * - * @see ActionEvent * @author Naveed Quadri + * @see ActionEvent */ -public interface SplitButtonActionListener extends EventListener -{ +public interface SplitButtonActionListener extends EventListener { /** * Invoked when the button part is clicked. - * - * @param e - * action to execute on button click + * + * @param e action to execute on button click */ - public void buttonClicked(ActionEvent e); + void buttonClicked(ActionEvent e); /** * Invoked when split part is clicked. - * - * @param e - * action to execute on split button click + * + * @param e action to execute on split button click */ - public void splitButtonClicked(ActionEvent e); - + void splitButtonClicked(ActionEvent e); } diff --git a/src/main/java/plugins/tprovoost/scripteditor/javasource/ClassOrInterfaceVisitor.java b/src/main/java/plugins/tprovoost/scripteditor/javasource/ClassOrInterfaceVisitor.java index 7a2a4b5ef9f9209132364adb3a5587c9d1706e29..365c4e6634490fb43eb4ace3f6062613a68515c7 100644 --- a/src/main/java/plugins/tprovoost/scripteditor/javasource/ClassOrInterfaceVisitor.java +++ b/src/main/java/plugins/tprovoost/scripteditor/javasource/ClassOrInterfaceVisitor.java @@ -2,11 +2,9 @@ package plugins.tprovoost.scripteditor.javasource; import japa.parser.ast.body.ClassOrInterfaceDeclaration; -public class ClassOrInterfaceVisitor extends JavaVisitor -{ +public class ClassOrInterfaceVisitor extends JavaVisitor { @Override - public void visit(ClassOrInterfaceDeclaration n, Object arg) - { + public void visit(final ClassOrInterfaceDeclaration n, final Object arg) { list.add(n); } diff --git a/src/main/java/plugins/tprovoost/scripteditor/javasource/ClassSource.java b/src/main/java/plugins/tprovoost/scripteditor/javasource/ClassSource.java index a719bcce9092652b415ba29b8cbb82d24ce3b394..fc12b0356a4a19c9e8d5746eebf4cc3c1073e096 100644 --- a/src/main/java/plugins/tprovoost/scripteditor/javasource/ClassSource.java +++ b/src/main/java/plugins/tprovoost/scripteditor/javasource/ClassSource.java @@ -1,5 +1,6 @@ package plugins.tprovoost.scripteditor.javasource; +import icy.system.IcyExceptionHandler; import icy.system.thread.ThreadUtil; import icy.util.StringUtil; import japa.parser.JavaParser; @@ -27,8 +28,7 @@ import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; -public class ClassSource -{ +public class ClassSource { /** * Optional leading text for doc comment lines (except the first line) that @@ -55,36 +55,33 @@ public class ClassSource * <li>fully.qualified.ClassName#method(params)</li> * </ul> */ - static final Pattern LINK_TAG_MEMBER_PATTERN = Pattern.compile("(?:\\w+\\.)*\\w+(?:#\\w+(?:\\([^\\)]*\\))?)?|" - + "#\\w+(?:\\([^\\)]*\\))?"); + static final Pattern LINK_TAG_MEMBER_PATTERN = Pattern.compile("(?:\\w+\\.)*\\w+(?:#\\w+(?:\\([^)]*\\))?)?|#\\w+(?:\\([^)]*\\))?"); /** * Cache containing all source codes for a given class. */ - private static HashMap<Class<?>, ClassSource> allClassSources = new HashMap<Class<?>, ClassSource>(); + private static final HashMap<Class<?>, ClassSource> allClassSources = new HashMap<>(); - private Class<?> clazz; + private final Class<?> clazz; private CompilationUnit cu; - private HashMap<String, ConstructorDeclaration> constructors = new HashMap<String, ConstructorDeclaration>(); - private HashMap<String, MethodDeclaration> methods = new HashMap<String, MethodDeclaration>(); - private HashMap<String, VariableDeclarator> fields = new HashMap<String, VariableDeclarator>(); - private HashMap<String, ClassOrInterfaceDeclaration> classOrInterfaces = new HashMap<String, ClassOrInterfaceDeclaration>(); - private HashMap<String, EnumDeclaration> enums = new HashMap<String, EnumDeclaration>(); + private final HashMap<String, ConstructorDeclaration> constructors = new HashMap<>(); + private final HashMap<String, MethodDeclaration> methods = new HashMap<>(); + private final HashMap<String, VariableDeclarator> fields = new HashMap<>(); + private final HashMap<String, ClassOrInterfaceDeclaration> classOrInterfaces = new HashMap<>(); + private final HashMap<String, EnumDeclaration> enums = new HashMap<>(); private boolean constructorsSet = false; private boolean methodsSet = false; - private boolean enumSet = false; + private final boolean enumSet = false; private boolean fieldsSet = false; private boolean classOrInterfacesSet = false; private boolean working = false; - private boolean DEBUG = false; + private static final boolean DEBUG = false; - public static synchronized ClassSource getClassSource(final Class<?> clazz) - { + public static synchronized ClassSource getClassSource(final Class<?> clazz) { ClassSource cm = allClassSources.get(clazz); - if (cm == null) - { + if (cm == null) { cm = new ClassSource(clazz); final ClassSource cmFinal = cm; allClassSources.put(clazz, cmFinal); @@ -94,14 +91,13 @@ public class ClassSource // @Override // public void run() // { - InputStream is = JarAccess.getJavaSourceInputStream(clazz); + final InputStream is = JarAccess.getJavaSourceInputStream(clazz); if (is != null) - try - { + try { cmFinal.cu = JavaParser.parse(is); } - catch (ParseException e) - { + catch (final ParseException e) { + IcyExceptionHandler.showErrorMessage(e, true); } // } // }); @@ -109,140 +105,111 @@ public class ClassSource return cm; } - private ClassSource(Class<?> clazz) - { + private ClassSource(final Class<?> clazz) { this.clazz = clazz; } - public Class<?> getSourceClass() - { + public Class<?> getSourceClass() { return clazz; } - public HashMap<String, ClassOrInterfaceDeclaration> getClassOrInterfaces() - { + public HashMap<String, ClassOrInterfaceDeclaration> getClassOrInterfaces() { return classOrInterfaces; } - public HashMap<String, ConstructorDeclaration> getConstructors() - { + public HashMap<String, ConstructorDeclaration> getConstructors() { return constructors; } - public HashMap<String, VariableDeclarator> getFields() - { + public HashMap<String, VariableDeclarator> getFields() { return fields; } - public HashMap<String, MethodDeclaration> getMethods() - { + public HashMap<String, MethodDeclaration> getMethods() { return methods; } - public HashMap<String, EnumDeclaration> getEnums() - { + public HashMap<String, EnumDeclaration> getEnums() { return enums; } - public synchronized boolean isFieldsSet() - { + public synchronized boolean isFieldsSet() { return fieldsSet; } - public synchronized boolean isEnumSet() - { + public synchronized boolean isEnumSet() { return enumSet; } - public synchronized boolean isClassOrInterfacesSet() - { + public synchronized boolean isClassOrInterfacesSet() { return classOrInterfacesSet; } - public synchronized boolean isConstructorsSet() - { + public synchronized boolean isConstructorsSet() { return constructorsSet; } - public synchronized boolean isMethodsSet() - { + public synchronized boolean isMethodsSet() { return methodsSet; } - public boolean isAllSet() - { + public boolean isAllSet() { return fieldsSet && classOrInterfacesSet && constructorsSet && methodsSet && enumSet; } - public void waitForAllSet() - { - while (!isAllSet()) - { + public void waitForAllSet() { + // FIXME: 07/04/2023 Does not loop + while (!isAllSet()) { ThreadUtil.sleep(100); return; } } - public synchronized boolean isWorking() - { + public synchronized boolean isWorking() { return working; } - public synchronized void setWorking(boolean working) - { + public synchronized void setWorking(final boolean working) { this.working = working; } - public void populateAll() - { - if (working) - { + public void populateAll() { + if (working) { waitForAllSet(); return; } working = true; - if (!classOrInterfacesSet) - { + if (!classOrInterfacesSet) { populateClassesOrInterfaces(); } - if (!fieldsSet) - { + if (!fieldsSet) { populateFields(); } - if (!constructorsSet) - { + if (!constructorsSet) { populateConstructors(); } - if (!methodsSet) - { + if (!methodsSet) { populateMethods(); } - if (!enumSet) - { + if (!enumSet) { populateEnums(); } } - @SuppressWarnings("unchecked") - public void populateClassesOrInterfaces() - { - if (working) - { + public void populateClassesOrInterfaces() { + if (working) { return; } - if (cu != null) - { + if (cu != null) { // JAVA SOURCE VERSION - ClassOrInterfaceVisitor coi = new ClassOrInterfaceVisitor(); + final ClassOrInterfaceVisitor coi = new ClassOrInterfaceVisitor(); coi.visit(cu, null); - ArrayList<BodyDeclaration> list = coi.getList(); - if (list.isEmpty()) - { + final ArrayList<BodyDeclaration> list = coi.getList(); + if (list.isEmpty()) { System.out.println("Empty Class/Interface Declaration in " + clazz.getName()); } - else - { + else { classOrInterfaces.put(clazz.getName(), (ClassOrInterfaceDeclaration) list.get(0)); } @@ -251,22 +218,16 @@ public class ClassSource startPopulating(); } - @SuppressWarnings("unchecked") - public void populateFields() - { - if (working) - { + public void populateFields() { + if (working) { return; } - if (cu != null) - { - FieldVisitor coi = new FieldVisitor(); + if (cu != null) { + final FieldVisitor coi = new FieldVisitor(); coi.visit(cu, null); - for (BodyDeclaration bd : coi.getList()) - { - FieldDeclaration fd = (FieldDeclaration) bd; - for (VariableDeclarator vd : fd.getVariables()) - { + for (final BodyDeclaration bd : coi.getList()) { + final FieldDeclaration fd = (FieldDeclaration) bd; + for (final VariableDeclarator vd : fd.getVariables()) { fields.put(vd.getId().getName(), vd); } } @@ -275,19 +236,15 @@ public class ClassSource fieldsSet = true; } - @SuppressWarnings("unchecked") - public void populateEnums() - { + public void populateEnums() { if (working) return; - if (cu != null) - { + if (cu != null) { // JAVA SOURCE VERSION - EnumVisitor ev = new EnumVisitor(); + final EnumVisitor ev = new EnumVisitor(); ev.visit(cu, null); - for (BodyDeclaration bd : ev.getList()) - { - EnumDeclaration ed = (EnumDeclaration) bd; + for (final BodyDeclaration bd : ev.getList()) { + final EnumDeclaration ed = (EnumDeclaration) bd; enums.put(ed.getName(), ed); } } @@ -295,42 +252,34 @@ public class ClassSource fieldsSet = true; } - @SuppressWarnings("unchecked") - public void populateConstructors() - { + public void populateConstructors() { if (working) return; - if (cu != null) - { - ConstructorVisitor cv = new ConstructorVisitor(); + if (cu != null) { + final ConstructorVisitor cv = new ConstructorVisitor(); cv.visit(cu, null); - for (Constructor<?> c : clazz.getDeclaredConstructors()) - { - L1: for (BodyDeclaration bd : cv.getList()) - { - ConstructorDeclaration cd = (ConstructorDeclaration) bd; + for (final Constructor<?> c : clazz.getDeclaredConstructors()) { + L1: + for (final BodyDeclaration bd : cv.getList()) { + final ConstructorDeclaration cd = (ConstructorDeclaration) bd; if (!cd.getName().contentEquals(clazz.getSimpleName())) continue; - List<japa.parser.ast.body.Parameter> paramsSource = cd.getParameters(); - Class<?> paramsReflect[] = c.getParameterTypes(); + final List<japa.parser.ast.body.Parameter> paramsSource = cd.getParameters(); + final Class<?>[] paramsReflect = c.getParameterTypes(); // ArrayList<Parameter> params = new ArrayList<Parameter>(); - if (paramsSource != null && paramsSource.size() == paramsReflect.length) - { - for (int i = 0; i < paramsSource.size(); ++i) - { - japa.parser.ast.body.Parameter paramSource = paramsSource.get(i); - Class<?> paramReflect = paramsReflect[i]; - String className; - if (paramReflect.isArray()) - { + if (paramsSource != null && paramsSource.size() == paramsReflect.length) { + for (int i = 0; i < paramsSource.size(); ++i) { + final japa.parser.ast.body.Parameter paramSource = paramsSource.get(i); + final Class<?> paramReflect = paramsReflect[i]; + final String className; + if (paramReflect.isArray()) { className = paramReflect.getCanonicalName(); } - else - { + else { className = paramReflect.getName(); } String paramSourceType = paramSource.getType().toString(); - int idx = paramSourceType.indexOf('<'); + final int idx = paramSourceType.indexOf('<'); if (idx != -1) paramSourceType = paramSourceType.substring(0, idx); if (!className.contains(paramSourceType)) @@ -353,45 +302,36 @@ public class ClassSource constructorsSet = true; } - @SuppressWarnings("unchecked") - public void populateMethods() - { + public void populateMethods() { if (working) waitForAllSet(); - if (cu != null) - { + if (cu != null) { // JAVA SOURCE VERSION - MethodVisitor mv = new MethodVisitor(); + final MethodVisitor mv = new MethodVisitor(); mv.visit(cu, null); - for (Method method : clazz.getDeclaredMethods()) - { - L1: for (BodyDeclaration cd : mv.getList()) - { - MethodDeclaration md = ((MethodDeclaration) cd); + for (final Method method : clazz.getDeclaredMethods()) { + L1: + for (final BodyDeclaration cd : mv.getList()) { + final MethodDeclaration md = ((MethodDeclaration) cd); if (!md.getName().contentEquals(method.getName())) continue; - List<japa.parser.ast.body.Parameter> paramsSource = md.getParameters(); - Class<?> paramsReflect[] = method.getParameterTypes(); - if (paramsSource == null || paramsSource.size() == paramsReflect.length) - { - if (paramsSource != null) - { - for (int i = 0; i < paramsSource.size(); ++i) - { - japa.parser.ast.body.Parameter paramSource = paramsSource.get(i); - Class<?> paramReflect = paramsReflect[i]; - String className; - if (paramReflect.isArray()) - { + final List<japa.parser.ast.body.Parameter> paramsSource = md.getParameters(); + final Class<?>[] paramsReflect = method.getParameterTypes(); + if (paramsSource == null || paramsSource.size() == paramsReflect.length) { + if (paramsSource != null) { + for (int i = 0; i < paramsSource.size(); ++i) { + final japa.parser.ast.body.Parameter paramSource = paramsSource.get(i); + final Class<?> paramReflect = paramsReflect[i]; + final String className; + if (paramReflect.isArray()) { className = paramReflect.getCanonicalName(); } - else - { + else { className = paramReflect.getName(); } String paramSourceType = paramSource.getType().toString(); - int idx = paramSourceType.indexOf('<'); + final int idx = paramSourceType.indexOf('<'); if (idx != -1) paramSourceType = paramSourceType.substring(0, idx); if (!className.contains(paramSourceType)) @@ -412,48 +352,34 @@ public class ClassSource /** * Reduces code size for the thread. */ - private void startPopulating() - { - ThreadUtil.bgRun(new Runnable() - { - - @Override - public void run() - { - populateAll(); - } - }); + private void startPopulating() { + ThreadUtil.bgRun(this::populateAll); } - private static final void appendDocCommentTail(StringBuffer sb, StringBuffer tail) - { - - StringBuffer params = null; - StringBuffer returns = null; - StringBuffer throwsItems = null; - StringBuffer see = null; - StringBuffer seeTemp = null; - StringBuffer since = null; - StringBuffer author = null; - StringBuffer version = null; - StringBuffer unknowns = null; + private static void appendDocCommentTail(final StringBuilder sb, final StringBuilder tail) { + + StringBuilder params = null; + StringBuilder returns = null; + StringBuilder throwsItems = null; + StringBuilder see = null; + StringBuilder seeTemp = null; + StringBuilder since = null; + StringBuilder author = null; + StringBuilder version = null; + StringBuilder unknowns = null; boolean inParams = false, inThrows = false, inReturns = false, inSeeAlso = false, inSince = false, inAuthor = false, inVersion = false, inUnknowns = false; - String[] st = tail.toString().split("[ \t\r\n\f]+"); - String token = null; + final String[] st = tail.toString().split("[ \t\r\n\f]+"); + String token; int i = 0; - while (i < st.length && (token = st[i++]) != null) - { - if ("@param".equals(token) && i < st.length) - { + while (i < st.length && (token = st[i++]) != null) { + if ("@param".equals(token) && i < st.length) { token = st[i++]; // Actual parameter - if (params == null) - { - params = new StringBuffer("<b>Parameters:</b><p class='indented'>"); + if (params == null) { + params = new StringBuilder("<b>Parameters:</b><p class='indented'>"); } - else - { + else { params.append("<br>"); } params.append("<b>").append(token).append("</b> "); @@ -466,11 +392,9 @@ public class ClassSource inVersion = false; inUnknowns = false; } - else if ("@return".equals(token) && i < st.length) - { - if (returns == null) - { - returns = new StringBuffer("<b>Returns:</b><p class='indented'>"); + else if ("@return".equals(token) && i < st.length) { + if (returns == null) { + returns = new StringBuilder("<b>Returns:</b><p class='indented'>"); } inSeeAlso = false; inReturns = true; @@ -481,18 +405,14 @@ public class ClassSource inVersion = false; inUnknowns = false; } - else if ("@see".equals(token) && i < st.length) - { - if (see == null) - { - see = new StringBuffer("<b>See Also:</b><p class='indented'>"); - seeTemp = new StringBuffer(); + else if ("@see".equals(token) && i < st.length) { + if (see == null) { + see = new StringBuilder("<b>See Also:</b><p class='indented'>"); + seeTemp = new StringBuilder(); } - else - { - if (seeTemp.length() > 0) - { - String temp = seeTemp.substring(0, seeTemp.length() - 1); + else { + if (seeTemp.length() > 0) { + final String temp = seeTemp.substring(0, seeTemp.length() - 1); // syntax is exactly the same as link appendLinkTagText(see, temp); } @@ -509,15 +429,12 @@ public class ClassSource inVersion = false; inUnknowns = false; } - else if (("@throws".equals(token)) || ("@exception".equals(token)) && i < st.length) - { + else if (("@throws".equals(token)) || ("@exception".equals(token)) && i < st.length) { token = st[i++]; // Actual throwable - if (throwsItems == null) - { - throwsItems = new StringBuffer("<b>Throws:</b><p class='indented'>"); + if (throwsItems == null) { + throwsItems = new StringBuilder("<b>Throws:</b><p class='indented'>"); } - else - { + else { throwsItems.append("<br>"); } throwsItems.append("<b>").append(token).append("</b> "); @@ -530,11 +447,9 @@ public class ClassSource inVersion = false; inUnknowns = false; } - else if ("@since".equals(token) && i < st.length) - { - if (since == null) - { - since = new StringBuffer("<b>Since:</b><p class='indented'>"); + else if ("@since".equals(token) && i < st.length) { + if (since == null) { + since = new StringBuilder("<b>Since:</b><p class='indented'>"); } inSeeAlso = false; inReturns = false; @@ -545,14 +460,11 @@ public class ClassSource inVersion = false; inUnknowns = false; } - else if ("@author".equals(token) && i < st.length) - { - if (author == null) - { - author = new StringBuffer("<b>Author:</b><p class='indented'>"); + else if ("@author".equals(token) && i < st.length) { + if (author == null) { + author = new StringBuilder("<b>Author:</b><p class='indented'>"); } - else - { + else { author.append("<br>"); } inSeeAlso = false; @@ -564,14 +476,11 @@ public class ClassSource inVersion = false; inUnknowns = false; } - else if ("@version".equals(token) && i < st.length) - { - if (version == null) - { - version = new StringBuffer("<b>Version:</b><p class='indented'>"); + else if ("@version".equals(token) && i < st.length) { + if (version == null) { + version = new StringBuilder("<b>Version:</b><p class='indented'>"); } - else - { + else { version.append("<br>"); } inSeeAlso = false; @@ -583,14 +492,11 @@ public class ClassSource inVersion = true; inUnknowns = false; } - else if (token.startsWith("@") && token.length() > 1) - { - if (unknowns == null) - { - unknowns = new StringBuffer(); + else if (token.startsWith("@") && token.length() > 1) { + if (unknowns == null) { + unknowns = new StringBuilder(); } - else - { + else { unknowns.append("</p>"); } unknowns.append("<b>").append(token).append("</b><p class='indented'>"); @@ -604,80 +510,63 @@ public class ClassSource inVersion = false; inUnknowns = true; } - else if (inParams) - { + else if (inParams) { params.append(token).append(' '); } - else if (inReturns) - { + else if (inReturns) { returns.append(token).append(' '); } - else if (inSeeAlso) - { + else if (inSeeAlso) { // see.append(token).append(' '); seeTemp.append(token).append(' '); } - else if (inThrows) - { + else if (inThrows) { throwsItems.append(token).append(' '); } - else if (inSince) - { + else if (inSince) { since.append(token).append(' '); } - else if (inAuthor) - { + else if (inAuthor) { author.append(token).append(' '); } - else if (inVersion) - { + else if (inVersion) { version.append(token).append(' '); } - else if (inUnknowns) - { + else if (inUnknowns) { unknowns.append(token).append(' '); } } sb.append("<p>"); - if (params != null) - { + if (params != null) { sb.append(params).append("</p>"); } - if (returns != null) - { + if (returns != null) { sb.append(returns).append("</p>"); } - if (throwsItems != null) - { + if (throwsItems != null) { sb.append(throwsItems).append("</p>"); } - if (see != null) - { - if (seeTemp.length() > 0) - { // Last @see contents - String temp = seeTemp.substring(0, seeTemp.length() - 1); + if (see != null) { + if (seeTemp.length() > 0) { // Last @see contents + final String temp = seeTemp.substring(0, seeTemp.length() - 1); // syntax is exactly the same as link appendLinkTagText(see, temp); } see.append("<br>"); sb.append(see).append("</p>"); } - if (author != null) - { + if (author != null) { sb.append(author).append("</p>"); } - if (version != null) - { + if (version != null) { sb.append(version).append("</p>"); } - if (since != null) - { + if (since != null) { sb.append(since).append("</p>"); } - if (unknowns != null) - { + if (unknowns != null) { sb.append(unknowns).append("</p>"); } @@ -686,78 +575,63 @@ public class ClassSource /** * Appends HTML representing a "link" or "linkplain" Javadoc element to * a string buffer. - * - * @param appendTo - * The buffer to append to. - * @param linkContent - * The content of a "link" or "linkplain" item. + * + * @param appendTo The buffer to append to. + * @param s The content of a "link" or "linkplain" item. */ - private static final void appendLinkTagText(StringBuffer appendTo, String linkContent) - { + private static void appendLinkTagText(final StringBuilder appendTo, final String s) { appendTo.append("<a href='"); - linkContent = linkContent.trim(); // If "@link" and text on different lines - Matcher m = LINK_TAG_MEMBER_PATTERN.matcher(linkContent); + final String linkContent = s.trim(); // If "@link" and text on different lines + final Matcher m = LINK_TAG_MEMBER_PATTERN.matcher(linkContent); - if (m.find() && m.start() == 0) - { + if (m.find() && m.start() == 0) { // System.out.println("Match!!! - '" + m.group(0)); - String match = m.group(0); // Prevents recalculation - String link = match; + final String match = m.group(0); // Prevents recalculation // TODO: If this starts with '#', "link" must be prepended with // class name. String text = null; // No link "text" after the link location - just use link location - if (match.length() == linkContent.length()) - { - int pound = match.indexOf('#'); - if (pound == 0) - { // Just a method or field in this class + if (match.length() == linkContent.length()) { + final int pound = match.indexOf('#'); + if (pound == 0) { // Just a method or field in this class text = match.substring(1); } - else if (pound > 0) - { // Not -1 - String prefix = match.substring(0, pound); - if ("java.lang.Object".equals(prefix)) - { + else if (pound > 0) { // Not -1 + final String prefix = match.substring(0, pound); + if ("java.lang.Object".equals(prefix)) { text = match.substring(pound + 1); } } - else - { // Just use whole match (invalid link?) - // TODO: Could be just a class name. Find on classpath + else { // Just use whole match (invalid link?) + // TODO: Could be just a class name. Find on classpath text = match; } } - else - { // match.length() < linkContent.length() + else { // match.length() < linkContent.length() int offs = match.length(); // Will usually skip just a single space - while (offs < linkContent.length() && Character.isWhitespace(linkContent.charAt(offs))) - { + while (offs < linkContent.length() && Character.isWhitespace(linkContent.charAt(offs))) { offs++; } - if (offs < linkContent.length()) - { + if (offs < linkContent.length()) { text = linkContent.substring(offs); } } // No "better" text for link found - just use match. - if (text == null) - { + if (text == null) { text = linkContent;// .substring(match.length()); } // Replace the '#' sign, if any. text = fixLinkText(text); - appendTo./* append("link://"). */append(link).append("'>").append(text); + appendTo./* append("link://"). */append(match).append("'>").append(text); } - else - { // Malformed link tag + else { // Malformed link tag System.out.println("Unmatched linkContent: " + linkContent); appendTo.append("'>").append(linkContent); } @@ -768,71 +642,60 @@ public class ClassSource /** * Converts a Java documentation comment to HTML. - * + * * <pre> * This is a * pre block * </pre> - * - * @param dc - * The documentation comment. + * + * @param dc The documentation comment. * @return An HTML version of the comment. */ - public static final String docCommentToHtml(String dc) - { + public static String docCommentToHtml(String dc) { - if (dc == null) - { + if (dc == null) { return null; } - if (dc.endsWith("*/")) - { + if (dc.endsWith("*/")) { dc = dc.substring(0, dc.length() - 2); } // First, strip the line transitions. These always seem to be stripped // first from Javadoc, even when in between <pre> and </pre> tags. - Matcher m = DOC_COMMENT_LINE_HEADER.matcher(dc); + final Matcher m = DOC_COMMENT_LINE_HEADER.matcher(dc); dc = m.replaceAll("\n"); - StringBuffer html = new StringBuffer(); + StringBuilder html = new StringBuilder(); // "<html><style> .indented { margin-top: 0px; padding-left: 30pt; } </style><body>"); - StringBuffer tailBuf = null; + StringBuilder tailBuf = null; - BufferedReader r = new BufferedReader(new StringReader(dc)); + final BufferedReader r = new BufferedReader(new StringReader(dc)); - try - { + try { // Handle the first line (guaranteed to be at least 1 line). String line = r.readLine().substring(3); line = possiblyStripDocCommentTail(line); int offs = 0; - while (offs < line.length() && Character.isWhitespace(line.charAt(offs))) - { + while (offs < line.length() && Character.isWhitespace(line.charAt(offs))) { offs++; } - if (offs < line.length()) - { + if (offs < line.length()) { html.append(line.substring(offs)); } boolean inPreBlock = isInPreBlock(line, false); html.append(inPreBlock ? '\n' : ' '); // Read all subsequent lines. - while ((line = r.readLine()) != null) - { + while ((line = r.readLine()) != null) { line = possiblyStripDocCommentTail(line); - if (tailBuf != null) - { + if (tailBuf != null) { tailBuf.append(line).append(' '); } - else if (line.trim().startsWith("@")) - { - tailBuf = new StringBuffer(); + else if (line.trim().startsWith("@")) { + tailBuf = new StringBuilder(); tailBuf.append(line).append(' '); } - else - { + else { html.append(line); inPreBlock = isInPreBlock(line, inPreBlock); html.append(inPreBlock ? '\n' : ' '); @@ -841,13 +704,11 @@ public class ClassSource } } - catch (IOException ioe) - { // Never happens + catch (final IOException ioe) { // Never happens ioe.printStackTrace(); } html = fixDocComment(html); // Fix stuff like "{@code}" - if (tailBuf != null) - { + if (tailBuf != null) { appendDocCommentTail(html, fixDocComment(tailBuf)); } @@ -855,35 +716,27 @@ public class ClassSource } - public static String forXML(String aText) - { - final StringBuffer result = new StringBuffer(); + public static String forXML(final String aText) { + final StringBuilder result = new StringBuilder(); final StringCharacterIterator iterator = new StringCharacterIterator(aText); char character = iterator.current(); - while (character != CharacterIterator.DONE) - { - if (character == '<') - { + while (character != CharacterIterator.DONE) { + if (character == '<') { result.append("<"); } - else if (character == '>') - { + else if (character == '>') { result.append(">"); } - else if (character == '\"') - { + else if (character == '\"') { result.append("""); } - else if (character == '\'') - { + else if (character == '\'') { result.append("'"); } - else if (character == '&') - { + else if (character == '&') { result.append("&"); } - else - { + else { // the char is not a special one // add it to the result as is result.append(character); @@ -893,71 +746,60 @@ public class ClassSource return result.toString(); } - private static final StringBuffer fixDocComment(StringBuffer text) - { + private static StringBuilder fixDocComment(final StringBuilder text) { // Nothing to do. int index = text.indexOf("{@"); - if (index == -1) - { + if (index == -1) { return text; } // TODO: In Java 5, replace "sb.append(sb2.substring(...))" // calls with "sb.append(sb2, offs, len)". - StringBuffer sb = new StringBuffer(); + final StringBuilder sb = new StringBuilder(); int textOffs = 0; - do - { + do { - int closingBrace = indexOf('}', text, index + 2); - if (closingBrace > -1) - { // Should practically always be true + final int closingBrace = indexOf('}', text, index + 2); + if (closingBrace > -1) { // Should practically always be true sb.append(text.substring(textOffs, index)); - String content = text.substring(index + 2, closingBrace); + final String content = text.substring(index + 2, closingBrace); index = textOffs = closingBrace + 1; - if (content.startsWith("code ")) - { + if (content.startsWith("code ")) { sb.append("<code>").append(forXML(content.substring(5))).append("</code>"); } - else if (content.startsWith("link ")) - { + else if (content.startsWith("link ")) { sb.append("<code>"); appendLinkTagText(sb, content.substring(5)); sb.append("</code>"); } - else if (content.startsWith("linkplain ")) - { + else if (content.startsWith("linkplain ")) { appendLinkTagText(sb, content.substring(10)); } - else if (content.startsWith("literal ")) - { + else if (content.startsWith("literal ")) { // TODO: Should escape HTML-breaking chars, such as '>'. sb.append(content.substring(8)); } - else - { // Unhandled Javadoc tag + else { // Unhandled Javadoc tag sb.append("<code>").append(content).append("</code>"); } } - else - { + else { break; // Unclosed javadoc tag - just bail } } while ((index = text.indexOf("{@", index)) > -1); - if (textOffs < text.length()) - { + if (textOffs < text.length()) { sb.append(text.substring(textOffs)); } return sb; @@ -965,15 +807,12 @@ public class ClassSource /** * Tidies up a link's display text for use in a <a> tag. - * - * @param text - * The text (a class, method, or field signature). + * + * @param text The text (a class, method, or field signature). * @return The display value for the signature. */ - private static final String fixLinkText(String text) - { - if (text.startsWith("#")) - { // Method in the current class + private static String fixLinkText(final String text) { + if (text.startsWith("#")) { // Method in the current class return text.substring(1); } return text.replace('#', '.'); @@ -983,22 +822,16 @@ public class ClassSource * Returns the next location of a single character in a character sequence. * This method is here because <tt>StringBuilder</tt> doesn't get this * method added to it until Java 1.5. - * - * @param ch - * The character to look for. - * @param sb - * The character sequence. - * @param offs - * The offset at which to start looking. + * + * @param ch The character to look for. + * @param sb The character sequence. + * @param offs The offset at which to start looking. * @return The next location of the character, or <tt>-1</tt> if it is not - * found. + * found. */ - private static final int indexOf(char ch, CharSequence sb, int offs) - { - while (offs < sb.length()) - { - if (ch == sb.charAt(offs)) - { + private static int indexOf(final char ch, final CharSequence sb, int offs) { + while (offs < sb.length()) { + if (ch == sb.charAt(offs)) { return offs; } offs++; @@ -1008,29 +841,22 @@ public class ClassSource /** * Returns whether this line ends in the middle of a pre-block. - * - * @param line - * The line's contents. - * @param prevValue - * Whether this line started in a pre-block. + * + * @param line The line's contents. + * @param prevValue Whether this line started in a pre-block. * @return Whether the line ends in a pre-block. */ - private static final boolean isInPreBlock(String line, boolean prevValue) - { - int lastPre = line.lastIndexOf("pre>"); - if (lastPre <= 0) - { + private static boolean isInPreBlock(final String line, final boolean prevValue) { + final int lastPre = line.lastIndexOf("pre>"); + if (lastPre <= 0) { return prevValue; } - char prevChar = line.charAt(lastPre - 1); - if (prevChar == '<') - { + final char prevChar = line.charAt(lastPre - 1); + if (prevChar == '<') { return true; } - else if (prevChar == '/' && lastPre >= 2) - { - if (line.charAt(lastPre - 2) == '<') - { + else if (prevChar == '/' && lastPre >= 2) { + if (line.charAt(lastPre - 2) == '<') { return false; } } @@ -1040,46 +866,38 @@ public class ClassSource /** * Removes the tail end of a documentation comment from a string, if it * exists. - * - * @param str - * The string. + * + * @param str The string. * @return The string, possibly with the documentation comment tail - * removed. + * removed. */ - private static final String possiblyStripDocCommentTail(String str) - { - if (str.endsWith("*/")) - { + private static String possiblyStripDocCommentTail(String str) { + if (str.endsWith("*/")) { str = str.substring(0, str.length() - 2); } return str; } - public static HashMap<String, String> getParameters(String doc) - { - HashMap<String, String> toReturn = new HashMap<String, String>(); - if (doc != null && doc.contains("<b>Parameters:</b>")) - { - int idx = doc.indexOf(PARAM_PATTERN) + PARAM_PATTERN.length(); + public static HashMap<String, String> getParameters(String doc) { + final HashMap<String, String> toReturn = new HashMap<>(); + if (doc != null && doc.contains("<b>Parameters:</b>")) { + final int idx = doc.indexOf(PARAM_PATTERN) + PARAM_PATTERN.length(); doc = doc.substring(idx, doc.indexOf("</p>", idx)); int end = doc.indexOf("<br>"); - while (!StringUtil.isEmpty(doc)) - { + while (!StringUtil.isEmpty(doc)) { String parameterDoc = doc; if (end != -1) parameterDoc = doc.substring(0, end); - Pattern p = Pattern.compile("<b>(.*)</b>(.*)"); - Matcher m = p.matcher(parameterDoc); - if (m.find()) - { + final Pattern p = Pattern.compile("<b>(.*)</b>(.*)"); + final Matcher m = p.matcher(parameterDoc); + if (m.find()) { toReturn.put(m.group(1), m.group(2)); } - if (end != -1) - { + if (end != -1) { doc = doc.substring(end + "<br>".length()); end = doc.indexOf("<br>"); } diff --git a/src/main/java/plugins/tprovoost/scripteditor/javasource/ConstructorVisitor.java b/src/main/java/plugins/tprovoost/scripteditor/javasource/ConstructorVisitor.java index 139305c3040c09e0c1a974ba44ccd71590ed0532..6ccab4ac483dc1b600c1e3418f6b1b67929ca087 100644 --- a/src/main/java/plugins/tprovoost/scripteditor/javasource/ConstructorVisitor.java +++ b/src/main/java/plugins/tprovoost/scripteditor/javasource/ConstructorVisitor.java @@ -2,11 +2,9 @@ package plugins.tprovoost.scripteditor.javasource; import japa.parser.ast.body.ConstructorDeclaration; -public class ConstructorVisitor extends JavaVisitor -{ +public class ConstructorVisitor extends JavaVisitor { @Override - public void visit(ConstructorDeclaration n, Object arg) - { + public void visit(final ConstructorDeclaration n, final Object arg) { list.add(n); } } diff --git a/src/main/java/plugins/tprovoost/scripteditor/javasource/EnumVisitor.java b/src/main/java/plugins/tprovoost/scripteditor/javasource/EnumVisitor.java index 54d2a5edf08b1e5c0b98dde84321cb64e072aedd..5bcce3aa73b0b29fe584c9833f67ceb2f2f515d2 100644 --- a/src/main/java/plugins/tprovoost/scripteditor/javasource/EnumVisitor.java +++ b/src/main/java/plugins/tprovoost/scripteditor/javasource/EnumVisitor.java @@ -2,11 +2,9 @@ package plugins.tprovoost.scripteditor.javasource; import japa.parser.ast.body.EnumDeclaration; -public class EnumVisitor extends JavaVisitor -{ +public class EnumVisitor extends JavaVisitor { @Override - public void visit(EnumDeclaration n, Object arg) - { + public void visit(final EnumDeclaration n, final Object arg) { list.add(n); } } diff --git a/src/main/java/plugins/tprovoost/scripteditor/javasource/FieldVisitor.java b/src/main/java/plugins/tprovoost/scripteditor/javasource/FieldVisitor.java index e138bbfa0f19a9a6ea7c7067644c1d3acf6a7987..aabb136965f8545207a10b9cf3e6ce7213d4e261 100644 --- a/src/main/java/plugins/tprovoost/scripteditor/javasource/FieldVisitor.java +++ b/src/main/java/plugins/tprovoost/scripteditor/javasource/FieldVisitor.java @@ -2,11 +2,9 @@ package plugins.tprovoost.scripteditor.javasource; import japa.parser.ast.body.FieldDeclaration; -public class FieldVisitor extends JavaVisitor -{ +public class FieldVisitor extends JavaVisitor { @Override - public void visit(FieldDeclaration n, Object arg) - { + public void visit(final FieldDeclaration n, final Object arg) { list.add(n); } } \ No newline at end of file diff --git a/src/main/java/plugins/tprovoost/scripteditor/javasource/JarAccess.java b/src/main/java/plugins/tprovoost/scripteditor/javasource/JarAccess.java index 9107c0172a23e5f4172d118678d071dd9c3c0299..dfb9e75031bd9563959c1387ca821078c32117f1 100644 --- a/src/main/java/plugins/tprovoost/scripteditor/javasource/JarAccess.java +++ b/src/main/java/plugins/tprovoost/scripteditor/javasource/JarAccess.java @@ -5,22 +5,20 @@ import java.io.InputStream; import java.net.URL; import java.util.LinkedList; +import icy.system.IcyExceptionHandler; import icy.util.ClassUtil; -public class JarAccess -{ - private static LinkedList<String> toSource = new LinkedList<String>(); +public class JarAccess { + private static final LinkedList<String> toSource = new LinkedList<>(); /** * Make a sensible effort to get the path of the source for a class. - * - * @param clazz - * the class we are looking source for + * + * @param clazz the class we are looking source for * @return the {@link InputStream} defining the source of the input {@link Class} */ - public static InputStream getJavaSourceInputStream(Class<?> clazz) - { - String className; + public static InputStream getJavaSourceInputStream(final Class<?> clazz) { + final String className; if (clazz.isArray()) className = clazz.getCanonicalName(); else @@ -31,46 +29,40 @@ public class JarAccess /** * Make a sensible effort to get the path of the source for a class. */ - private static InputStream getJavaSourceInputStream(String className) - { - // pauseSourcingProcess(); TODO + private static InputStream getJavaSourceInputStream(final String className) { + // TODO: + // pauseSourcingProcess(); // First, let's try to get the .jar file for said class. - URL result = getURLJava(className); + final URL result = getURLJava(className); if (result == null) return null; - try - { - InputStream stream = result.openStream(); + try { + final InputStream stream = result.openStream(); toSource.add(className); return stream; } - catch (IOException e) - { + catch (final IOException e) { e.printStackTrace(); } return null; } - private static URL getURLJava(String className) - { - try - { - Class<?> clazz = ClassUtil.findClass(className); + private static URL getURLJava(final String className) { + try { + final Class<?> clazz = ClassUtil.findClass(className); String baseName = className; - int dot = baseName.lastIndexOf('.'); + final int dot = baseName.lastIndexOf('.'); if (dot > 0) baseName = baseName.substring(dot + 1); - URL urlResource = clazz.getResource(baseName + ".java"); - if (urlResource != null) - { + final URL urlResource = clazz.getResource(baseName + ".java"); + if (urlResource != null) { return urlResource; } } - catch (ClassNotFoundException e) - { - // ignore + catch (final ClassNotFoundException e) { + IcyExceptionHandler.showErrorMessage(e, true); } return null; } diff --git a/src/main/java/plugins/tprovoost/scripteditor/javasource/JavaVisitor.java b/src/main/java/plugins/tprovoost/scripteditor/javasource/JavaVisitor.java index 93d1d611390d8370387cfd497353833feb96fe4b..c3c79a2537b8d598416136ea9dc5f0c41c45d825 100644 --- a/src/main/java/plugins/tprovoost/scripteditor/javasource/JavaVisitor.java +++ b/src/main/java/plugins/tprovoost/scripteditor/javasource/JavaVisitor.java @@ -5,13 +5,10 @@ import japa.parser.ast.visitor.VoidVisitorAdapter; import java.util.ArrayList; -@SuppressWarnings("rawtypes") -public abstract class JavaVisitor extends VoidVisitorAdapter -{ - protected ArrayList<BodyDeclaration> list = new ArrayList<BodyDeclaration>(); +public abstract class JavaVisitor extends VoidVisitorAdapter<Object> { + protected ArrayList<BodyDeclaration> list = new ArrayList<>(); - public ArrayList<BodyDeclaration> getList() - { + public ArrayList<BodyDeclaration> getList() { return list; } } \ No newline at end of file diff --git a/src/main/java/plugins/tprovoost/scripteditor/javasource/MethodVisitor.java b/src/main/java/plugins/tprovoost/scripteditor/javasource/MethodVisitor.java index 8cad47ccac92e7f6f28f67988345eb5b12b2a7b6..704b604a0235d39dda21b48e280674e7cbd0a9aa 100644 --- a/src/main/java/plugins/tprovoost/scripteditor/javasource/MethodVisitor.java +++ b/src/main/java/plugins/tprovoost/scripteditor/javasource/MethodVisitor.java @@ -2,11 +2,9 @@ package plugins.tprovoost.scripteditor.javasource; import japa.parser.ast.body.MethodDeclaration; -public class MethodVisitor extends JavaVisitor -{ +public class MethodVisitor extends JavaVisitor { @Override - public void visit(MethodDeclaration n, Object arg) - { + public void visit(final MethodDeclaration n, final Object arg) { list.add(n); } } diff --git a/src/main/java/plugins/tprovoost/scripteditor/main/ScriptEditorPlugin.java b/src/main/java/plugins/tprovoost/scripteditor/main/ScriptEditorPlugin.java index 5421a45eb4bc09d0e97218f6318fa207109b98ea..55bf2f5ca8b9a25d1cb5f27dfc339ab613bd178d 100644 --- a/src/main/java/plugins/tprovoost/scripteditor/main/ScriptEditorPlugin.java +++ b/src/main/java/plugins/tprovoost/scripteditor/main/ScriptEditorPlugin.java @@ -1,20 +1,20 @@ /* - * Copyright 2010-2015 Institut Pasteur. - * + * Copyright 2010-2023 Institut Pasteur. + * * This file is part of Icy. - * + * * Icy 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. - * + * * Icy 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 Icy. If not, see <http://www.gnu.org/licenses/>. + * along with Icy. If not, see <https://www.gnu.org/licenses/>. */ package plugins.tprovoost.scripteditor.main; @@ -25,14 +25,11 @@ import java.io.IOException; import java.util.ArrayList; import java.util.List; -import javax.script.ScriptEngineManager; - import icy.file.FileUtil; import icy.gui.frame.IcyFrameAdapter; import icy.gui.frame.IcyFrameEvent; import icy.gui.frame.progress.FailedAnnounceFrame; import icy.main.Icy; -import icy.plugin.PluginLoader; import icy.plugin.abstract_.PluginActionable; import icy.system.IcyExceptionHandler; import icy.system.thread.ThreadUtil; @@ -41,72 +38,67 @@ import plugins.tprovoost.scripteditor.gui.ScriptingPanel; import plugins.tprovoost.scripteditor.scriptinghandlers.ScriptEngineHandler; import plugins.tprovoost.scripteditor.scriptinghandlers.ScriptingHandler; -public class ScriptEditorPlugin extends PluginActionable -{ - static List<ScriptingEditor> editors = new ArrayList<ScriptingEditor>(); +public class ScriptEditorPlugin extends PluginActionable { + static List<ScriptingEditor> editors = new ArrayList<>(); @Override - public void run() - { - if (ScriptEngineHandler.getEngineManager().getEngineFactories().isEmpty()) - { - new FailedAnnounceFrame("No interpreter found. Impossible to compile/run a script."); - System.out.println("No interpreter found. Impossible to compile/run a script."); - return; - } - - final ScriptingEditor frame = new ScriptingEditor(); - frame.setSize(500, 500); - frame.addToDesktopPane(); - frame.setVisible(true); - frame.requestFocus(); - - editors.add(frame); - frame.addFrameListener(new IcyFrameAdapter() - { + public void run() { + ThreadUtil.invokeLater(new Runnable() { @Override - public void icyFrameClosed(IcyFrameEvent e) - { - frame.removeFrameListener(this); - editors.remove(frame); - } - }); - - // get command line arguments - final String[] args = Icy.getCommandLinePluginArgs(); - - // verify that arguments exists and are not 'consumed' - if ((args.length > 0) && (args[0] != null)) - { - try - { - if (FileUtil.exists(args[0])) - { - // open the script - frame.openFile(new File(args[0])); - // retrieve the scripting panel - final ScriptingPanel pane = (ScriptingPanel) frame.getTabbedPane().getSelectedComponent(); - final ScriptingHandler handler = pane.getScriptHandler(); + public void run() { + if (ScriptEngineHandler.getEngineManager().getEngineFactories().isEmpty()) { + new FailedAnnounceFrame("No interpreter found. Impossible to compile/run a script."); + System.out.println("No interpreter found. Impossible to compile/run a script."); + return; + } - if (handler != null) - { - handler.setNewEngine(true); - handler.setForceRun(false); - handler.setStrict(true); - handler.setVarInterpretation(true); - handler.interpret(true); + final ScriptingEditor frame = new ScriptingEditor(); + frame.setSize(500, 500); + frame.addToDesktopPane(); + frame.setVisible(true); + frame.requestFocus(); + + editors.add(frame); + frame.addFrameListener(new IcyFrameAdapter() { + @Override + public void icyFrameClosed(final IcyFrameEvent e) { + frame.removeFrameListener(this); + editors.remove(frame); } + }); + + // get command line arguments + final String[] args = Icy.getCommandLinePluginArgs(); + + // verify that arguments exists and are not 'consumed' + if ((args.length > 0) && (args[0] != null)) { + try { + if (FileUtil.exists(args[0])) { + // open the script + frame.openFile(new File(args[0])); + // retrieve the scripting panel + final ScriptingPanel pane = (ScriptingPanel) frame.getTabbedPane().getSelectedComponent(); + final ScriptingHandler handler = pane.getScriptHandler(); + + if (handler != null) { + handler.setNewEngine(true); + handler.setForceRun(false); + handler.setStrict(true); + handler.setVarInterpretation(true); + handler.interpret(true); + } + } + } + catch (final Exception e) { + System.err.println("Script Editor: cannot execute specified '" + args[0] + "' script file"); + IcyExceptionHandler.showErrorMessage(e, true); + } + + // argument consumed + args[0] = null; } } - catch (Exception e) - { - System.err.println("Script Editor: cannot execute specified '" + args[0] + "' script file"); - IcyExceptionHandler.showErrorMessage(e, true); - } - - // argument consumed - args[0] = null; - } + }); } // @BindingFunction(value = "displayHelloString") @@ -135,71 +127,50 @@ public class ScriptEditorPlugin extends PluginActionable /** * Creates a new tab from a file. - * - * @param f - * input file - * @throws IOException - * if the file cannot be opened + * + * @param f input file + * @throws IOException if the file cannot be opened */ - public static void openInScriptEditor(final File f) throws IOException - { + public static void openInScriptEditor(final File f) throws IOException { // TODO gen text - BufferedReader reader = new BufferedReader(new FileReader(f)); - String text = ""; + final BufferedReader reader = new BufferedReader(new FileReader(f)); + final StringBuilder text = new StringBuilder(); String line; - while ((line = reader.readLine()) != null) - { - text += (line + "\n"); + while ((line = reader.readLine()) != null) { + text.append(line).append("\n"); } reader.close(); - openInScriptEditor(text, f.getName()); + openInScriptEditor(text.toString(), f.getName()); } /** * Creates a new tab containing the <code>text</code>, with no title. - * - * @param text - * the input script in String format + * + * @param text the input script in String format */ - public static void openInScriptEditor(final String text) - { + public static void openInScriptEditor(final String text) { openInScriptEditor(text, "Untitled*"); } /** * Creates a new tab with the <code>title</code> and containing the <code>text</code>. - * - * @param text - * the input script in String format - * @param title - * tab title + * + * @param text the input script in String format + * @param title tab title */ - public static void openInScriptEditor(final String text, final String title) - { - if (!editors.isEmpty()) - { - ThreadUtil.invokeLater(new Runnable() - { - @Override - public void run() - { - ScriptingPanel panel = editors.get(0).createNewPane(title); - panel.getTextArea().setText(text); - } + public static void openInScriptEditor(final String text, final String title) { + if (!editors.isEmpty()) { + ThreadUtil.invokeLater(() -> { + final ScriptingPanel panel = editors.get(0).createNewPane(title); + panel.getTextArea().setText(text); }); } - else - { - ThreadUtil.invokeLater(new Runnable() - { - @Override - public void run() - { - new ScriptEditorPlugin().run(); - ScriptingPanel panel = editors.get(0).createNewPane(title); - panel.getTextArea().setText(text); - } + else { + ThreadUtil.invokeLater(() -> { + new ScriptEditorPlugin().run(); + final ScriptingPanel panel = editors.get(0).createNewPane(title); + panel.getTextArea().setText(text); }); } } diff --git a/src/main/java/plugins/tprovoost/scripteditor/main/ScriptListener.java b/src/main/java/plugins/tprovoost/scripteditor/main/ScriptListener.java index 844be261e586b70924f9c7541e6474bfbac92e0d..2a8307b71206b03c8d66ea0222a24bf3b993b0bf 100644 --- a/src/main/java/plugins/tprovoost/scripteditor/main/ScriptListener.java +++ b/src/main/java/plugins/tprovoost/scripteditor/main/ScriptListener.java @@ -1,8 +1,7 @@ package plugins.tprovoost.scripteditor.main; -public interface ScriptListener -{ - public void evaluationStarted(); - - public void evaluationOver(); +public interface ScriptListener { + void evaluationStarted(); + + void evaluationOver(); } diff --git a/src/main/java/plugins/tprovoost/scripteditor/scriptblock/JSScriptBlock.java b/src/main/java/plugins/tprovoost/scripteditor/scriptblock/JSScriptBlock.java index f98410d2a0e31bdf51e6e981b1b66d2a82968029..b72a4c3991f9720d090523ff71fbbc5405e3f0a3 100644 --- a/src/main/java/plugins/tprovoost/scripteditor/scriptblock/JSScriptBlock.java +++ b/src/main/java/plugins/tprovoost/scripteditor/scriptblock/JSScriptBlock.java @@ -4,30 +4,24 @@ import org.mozilla.javascript.Context; import org.mozilla.javascript.NativeArray; import org.mozilla.javascript.NativeJavaObject; -public class JSScriptBlock -{ +public class JSScriptBlock { - public static Object transformScriptOutput(Object o) - { - Object toReturn = o; - if (o instanceof NativeArray) - { + public static Object transformScriptOutput(final Object o) { + final Object toReturn; + if (o instanceof NativeArray) { toReturn = convertNativeArraytoJSArray((NativeArray) o); } - else if (o instanceof NativeJavaObject) - { + else if (o instanceof NativeJavaObject) { return ((NativeJavaObject) o).unwrap(); } - else - { + else { toReturn = Context.jsToJava(o, Object.class); } return toReturn; } - public static Object transformInputForScript(Object o) - { - Object toReturn = o; + public static Object transformInputForScript(final Object o) { + // Object toReturn = o; // Context cx = Context.enter(); // try // { @@ -42,15 +36,13 @@ public class JSScriptBlock // { // toReturn = ((NativeJavaArray) toReturn).unwrap(); // } - return toReturn; + return o; } - public static Object convertNativeArraytoJSArray(NativeArray array) - { - int len = (int) array.getLength(); - Object[] toReturn = new Object[len]; - for (int i = 0; i < array.getLength(); ++i) - { + public static Object convertNativeArraytoJSArray(final NativeArray array) { + final int len = (int) array.getLength(); + final Object[] toReturn = new Object[len]; + for (int i = 0; i < array.getLength(); ++i) { toReturn[i] = transformScriptOutput(array.get(i, null)); } return toReturn; diff --git a/src/main/java/plugins/tprovoost/scripteditor/scriptblock/Javascript.java b/src/main/java/plugins/tprovoost/scripteditor/scriptblock/Javascript.java index 5af4ccecc7017132cea2d1ccaff674fbe32509e9..2e3cbf8cff5b188524abe81bd069efaf1a1ae085 100644 --- a/src/main/java/plugins/tprovoost/scripteditor/scriptblock/Javascript.java +++ b/src/main/java/plugins/tprovoost/scripteditor/scriptblock/Javascript.java @@ -1,20 +1,20 @@ /* - * Copyright 2010-2015 Institut Pasteur. - * + * Copyright 2010-2023 Institut Pasteur. + * * This file is part of Icy. - * + * * Icy 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. - * + * * Icy 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 Icy. If not, see <http://www.gnu.org/licenses/>. + * along with Icy. If not, see <https://www.gnu.org/licenses/>. */ package plugins.tprovoost.scripteditor.scriptblock; @@ -24,6 +24,7 @@ import java.util.ArrayList; import javax.script.ScriptException; +import icy.system.IcyExceptionHandler; import org.fife.ui.autocomplete.ParameterizedCompletion.Parameter; import plugins.adufour.vars.lang.Var; @@ -37,105 +38,112 @@ import plugins.tprovoost.scripteditor.scriptinghandlers.ScriptEngine; /** * This block allows to define a JavaScript script using multiple inputs from * other blocks and produce multiple results when executed. - * + * <p> * It is possible to specify multiple inputs using the "Add Input" button. It is * also possible to add several outputs by using the "Add Output" button. - * + * <p> * Please check the online documentation for more information. - * + * * @author Thomas Provoost * @author Daniel Gonzalez */ public class Javascript extends ScriptBlock { - public Javascript() { - super(new VarJavaScriptScript("", "// Click on the button\n// to edit in a frame.\n\noutput0 = input0 * 2")); - } - - @Override - protected void installEngineMethods(ScriptEngine engine, ArrayList<Method> methods) { - // hardcoded functions, to remove in the future - try { - engine.eval( - "function getSequence() { return Packages.icy.main.Icy.getMainInterface().getFocusedSequence() }"); - } catch (ScriptException e1) { - } - try { - engine.eval("function getImage() { return Packages.icy.main.Icy.getMainInterface().getFocusedImage(); }"); - } catch (ScriptException e1) { - } - try { - engine.eval("gui = Packages.icy.main.Icy.getMainInterface()"); - } catch (ScriptException e1) { - } - - for (Method method : methods) { - // is it an annotated with BindingFunction? - BindingFunction blockFunction = method.getAnnotation(BindingFunction.class); - if (blockFunction == null) - continue; - // Generate the function for the provider - ArrayList<Parameter> fParams = new ArrayList<Parameter>(); - Class<?>[] paramTypes = method.getParameterTypes(); - - // get the parameters - String params = ""; - String functionName = blockFunction.value(); - // get the parameters - for (int i = 0; i < paramTypes.length; ++i) { - fParams.add(new Parameter(IcyCompletionProvider.getType(paramTypes[i], true), "arg" + i)); - params += ",arg" + i; - } - if (params.length() > 0) - params = params.substring(1); - - // the object for the provider - ScriptFunctionCompletion sfc; - if (Modifier.isStatic(method.getModifiers())) - sfc = new ScriptFunctionCompletion(null, functionName, method); - else - sfc = new ScriptFunctionCompletion(null, method.getName(), method); - - try { - // FIXME? - // if (engine instanceof RhinoScriptEngine) - // { - if (method.getReturnType() == void.class) { - engine.eval("function " + functionName + " (" + params + ") {\n\t" + sfc.getMethodCall() + "\n}"); - } else { - engine.eval("function " + functionName + " (" + params + ") {\n\treturn " + sfc.getMethodCall() - + "\n}"); - } - // } - } catch (ScriptException e) { - e.printStackTrace(); - } - } - } - - @Override - protected void injectInputVariables(ScriptEngine engine) { - for (Var<?> var : getVarScript().getInputVariables()) { - Object value = var.getValue(); - String name = var.getName(); - if (name.contains("input")) { - // For another language, remove this, or use the right one. - value = JSScriptBlock.transformInputForScript(value); - - // put in the engine the value. - engine.put(name, value); - } - } - - } - - @Override - protected void setOutputVariables(ScriptEngine engine) { - for (VarMutable output : getVarScript().getOutputVariables()) { - Object resObject = engine.get(output.getName()); - output.setValue(JSScriptBlock.transformScriptOutput(resObject)); - } - - } + public Javascript() { + super(new VarJavaScriptScript("", "// Click on the button\n// to edit in a frame.\n\noutput0 = input0 * 2")); + } + + @Override + protected void installEngineMethods(final ScriptEngine engine, final ArrayList<Method> methods) { + // hardcoded functions, to remove in the future + try { + engine.eval("function getSequence() { return Packages.icy.main.Icy.getMainInterface().getFocusedSequence() }"); + } + catch (final ScriptException e) { + IcyExceptionHandler.showErrorMessage(e, true); + } + try { + engine.eval("function getImage() { return Packages.icy.main.Icy.getMainInterface().getFocusedImage(); }"); + } + catch (final ScriptException e) { + IcyExceptionHandler.showErrorMessage(e, true); + } + try { + engine.eval("gui = Packages.icy.main.Icy.getMainInterface()"); + } + catch (final ScriptException e) { + IcyExceptionHandler.showErrorMessage(e, true); + } + + for (final Method method : methods) { + // is it an annotated with BindingFunction? + final BindingFunction blockFunction = method.getAnnotation(BindingFunction.class); + if (blockFunction == null) + continue; + // Generate the function for the provider + final ArrayList<Parameter> fParams = new ArrayList<>(); + final Class<?>[] paramTypes = method.getParameterTypes(); + + // get the parameters + StringBuilder params = new StringBuilder(); + final String functionName = blockFunction.value(); + // get the parameters + for (int i = 0; i < paramTypes.length; ++i) { + fParams.add(new Parameter(IcyCompletionProvider.getType(paramTypes[i], true), "arg" + i)); + params.append(",arg").append(i); + } + if (params.length() > 0) + params = new StringBuilder(params.substring(1)); + + // the object for the provider + final ScriptFunctionCompletion sfc; + if (Modifier.isStatic(method.getModifiers())) + sfc = new ScriptFunctionCompletion(null, functionName, method); + else + sfc = new ScriptFunctionCompletion(null, method.getName(), method); + + try { + // FIXME? + // if (engine instanceof RhinoScriptEngine) + // { + if (method.getReturnType() == void.class) { + engine.eval("function " + functionName + " (" + params + ") {\n\t" + sfc.getMethodCall() + "\n}"); + } + else { + engine.eval("function " + functionName + " (" + params + ") {\n\treturn " + sfc.getMethodCall() + "\n}"); + } + // } + } + catch (final ScriptException e) { + //e.printStackTrace(); + IcyExceptionHandler.showErrorMessage(e, true); + } + } + } + + @Override + protected void injectInputVariables(final ScriptEngine engine) { + for (final Var<?> var : getVarScript().getInputVariables()) { + Object value = var.getValue(); + final String name = var.getName(); + if (name.contains("input")) { + // For another language, remove this, or use the right one. + value = JSScriptBlock.transformInputForScript(value); + + // put in the engine the value. + engine.put(name, value); + } + } + + } + + @Override + protected void setOutputVariables(final ScriptEngine engine) { + for (final VarMutable output : getVarScript().getOutputVariables()) { + final Object resObject = engine.get(output.getName()); + output.setValue(JSScriptBlock.transformScriptOutput(resObject)); + } + + } } diff --git a/src/main/java/plugins/tprovoost/scripteditor/scriptblock/OldJavascript.java b/src/main/java/plugins/tprovoost/scripteditor/scriptblock/OldJavascript.java index 2c4d07e1567039b11d6e95beab984aa1d8f54e71..25d959263756b40462c6fd962e67d1ee45c27794 100644 --- a/src/main/java/plugins/tprovoost/scripteditor/scriptblock/OldJavascript.java +++ b/src/main/java/plugins/tprovoost/scripteditor/scriptblock/OldJavascript.java @@ -5,7 +5,6 @@ import java.util.ArrayList; import java.util.HashMap; import javax.script.ScriptEngineFactory; -import javax.script.ScriptEngineManager; import javax.script.ScriptException; import icy.plugin.abstract_.Plugin; @@ -28,23 +27,22 @@ import plugins.tprovoost.scripteditor.scriptinghandlers.ScriptingHandler; import plugins.tprovoost.scripteditor.scriptinghandlers.VariableType; import plugins.tprovoost.scripteditor.scriptinghandlers.js.JSScriptEngine; -public class OldJavascript extends Plugin implements Block, VarListListener, TypeChangeListener -{ - ArrayList<String> languagesInstalled = new ArrayList<String>(); - - private VarScript inputScript = new VarScript("", "// Click on the button\n// to edit in a frame.\n\noutput0 = input0 * 2"); - +public class OldJavascript extends Plugin implements Block, VarListListener, TypeChangeListener { + ArrayList<String> languagesInstalled = new ArrayList<>(); + + private final VarScript inputScript = new VarScript("", "// Click on the button\n// to edit in a frame.\n\noutput0 = input0 * 2"); + private VarList inputMap; private VarList outputMap; - - private int inputIdx = 0; + + private int inputIdx = 0; private int outputIdx = 0; - + private VarTrigger triggerInput; - + private VarTrigger triggerOutput; - - private final TypeSelectionModel typeSelector = new TypeSelectionModel(new Class<?>[] { + + private final TypeSelectionModel typeSelector = new TypeSelectionModel( Object.class, Object[].class, Sequence.class, @@ -55,221 +53,176 @@ public class OldJavascript extends Plugin implements Block, VarListListener, Typ double[].class, String.class, File.class, - File[].class }); - - public OldJavascript() - { - for (ScriptEngineFactory f : ScriptEngineHandler.getEngineManager().getEngineFactories()) - { + File[].class + ); + + public OldJavascript() { + for (final ScriptEngineFactory f : ScriptEngineHandler.getEngineManager().getEngineFactories()) { languagesInstalled.add(ScriptEngineHandler.getLanguageName(f)); } } - - @SuppressWarnings({ "unchecked", "rawtypes" }) + @Override - public void run() - { - ScriptingHandler handler = inputScript.getEditor().getPanelIn().getScriptHandler(); - JSScriptEngine engine = (JSScriptEngine) handler.createNewEngine(); + public void run() { + final ScriptingHandler handler = inputScript.getEditor().getPanelIn().getScriptHandler(); + final JSScriptEngine engine = (JSScriptEngine) handler.createNewEngine(); // String language = inputScript.getEditor().panelIn.getLanguage(); - - for (Var<?> var : inputMap) - { + + for (final Var<?> var : inputMap) { Object value = var.getValue(); - String name = var.getName(); - if (name.contains("input")) - { + final String name = var.getName(); + if (name.contains("input")) { // For another language, remove this, or use the right one. value = JSScriptBlock.transformInputForScript(value); - + // put in the engine the value. engine.put(name, value); } } - try - { + try { inputScript.evaluate(); } - catch (ScriptException e) - { + catch (final ScriptException e) { throw new IcyHandledException(e.getMessage()); } - - for (Var output : outputMap) - { - Object resObject = engine.get(output.getName()); + + for (final Var output : outputMap) { + final Object resObject = engine.get(output.getName()); output.setValue(JSScriptBlock.transformScriptOutput(resObject)); } } - + @Override - public void declareInput(VarList inputMap) - { + public void declareInput(final VarList inputMap) { if (this.inputMap == null) this.inputMap = inputMap; inputMap.addVarListListener(this); - triggerInput = new VarTrigger("Add Input", new VarTrigger.TriggerListener() - { - + triggerInput = new VarTrigger("Add Input", new VarTrigger.TriggerListener() { + @Override - public void valueChanged(Var<Integer> source, Integer oldValue, Integer newValue) - { + public void valueChanged(final Var<Integer> source, final Integer oldValue, final Integer newValue) { registerVariables(); } - + @Override - public void referenceChanged(Var<Integer> source, Var<? extends Integer> oldReference, Var<? extends Integer> newReference) - { + public void referenceChanged(final Var<Integer> source, final Var<? extends Integer> oldReference, final Var<? extends Integer> newReference) { registerVariables(); } - + @Override - public void triggered(VarTrigger source) - { - String name = "input" + inputIdx; - VarMutableScript myVariable = new VarMutableScript(name, Object.class); + public void triggered(final VarTrigger source) { + final String name = "input" + inputIdx; + final VarMutableScript myVariable = new VarMutableScript(name, Object.class); myVariable.setDefaultEditorModel(typeSelector); - myVariable.addTypeChangeListener(new TypeChangeListener() - { - - @Override - public void typeChanged(Object source, Class<?> oldType, Class<?> newType) - { - registerVariables(); - } - }); - OldJavascript.this.inputMap.addRuntimeVariable("" + myVariable.hashCode(), myVariable); + myVariable.addTypeChangeListener((source1, oldType, newType) -> registerVariables()); + OldJavascript.this.inputMap.addRuntimeVariable(String.valueOf(myVariable.hashCode()), myVariable); registerVariables(); - + } }); triggerInput.setReferencingPolicy(VarReferencingPolicy.NONE); - - triggerOutput = new VarTrigger("Add output", new VarTrigger.TriggerListener() - { - + + triggerOutput = new VarTrigger("Add output", new VarTrigger.TriggerListener() { + @Override - public void valueChanged(Var<Integer> source, Integer oldValue, Integer newValue) - { + public void valueChanged(final Var<Integer> source, final Integer oldValue, final Integer newValue) { registerVariables(); } - + @Override - public void referenceChanged(Var<Integer> source, Var<? extends Integer> oldReference, Var<? extends Integer> newReference) - { + public void referenceChanged(final Var<Integer> source, final Var<? extends Integer> oldReference, final Var<? extends Integer> newReference) { registerVariables(); } - + @Override - public void triggered(VarTrigger source) - { - String name = "output" + outputIdx; - VarMutableScript myVariable = new VarMutableScript(name, Object.class); + public void triggered(final VarTrigger source) { + final String name = "output" + outputIdx; + final VarMutableScript myVariable = new VarMutableScript(name, Object.class); myVariable.setDefaultEditorModel(typeSelector); - myVariable.addTypeChangeListener(new TypeChangeListener() - { - - @Override - public void typeChanged(Object source, Class<?> oldType, Class<?> newType) - { - registerVariables(); - } - }); - outputMap.addRuntimeVariable("" + myVariable.hashCode(), myVariable); + myVariable.addTypeChangeListener((source12, oldType, newType) -> registerVariables()); + outputMap.addRuntimeVariable(String.valueOf(myVariable.hashCode()), myVariable); registerVariables(); } }); triggerOutput.setReferencingPolicy(VarReferencingPolicy.NONE); - + inputScript.setReferencingPolicy(VarReferencingPolicy.NONE); - + inputMap.add("Script", inputScript); inputMap.add("Add Input", triggerInput); inputMap.add("Add output", triggerOutput); - - String name = "input" + inputIdx; - VarMutableScript myVariable = new VarMutableScript(name, Object.class); + + final String name = "input" + inputIdx; + final VarMutableScript myVariable = new VarMutableScript(name, Object.class); myVariable.setDefaultEditorModel(typeSelector); myVariable.addTypeChangeListener(this); inputMap.add(name, myVariable); } - + @Override - public void declareOutput(final VarList outputMap) - { + public void declareOutput(final VarList outputMap) { this.outputMap = outputMap; outputMap.addVarListListener(this); - String name = "output" + outputIdx; - VarMutableScript myVariable = new VarMutableScript(name, Object.class); + final String name = "output" + outputIdx; + final VarMutableScript myVariable = new VarMutableScript(name, Object.class); myVariable.setDefaultEditorModel(typeSelector); myVariable.addTypeChangeListener(this); outputMap.add(name, myVariable); registerVariables(); } - + @Override - public void typeChanged(Object source, Class<?> oldType, Class<?> newType) - { + public void typeChanged(final Object source, final Class<?> oldType, final Class<?> newType) { registerVariables(); } - - private void registerVariables() - { + + private void registerVariables() { final ScriptingHandler handlerIn = inputScript.getEditor().getPanelIn().getScriptHandler(); final ScriptingHandler handlerOut = inputScript.getEditor().getPanelOut().getScriptHandler(); - - HashMap<String, ScriptVariable> variablesInt = handlerIn.getExternalVariables(); - HashMap<String, ScriptVariable> variablesExt = handlerOut.getExternalVariables(); - + + final HashMap<String, ScriptVariable> variablesInt = handlerIn.getExternalVariables(); + final HashMap<String, ScriptVariable> variablesExt = handlerOut.getExternalVariables(); + variablesInt.clear(); variablesExt.clear(); - if (inputMap != null) for (Var<?> v : inputMap) - { - if (v instanceof VarMutableScript || inputMap.isRuntimeVariable(v)) - { - variablesInt.put(v.getName(), new ScriptVariable(new VariableType(v.getType()))); - variablesExt.put(v.getName(), new ScriptVariable(new VariableType(v.getType()))); + if (inputMap != null) { + for (final Var<?> v : inputMap) { + if (v instanceof VarMutableScript || inputMap.isRuntimeVariable(v)) { + variablesInt.put(v.getName(), new ScriptVariable(new VariableType(v.getType()))); + variablesExt.put(v.getName(), new ScriptVariable(new VariableType(v.getType()))); + } } } - if (outputMap != null) for (Var<?> v : outputMap) - { - if (v instanceof VarMutableScript || outputMap.isRuntimeVariable(v)) - { - variablesInt.put(v.getName(), new ScriptVariable(new VariableType(v.getType()))); - variablesExt.put(v.getName(), new ScriptVariable(new VariableType(v.getType()))); + if (outputMap != null) { + for (final Var<?> v : outputMap) { + if (v instanceof VarMutableScript || outputMap.isRuntimeVariable(v)) { + variablesInt.put(v.getName(), new ScriptVariable(new VariableType(v.getType()))); + variablesExt.put(v.getName(), new ScriptVariable(new VariableType(v.getType()))); + } } } - ThreadUtil.invokeLater(new Runnable() - { - - @Override - public void run() - { - handlerIn.interpret(false); - handlerOut.interpret(false); - } + ThreadUtil.invokeLater(() -> { + handlerIn.interpret(false); + handlerOut.interpret(false); }); } - + @Override - public void variableAdded(VarList list, Var<?> variable) - { + public void variableAdded(final VarList list, final Var<?> variable) { if (list == inputMap && variable != triggerInput && variable != inputScript && variable != triggerOutput) inputIdx++; else if (list == outputMap) outputIdx++; - - if (list.isRuntimeVariable(variable) && variable instanceof VarMutable) - { - VarMutable mutable = (VarMutable) variable; - Class<?> type = mutable.getType(); + + if (list.isRuntimeVariable(variable) && variable instanceof VarMutable) { + final VarMutable mutable = (VarMutable) variable; + final Class<?> type = mutable.getType(); mutable.setDefaultEditorModel(typeSelector); mutable.addTypeChangeListener(this); mutable.setType(type); } } - + @Override - public void variableRemoved(VarList list, Var<?> variable) - { + public void variableRemoved(final VarList list, final Var<?> variable) { if (list.isRuntimeVariable(variable) && variable instanceof VarMutable) ((VarMutable) variable).removeTypeChangeListener(this); - registerVariables(); - } + registerVariables(); + } } diff --git a/src/main/java/plugins/tprovoost/scripteditor/scriptblock/OldPythonscript.java b/src/main/java/plugins/tprovoost/scripteditor/scriptblock/OldPythonscript.java index a13e5ffde5a3f80f55c447c45c7fd95acfb3646e..e39fdf2fbc0756ee6951cbe45d8a278fcb1c4f08 100644 --- a/src/main/java/plugins/tprovoost/scripteditor/scriptblock/OldPythonscript.java +++ b/src/main/java/plugins/tprovoost/scripteditor/scriptblock/OldPythonscript.java @@ -17,18 +17,14 @@ import plugins.adufour.blocks.util.VarListListener; import plugins.adufour.vars.gui.model.TypeSelectionModel; import plugins.adufour.vars.lang.Var; import plugins.adufour.vars.lang.VarTrigger; -import plugins.adufour.vars.util.TypeChangeListener; import plugins.adufour.vars.util.VarReferencingPolicy; import plugins.tprovoost.scripteditor.scriptinghandlers.ScriptEngine; import plugins.tprovoost.scripteditor.scriptinghandlers.ScriptVariable; import plugins.tprovoost.scripteditor.scriptinghandlers.ScriptingHandler; import plugins.tprovoost.scripteditor.scriptinghandlers.VariableType; -import plugins.tprovoost.scripteditor.scriptinghandlers.py.PyScriptEngine; -public class OldPythonscript extends Plugin implements Block, VarListListener -{ - private VarScriptPython inputScript = new VarScriptPython("Script", - "# Click on the button\n# to edit in a frame.\n\noutput0 = input0 * 2"); +public class OldPythonscript extends Plugin implements Block, VarListListener { + private final VarScriptPython inputScript = new VarScriptPython("Script", "# Click on the button\n# to edit in a frame.\n\noutput0 = input0 * 2"); private VarList inputMap; private VarList outputMap; @@ -40,24 +36,19 @@ public class OldPythonscript extends Plugin implements Block, VarListListener private VarTrigger triggerOutput; - public OldPythonscript() - { + public OldPythonscript() { } - @SuppressWarnings({"unchecked", "rawtypes"}) @Override - public void run() - { - ScriptingHandler handler = inputScript.getEditor().getPanelIn().getScriptHandler(); - ScriptEngine engine = (PyScriptEngine) handler.createNewEngine(); + public void run() { + final ScriptingHandler handler = inputScript.getEditor().getPanelIn().getScriptHandler(); + final ScriptEngine engine = handler.createNewEngine(); // String language = inputScript.getEditor().panelIn.getLanguage(); - for (Var<?> var : inputMap) - { + for (final Var<?> var : inputMap) { Object value = var.getValue(); - String name = var.getName(); - if (name.contains("input")) - { + final String name = var.getName(); + if (name.contains("input")) { // For another language, remove this, or use the right one. value = PythonScriptBlock.transformInputForScript(value); @@ -65,102 +56,96 @@ public class OldPythonscript extends Plugin implements Block, VarListListener engine.put(name, value); } } - try - { + try { inputScript.evaluate(); } - catch (ScriptException e) - { + catch (final ScriptException e) { throw new IcyHandledException(e.getMessage()); } - for (Var output : outputMap) - { - Object resObject = engine.get(output.getName()); + for (final Var output : outputMap) { + final Object resObject = engine.get(output.getName()); output.setValue(PythonScriptBlock.transformScriptOutput(resObject)); } } @Override - public void declareInput(VarList inputMap) - { + public void declareInput(final VarList inputMap) { if (this.inputMap == null) this.inputMap = inputMap; inputMap.addVarListListener(this); - triggerInput = new VarTrigger("Add Input", new VarTrigger.TriggerListener() - { + triggerInput = new VarTrigger("Add Input", new VarTrigger.TriggerListener() { @Override - public void valueChanged(Var<Integer> source, Integer oldValue, Integer newValue) - { + public void valueChanged(final Var<Integer> source, final Integer oldValue, final Integer newValue) { registerVariables(); } @Override - public void referenceChanged(Var<Integer> source, Var<? extends Integer> oldReference, - Var<? extends Integer> newReference) - { + public void referenceChanged(final Var<Integer> source, final Var<? extends Integer> oldReference, final Var<? extends Integer> newReference) { registerVariables(); } @Override - public void triggered(VarTrigger source) - { - String name = "input" + inputIdx; - VarMutableScript myVariable = new VarMutableScript(name, Object.class); - myVariable.setDefaultEditorModel(new TypeSelectionModel(new Class<?>[] {Object.class, Object[].class, - Sequence.class, ROI[].class, Integer.class, Double.class, int[].class, double[].class, - String.class, File.class, File[].class})); - myVariable.addTypeChangeListener(new TypeChangeListener() - { - - @Override - public void typeChanged(Object source, Class<?> oldType, Class<?> newType) - { - registerVariables(); - } - }); - OldPythonscript.this.inputMap.addRuntimeVariable("" + myVariable.hashCode(), myVariable); + public void triggered(final VarTrigger source) { + final String name = "input" + inputIdx; + final VarMutableScript myVariable = new VarMutableScript(name, Object.class); + myVariable.setDefaultEditorModel( + new TypeSelectionModel( + Object.class, + Object[].class, + Sequence.class, + ROI[].class, + Integer.class, + Double.class, + int[].class, + double[].class, + String.class, + File.class, + File[].class + ) + ); + myVariable.addTypeChangeListener((source1, oldType, newType) -> registerVariables()); + OldPythonscript.this.inputMap.addRuntimeVariable(String.valueOf(myVariable.hashCode()), myVariable); registerVariables(); } }); triggerInput.setReferencingPolicy(VarReferencingPolicy.NONE); - triggerOutput = new VarTrigger("Add output", new VarTrigger.TriggerListener() - { + triggerOutput = new VarTrigger("Add output", new VarTrigger.TriggerListener() { @Override - public void valueChanged(Var<Integer> source, Integer oldValue, Integer newValue) - { + public void valueChanged(final Var<Integer> source, final Integer oldValue, final Integer newValue) { registerVariables(); } @Override - public void referenceChanged(Var<Integer> source, Var<? extends Integer> oldReference, - Var<? extends Integer> newReference) - { + public void referenceChanged(final Var<Integer> source, final Var<? extends Integer> oldReference, final Var<? extends Integer> newReference) { registerVariables(); } @Override - public void triggered(VarTrigger source) - { - String name = "output" + outputIdx; - VarMutableScript myVariable = new VarMutableScript(name, Object.class); - myVariable.setDefaultEditorModel(new TypeSelectionModel(new Class<?>[] {Object.class, Object[].class, - Sequence.class, ROI[].class, Integer.class, Double.class, int[].class, double[].class, - String.class, File.class, File[].class})); - myVariable.addTypeChangeListener(new TypeChangeListener() - { - - @Override - public void typeChanged(Object source, Class<?> oldType, Class<?> newType) - { - registerVariables(); - } - }); - outputMap.addRuntimeVariable("" + myVariable.hashCode(), myVariable); + public void triggered(final VarTrigger source) { + final String name = "output" + outputIdx; + final VarMutableScript myVariable = new VarMutableScript(name, Object.class); + myVariable.setDefaultEditorModel( + new TypeSelectionModel( + Object.class, + Object[].class, + Sequence.class, + ROI[].class, + Integer.class, + Double.class, + int[].class, + double[].class, + String.class, + File.class, + File[].class + ) + ); + myVariable.addTypeChangeListener((source12, oldType, newType) -> registerVariables()); + outputMap.addRuntimeVariable(String.valueOf(myVariable.hashCode()), myVariable); registerVariables(); } }); @@ -172,87 +157,84 @@ public class OldPythonscript extends Plugin implements Block, VarListListener inputMap.add(triggerInput.getName(), triggerInput); inputMap.add(triggerOutput.getName(), triggerOutput); - String name = "input" + inputIdx; - VarMutableScript myVariable = new VarMutableScript(name, Object.class); - myVariable.setDefaultEditorModel(new TypeSelectionModel(new Class<?>[] {Object.class, Object[].class, - Sequence.class, ROI[].class, Boolean.class, Integer.class, Double.class, int[].class, double[].class, - String.class, File.class, File[].class})); - myVariable.addTypeChangeListener(new TypeChangeListener() - { - - @Override - public void typeChanged(Object source, Class<?> oldType, Class<?> newType) - { - registerVariables(); - } - }); + final String name = "input" + inputIdx; + final VarMutableScript myVariable = new VarMutableScript(name, Object.class); + myVariable.setDefaultEditorModel( + new TypeSelectionModel( + Object.class, + Object[].class, + Sequence.class, + ROI[].class, + Boolean.class, + Integer.class, + Double.class, + int[].class, + double[].class, + String.class, + File.class, + File[].class + ) + ); + myVariable.addTypeChangeListener((source, oldType, newType) -> registerVariables()); inputMap.add(name, myVariable); } @Override - public void declareOutput(final VarList outputMap) - { + public void declareOutput(final VarList outputMap) { this.outputMap = outputMap; outputMap.addVarListListener(this); - String name = "output" + outputIdx; - VarMutableScript myVariable = new VarMutableScript(name, Object.class); - myVariable.setDefaultEditorModel(new TypeSelectionModel(new Class<?>[] {Object.class, Object[].class, - Sequence.class, ROI[].class, Boolean.class, Integer.class, Double.class, int[].class, double[].class, - String.class, File.class, File[].class})); - myVariable.addTypeChangeListener(new TypeChangeListener() - { - - @Override - public void typeChanged(Object source, Class<?> oldType, Class<?> newType) - { - registerVariables(); - } - }); + final String name = "output" + outputIdx; + final VarMutableScript myVariable = new VarMutableScript(name, Object.class); + myVariable.setDefaultEditorModel( + new TypeSelectionModel( + Object.class, + Object[].class, + Sequence.class, + ROI[].class, + Boolean.class, + Integer.class, + Double.class, + int[].class, + double[].class, + String.class, + File.class, + File[].class + ) + ); + myVariable.addTypeChangeListener((source, oldType, newType) -> registerVariables()); outputMap.add(name, myVariable); registerVariables(); } - private void registerVariables() - { + private void registerVariables() { final ScriptingHandler handlerIn = inputScript.getEditor().getPanelIn().getScriptHandler(); final ScriptingHandler handlerOut = inputScript.getEditor().getPanelOut().getScriptHandler(); - HashMap<String, ScriptVariable> variablesInt = handlerIn.getExternalVariables(); - HashMap<String, ScriptVariable> variablesExt = handlerOut.getExternalVariables(); + final HashMap<String, ScriptVariable> variablesInt = handlerIn.getExternalVariables(); + final HashMap<String, ScriptVariable> variablesExt = handlerOut.getExternalVariables(); variablesInt.clear(); variablesExt.clear(); - for (Var<?> v : inputMap) - { - if (v instanceof VarMutableScript) - { + for (final Var<?> v : inputMap) { + if (v instanceof VarMutableScript) { variablesInt.put(v.getName(), new ScriptVariable(new VariableType(v.getType()))); variablesExt.put(v.getName(), new ScriptVariable(new VariableType(v.getType()))); } } - for (Var<?> v : outputMap) - { - if (v instanceof VarMutableScript) - { + for (final Var<?> v : outputMap) { + if (v instanceof VarMutableScript) { variablesInt.put(v.getName(), new ScriptVariable(new VariableType(v.getType()))); variablesExt.put(v.getName(), new ScriptVariable(new VariableType(v.getType()))); } } - ThreadUtil.invokeLater(new Runnable() - { - - @Override - public void run() - { - handlerIn.interpret(false); - handlerOut.interpret(false); - } + ThreadUtil.invokeLater(() -> { + handlerIn.interpret(false); + handlerOut.interpret(false); }); } @Override - public void variableAdded(VarList list, Var<?> variable) - { + public void variableAdded(final VarList list, final Var<?> variable) { if (list == inputMap && variable != triggerInput && variable != inputScript && variable != triggerOutput) inputIdx++; else if (list == outputMap) @@ -260,7 +242,6 @@ public class OldPythonscript extends Plugin implements Block, VarListListener } @Override - public void variableRemoved(VarList list, Var<?> variable) - { + public void variableRemoved(final VarList list, final Var<?> variable) { } } diff --git a/src/main/java/plugins/tprovoost/scripteditor/scriptblock/PythonScriptBlock.java b/src/main/java/plugins/tprovoost/scripteditor/scriptblock/PythonScriptBlock.java index a6859dae492d75f2346396c1d1664333726202a1..42b03e5a4ba248674ec42d4c1329efe4871ff001 100644 --- a/src/main/java/plugins/tprovoost/scripteditor/scriptblock/PythonScriptBlock.java +++ b/src/main/java/plugins/tprovoost/scripteditor/scriptblock/PythonScriptBlock.java @@ -2,21 +2,19 @@ package plugins.tprovoost.scripteditor.scriptblock; import org.python.core.PyObject; -public class PythonScriptBlock -{ +public class PythonScriptBlock { - public static Object transformScriptOutput(Object o) - { + public static Object transformScriptOutput(final Object o) { if (o instanceof PyObject) return ((PyObject) o).__tojava__(Object.class); return o; } - public static Object transformInputForScript(Object value) { - // place here any modification to a type - // that is not natively supported. - - return value; - } + public static Object transformInputForScript(final Object value) { + // place here any modification to a type + // that is not natively supported. + + return value; + } } diff --git a/src/main/java/plugins/tprovoost/scripteditor/scriptblock/Pythonscript.java b/src/main/java/plugins/tprovoost/scripteditor/scriptblock/Pythonscript.java index e062211ff7e6723185c95d8086d39c140eaebe1f..64419af014d11e7d8436667b84fde04b6d489963 100644 --- a/src/main/java/plugins/tprovoost/scripteditor/scriptblock/Pythonscript.java +++ b/src/main/java/plugins/tprovoost/scripteditor/scriptblock/Pythonscript.java @@ -1,20 +1,20 @@ /* - * Copyright 2010-2015 Institut Pasteur. - * + * Copyright 2010-2023 Institut Pasteur. + * * This file is part of Icy. - * + * * Icy 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. - * + * * Icy 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 Icy. If not, see <http://www.gnu.org/licenses/>. + * along with Icy. If not, see <https://www.gnu.org/licenses/>. */ package plugins.tprovoost.scripteditor.scriptblock; @@ -30,48 +30,47 @@ import plugins.tprovoost.scripteditor.scriptinghandlers.ScriptEngine; /** * This block allows to define a Python script using multiple inputs from * other blocks and produce multiple results when executed. - * + * <p> * It is possible to specify multiple inputs using the "Add Input" button. It is * also possible to add several outputs by using the "Add Output" button. - * + * <p> * Please check the online documentation for more information. - * + * * @author Thomas Provoost * @author Daniel Gonzalez */ public class Pythonscript extends ScriptBlock { - public Pythonscript() { - super(new VarPythonScript("", "# Click on the button\n# to edit in a frame.\n\noutput0 = input0 * 2")); - } + public Pythonscript() { + super(new VarPythonScript("", "# Click on the button\n# to edit in a frame.\n\noutput0 = input0 * 2")); + } - @Override - protected void installEngineMethods(ScriptEngine engine, ArrayList<Method> methods) { - // TODO nothing for now? + @Override + protected void installEngineMethods(final ScriptEngine engine, final ArrayList<Method> methods) { + // TODO nothing for now? + } - } + @Override + protected void injectInputVariables(final ScriptEngine engine) { + for (final Var<?> var : getVarScript().getInputVariables()) { + Object value = var.getValue(); + final String name = var.getName(); + if (name.contains("input")) { + // For another language, remove this, or use the right one. + value = PythonScriptBlock.transformInputForScript(value); - @Override - protected void injectInputVariables(ScriptEngine engine) { - for (Var<?> var : getVarScript().getInputVariables()) { - Object value = var.getValue(); - String name = var.getName(); - if (name.contains("input")) { - // For another language, remove this, or use the right one. - value = PythonScriptBlock.transformInputForScript(value); + // put in the engine the value. + engine.put(name, value); + } + } + } - // put in the engine the value. - engine.put(name, value); - } - } - } - - @Override - protected void setOutputVariables(ScriptEngine engine) { - for (VarMutable output : getVarScript().getOutputVariables()) { - Object resObject = engine.get(output.getName()); - output.setValue(PythonScriptBlock.transformScriptOutput(resObject)); - } - } + @Override + protected void setOutputVariables(final ScriptEngine engine) { + for (final VarMutable output : getVarScript().getOutputVariables()) { + final Object resObject = engine.get(output.getName()); + output.setValue(PythonScriptBlock.transformScriptOutput(resObject)); + } + } } diff --git a/src/main/java/plugins/tprovoost/scripteditor/scriptblock/ScriptBlock.java b/src/main/java/plugins/tprovoost/scripteditor/scriptblock/ScriptBlock.java index c0944553cf95ca85953d01ada1776639458beae5..6bd1ea7a49ca49b4f1934a7ae41dbf1d33a94d3e 100644 --- a/src/main/java/plugins/tprovoost/scripteditor/scriptblock/ScriptBlock.java +++ b/src/main/java/plugins/tprovoost/scripteditor/scriptblock/ScriptBlock.java @@ -1,6 +1,3 @@ -/** - * - */ package plugins.tprovoost.scripteditor.scriptblock; import java.io.File; @@ -8,11 +5,9 @@ import java.io.PrintWriter; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.HashSet; -import java.util.List; import java.util.Set; import javax.script.ScriptEngineFactory; -import javax.script.ScriptEngineManager; import javax.script.ScriptException; import icy.plugin.abstract_.Plugin; @@ -38,235 +33,240 @@ import plugins.tprovoost.scripteditor.scriptinghandlers.ScriptEngineHandler; * languages: JavaScript ({@link Javascript}) and Python({@link Pythonscript}). * These two blocks inherit from this class to perform common tasks of a * scripting protocol block. - * + * * @author Daniel Gonzalez */ public abstract class ScriptBlock extends Plugin implements Block, VarListListener, TypeChangeListener { - - private List<String> languagesInstalled; - - private VarScript script; - - private VarList inputMap; - private int inputVarIdx = 0; - private VarTrigger inputVarTrigger; - - private VarList outputMap; - private int outputVarIdx = 0; - private VarTrigger outputVarTrigger; - - private final TypeSelectionModel typeSelector = new TypeSelectionModel( - new Class<?>[] { Object.class, Object[].class, Sequence.class, ROI[].class, Integer.class, Double.class, - int[].class, double[].class, String.class, File.class, File[].class }); - - public ScriptBlock(VarScript script) { - this.script = script; - } - - protected VarScript getVarScript() { - return script; - } - - @Override - public void declareInput(VarList inputMap) { - languagesInstalled = new ArrayList<String>(); - for (ScriptEngineFactory f : ScriptEngineHandler.getEngineManager().getEngineFactories()) { - languagesInstalled.add(ScriptEngineHandler.getLanguageName(f)); - } - - if (this.inputMap == null) - this.inputMap = inputMap; - - script.setReferencingPolicy(VarReferencingPolicy.NONE); - createAddInputVarTrigger(); - createAddOutputVarTrigger(); - - inputMap.addVarListListener(this); - - inputMap.add("Script", script); - inputMap.add("Add Input", inputVarTrigger); - inputMap.add("Add output", outputVarTrigger); - VarMutable firstInputVariable = createInputVariable(inputVarIdx); - inputMap.add(firstInputVariable.getName(), firstInputVariable); - } - - private void createAddInputVarTrigger() { - inputVarTrigger = new VarTrigger("Add Input", new VarTrigger.TriggerListener() { - - @Override - public void valueChanged(Var<Integer> source, Integer oldValue, Integer newValue) { - registerVariables(); - } - - @Override - public void referenceChanged(Var<Integer> source, Var<? extends Integer> oldReference, - Var<? extends Integer> newReference) { - registerVariables(); - } - - @Override - public void triggered(VarTrigger source) { - VarMutable newVariable = createInputVariable(inputVarIdx); - inputMap.addRuntimeVariable("" + newVariable.hashCode(), newVariable); - registerVariables(); - } - }); - inputVarTrigger.setReferencingPolicy(VarReferencingPolicy.NONE); - } - - private void createAddOutputVarTrigger() { - outputVarTrigger = new VarTrigger("Add Output", new VarTrigger.TriggerListener() { - - @Override - public void valueChanged(Var<Integer> source, Integer oldValue, Integer newValue) { - registerVariables(); - } - - @Override - public void referenceChanged(Var<Integer> source, Var<? extends Integer> oldReference, - Var<? extends Integer> newReference) { - registerVariables(); - } - - @Override - public void triggered(VarTrigger source) { - VarMutable newVariable = createOutputVariable(outputVarIdx); - outputMap.addRuntimeVariable("" + newVariable.hashCode(), newVariable); - registerVariables(); - } - }); - outputVarTrigger.setReferencingPolicy(VarReferencingPolicy.NONE); - } - - private VarMutable createInputVariable(int varIdx) { - VarMutable newVariable = new VarMutable("input" + varIdx, Object.class); - setupVariable(newVariable); - return newVariable; - } - - @Override - public void declareOutput(VarList outputMap) { - if (this.outputMap == null) - this.outputMap = outputMap; - - outputMap.addVarListListener(this); - - VarMutable firstOutputVariable = createOutputVariable(outputVarIdx); - outputMap.add(firstOutputVariable.getName(), firstOutputVariable); - registerVariables(); - } - - private VarMutable createOutputVariable(int varIdx) { - VarMutable newVariable = new VarMutable("output" + varIdx, Object.class); - setupVariable(newVariable); - return newVariable; - } - - private void setupVariable(VarMutable newVariable) { - newVariable.setDefaultEditorModel(typeSelector); - newVariable.addTypeChangeListener(this); - } - - @Override - public void variableAdded(VarList list, Var<?> variable) { - if (list == inputMap && variable != script && variable != inputVarTrigger && variable != outputVarTrigger) - inputVarIdx++; - else if (list == outputMap) - outputVarIdx++; - - if (list.isRuntimeVariable(variable) && variable instanceof VarMutable) { - VarMutable mutable = (VarMutable) variable; - Class<?> type = mutable.getType(); - mutable.setDefaultEditorModel(typeSelector); - mutable.addTypeChangeListener(this); - mutable.setType(type); - } - } - - @Override - public void variableRemoved(VarList list, Var<?> variable) { - if (list.isRuntimeVariable(variable) && variable instanceof VarMutable) - ((VarMutable) variable).removeTypeChangeListener(this); - registerVariables(); - } - - @Override - public void typeChanged(Object source, Class<?> oldType, Class<?> newType) { - registerVariables(); - } - - private void registerVariables() { - Set<VarMutable> inputVars = new HashSet<VarMutable>(); - Set<VarMutable> outputVars = new HashSet<VarMutable>(); - if (inputMap != null) - for (Var<?> v : inputMap) { - if (v instanceof VarMutable || inputMap.isRuntimeVariable(v)) { - inputVars.add((VarMutable) v); - } - } - if (outputMap != null) - for (Var<?> v : outputMap) { - if (v instanceof VarMutable || outputMap.isRuntimeVariable(v)) { - outputVars.add((VarMutable) v); - } - } - - script.setupInputVariables(inputVars); - script.setupOutputVariables(outputVars); - } - - @Override - public void run() { - ScriptEngine engine = createEngine(); - injectInputVariables(engine); - try { - evaluateCode(engine, script.getCode()); - } catch (ScriptException e) { - e.printStackTrace(); - throw new IcyHandledException(e.getMessage(), e); - } - setOutputVariables(engine); - } - - private ScriptEngine createEngine() { - ScriptEngine oldEngine = ScriptEngineHandler.getEngine(getScriptType().toString()); - if (oldEngine != null) { - // retrieve the methods known to the old engine to transfert them to the new - // engine - ScriptEngineHandler engineHandler = ScriptEngineHandler.getEngineHandler(oldEngine); - ArrayList<Method> functions = engineHandler.getFunctions(); - - // unregister the old engine (will do the housekeeping) - ScriptEngineHandler.disposeEngine(oldEngine); - - // create a new engine - String newEngineType = oldEngine.getName(); - ScriptEngine newEngine = ScriptEngineHandler.getEngine(newEngineType, true); - installEngineMethods(newEngine, functions); - - newEngine.setWriter(new PrintWriter(System.out)); - newEngine.setErrorWriter(new PrintWriter(System.err)); - - return newEngine; - } else { - // Failed to retrieve the current engine - return null; - } - } - - private ScriptType getScriptType() { - return script.getValue().getScriptType(); - } - - protected abstract void installEngineMethods(ScriptEngine engine, ArrayList<Method> methods); - - protected abstract void injectInputVariables(ScriptEngine engine); - - private void evaluateCode(ScriptEngine engine, String code) throws ScriptException { - engine.eval(script.getCode()); - - } - - protected abstract void setOutputVariables(ScriptEngine engine); - + private final VarScript script; + + private VarList inputMap; + private int inputVarIdx = 0; + private VarTrigger inputVarTrigger; + + private VarList outputMap; + private int outputVarIdx = 0; + private VarTrigger outputVarTrigger; + + private final TypeSelectionModel typeSelector = new TypeSelectionModel( + Object.class, + Object[].class, + Sequence.class, + ROI[].class, + Integer.class, + Double.class, + int[].class, + double[].class, + String.class, + File.class, + File[].class + ); + + public ScriptBlock(final VarScript script) { + this.script = script; + } + + protected VarScript getVarScript() { + return script; + } + + @Override + public void declareInput(final VarList inputMap) { + final ArrayList<String> languagesInstalled = new ArrayList<>(); + for (final ScriptEngineFactory f : ScriptEngineHandler.getEngineManager().getEngineFactories()) { + languagesInstalled.add(ScriptEngineHandler.getLanguageName(f)); + } + + if (this.inputMap == null) + this.inputMap = inputMap; + + script.setReferencingPolicy(VarReferencingPolicy.NONE); + createAddInputVarTrigger(); + createAddOutputVarTrigger(); + + inputMap.addVarListListener(this); + + inputMap.add("Script", script); + inputMap.add("Add Input", inputVarTrigger); + inputMap.add("Add output", outputVarTrigger); + final VarMutable firstInputVariable = createInputVariable(inputVarIdx); + inputMap.add(firstInputVariable.getName(), firstInputVariable); + } + + private void createAddInputVarTrigger() { + inputVarTrigger = new VarTrigger("Add Input", new VarTrigger.TriggerListener() { + + @Override + public void valueChanged(final Var<Integer> source, final Integer oldValue, final Integer newValue) { + registerVariables(); + } + + @Override + public void referenceChanged(final Var<Integer> source, final Var<? extends Integer> oldReference, final Var<? extends Integer> newReference) { + registerVariables(); + } + + @Override + public void triggered(final VarTrigger source) { + final VarMutable newVariable = createInputVariable(inputVarIdx); + inputMap.addRuntimeVariable(String.valueOf(newVariable.hashCode()), newVariable); + registerVariables(); + } + }); + inputVarTrigger.setReferencingPolicy(VarReferencingPolicy.NONE); + } + + private void createAddOutputVarTrigger() { + outputVarTrigger = new VarTrigger("Add Output", new VarTrigger.TriggerListener() { + + @Override + public void valueChanged(final Var<Integer> source, final Integer oldValue, final Integer newValue) { + registerVariables(); + } + + @Override + public void referenceChanged(final Var<Integer> source, final Var<? extends Integer> oldReference, final Var<? extends Integer> newReference) { + registerVariables(); + } + + @Override + public void triggered(final VarTrigger source) { + final VarMutable newVariable = createOutputVariable(outputVarIdx); + outputMap.addRuntimeVariable(String.valueOf(newVariable.hashCode()), newVariable); + registerVariables(); + } + }); + outputVarTrigger.setReferencingPolicy(VarReferencingPolicy.NONE); + } + + private VarMutable createInputVariable(final int varIdx) { + final VarMutable newVariable = new VarMutable("input" + varIdx, Object.class); + setupVariable(newVariable); + return newVariable; + } + + @Override + public void declareOutput(final VarList outputMap) { + if (this.outputMap == null) + this.outputMap = outputMap; + + outputMap.addVarListListener(this); + + final VarMutable firstOutputVariable = createOutputVariable(outputVarIdx); + outputMap.add(firstOutputVariable.getName(), firstOutputVariable); + registerVariables(); + } + + private VarMutable createOutputVariable(final int varIdx) { + final VarMutable newVariable = new VarMutable("output" + varIdx, Object.class); + setupVariable(newVariable); + return newVariable; + } + + private void setupVariable(final VarMutable newVariable) { + newVariable.setDefaultEditorModel(typeSelector); + newVariable.addTypeChangeListener(this); + } + + @Override + public void variableAdded(final VarList list, final Var<?> variable) { + if (list == inputMap && variable != script && variable != inputVarTrigger && variable != outputVarTrigger) + inputVarIdx++; + else if (list == outputMap) + outputVarIdx++; + + if (list.isRuntimeVariable(variable) && variable instanceof VarMutable) { + final VarMutable mutable = (VarMutable) variable; + final Class<?> type = mutable.getType(); + mutable.setDefaultEditorModel(typeSelector); + mutable.addTypeChangeListener(this); + mutable.setType(type); + } + } + + @Override + public void variableRemoved(final VarList list, final Var<?> variable) { + if (list.isRuntimeVariable(variable) && variable instanceof VarMutable) + ((VarMutable) variable).removeTypeChangeListener(this); + registerVariables(); + } + + @Override + public void typeChanged(final Object source, final Class<?> oldType, final Class<?> newType) { + registerVariables(); + } + + private void registerVariables() { + final Set<VarMutable> inputVars = new HashSet<>(); + final Set<VarMutable> outputVars = new HashSet<>(); + if (inputMap != null) + for (final Var<?> v : inputMap) { + if (v instanceof VarMutable || inputMap.isRuntimeVariable(v)) { + inputVars.add((VarMutable) v); + } + } + if (outputMap != null) + for (final Var<?> v : outputMap) { + if (v instanceof VarMutable || outputMap.isRuntimeVariable(v)) { + outputVars.add((VarMutable) v); + } + } + + script.setupInputVariables(inputVars); + script.setupOutputVariables(outputVars); + } + + @Override + public void run() { + final ScriptEngine engine = createEngine(); + injectInputVariables(engine); + try { + evaluateCode(engine, script.getCode()); + } + catch (final ScriptException e) { + e.printStackTrace(); + throw new IcyHandledException(e.getMessage(), e); + } + setOutputVariables(engine); + } + + private ScriptEngine createEngine() { + final ScriptEngine oldEngine = ScriptEngineHandler.getEngine(getScriptType().toString()); + if (oldEngine != null) { + // retrieve the methods known to the old engine to transfert them to the new + // engine + final ScriptEngineHandler engineHandler = ScriptEngineHandler.getEngineHandler(oldEngine); + final ArrayList<Method> functions = engineHandler.getFunctions(); + + // unregister the old engine (will do the housekeeping) + ScriptEngineHandler.disposeEngine(oldEngine); + + // create a new engine + final String newEngineType = oldEngine.getName(); + final ScriptEngine newEngine = ScriptEngineHandler.getEngine(newEngineType, true); + installEngineMethods(newEngine, functions); + + newEngine.setWriter(new PrintWriter(System.out)); + newEngine.setErrorWriter(new PrintWriter(System.err)); + + return newEngine; + } + else { + // Failed to retrieve the current engine + return null; + } + } + + private ScriptType getScriptType() { + return script.getValue().getScriptType(); + } + + protected abstract void installEngineMethods(ScriptEngine engine, ArrayList<Method> methods); + + protected abstract void injectInputVariables(ScriptEngine engine); + + private void evaluateCode(final ScriptEngine engine, final String code) throws ScriptException { + engine.eval(script.getCode()); + } + + protected abstract void setOutputVariables(ScriptEngine engine); } diff --git a/src/main/java/plugins/tprovoost/scripteditor/scriptblock/VarMutableScript.java b/src/main/java/plugins/tprovoost/scripteditor/scriptblock/VarMutableScript.java index eafc12d239fb877b61c5d9fdbb5e78e6b7f723b6..61223fda919b9bd2094dd858fed8fcc655033082 100644 --- a/src/main/java/plugins/tprovoost/scripteditor/scriptblock/VarMutableScript.java +++ b/src/main/java/plugins/tprovoost/scripteditor/scriptblock/VarMutableScript.java @@ -2,12 +2,8 @@ package plugins.tprovoost.scripteditor.scriptblock; import plugins.adufour.vars.lang.VarMutable; -public class VarMutableScript extends VarMutable -{ - - public VarMutableScript(String name, Class<?> initialType) - { +public class VarMutableScript extends VarMutable { + public VarMutableScript(final String name, final Class<?> initialType) { super(name, initialType); } - } diff --git a/src/main/java/plugins/tprovoost/scripteditor/scriptblock/VarScript.java b/src/main/java/plugins/tprovoost/scripteditor/scriptblock/VarScript.java index e0bc4f85a4d8a87a306d679e468a09da6e4e5509..24078a25081c63145af2c75b31c25d58b5adc0be 100644 --- a/src/main/java/plugins/tprovoost/scripteditor/scriptblock/VarScript.java +++ b/src/main/java/plugins/tprovoost/scripteditor/scriptblock/VarScript.java @@ -2,79 +2,50 @@ package plugins.tprovoost.scripteditor.scriptblock; import javax.script.ScriptException; -import org.w3c.dom.Node; - import plugins.adufour.vars.gui.VarEditor; import plugins.adufour.vars.lang.VarString; import plugins.tprovoost.scripteditor.scriptinghandlers.ScriptEngine; import plugins.tprovoost.scripteditor.scriptinghandlers.ScriptEngineHandler; -public class VarScript extends VarString -{ +public class VarScript extends VarString { private VarScriptEditorV3 editor; - public VarScript(String name, String defaultValue) - { + public VarScript(final String name, final String defaultValue) { super(name, defaultValue); setEditor(new VarScriptEditorV3(this, defaultValue)); } @Override - public String getValue() - { + public String getValue() { if (getEditor() != null) return getEditor().getText(); return getDefaultValue(); } @Override - public void setValue(String newValue) throws IllegalAccessError - { + public void setValue(final String newValue) throws IllegalAccessError { getEditor().setText(newValue); } @Override - public VarEditor<String> createVarEditor() - { + public VarEditor<String> createVarEditor() { return getEditor(); } - public void evaluate() throws ScriptException - { - ScriptEngine engine = ScriptEngineHandler.getEngine("javascript"); + public void evaluate() throws ScriptException { + final ScriptEngine engine = ScriptEngineHandler.getEngine("javascript"); engine.eval(getValue()); } - public ScriptEngine getEngine() - { + public ScriptEngine getEngine() { return getEditor().getPanelIn().getScriptHandler().getEngine(); } - public VarScriptEditorV3 getEditor() - { + public VarScriptEditorV3 getEditor() { return editor; } - public void setEditor(VarScriptEditorV3 editor) - { + public void setEditor(final VarScriptEditorV3 editor) { this.editor = editor; } - - @Override - public boolean saveToXML(Node node) throws UnsupportedOperationException - { - boolean res = super.saveToXML(node); - // XMLUtil.setAttributeValue((Element) node, "scriptTitle", - // editor.getTitle()); - return res; - } - - @Override - public boolean loadFromXML(Node node) - { - boolean res = super.loadFromXML(node); - // editor.setTitle(XMLUtil.getAttributeValue((Element) node, - // "scriptTitle", "untitled")); - return res; - } } diff --git a/src/main/java/plugins/tprovoost/scripteditor/scriptblock/VarScriptEditorPython.java b/src/main/java/plugins/tprovoost/scripteditor/scriptblock/VarScriptEditorPython.java index 9a6f4499e7906d71c4a5687cc6bef271dbb264e9..62562346ae1ffe8bd37791d4b48a0fdedf7f5eda 100644 --- a/src/main/java/plugins/tprovoost/scripteditor/scriptblock/VarScriptEditorPython.java +++ b/src/main/java/plugins/tprovoost/scripteditor/scriptblock/VarScriptEditorPython.java @@ -7,8 +7,6 @@ import icy.gui.frame.IcyFrameEvent; import icy.resource.icon.IcyIcon; import java.awt.BorderLayout; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; import javax.swing.BorderFactory; import javax.swing.Box; @@ -21,70 +19,59 @@ import org.fife.ui.rsyntaxtextarea.RSyntaxTextArea; import plugins.tprovoost.scripteditor.gui.ScriptingPanel; -public class VarScriptEditorPython extends VarScriptEditorV3 -{ - public VarScriptEditorPython(VarScriptPython varScript, String defaultValue) - { - super(varScript, defaultValue); - } +public class VarScriptEditorPython extends VarScriptEditorV3 { + public VarScriptEditorPython(final VarScriptPython varScript, final String defaultValue) { + super(varScript, defaultValue); + } - @Override - protected JComponent createEditorComponent() - { - panelIn = new ScriptingPanel("Internal Editor", "Python"); - panelOut = new ScriptingPanel("External Editor", "Python"); - panelOut.setBorder(BorderFactory.createEmptyBorder(4, 4, 4, 4)); + @Override + protected JComponent createEditorComponent() { + panelIn = new ScriptingPanel("Internal Editor", "Python"); + panelOut = new ScriptingPanel("External Editor", "Python"); + panelOut.setBorder(BorderFactory.createEmptyBorder(4, 4, 4, 4)); - frame = new IcyFrame("External Editor", true, true, true, true); - frame.setContentPane(panelOut); - frame.setSize(500, 500); - frame.setVisible(true); - frame.addToDesktopPane(); - frame.setDefaultCloseOperation(WindowConstants.HIDE_ON_CLOSE); - frame.center(); + frame = new IcyFrame("External Editor", true, true, true, true); + frame.setContentPane(panelOut); + frame.setSize(500, 500); + frame.setVisible(true); + frame.addToDesktopPane(); + frame.setDefaultCloseOperation(WindowConstants.HIDE_ON_CLOSE); + frame.center(); - frameListener = new IcyFrameAdapter() - { - @Override - public void icyFrameClosing(IcyFrameEvent e) - { - RSyntaxTextArea textArea = panelIn.getTextArea(); - textArea.setEnabled(true); - textArea.setText(panelOut.getTextArea().getText()); - textArea.repaint(); - } - }; + frameListener = new IcyFrameAdapter() { + @Override + public void icyFrameClosing(final IcyFrameEvent e) { + final RSyntaxTextArea textArea = panelIn.getTextArea(); + textArea.setEnabled(true); + textArea.setText(panelOut.getTextArea().getText()); + textArea.repaint(); + } + }; - // building east component - IcyButton buttonEdit = new IcyButton(new IcyIcon("redo.png", 12)); - buttonEdit.addActionListener(new ActionListener() - { + // building east component + final IcyButton buttonEdit = new IcyButton(new IcyIcon("redo.png", 12)); + buttonEdit.addActionListener(e -> { + panelOut.getTextArea().setText(panelIn.getTextArea().getText()); + panelIn.getTextArea().setEnabled(false); + frame.setVisible(true); + frame.requestFocus(); + }); + final JPanel eastPanel = new JPanel(); + eastPanel.setLayout(new BoxLayout(eastPanel, BoxLayout.Y_AXIS)); + eastPanel.add(Box.createVerticalGlue()); + eastPanel.add(buttonEdit); + eastPanel.add(Box.createVerticalGlue()); + eastPanel.setOpaque(false); - @Override - public void actionPerformed(ActionEvent e) - { - panelOut.getTextArea().setText(panelIn.getTextArea().getText()); - panelIn.getTextArea().setEnabled(false); - frame.setVisible(true); - frame.requestFocus(); - } - }); - JPanel eastPanel = new JPanel(); - eastPanel.setLayout(new BoxLayout(eastPanel, BoxLayout.Y_AXIS)); - eastPanel.add(Box.createVerticalGlue()); - eastPanel.add(buttonEdit); - eastPanel.add(Box.createVerticalGlue()); - eastPanel.setOpaque(false); + // to Return panel + final JPanel toReturn = new JPanel(new BorderLayout()); + toReturn.add(panelIn, BorderLayout.CENTER); + toReturn.setOpaque(false); + toReturn.add(eastPanel, BorderLayout.EAST); - // to Return panel - JPanel toReturn = new JPanel(new BorderLayout()); - toReturn.add(panelIn, BorderLayout.CENTER); - toReturn.setOpaque(false); - toReturn.add(eastPanel, BorderLayout.EAST); - - setComponentResizeable(true); - panelIn.getTextArea().setCaretPosition(0); - panelOut.getTextArea().setCaretPosition(0); - return toReturn; - } + setComponentResizeable(true); + panelIn.getTextArea().setCaretPosition(0); + panelOut.getTextArea().setCaretPosition(0); + return toReturn; + } } diff --git a/src/main/java/plugins/tprovoost/scripteditor/scriptblock/VarScriptEditorV3.java b/src/main/java/plugins/tprovoost/scripteditor/scriptblock/VarScriptEditorV3.java index 61f122788a1a0903c9a0af6694ca84e93e07f22c..252d82aeea15a9d5fe2952b018452314748c80ff 100644 --- a/src/main/java/plugins/tprovoost/scripteditor/scriptblock/VarScriptEditorV3.java +++ b/src/main/java/plugins/tprovoost/scripteditor/scriptblock/VarScriptEditorV3.java @@ -9,8 +9,6 @@ import icy.resource.icon.IcyIcon; import java.awt.BorderLayout; import java.awt.Dimension; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; import javax.swing.BorderFactory; import javax.swing.Box; @@ -24,29 +22,25 @@ import org.fife.ui.rsyntaxtextarea.RSyntaxTextArea; import plugins.adufour.vars.gui.swing.SwingVarEditor; import plugins.tprovoost.scripteditor.gui.ScriptingPanel; -public class VarScriptEditorV3 extends SwingVarEditor<String> -{ +public class VarScriptEditorV3 extends SwingVarEditor<String> { protected ScriptingPanel panelOut; protected ScriptingPanel panelIn; protected IcyFrame frame; protected IcyFrameListener frameListener; - public VarScriptEditorV3(VarScript varScript, String defaultValue) - { + public VarScriptEditorV3(final VarScript varScript, final String defaultValue) { super(varScript); - + panelIn.getTextArea().setText(defaultValue); } @Override - public Dimension getPreferredSize() - { + public Dimension getPreferredSize() { return super.getPreferredSize(); } @Override - protected JComponent createEditorComponent() - { + protected JComponent createEditorComponent() { setNameVisible(false); panelIn = new ScriptingPanel("Internal Editor", "JavaScript"); panelOut = new ScriptingPanel("External Editor", "JavaScript"); @@ -60,12 +54,10 @@ public class VarScriptEditorV3 extends SwingVarEditor<String> frame.setDefaultCloseOperation(WindowConstants.HIDE_ON_CLOSE); frame.center(); - frameListener = new IcyFrameAdapter() - { + frameListener = new IcyFrameAdapter() { @Override - public void icyFrameClosing(IcyFrameEvent e) - { - RSyntaxTextArea textArea = panelIn.getTextArea(); + public void icyFrameClosing(final IcyFrameEvent e) { + final RSyntaxTextArea textArea = panelIn.getTextArea(); textArea.setEnabled(true); textArea.setText(panelOut.getTextArea().getText()); textArea.repaint(); @@ -73,19 +65,14 @@ public class VarScriptEditorV3 extends SwingVarEditor<String> }; // building east component - IcyButton buttonEdit = new IcyButton(new IcyIcon("redo.png", 12)); - buttonEdit.addActionListener(new ActionListener() - { - @Override - public void actionPerformed(ActionEvent e) - { - panelOut.getTextArea().setText(panelIn.getTextArea().getText()); - panelIn.getTextArea().setEnabled(false); - frame.setVisible(true); - frame.requestFocus(); - } + final IcyButton buttonEdit = new IcyButton(new IcyIcon("redo.png", 12)); + buttonEdit.addActionListener(e -> { + panelOut.getTextArea().setText(panelIn.getTextArea().getText()); + panelIn.getTextArea().setEnabled(false); + frame.setVisible(true); + frame.requestFocus(); }); - JPanel eastPanel = new JPanel(); + final JPanel eastPanel = new JPanel(); eastPanel.setLayout(new BoxLayout(eastPanel, BoxLayout.Y_AXIS)); eastPanel.add(Box.createVerticalGlue()); eastPanel.add(buttonEdit); @@ -93,7 +80,7 @@ public class VarScriptEditorV3 extends SwingVarEditor<String> eastPanel.setOpaque(false); // to Return panel - JPanel toReturn = new JPanel(new BorderLayout()); + final JPanel toReturn = new JPanel(new BorderLayout()); toReturn.add(panelIn, BorderLayout.CENTER); toReturn.setOpaque(false); toReturn.add(eastPanel, BorderLayout.EAST); @@ -105,50 +92,42 @@ public class VarScriptEditorV3 extends SwingVarEditor<String> } @Override - public double getComponentVerticalResizeFactor() - { + public double getComponentVerticalResizeFactor() { return 1d; } @Override - protected void activateListeners() - { + protected void activateListeners() { frame.addFrameListener(frameListener); } @Override - protected void deactivateListeners() - { + protected void deactivateListeners() { frame.removeFrameListener(frameListener); frame.close(); } @Override - protected void updateInterfaceValue() - { + protected void updateInterfaceValue() { } - public String getText() - { + public String getText() { if (panelIn == null || panelIn.getTextArea() == null) return getVariable().getDefaultValue(); return panelIn.getTextArea().getText(); } - public void setText(String newValue) - { + public void setText(final String newValue) { panelOut.getTextArea().setText(newValue); panelIn.getTextArea().setText(newValue); } - public ScriptingPanel getPanelIn() - { + public ScriptingPanel getPanelIn() { return panelIn; } - public ScriptingPanel getPanelOut() - { + public ScriptingPanel getPanelOut() { return panelOut; } diff --git a/src/main/java/plugins/tprovoost/scripteditor/scriptblock/VarScriptPython.java b/src/main/java/plugins/tprovoost/scripteditor/scriptblock/VarScriptPython.java index f00b95fd6a4bbe9987abfb6dbf4bc9d2b62face6..54f8bf6c494663e4eaf7b54d1e28c50e012d72c3 100644 --- a/src/main/java/plugins/tprovoost/scripteditor/scriptblock/VarScriptPython.java +++ b/src/main/java/plugins/tprovoost/scripteditor/scriptblock/VarScriptPython.java @@ -5,17 +5,15 @@ import javax.script.ScriptException; import plugins.tprovoost.scripteditor.scriptinghandlers.ScriptEngine; import plugins.tprovoost.scripteditor.scriptinghandlers.ScriptEngineHandler; -public class VarScriptPython extends VarScript -{ - public VarScriptPython(String name, String defaultValue) - { - super(name, defaultValue); - setEditor(new VarScriptEditorPython(this, defaultValue)); - } +public class VarScriptPython extends VarScript { + public VarScriptPython(final String name, final String defaultValue) { + super(name, defaultValue); + setEditor(new VarScriptEditorPython(this, defaultValue)); + } - public void evaluate() throws ScriptException - { - ScriptEngine engine = ScriptEngineHandler.getEngine("python"); - engine.eval(getValue()); - } + @Override + public void evaluate() throws ScriptException { + final ScriptEngine engine = ScriptEngineHandler.getEngine("python"); + engine.eval(getValue()); + } } diff --git a/src/main/java/plugins/tprovoost/scripteditor/scriptblock/editor/DefaultScriptVarEditorFactory.java b/src/main/java/plugins/tprovoost/scripteditor/scriptblock/editor/DefaultScriptVarEditorFactory.java index c4f7b69e588db69092434a6905e469fa3bb78f72..bdf9bfcd7dd6ab6abe42d2d70856178ce472978f 100644 --- a/src/main/java/plugins/tprovoost/scripteditor/scriptblock/editor/DefaultScriptVarEditorFactory.java +++ b/src/main/java/plugins/tprovoost/scripteditor/scriptblock/editor/DefaultScriptVarEditorFactory.java @@ -6,20 +6,20 @@ import plugins.tprovoost.scripteditor.scriptblock.var.VarScript; public class DefaultScriptVarEditorFactory { - private static DefaultScriptVarEditorFactory defaultFactory = new DefaultScriptVarEditorFactory();; - - public static DefaultScriptVarEditorFactory getDefaultFactory() { - return defaultFactory; - } + private static final DefaultScriptVarEditorFactory defaultFactory = new DefaultScriptVarEditorFactory(); - public VarScriptEditor createScriptEditor(VarScript var) { - switch (var.getValue().getScriptType()) { - case JAVASCRIPT: - return new JavaScriptScriptVarEditor((VarJavaScriptScript)var); - case PYTHON: - return new PythonScriptVarEditor((VarPythonScript)var); - default: - throw new RuntimeException("Unsupported script type: " + var.getValue().getScriptType()); - } - } + public static DefaultScriptVarEditorFactory getDefaultFactory() { + return defaultFactory; + } + + public VarScriptEditor createScriptEditor(final VarScript var) { + switch (var.getValue().getScriptType()) { + case JAVASCRIPT: + return new JavaScriptScriptVarEditor((VarJavaScriptScript) var); + case PYTHON: + return new PythonScriptVarEditor((VarPythonScript) var); + default: + throw new RuntimeException("Unsupported script type: " + var.getValue().getScriptType()); + } + } } diff --git a/src/main/java/plugins/tprovoost/scripteditor/scriptblock/editor/JavaScriptScriptVarEditor.java b/src/main/java/plugins/tprovoost/scripteditor/scriptblock/editor/JavaScriptScriptVarEditor.java index bf8d2e212c74abc577fac9b1c6cdd6d83488d9dd..3e603d899655f8488991a417590cc668836d2ae7 100644 --- a/src/main/java/plugins/tprovoost/scripteditor/scriptblock/editor/JavaScriptScriptVarEditor.java +++ b/src/main/java/plugins/tprovoost/scripteditor/scriptblock/editor/JavaScriptScriptVarEditor.java @@ -3,8 +3,7 @@ package plugins.tprovoost.scripteditor.scriptblock.editor; import plugins.tprovoost.scripteditor.scriptblock.var.VarJavaScriptScript; public class JavaScriptScriptVarEditor extends VarScriptEditor { - - public JavaScriptScriptVarEditor(VarJavaScriptScript variable) { - super(variable); - } + public JavaScriptScriptVarEditor(final VarJavaScriptScript variable) { + super(variable); + } } diff --git a/src/main/java/plugins/tprovoost/scripteditor/scriptblock/editor/PythonScriptVarEditor.java b/src/main/java/plugins/tprovoost/scripteditor/scriptblock/editor/PythonScriptVarEditor.java index 79f15f736ec155d0b235599f5ccdd8effdfdcb1d..a8e985ac6c6c8149f4608eea4d28197513af956d 100644 --- a/src/main/java/plugins/tprovoost/scripteditor/scriptblock/editor/PythonScriptVarEditor.java +++ b/src/main/java/plugins/tprovoost/scripteditor/scriptblock/editor/PythonScriptVarEditor.java @@ -4,7 +4,7 @@ import plugins.tprovoost.scripteditor.scriptblock.var.VarPythonScript; public class PythonScriptVarEditor extends VarScriptEditor { - public PythonScriptVarEditor(VarPythonScript variable) { - super(variable); // Calls createEditorComponent - } + public PythonScriptVarEditor(final VarPythonScript variable) { + super(variable); // Calls createEditorComponent + } } diff --git a/src/main/java/plugins/tprovoost/scripteditor/scriptblock/editor/VarScriptEditor.java b/src/main/java/plugins/tprovoost/scripteditor/scriptblock/editor/VarScriptEditor.java index e3d08c4f2c78c0a55db2dfd5934e0a17e38d5c26..c2b0c55b9478b853b0b67c51ed29e2aabb3d583a 100644 --- a/src/main/java/plugins/tprovoost/scripteditor/scriptblock/editor/VarScriptEditor.java +++ b/src/main/java/plugins/tprovoost/scripteditor/scriptblock/editor/VarScriptEditor.java @@ -1,8 +1,6 @@ package plugins.tprovoost.scripteditor.scriptblock.editor; import java.awt.BorderLayout; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; import java.util.HashMap; import java.util.Set; @@ -33,184 +31,171 @@ import plugins.tprovoost.scripteditor.scriptinghandlers.ScriptingHandler; import plugins.tprovoost.scripteditor.scriptinghandlers.VariableType; public abstract class VarScriptEditor extends SwingVarEditor<Script> { - private ScriptingPanel panelIn; - private ScriptingPanel panelOut; - - private IcyFrame frame; - private IcyFrameListener frameListener; - - public VarScriptEditor(VarScript variable) { - super(variable); // Calls createEditorComponent - } - - @Override - public VarScript getVariable() { - return (VarScript) super.getVariable(); - } - - @Override - protected JComponent createEditorComponent() { - setNameVisible(false); - setComponentResizeable(true); - JPanel component = buildComponentPanel(); - final Set<VarMutable> inputVariables = getVariable().getInputVariables(); - final Set<VarMutable> outputVariables = getVariable().getOutputVariables(); - ThreadUtil.invokeLater(new Runnable() { - @Override - public void run() { - setupVariables(inputVariables, outputVariables); - panelIn.getScriptHandler().interpret(false); - panelOut.getScriptHandler().interpret(false); - } - }); - return component; - } - - private JPanel buildComponentPanel() { - JPanel componentPanel = new JPanel(new BorderLayout()); - componentPanel.setOpaque(false); - componentPanel.add(buildInternalEditorPanel(), BorderLayout.CENTER); - componentPanel.add(buildInternalEastPanel(), BorderLayout.EAST); - return componentPanel; - } - - private JPanel buildInternalEditorPanel() { - panelIn = new ScriptingPanel("Internal Editor", getEditorScriptType()); - panelIn.setText(getVariable().getCode()); - panelIn.getTextArea().setCaretPosition(0); - panelIn.getTextArea().getDocument().addDocumentListener(new DocumentListener() { - - @Override - public void removeUpdate(DocumentEvent e) { - getVariable().getValue().updateCode(panelIn.getTextArea().getText()); - } - - @Override - public void insertUpdate(DocumentEvent e) { - getVariable().getValue().updateCode(panelIn.getTextArea().getText()); - } - - @Override - public void changedUpdate(DocumentEvent e) { - } - }); - return panelIn; - } - - private String getEditorScriptType() { - switch (getVariable().getValue().getScriptType()) { - case JAVASCRIPT: - return "JavaScript"; - case PYTHON: - return "Python"; - default: - throw new RuntimeException("Unsupported script type: " + getVariable().getValue().getScriptType()); - } - } - - private JPanel buildInternalEastPanel() { - JPanel eastPanel = new JPanel(); - eastPanel.setOpaque(false); - eastPanel.setLayout(new BoxLayout(eastPanel, BoxLayout.Y_AXIS)); - eastPanel.add(Box.createVerticalGlue()); - - IcyButton editButton = new IcyButton(new IcyIcon("redo.png", 12)); - eastPanel.add(editButton); - eastPanel.add(Box.createVerticalGlue()); - - buildExternalEditorFrame(); - - editButton.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - getVariable().updateCode(panelIn.getTextArea().getText()); - panelOut.getTextArea().setText(getVariable().getCode()); - panelOut.getTextArea().setCaretPosition(panelIn.getTextArea().getCaretPosition()); - panelIn.getTextArea().setEnabled(false); - frame.setVisible(true); - frame.requestFocus(); - } - }); - - return eastPanel; - } - - private void buildExternalEditorFrame() { - frame = new IcyFrame("External Editor", true, true, true, true); - frame.setSize(500, 500); - - buildExternalPanel(); - frame.setContentPane(panelOut); - - frame.addToDesktopPane(); - frame.setDefaultCloseOperation(WindowConstants.HIDE_ON_CLOSE); - frame.center(); - - frameListener = new IcyFrameAdapter() { - @Override - public void icyFrameClosing(IcyFrameEvent e) { - panelIn.getTextArea().setText(panelOut.getTextArea().getText()); - panelIn.getTextArea().setCaretPosition(panelOut.getTextArea().getCaretPosition()); - panelIn.getTextArea().setEnabled(true); - panelIn.getTextArea().repaint(); - } - }; - } - - private void buildExternalPanel() { - panelOut = new ScriptingPanel("External Editor", getEditorScriptType()); - panelOut.setBorder(BorderFactory.createEmptyBorder(4, 4, 4, 4)); - panelOut.getTextArea().setCaretPosition(0); - panelOut.getTextArea().setText(panelIn.getTextArea().getText()); - } - - @Override - public double getComponentVerticalResizeFactor() { - return 1d; - } - - @Override - protected void activateListeners() { - frame.addFrameListener(frameListener); - } - - @Override - protected void deactivateListeners() { - frame.removeFrameListener(frameListener); - frame.close(); - } - - @Override - protected void updateInterfaceValue() { - panelIn.getTextArea().setText(getVariable().getValue().getCode()); - panelOut.getTextArea().setText(getVariable().getValue().getCode()); - setupVariables(getVariable().getInputVariables(), getVariable().getOutputVariables()); - } - - public void setupVariables(Set<VarMutable> inputVariables, Set<VarMutable> outputVariables) { - ScriptingHandler inHandler = panelIn.getScriptHandler(); - ScriptingHandler outHandler = panelOut.getScriptHandler(); - setupVariables(inputVariables, outputVariables, inHandler); - setupVariables(inputVariables, outputVariables, outHandler); - } - - private void setupVariables(Set<VarMutable> inputVariables, Set<VarMutable> outputVariables, - final ScriptingHandler handler) { - HashMap<String, ScriptVariable> handlerVariables = handler.getExternalVariables(); - - handlerVariables.clear(); - for (Var<?> inputVar : inputVariables) { - handlerVariables.put(inputVar.getName(), new ScriptVariable(new VariableType(inputVar.getType()))); - } - for (Var<?> outputVar : outputVariables) { - handlerVariables.put(outputVar.getName(), new ScriptVariable(new VariableType(outputVar.getType()))); - } - ThreadUtil.invokeLater(new Runnable() { - - @Override - public void run() { - handler.interpret(false); - } - }); - } + private ScriptingPanel panelIn; + private ScriptingPanel panelOut; + + private IcyFrame frame; + private IcyFrameListener frameListener; + + public VarScriptEditor(final VarScript variable) { + super(variable); // Calls createEditorComponent + } + + @Override + public VarScript getVariable() { + return (VarScript) super.getVariable(); + } + + @Override + protected JComponent createEditorComponent() { + setNameVisible(false); + setComponentResizeable(true); + final JPanel component = buildComponentPanel(); + final Set<VarMutable> inputVariables = getVariable().getInputVariables(); + final Set<VarMutable> outputVariables = getVariable().getOutputVariables(); + ThreadUtil.invokeLater(() -> { + setupVariables(inputVariables, outputVariables); + panelIn.getScriptHandler().interpret(false); + panelOut.getScriptHandler().interpret(false); + }); + return component; + } + + private JPanel buildComponentPanel() { + final JPanel componentPanel = new JPanel(new BorderLayout()); + componentPanel.setOpaque(false); + componentPanel.add(buildInternalEditorPanel(), BorderLayout.CENTER); + componentPanel.add(buildInternalEastPanel(), BorderLayout.EAST); + return componentPanel; + } + + private JPanel buildInternalEditorPanel() { + panelIn = new ScriptingPanel("Internal Editor", getEditorScriptType()); + panelIn.setText(getVariable().getCode()); + panelIn.getTextArea().setCaretPosition(0); + panelIn.getTextArea().getDocument().addDocumentListener(new DocumentListener() { + + @Override + public void removeUpdate(final DocumentEvent e) { + getVariable().getValue().updateCode(panelIn.getTextArea().getText()); + } + + @Override + public void insertUpdate(final DocumentEvent e) { + getVariable().getValue().updateCode(panelIn.getTextArea().getText()); + } + + @Override + public void changedUpdate(final DocumentEvent e) { + } + }); + return panelIn; + } + + private String getEditorScriptType() { + switch (getVariable().getValue().getScriptType()) { + case JAVASCRIPT: + return "JavaScript"; + case PYTHON: + return "Python"; + default: + throw new RuntimeException("Unsupported script type: " + getVariable().getValue().getScriptType()); + } + } + + private JPanel buildInternalEastPanel() { + final JPanel eastPanel = new JPanel(); + eastPanel.setOpaque(false); + eastPanel.setLayout(new BoxLayout(eastPanel, BoxLayout.Y_AXIS)); + eastPanel.add(Box.createVerticalGlue()); + + final IcyButton editButton = new IcyButton(new IcyIcon("redo.png", 12)); + eastPanel.add(editButton); + eastPanel.add(Box.createVerticalGlue()); + + buildExternalEditorFrame(); + + editButton.addActionListener(e -> { + getVariable().updateCode(panelIn.getTextArea().getText()); + panelOut.getTextArea().setText(getVariable().getCode()); + panelOut.getTextArea().setCaretPosition(panelIn.getTextArea().getCaretPosition()); + panelIn.getTextArea().setEnabled(false); + frame.setVisible(true); + frame.requestFocus(); + }); + + return eastPanel; + } + + private void buildExternalEditorFrame() { + frame = new IcyFrame("External Editor", true, true, true, true); + frame.setSize(500, 500); + + buildExternalPanel(); + frame.setContentPane(panelOut); + + frame.addToDesktopPane(); + frame.setDefaultCloseOperation(WindowConstants.HIDE_ON_CLOSE); + frame.center(); + + frameListener = new IcyFrameAdapter() { + @Override + public void icyFrameClosing(final IcyFrameEvent e) { + panelIn.getTextArea().setText(panelOut.getTextArea().getText()); + panelIn.getTextArea().setCaretPosition(panelOut.getTextArea().getCaretPosition()); + panelIn.getTextArea().setEnabled(true); + panelIn.getTextArea().repaint(); + } + }; + } + + private void buildExternalPanel() { + panelOut = new ScriptingPanel("External Editor", getEditorScriptType()); + panelOut.setBorder(BorderFactory.createEmptyBorder(4, 4, 4, 4)); + panelOut.getTextArea().setCaretPosition(0); + panelOut.getTextArea().setText(panelIn.getTextArea().getText()); + } + + @Override + public double getComponentVerticalResizeFactor() { + return 1d; + } + + @Override + protected void activateListeners() { + frame.addFrameListener(frameListener); + } + + @Override + protected void deactivateListeners() { + frame.removeFrameListener(frameListener); + frame.close(); + } + + @Override + protected void updateInterfaceValue() { + panelIn.getTextArea().setText(getVariable().getValue().getCode()); + panelOut.getTextArea().setText(getVariable().getValue().getCode()); + setupVariables(getVariable().getInputVariables(), getVariable().getOutputVariables()); + } + + public void setupVariables(final Set<VarMutable> inputVariables, final Set<VarMutable> outputVariables) { + final ScriptingHandler inHandler = panelIn.getScriptHandler(); + final ScriptingHandler outHandler = panelOut.getScriptHandler(); + setupVariables(inputVariables, outputVariables, inHandler); + setupVariables(inputVariables, outputVariables, outHandler); + } + + private void setupVariables(final Set<VarMutable> inputVariables, final Set<VarMutable> outputVariables, final ScriptingHandler handler) { + final HashMap<String, ScriptVariable> handlerVariables = handler.getExternalVariables(); + + handlerVariables.clear(); + for (final Var<?> inputVar : inputVariables) { + handlerVariables.put(inputVar.getName(), new ScriptVariable(new VariableType(inputVar.getType()))); + } + for (final Var<?> outputVar : outputVariables) { + handlerVariables.put(outputVar.getName(), new ScriptVariable(new VariableType(outputVar.getType()))); + } + ThreadUtil.invokeLater(() -> handler.interpret(false)); + } } diff --git a/src/main/java/plugins/tprovoost/scripteditor/scriptblock/script/DefaultScript.java b/src/main/java/plugins/tprovoost/scripteditor/scriptblock/script/DefaultScript.java index f6b0f82ed55af6d289c530d1d5cb85c9b38e07b0..1442a4a2cd513438abc4dd3c9af09fcec6e74328 100644 --- a/src/main/java/plugins/tprovoost/scripteditor/scriptblock/script/DefaultScript.java +++ b/src/main/java/plugins/tprovoost/scripteditor/scriptblock/script/DefaultScript.java @@ -9,60 +9,60 @@ import plugins.adufour.vars.lang.VarMutable; public abstract class DefaultScript implements Script { - private String code; - private Set<VarMutable> variables; - - public DefaultScript() { - this(""); - } - - public DefaultScript(String code) { - this(code, Collections.<VarMutable>emptyList()); - } - - public DefaultScript(String code, Collection<VarMutable> variables) { - this.code = code; - this.variables = new HashSet<VarMutable>(variables); - } - - @Override - public String getCode() { - return code; - } - - @Override - public Set<VarMutable> getVariables() { - return Collections.unmodifiableSet(variables); - } - - @Override - public void updateCode(String newCode) { - this.code = newCode; - } - - @Override - public void addVariable(VarMutable variable) { - variables.add(variable); - } - - @Override - public void addVariables(Collection<VarMutable> variables) { - this.variables.addAll(variables); - } - - @Override - public void removeVariable(VarMutable variable) { - variables.remove(variable); - } - - @Override - public void removeVariables(Collection<VarMutable> variables) { - this.variables.removeAll(variables); - } - - @Override - public String toString() { - return getCode(); - } + private String code; + private final Set<VarMutable> variables; + + public DefaultScript() { + this(""); + } + + public DefaultScript(final String code) { + this(code, Collections.emptyList()); + } + + public DefaultScript(final String code, final Collection<VarMutable> variables) { + this.code = code; + this.variables = new HashSet<>(variables); + } + + @Override + public String getCode() { + return code; + } + + @Override + public Set<VarMutable> getVariables() { + return Collections.unmodifiableSet(variables); + } + + @Override + public void updateCode(final String newCode) { + this.code = newCode; + } + + @Override + public void addVariable(final VarMutable variable) { + variables.add(variable); + } + + @Override + public void addVariables(final Collection<VarMutable> variables) { + this.variables.addAll(variables); + } + + @Override + public void removeVariable(final VarMutable variable) { + variables.remove(variable); + } + + @Override + public void removeVariables(final Collection<VarMutable> variables) { + this.variables.removeAll(variables); + } + + @Override + public String toString() { + return getCode(); + } } diff --git a/src/main/java/plugins/tprovoost/scripteditor/scriptblock/script/JavaScriptScript.java b/src/main/java/plugins/tprovoost/scripteditor/scriptblock/script/JavaScriptScript.java index 548f2685a9a2c21369e878411860e9e4742c43f0..86c772502013d4ec112f4eae513d04f2bf1a9f8a 100644 --- a/src/main/java/plugins/tprovoost/scripteditor/scriptblock/script/JavaScriptScript.java +++ b/src/main/java/plugins/tprovoost/scripteditor/scriptblock/script/JavaScriptScript.java @@ -7,21 +7,21 @@ import plugins.adufour.vars.lang.VarMutable; public class JavaScriptScript extends DefaultScript { - public JavaScriptScript() { - this(""); - } - - public JavaScriptScript(String code) { - this(code, Collections.<VarMutable>emptyList()); - } - - public JavaScriptScript(String code, Collection<VarMutable> variables) { - super(code, variables); - } - - @Override - public ScriptType getScriptType() { - return ScriptType.JAVASCRIPT; - } + public JavaScriptScript() { + this(""); + } + + public JavaScriptScript(final String code) { + this(code, Collections.emptyList()); + } + + public JavaScriptScript(final String code, final Collection<VarMutable> variables) { + super(code, variables); + } + + @Override + public ScriptType getScriptType() { + return ScriptType.JAVASCRIPT; + } } diff --git a/src/main/java/plugins/tprovoost/scripteditor/scriptblock/script/PythonScript.java b/src/main/java/plugins/tprovoost/scripteditor/scriptblock/script/PythonScript.java index 8480016a7260c334a16d88d95939128948d32c40..430b84f4c4617a62b952ea33390428e6388d178a 100644 --- a/src/main/java/plugins/tprovoost/scripteditor/scriptblock/script/PythonScript.java +++ b/src/main/java/plugins/tprovoost/scripteditor/scriptblock/script/PythonScript.java @@ -7,21 +7,20 @@ import plugins.adufour.vars.lang.VarMutable; public class PythonScript extends DefaultScript { - public PythonScript() { - this(""); - } - - public PythonScript(String code) { - this(code, Collections.<VarMutable>emptyList()); - } - - public PythonScript(String code, Collection<VarMutable> variables) { - super(code, variables); - } - - @Override - public ScriptType getScriptType() { - return ScriptType.PYTHON; - } - + public PythonScript() { + this(""); + } + + public PythonScript(final String code) { + this(code, Collections.emptyList()); + } + + public PythonScript(final String code, final Collection<VarMutable> variables) { + super(code, variables); + } + + @Override + public ScriptType getScriptType() { + return ScriptType.PYTHON; + } } diff --git a/src/main/java/plugins/tprovoost/scripteditor/scriptblock/script/Script.java b/src/main/java/plugins/tprovoost/scripteditor/scriptblock/script/Script.java index 4d2eddc0da854e47c847eb16cdc33ede4382ffbf..2a6fea4f5fa2470216b0200f7b37b765a8a6752f 100644 --- a/src/main/java/plugins/tprovoost/scripteditor/scriptblock/script/Script.java +++ b/src/main/java/plugins/tprovoost/scripteditor/scriptblock/script/Script.java @@ -6,19 +6,19 @@ import java.util.Set; import plugins.adufour.vars.lang.VarMutable; public interface Script { - ScriptType getScriptType(); + ScriptType getScriptType(); - String getCode(); + String getCode(); - Set<VarMutable> getVariables(); + Set<VarMutable> getVariables(); - void updateCode(String newCode); + void updateCode(final String newCode); - void addVariable(VarMutable variable); + void addVariable(final VarMutable variable); - void addVariables(Collection<VarMutable> inputVariables); + void addVariables(final Collection<VarMutable> inputVariables); - void removeVariable(VarMutable variable); + void removeVariable(final VarMutable variable); - void removeVariables(Collection<VarMutable> inputVariables); + void removeVariables(final Collection<VarMutable> inputVariables); } diff --git a/src/main/java/plugins/tprovoost/scripteditor/scriptblock/script/ScriptType.java b/src/main/java/plugins/tprovoost/scripteditor/scriptblock/script/ScriptType.java index 36a102c2b16ba7f9eb4737f6d8d811fc20620f56..448337f37c2f234e54f5852a9e248807a85a7b74 100644 --- a/src/main/java/plugins/tprovoost/scripteditor/scriptblock/script/ScriptType.java +++ b/src/main/java/plugins/tprovoost/scripteditor/scriptblock/script/ScriptType.java @@ -1,16 +1,16 @@ package plugins.tprovoost.scripteditor.scriptblock.script; public enum ScriptType { - JAVASCRIPT("javascript"), PYTHON("python"); - - private String stringVal; - - ScriptType(String stringVal) { - this.stringVal = stringVal; - } - - @Override - public String toString() { - return stringVal; - } + JAVASCRIPT("javascript"), PYTHON("python"); + + private final String stringVal; + + ScriptType(final String stringVal) { + this.stringVal = stringVal; + } + + @Override + public String toString() { + return stringVal; + } } diff --git a/src/main/java/plugins/tprovoost/scripteditor/scriptblock/var/VarJavaScriptScript.java b/src/main/java/plugins/tprovoost/scripteditor/scriptblock/var/VarJavaScriptScript.java index 499e3370a32a62b0fb9ebf1c1160d42971c5b6dd..ba5c024d0a8755e02b62238601161f3e6bf90449 100644 --- a/src/main/java/plugins/tprovoost/scripteditor/scriptblock/var/VarJavaScriptScript.java +++ b/src/main/java/plugins/tprovoost/scripteditor/scriptblock/var/VarJavaScriptScript.java @@ -11,34 +11,30 @@ import plugins.tprovoost.scripteditor.scriptblock.script.Script; public class VarJavaScriptScript extends VarScript { - public VarJavaScriptScript(String name, String defaultValue) { - this(name, defaultValue, Collections.<VarMutable>emptySet(), Collections.<VarMutable>emptySet()); - } - - public VarJavaScriptScript(String name, String defaultValue, Collection<VarMutable> inputVariables, - Collection<VarMutable> outputVariables) throws NullPointerException { - this(name, defaultValue, inputVariables, outputVariables, null); - } - - public VarJavaScriptScript(String name, String defaultValue, VarListener<Script> defaultListener) - throws NullPointerException { - this(name, defaultValue, Collections.<VarMutable>emptyList(), Collections.<VarMutable>emptyList(), defaultListener); - } - - public VarJavaScriptScript(String name, String defaultValue, Collection<VarMutable> inputVariables, - Collection<VarMutable> outputVariables, VarListener<Script> defaultListener) - throws NullPointerException { - super(name, new JavaScriptScript(filterNullValue(defaultValue)), defaultListener); - this.inputVariables = new HashSet<VarMutable>(inputVariables); - this.outputVariables = new HashSet<VarMutable>(outputVariables); - } - - private static String filterNullValue(String defaultValue) { - return defaultValue == null ? "" : defaultValue; - } - - @Override - public JavaScriptScript parse(String text) { - return new JavaScriptScript(text); - } + public VarJavaScriptScript(final String name, final String defaultValue) { + this(name, defaultValue, Collections.emptySet(), Collections.emptySet()); + } + + public VarJavaScriptScript(final String name, final String defaultValue, final Collection<VarMutable> inputVariables, final Collection<VarMutable> outputVariables) throws NullPointerException { + this(name, defaultValue, inputVariables, outputVariables, null); + } + + public VarJavaScriptScript(final String name, final String defaultValue, final VarListener<Script> defaultListener) throws NullPointerException { + this(name, defaultValue, Collections.emptyList(), Collections.emptyList(), defaultListener); + } + + public VarJavaScriptScript(final String name, final String defaultValue, final Collection<VarMutable> inputVariables, final Collection<VarMutable> outputVariables, final VarListener<Script> defaultListener) throws NullPointerException { + super(name, new JavaScriptScript(filterNullValue(defaultValue)), defaultListener); + this.inputVariables = new HashSet<>(inputVariables); + this.outputVariables = new HashSet<>(outputVariables); + } + + private static String filterNullValue(final String defaultValue) { + return defaultValue == null ? "" : defaultValue; + } + + @Override + public JavaScriptScript parse(final String text) { + return new JavaScriptScript(text); + } } diff --git a/src/main/java/plugins/tprovoost/scripteditor/scriptblock/var/VarPythonScript.java b/src/main/java/plugins/tprovoost/scripteditor/scriptblock/var/VarPythonScript.java index 43995af28f373aa4b4f0fbd944d5323ae91174c7..143b2d1b9dbe68be36251507ad75dd6f883073ac 100644 --- a/src/main/java/plugins/tprovoost/scripteditor/scriptblock/var/VarPythonScript.java +++ b/src/main/java/plugins/tprovoost/scripteditor/scriptblock/var/VarPythonScript.java @@ -11,35 +11,31 @@ import plugins.tprovoost.scripteditor.scriptblock.script.Script; public class VarPythonScript extends VarScript { - public VarPythonScript(String name, String defaultValue) { - this(name, defaultValue, Collections.<VarMutable>emptySet(), Collections.<VarMutable>emptySet()); - } - - public VarPythonScript(String name, String defaultValue, Collection<VarMutable> inputVariables, - Collection<VarMutable> outputVariables) throws NullPointerException { - this(name, defaultValue, inputVariables, outputVariables, null); - } - - public VarPythonScript(String name, String defaultValue, VarListener<Script> defaultListener) - throws NullPointerException { - this(name, defaultValue, Collections.<VarMutable>emptyList(), Collections.<VarMutable>emptyList(), - defaultListener); - } - - public VarPythonScript(String name, String defaultValue, Collection<VarMutable> inputVariables, - Collection<VarMutable> outputVariables, VarListener<Script> defaultListener) throws NullPointerException { - super(name, new PythonScript(filterNullValue(defaultValue)), defaultListener); - this.inputVariables = new HashSet<VarMutable>(inputVariables); - this.outputVariables = new HashSet<VarMutable>(outputVariables); - } - - private static String filterNullValue(String defaultValue) { - return defaultValue == null ? "" : defaultValue; - } - - @Override - public PythonScript parse(String text) { - return new PythonScript(text); - } + public VarPythonScript(final String name, final String defaultValue) { + this(name, defaultValue, Collections.emptySet(), Collections.emptySet()); + } + + public VarPythonScript(final String name, final String defaultValue, final Collection<VarMutable> inputVariables, final Collection<VarMutable> outputVariables) throws NullPointerException { + this(name, defaultValue, inputVariables, outputVariables, null); + } + + public VarPythonScript(final String name, final String defaultValue, final VarListener<Script> defaultListener) throws NullPointerException { + this(name, defaultValue, Collections.emptyList(), Collections.emptyList(), defaultListener); + } + + public VarPythonScript(final String name, final String defaultValue, final Collection<VarMutable> inputVariables, final Collection<VarMutable> outputVariables, final VarListener<Script> defaultListener) throws NullPointerException { + super(name, new PythonScript(filterNullValue(defaultValue)), defaultListener); + this.inputVariables = new HashSet<>(inputVariables); + this.outputVariables = new HashSet<>(outputVariables); + } + + private static String filterNullValue(final String defaultValue) { + return defaultValue == null ? "" : defaultValue; + } + + @Override + public PythonScript parse(final String text) { + return new PythonScript(text); + } } diff --git a/src/main/java/plugins/tprovoost/scripteditor/scriptblock/var/VarScript.java b/src/main/java/plugins/tprovoost/scripteditor/scriptblock/var/VarScript.java index 0a4a9a8bfb348868d85fe13c25ade7b4f4550e08..3413d2f85bad49ad6b4e1d4abeb9ad7736663f31 100644 --- a/src/main/java/plugins/tprovoost/scripteditor/scriptblock/var/VarScript.java +++ b/src/main/java/plugins/tprovoost/scripteditor/scriptblock/var/VarScript.java @@ -10,112 +10,106 @@ import plugins.adufour.vars.lang.Var; import plugins.adufour.vars.lang.VarMutable; import plugins.adufour.vars.util.VarListener; import plugins.tprovoost.scripteditor.scriptblock.editor.DefaultScriptVarEditorFactory; -import plugins.tprovoost.scripteditor.scriptblock.editor.VarScriptEditor; import plugins.tprovoost.scripteditor.scriptblock.script.Script; public abstract class VarScript extends Var<Script> { - Set<VarMutable> inputVariables; - Set<VarMutable> outputVariables; - - public VarScript(String name, Script defaultValue) { - this(name, defaultValue, Collections.<VarMutable>emptySet(), Collections.<VarMutable>emptySet()); - } - - public VarScript(String name, Script defaultValue, Collection<VarMutable> inputVariables, - Collection<VarMutable> outputVariables) throws NullPointerException { - this(name, defaultValue, inputVariables, outputVariables, null); - } - - public VarScript(String name, Script defaultValue, VarListener<Script> defaultListener) - throws NullPointerException { - this(name, defaultValue, Collections.<VarMutable>emptyList(), Collections.<VarMutable>emptyList(), defaultListener); - } - - public VarScript(String name, Script defaultValue, Collection<VarMutable> inputVariables, - Collection<VarMutable> outputVariables, VarListener<Script> defaultListener) - throws NullPointerException { - super(name, defaultValue, defaultListener); - setValue(defaultValue); - this.inputVariables = new HashSet<VarMutable>(inputVariables); - this.outputVariables = new HashSet<VarMutable>(outputVariables); - } - - public String getCode() { - return getValue().getCode(); - } - - public Set<VarMutable> getVariables() { - return getValue().getVariables(); - } - - public Set<VarMutable> getInputVariables() { - return Collections.unmodifiableSet(inputVariables); - } - - public Set<VarMutable> getOutputVariables() { - return Collections.unmodifiableSet(outputVariables); - } - - @Override - public void setValue(Script newValue) throws IllegalArgumentException { - if (newValue != null && newValue.getCode() != null) - super.setValue(newValue); - } - - public void updateCode(String newCode) { - if (newCode != null) { - getValue().updateCode(newCode); - fireVariableChanged(getValue(), getValue()); - } - } - - public void setupInputVariables(Collection<VarMutable> variables) { - getValue().removeVariables(getInputVariables()); - inputVariables.clear(); - inputVariables.addAll(variables); - getValue().addVariables(getInputVariables()); - - } - - public void setupOutputVariables(Collection<VarMutable> variables) { - getValue().removeVariables(getOutputVariables()); - outputVariables.clear(); - outputVariables.addAll(variables); - getValue().addVariables(getOutputVariables()); - - } - - public void addInputVariable(VarMutable variable) { - getValue().addVariable(variable); - inputVariables.add(variable); - fireVariableChanged(getValue(), getValue()); - } - - public void addOutputVariable(VarMutable variable) { - getValue().addVariable(variable); - outputVariables.add(variable); - fireVariableChanged(getValue(), getValue()); - } - - public void removeInputVariable(VarMutable variable) { - getValue().removeVariable(variable); - inputVariables.remove(variable); - fireVariableChanged(getValue(), getValue()); - } - - public void removeOutputVariable(VarMutable variable) { - getValue().removeVariable(variable); - outputVariables.remove(variable); - fireVariableChanged(getValue(), getValue()); - } - - @Override - public VarEditor<Script> createVarEditor() { - DefaultScriptVarEditorFactory factory = DefaultScriptVarEditorFactory.getDefaultFactory(); - VarScriptEditor editor = factory.createScriptEditor(this); - return editor; - } + Set<VarMutable> inputVariables; + Set<VarMutable> outputVariables; + + public VarScript(final String name, final Script defaultValue) { + this(name, defaultValue, Collections.emptySet(), Collections.emptySet()); + } + + public VarScript(final String name, final Script defaultValue, final Collection<VarMutable> inputVariables, final Collection<VarMutable> outputVariables) throws NullPointerException { + this(name, defaultValue, inputVariables, outputVariables, null); + } + + public VarScript(final String name, final Script defaultValue, final VarListener<Script> defaultListener) throws NullPointerException { + this(name, defaultValue, Collections.emptyList(), Collections.emptyList(), defaultListener); + } + + public VarScript(final String name, final Script defaultValue, final Collection<VarMutable> inputVariables, final Collection<VarMutable> outputVariables, final VarListener<Script> defaultListener) throws NullPointerException { + super(name, defaultValue, defaultListener); + setValue(defaultValue); + this.inputVariables = new HashSet<>(inputVariables); + this.outputVariables = new HashSet<>(outputVariables); + } + + public String getCode() { + return getValue().getCode(); + } + + public Set<VarMutable> getVariables() { + return getValue().getVariables(); + } + + public Set<VarMutable> getInputVariables() { + return Collections.unmodifiableSet(inputVariables); + } + + public Set<VarMutable> getOutputVariables() { + return Collections.unmodifiableSet(outputVariables); + } + + @Override + public void setValue(final Script newValue) throws IllegalArgumentException { + if (newValue != null && newValue.getCode() != null) + super.setValue(newValue); + } + + public void updateCode(final String newCode) { + if (newCode != null) { + getValue().updateCode(newCode); + fireVariableChanged(getValue(), getValue()); + } + } + + public void setupInputVariables(final Collection<VarMutable> variables) { + getValue().removeVariables(getInputVariables()); + inputVariables.clear(); + inputVariables.addAll(variables); + getValue().addVariables(getInputVariables()); + + } + + public void setupOutputVariables(final Collection<VarMutable> variables) { + getValue().removeVariables(getOutputVariables()); + outputVariables.clear(); + outputVariables.addAll(variables); + getValue().addVariables(getOutputVariables()); + + } + + public void addInputVariable(final VarMutable variable) { + getValue().addVariable(variable); + inputVariables.add(variable); + fireVariableChanged(getValue(), getValue()); + } + + public void addOutputVariable(final VarMutable variable) { + getValue().addVariable(variable); + outputVariables.add(variable); + fireVariableChanged(getValue(), getValue()); + } + + public void removeInputVariable(final VarMutable variable) { + getValue().removeVariable(variable); + inputVariables.remove(variable); + fireVariableChanged(getValue(), getValue()); + } + + public void removeOutputVariable(final VarMutable variable) { + getValue().removeVariable(variable); + outputVariables.remove(variable); + fireVariableChanged(getValue(), getValue()); + } + + @Override + public VarEditor<Script> createVarEditor() { + final DefaultScriptVarEditorFactory factory = DefaultScriptVarEditorFactory.getDefaultFactory(); + return factory.createScriptEditor(this); + } // private Set<VarMutableScript> inputVariables; // private Set<VarMutableScript> outputVariables; diff --git a/src/main/java/plugins/tprovoost/scripteditor/scriptingconsole/BindingsScriptFrame.java b/src/main/java/plugins/tprovoost/scripteditor/scriptingconsole/BindingsScriptFrame.java index 3b18189fe28e7e18033ec3b7ba53ee64d6eac871..048f065685fdf352dc5f128185ccf39e3fe1c080 100644 --- a/src/main/java/plugins/tprovoost/scripteditor/scriptingconsole/BindingsScriptFrame.java +++ b/src/main/java/plugins/tprovoost/scripteditor/scriptingconsole/BindingsScriptFrame.java @@ -27,167 +27,129 @@ import plugins.tprovoost.scripteditor.scriptinghandlers.ScriptEngine; import plugins.tprovoost.scripteditor.scriptinghandlers.ScriptEngineHandler; // FIXME -public class BindingsScriptFrame extends IcyFrame -{ - // Warning! The BindingsFrame keeps a reference on the engine, and is a singleton - // It means that the referenced engine will not be garbage-collected unless - // it is set as null - private ScriptEngine engine; - private JButton btnFreeVar; - private JTable listVariables; - private BindingsTableModel model; - private static BindingsScriptFrame singleton = new BindingsScriptFrame(); - - protected BindingsScriptFrame() - { - super("Engine Bindings", true, true, true); - - JPanel mainPanel = new JPanel(); - - btnFreeVar = new JButton("Free Var"); - btnFreeVar.addActionListener(new ActionListener() - { - @Override - public void actionPerformed(ActionEvent arg0) - { - int selectedRow = listVariables.getSelectedRow(); - Object o = listVariables.getValueAt(selectedRow, 0); - Object val = listVariables.getValueAt(selectedRow, 1); - if (val instanceof NativeArray) - { - for (int i = 0; i < ((NativeArray) val).getLength(); ++i) - { - ((NativeArray) val).delete(i); - } - } else if (val instanceof IdScriptableObject || val instanceof NativeJavaObject) - { - Scriptable scope = ((NativeJavaObject) val).getParentScope(); - scope.put((String) o, scope, null); - } - engine.deleteBinding((String) o); - update(); - } - }); - JButton btnRefresh = new JButton("Refresh"); - btnRefresh.addActionListener(new ActionListener() - { - - @Override - public void actionPerformed(ActionEvent e) - { - update(); - } - }); - - model = new BindingsTableModel(); - listVariables = new JTable(model); - - mainPanel.setLayout(new BorderLayout()); - JScrollPane scroll = new JScrollPane(listVariables); - scroll.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS); - scroll.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS); - mainPanel.add(scroll, BorderLayout.CENTER); - JPanel panelSouth = new JPanel(); - panelSouth.setLayout(new BoxLayout(panelSouth, BoxLayout.X_AXIS)); - panelSouth.add(Box.createHorizontalGlue()); - panelSouth.add(btnFreeVar); - panelSouth.add(Box.createHorizontalGlue()); - panelSouth.add(btnRefresh); - panelSouth.add(Box.createHorizontalGlue()); - mainPanel.add(panelSouth, BorderLayout.SOUTH); - - setDefaultCloseOperation(WindowConstants.HIDE_ON_CLOSE); - setContentPane(mainPanel); - addToDesktopPane(); - setSize(200, 700); - } - - public void setEngine(ScriptEngine engine) - { - this.engine = engine; - } - - public void update() - { - if (engine != null) - { - String languageName = engine.getName(); - ScriptEngine engine = ScriptEngineHandler.getEngine(languageName); - if (engine != this.engine) - this.engine = engine; - ThreadUtil.invokeLater(new Runnable() - { - @Override - public void run() - { - model.fireTableDataChanged(); - listVariables.repaint(); - } - }); - } - } - - private class BindingsTableModel extends AbstractTableModel - { - - /** - * - */ - private static final long serialVersionUID = 1L; - - @Override - public String getColumnName(int column) - { - if (column == 0) - { - return "Binding"; - } else if (column == 1) - { - return "Value"; - } else - { - return ""; - } - } - - @Override - public int getColumnCount() - { - return 2; - } - - @Override - public int getRowCount() - { - if (engine != null) - return engine.getBindings().values().size(); - return 0; - } - - @Override - public Object getValueAt(int rowIndex, int columnIndex) - { - Set<String> keyset = engine.getBindings().keySet(); - if (rowIndex >= 0 && rowIndex < keyset.size()) - { - if (engine == null) - return null; - if (columnIndex == 0) - { - return keyset.toArray()[rowIndex]; - } else - { - Object o = engine.getBindings().values().toArray()[rowIndex]; - // Class<?> clazz = o.getClass(); - return o; - } - } - return null; - } - } - - public static BindingsScriptFrame getInstance() - { - return singleton; - } +public class BindingsScriptFrame extends IcyFrame { + // Warning! The BindingsFrame keeps a reference on the engine, and is a singleton + // It means that the referenced engine will not be garbage-collected unless + // it is set as null + private ScriptEngine engine; + private final JTable listVariables; + private final BindingsTableModel model; + private final static BindingsScriptFrame singleton = new BindingsScriptFrame(); + + protected BindingsScriptFrame() { + super("Engine Bindings", true, true, true); + + final JPanel mainPanel = new JPanel(); + + final JButton btnFreeVar = new JButton("Free Var"); + btnFreeVar.addActionListener(new ActionListener() { + @Override + public void actionPerformed(final ActionEvent arg0) { + final int selectedRow = listVariables.getSelectedRow(); + final Object o = listVariables.getValueAt(selectedRow, 0); + final Object val = listVariables.getValueAt(selectedRow, 1); + if (val instanceof NativeArray) { + for (int i = 0; i < ((NativeArray) val).getLength(); ++i) { + ((NativeArray) val).delete(i); + } + } + else if (val instanceof IdScriptableObject || val instanceof NativeJavaObject) { + final Scriptable scope = ((NativeJavaObject) val).getParentScope(); + scope.put((String) o, scope, null); + } + engine.deleteBinding((String) o); + update(); + } + }); + final JButton btnRefresh = new JButton("Refresh"); + btnRefresh.addActionListener(e -> update()); + + model = new BindingsTableModel(); + listVariables = new JTable(model); + + mainPanel.setLayout(new BorderLayout()); + final JScrollPane scroll = new JScrollPane(listVariables); + scroll.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS); + scroll.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS); + mainPanel.add(scroll, BorderLayout.CENTER); + final JPanel panelSouth = new JPanel(); + panelSouth.setLayout(new BoxLayout(panelSouth, BoxLayout.X_AXIS)); + panelSouth.add(Box.createHorizontalGlue()); + panelSouth.add(btnFreeVar); + panelSouth.add(Box.createHorizontalGlue()); + panelSouth.add(btnRefresh); + panelSouth.add(Box.createHorizontalGlue()); + mainPanel.add(panelSouth, BorderLayout.SOUTH); + + setDefaultCloseOperation(WindowConstants.HIDE_ON_CLOSE); + setContentPane(mainPanel); + addToDesktopPane(); + setSize(200, 700); + } + + public void setEngine(final ScriptEngine engine) { + this.engine = engine; + } + + public void update() { + if (engine != null) { + final String languageName = engine.getName(); + final ScriptEngine engine = ScriptEngineHandler.getEngine(languageName); + if (engine != this.engine) + this.engine = engine; + ThreadUtil.invokeLater(() -> { + model.fireTableDataChanged(); + listVariables.repaint(); + }); + } + } + + private class BindingsTableModel extends AbstractTableModel { + @Override + public String getColumnName(final int column) { + if (column == 0) { + return "Binding"; + } + else if (column == 1) { + return "Value"; + } + else { + return ""; + } + } + + @Override + public int getColumnCount() { + return 2; + } + + @Override + public int getRowCount() { + if (engine != null) + return engine.getBindings().values().size(); + return 0; + } + + @Override + public Object getValueAt(final int rowIndex, final int columnIndex) { + final Set<String> keyset = engine.getBindings().keySet(); + if (rowIndex >= 0 && rowIndex < keyset.size()) { + if (engine == null) + return null; + if (columnIndex == 0) { + return keyset.toArray()[rowIndex]; + } + else { + //Object o = engine.getBindings().values().toArray()[rowIndex]; + // Class<?> clazz = o.getClass(); + return engine.getBindings().values().toArray()[rowIndex]; + } + } + return null; + } + } + + public static BindingsScriptFrame getInstance() { + return singleton; + } } diff --git a/src/main/java/plugins/tprovoost/scripteditor/scriptingconsole/PythonScriptingconsole.java b/src/main/java/plugins/tprovoost/scripteditor/scriptingconsole/PythonScriptingconsole.java index 8e4c73781b445075cf0b9a3b65c54f21e1702bce..06c6d4c8b98205f89de74836b12d707bc07841ab 100644 --- a/src/main/java/plugins/tprovoost/scripteditor/scriptingconsole/PythonScriptingconsole.java +++ b/src/main/java/plugins/tprovoost/scripteditor/scriptingconsole/PythonScriptingconsole.java @@ -19,28 +19,22 @@ import org.python.util.InteractiveConsole; import plugins.tprovoost.scripteditor.gui.ConsoleOutput; import plugins.tprovoost.scripteditor.scriptinghandlers.py.PythonScriptingHandler; -public class PythonScriptingconsole extends Scriptingconsole -{ +import javax.annotation.Nonnull; - /** - * - */ - private static final long serialVersionUID = 1L; +public class PythonScriptingconsole extends Scriptingconsole { private static final String STRING_INPUT = ">>> "; private static final String STRING_INPUT_MORE = "... "; - private InteractiveConsole console; + private final InteractiveConsole console; private boolean waitingForMore; - public PythonScriptingconsole() - { + public PythonScriptingconsole() { // Note: there is no way to reset the system state for an // InteractiveConsole, // so sys.path (for example) is shared for all instances of them! console = new InteractiveConsole(); - if (PythonScriptingHandler.getInterpreter() == null) - { + if (PythonScriptingHandler.getInterpreter() == null) { PythonScriptingHandler.setInterpreter(console); } @@ -49,43 +43,30 @@ public class PythonScriptingconsole extends Scriptingconsole setMinimumSize(new Dimension(0, 25)); setPreferredSize(new Dimension(0, 25)); - Insets insets = getMargin(); - if (insets != null) - { + final Insets insets = getMargin(); + if (insets != null) { setMargin(new Insets(insets.top, 30, insets.bottom, insets.right)); } - else - { + else { setMargin(new Insets(0, 30, 0, 0)); } } @Override - public boolean isEditable() - { + public boolean isEditable() { return super.isEditable(); } - public void setLanguage(String language) - { - } - @Override - public void keyTyped(KeyEvent e) - { - - } + public void setLanguage(final String language) {} @Override - public void keyPressed(KeyEvent e) - { - String text = getText(); - switch (e.getKeyCode()) - { + public void keyPressed(final KeyEvent e) { + final String text = getText(); + switch (e.getKeyCode()) { case KeyEvent.VK_UP: - if (posInHistory < history.size() - 1) - { + if (posInHistory < history.size() - 1) { ++posInHistory; setText(history.get(posInHistory)); e.consume(); @@ -93,8 +74,7 @@ public class PythonScriptingconsole extends Scriptingconsole break; case KeyEvent.VK_DOWN: - if (posInHistory > 0) - { + if (posInHistory > 0) { --posInHistory; setText(history.get(posInHistory)); e.consume(); @@ -102,11 +82,9 @@ public class PythonScriptingconsole extends Scriptingconsole break; case KeyEvent.VK_ENTER: - if (!text.isEmpty()) - { - String time = DateUtil.now("HH:mm:ss"); - if (output != null) - { + if (!text.isEmpty()) { + final String time = DateUtil.now("HH:mm:ss"); + if (output != null) { if (waitingForMore) output.append(STRING_INPUT_MORE + getText() + "\n"); else @@ -114,12 +92,10 @@ public class PythonScriptingconsole extends Scriptingconsole } else System.out.println(time + ": " + text); - try - { + try { waitingForMore = console.push(text); } - catch (PyException pe) - { + catch (final PyException pe) { if (scriptHandler != null) scriptHandler.getEngine().getWriter().write(pe.toString()); } @@ -134,22 +110,13 @@ public class PythonScriptingconsole extends Scriptingconsole } @Override - public void keyReleased(KeyEvent e) - { - - } - - public void setOutput(ConsoleOutput outputNew) - { + public void setOutput(final ConsoleOutput outputNew) { output = outputNew; final StringWriter sw = new StringWriter(); - PrintWriter pw = new PrintWriter(sw, true) - { + final PrintWriter pw = new PrintWriter(sw, true) { @Override - public void write(String s) - { - if (output != null) - { + public void write(@Nonnull final String s) { + if (output != null) { output.append(s); } } @@ -159,10 +126,9 @@ public class PythonScriptingconsole extends Scriptingconsole } @Override - protected void paintComponent(Graphics g) - { + protected void paintComponent(final Graphics g) { super.paintComponent(g); - Graphics2D g2 = (Graphics2D) g.create(); + final Graphics2D g2 = (Graphics2D) g.create(); g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); g2.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON); g2.setColor(Color.BLACK); diff --git a/src/main/java/plugins/tprovoost/scripteditor/scriptingconsole/Scriptingconsole.java b/src/main/java/plugins/tprovoost/scripteditor/scriptingconsole/Scriptingconsole.java index e2942b25f4a1914cd4188d0d6a6ce8547871b73d..2b044158d9a3e7f467aabff0d3a4a44d28d7d0bc 100644 --- a/src/main/java/plugins/tprovoost/scripteditor/scriptingconsole/Scriptingconsole.java +++ b/src/main/java/plugins/tprovoost/scripteditor/scriptingconsole/Scriptingconsole.java @@ -5,8 +5,6 @@ import icy.util.DateUtil; import icy.util.EventUtil; import java.awt.Dimension; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; import java.awt.event.KeyEvent; import java.awt.event.KeyListener; import java.awt.event.MouseEvent; @@ -27,24 +25,15 @@ import plugins.tprovoost.scripteditor.scriptinghandlers.ScriptingHandler; import plugins.tprovoost.scripteditor.scriptinghandlers.js.JSScriptingHandlerRhino; import plugins.tprovoost.scripteditor.scriptinghandlers.py.PythonScriptingHandler; -// import plugins.tprovoost.scripteditor.main.scriptinghandlers.JSScriptingHandler7; - -public class Scriptingconsole extends JTextField implements KeyListener, MouseListener -{ - - /** - * - */ - private static final long serialVersionUID = 1L; +public class Scriptingconsole extends JTextField implements KeyListener, MouseListener { private static final int MAX_PER_LINE = 5; protected IcyCompletionProvider provider; protected ScriptingHandler scriptHandler; - protected ArrayList<String> history = new ArrayList<String>(); + protected ArrayList<String> history = new ArrayList<>(); protected int posInHistory = 0; protected ConsoleOutput output; - public Scriptingconsole() - { + public Scriptingconsole() { addKeyListener(this); addMouseListener(this); @@ -66,17 +55,14 @@ public class Scriptingconsole extends JTextField implements KeyListener, MouseLi setPreferredSize(new Dimension(0, 25)); } - public void close() - { + public void close() { removeKeyListener(this); removeMouseListener(this); } - public void setLanguage(String language) - { + public void setLanguage(final String language) { provider.clear(); - if (language.contentEquals("JavaScript")) - { + if (language.contentEquals("JavaScript")) { provider = new IcyCompletionProvider(); provider.installDefaultCompletions("javascript"); // if (System.getProperty("java.version").startsWith("1.6.")) @@ -85,18 +71,15 @@ public class Scriptingconsole extends JTextField implements KeyListener, MouseLi // else scriptHandler = new JSScriptingHandlerRhino(provider, this, null, false); } - else if (language.contentEquals("Python")) - { + else if (language.contentEquals("Python")) { provider = new IcyCompletionProvider(); provider.installDefaultCompletions("Python"); scriptHandler = new PythonScriptingHandler(provider, this, null, false); } - else - { + else { scriptHandler = null; } - if (scriptHandler != null) - { + if (scriptHandler != null) { scriptHandler.setNewEngine(false); scriptHandler.setForceRun(false); scriptHandler.setStrict(false); @@ -105,47 +88,38 @@ public class Scriptingconsole extends JTextField implements KeyListener, MouseLi } @Override - public void keyTyped(KeyEvent e) - { - } + public void keyTyped(final KeyEvent e) {} @Override - public void keyPressed(KeyEvent e) - { - String text = getText(); - switch (e.getKeyCode()) - { + public void keyPressed(final KeyEvent e) { + final String text = getText(); + switch (e.getKeyCode()) { case KeyEvent.VK_SPACE: e.consume(); - List<Completion> completions = provider.getCompletions(this); - if (completions == null || !e.isControlDown()) - { + final List<Completion> completions = provider.getCompletions(this); + if (completions == null || !e.isControlDown()) { return; } - if (completions.size() == 1) - { + if (completions.size() == 1) { this.setText(completions.get(0).getReplacementText()); } - else - { + else { int i = 0; - String s = ""; - for (Completion c : completions) - { - s += c.getReplacementText() + "\t"; + final StringBuilder s = new StringBuilder(); + for (final Completion c : completions) { + s.append(c.getReplacementText()).append("\t"); if (i != 0 && i % MAX_PER_LINE == 0) - s += "\n"; + s.append("\n"); ++i; } - if (!s.endsWith("\n")) - s += "\n"; - output.append(s); + if (!s.toString().endsWith("\n")) + s.append("\n"); + output.append(s.toString()); System.out.println(s); } break; case KeyEvent.VK_UP: - if (posInHistory < history.size() - 1) - { + if (posInHistory < history.size() - 1) { ++posInHistory; setText(history.get(posInHistory)); e.consume(); @@ -153,8 +127,7 @@ public class Scriptingconsole extends JTextField implements KeyListener, MouseLi break; case KeyEvent.VK_DOWN: - if (posInHistory > 0) - { + if (posInHistory > 0) { --posInHistory; setText(history.get(posInHistory)); e.consume(); @@ -162,11 +135,9 @@ public class Scriptingconsole extends JTextField implements KeyListener, MouseLi break; case KeyEvent.VK_ENTER: - if (!text.isEmpty()) - { - String time = DateUtil.now("HH:mm:ss"); - if (output != null) - { + if (!text.isEmpty()) { + final String time = DateUtil.now("HH:mm:ss"); + if (output != null) { output.append("> " + text + "\n"); } else @@ -184,40 +155,25 @@ public class Scriptingconsole extends JTextField implements KeyListener, MouseLi } @Override - public void keyReleased(KeyEvent e) - { - - } + public void keyReleased(final KeyEvent e) {} - public void setOutput(ConsoleOutput consoleOutput) - { + public void setOutput(final ConsoleOutput consoleOutput) { this.output = consoleOutput; if (scriptHandler != null) scriptHandler.setOutput(consoleOutput); } - public void clear() - { + public void clear() { if (output != null) output.clear(); } @Override - public void mouseClicked(MouseEvent e) - { - if (EventUtil.isRightMouseButton(e)) - { - JPopupMenu popup = new JPopupMenu(); - JMenuItem itemPaste = new JMenuItem("Paste"); - itemPaste.addActionListener(new ActionListener() - { - - @Override - public void actionPerformed(ActionEvent e) - { - paste(); - } - }); + public void mouseClicked(final MouseEvent e) { + if (EventUtil.isRightMouseButton(e)) { + final JPopupMenu popup = new JPopupMenu(); + final JMenuItem itemPaste = new JMenuItem("Paste"); + itemPaste.addActionListener(e1 -> paste()); popup.add(itemPaste); popup.show(this, e.getX(), e.getY()); e.consume(); @@ -225,23 +181,14 @@ public class Scriptingconsole extends JTextField implements KeyListener, MouseLi } @Override - public void mousePressed(MouseEvent e) - { - } + public void mousePressed(final MouseEvent e) {} @Override - public void mouseReleased(MouseEvent e) - { - } + public void mouseReleased(final MouseEvent e) {} @Override - public void mouseEntered(MouseEvent e) - { - } + public void mouseEntered(final MouseEvent e) {} @Override - public void mouseExited(MouseEvent e) - { - } - + public void mouseExited(final MouseEvent e) {} } diff --git a/src/main/java/plugins/tprovoost/scripteditor/scriptinghandlers/IcyFunctionBlock.java b/src/main/java/plugins/tprovoost/scripteditor/scriptinghandlers/IcyFunctionBlock.java index e0f25510106b1a2a069482eba10fa1cf32ac47f0..f76d7a0e701e0b980f3098223e2906eb80bcb632 100644 --- a/src/main/java/plugins/tprovoost/scripteditor/scriptinghandlers/IcyFunctionBlock.java +++ b/src/main/java/plugins/tprovoost/scripteditor/scriptinghandlers/IcyFunctionBlock.java @@ -2,46 +2,36 @@ package plugins.tprovoost.scripteditor.scriptinghandlers; import java.lang.reflect.Method; -public class IcyFunctionBlock -{ - - private String functionName; +public class IcyFunctionBlock { + private final String functionName; private int startOffset; private VariableType returnType; private Method m; /** - * @param functionName - * function name - * @param startOffset - * start offset - * @param returnType - * variable type + * @param functionName function name + * @param startOffset start offset + * @param returnType variable type */ - public IcyFunctionBlock(String functionName, int startOffset, VariableType returnType) - { + public IcyFunctionBlock(final String functionName, final int startOffset, final VariableType returnType) { this.functionName = functionName; this.startOffset = startOffset; this.returnType = returnType; } - public String getFunctionName() - { + public String getFunctionName() { return functionName; } - public int getStartOffset() - { + public int getStartOffset() { return startOffset; } - public VariableType getReturnType() - { + public VariableType getReturnType() { return returnType; } - public void setStartOffset(int startOffset) - { + public void setStartOffset(final int startOffset) { this.startOffset = startOffset; } @@ -69,18 +59,15 @@ public class IcyFunctionBlock // } // } - public void setReturnType(VariableType returnType) - { + public void setReturnType(final VariableType returnType) { this.returnType = returnType; } - public void setMethod(Method m) - { + public void setMethod(final Method m) { this.m = m; } - public Method getMethod() - { + public Method getMethod() { return m; } diff --git a/src/main/java/plugins/tprovoost/scripteditor/scriptinghandlers/ScriptEngine.java b/src/main/java/plugins/tprovoost/scripteditor/scriptinghandlers/ScriptEngine.java index 41f24e6f3af86ebd757f1bdabacdeb2390cd1adc..1102ebd0c14d8ad44026494378fc73e5bcc43f2e 100644 --- a/src/main/java/plugins/tprovoost/scripteditor/scriptinghandlers/ScriptEngine.java +++ b/src/main/java/plugins/tprovoost/scripteditor/scriptinghandlers/ScriptEngine.java @@ -5,78 +5,65 @@ import java.util.HashMap; import javax.script.ScriptException; -public abstract class ScriptEngine -{ - protected HashMap<String, Object> bindings = new HashMap<String, Object>(); - private PrintWriter pw; - private PrintWriter pwE; - - protected ScriptEngine() { - pw = new PrintWriter(System.out); - pwE = new PrintWriter(System.err); - } - - public void setWriter(PrintWriter pw) - { - this.pw = pw; - } - - public void setErrorWriter(PrintWriter pwE) - { - this.pwE = pwE; - } - - public abstract void eval(String string) throws ScriptException; - - public abstract void evalFile(String fileName) throws ScriptException; - - public PrintWriter getWriter() - { - return pw; - } - - public PrintWriter getErrorWriter() - { - return pwE; - } - - public abstract String getName(); - - public void clear() - { - HashMap<String, Object> bindings = getBindings(); - for (String s : bindings.keySet()) - { - bindings.put(s, null); - } - bindings.clear(); - } - - protected abstract void putInRealEngine(String name, Object value); - - protected abstract void removeFromRealEngine(String name); - - public void put(String name, Object value) - { - putInRealEngine(name, value); - bindings.put(name, value); - } - - public void deleteBinding(String name) - { - put(name, null); - bindings.remove(name); - removeFromRealEngine(name); - } - - public Object get(String name) - { - return bindings.get(name); - } - - public HashMap<String, Object> getBindings() - { - return bindings; - } +public abstract class ScriptEngine { + protected HashMap<String, Object> bindings = new HashMap<>(); + private PrintWriter pw; + private PrintWriter pwE; + protected ScriptEngine() { + pw = new PrintWriter(System.out); + pwE = new PrintWriter(System.err); + } + + public void setWriter(final PrintWriter pw) { + this.pw = pw; + } + + public void setErrorWriter(final PrintWriter pwE) { + this.pwE = pwE; + } + + public abstract void eval(String string) throws ScriptException; + + public abstract void evalFile(String fileName) throws ScriptException; + + public PrintWriter getWriter() { + return pw; + } + + public PrintWriter getErrorWriter() { + return pwE; + } + + public abstract String getName(); + + // TODO: 11/04/2023 Check if replaceAll is necessary + public void clear() { + final HashMap<String, Object> bindings = getBindings(); + bindings.replaceAll((s, v) -> null); + bindings.clear(); + } + + protected abstract void putInRealEngine(String name, Object value); + + protected abstract void removeFromRealEngine(String name); + + public void put(final String name, final Object value) { + putInRealEngine(name, value); + bindings.put(name, value); + } + + public void deleteBinding(final String name) { + put(name, null); + bindings.remove(name); + removeFromRealEngine(name); + } + + public Object get(final String name) { + return bindings.get(name); + } + + public HashMap<String, Object> getBindings() { + return bindings; + } } \ No newline at end of file diff --git a/src/main/java/plugins/tprovoost/scripteditor/scriptinghandlers/ScriptEngineHandler.java b/src/main/java/plugins/tprovoost/scripteditor/scriptinghandlers/ScriptEngineHandler.java index 303fe4762ab3eafde13314147ced517ef85aba6b..cd6e1431e81aefaf29e666952519b1143e010166 100644 --- a/src/main/java/plugins/tprovoost/scripteditor/scriptinghandlers/ScriptEngineHandler.java +++ b/src/main/java/plugins/tprovoost/scripteditor/scriptinghandlers/ScriptEngineHandler.java @@ -10,6 +10,7 @@ import java.util.HashMap; import javax.script.ScriptEngineFactory; +import icy.system.IcyExceptionHandler; import org.fife.ui.autocomplete.ParameterizedCompletion.Parameter; import icy.gui.frame.progress.ProgressFrame; @@ -25,59 +26,47 @@ import plugins.tprovoost.scripteditor.completion.types.ScriptFunctionCompletion. import plugins.tprovoost.scripteditor.scriptinghandlers.js.JSScriptEngine; import plugins.tprovoost.scripteditor.scriptinghandlers.py.PyScriptEngine; -public class ScriptEngineHandler implements PluginInstallerListener -{ - - /*--------------- - * static - *---------------*/ +public class ScriptEngineHandler implements PluginInstallerListener { /** * This {@link HashMap} is used to avoid multiple different engines for the same * language to be initialized. */ - private static final HashMap<String, ScriptEngine> engines = new HashMap<String, ScriptEngine>(); + private static final HashMap<String, ScriptEngine> engines = new HashMap<>(); - /** The engineManager contains all the engines. */ + /** + * The engineManager contains all the engines. + */ public static final ScriptEngineManager engineManager = new ScriptEngineManager(); - private static HashMap<ScriptEngine, ScriptEngineHandler> engineHandlers = new HashMap<ScriptEngine, ScriptEngineHandler>(); + private static final HashMap<ScriptEngine, ScriptEngineHandler> engineHandlers = new HashMap<>(); private static ScriptEngineHandler lastEngineHandler = null; private static ArrayList<Method> bindingFunctions; - private static ArrayList<String> allClasses = new ArrayList<String>(); + private static final ArrayList<String> allClasses = new ArrayList<>(); - /* - * ------------ non static ------------ - */ - private HashMap<String, VariableType> engineVariables = new HashMap<String, VariableType>(); - private HashMap<String, VariableType> engineFunctions = new HashMap<String, VariableType>(); - private ArrayList<String> engineDeclaredImports = new ArrayList<String>(); - private ArrayList<String> engineDeclaredImportClasses = new ArrayList<String>(); - private HashMap<Class<?>, ArrayList<ScriptFunctionCompletion>> engineTypesMethod = new HashMap<Class<?>, ArrayList<ScriptFunctionCompletion>>();; - - private ScriptEngineHandler() - { - if (bindingFunctions == null) - { - bindingFunctions = new ArrayList<Method>(); + private final HashMap<String, VariableType> engineVariables = new HashMap<>(); + private final HashMap<String, VariableType> engineFunctions = new HashMap<>(); + private final ArrayList<String> engineDeclaredImports = new ArrayList<>(); + private final ArrayList<String> engineDeclaredImportClasses = new ArrayList<>(); + private final HashMap<Class<?>, ArrayList<ScriptFunctionCompletion>> engineTypesMethod = new HashMap<>(); + + private ScriptEngineHandler() { + if (bindingFunctions == null) { + bindingFunctions = new ArrayList<>(); findBindingMethodsPlugins(); } } - public static ScriptEngineHandler getLastEngineHandler() - { + public static ScriptEngineHandler getLastEngineHandler() { return lastEngineHandler; } - public static void setEngine(String engineType, ScriptEngine engine) - { + public static void setEngine(final String engineType, final ScriptEngine engine) { engines.put(engineType, engine); } - public static ScriptEngineHandler getEngineHandler(ScriptEngine engine) - { + public static ScriptEngineHandler getEngineHandler(final ScriptEngine engine) { ScriptEngineHandler engineHandler = engineHandlers.get(engine); - if (engineHandler == null) - { + if (engineHandler == null) { engineHandler = new ScriptEngineHandler(); engineHandlers.put(engine, engineHandler); } @@ -85,25 +74,20 @@ public class ScriptEngineHandler implements PluginInstallerListener return engineHandler; } - public static ScriptEngine getEngine(String engineType) - { + public static ScriptEngine getEngine(final String engineType) { return getEngine(engineType, false); } - public static ScriptEngine getEngine(String engineType, boolean create) - { - String engineTypeL = engineType.toLowerCase(); + public static ScriptEngine getEngine(final String engineType, final boolean create) { + final String engineTypeL = engineType.toLowerCase(); ScriptEngine engineHash = engines.get(engineTypeL); - if (engineHash == null || create) - { + if (engineHash == null || create) { // engineHash = factory.getEngineByName(engineType); - if (engineTypeL.contentEquals("javascript")) - { + if (engineTypeL.contentEquals("javascript")) { engineHash = new JSScriptEngine(); engines.put(engineTypeL, engineHash); } - else if (engineTypeL.contentEquals("python")) - { + else if (engineTypeL.contentEquals("python")) { engineHash = new PyScriptEngine(); engines.put(engineTypeL, engineHash); } @@ -111,8 +95,7 @@ public class ScriptEngineHandler implements PluginInstallerListener return engineHash; } - public static void disposeEngine(ScriptEngine engine) - { + public static void disposeEngine(final ScriptEngine engine) { engine.clear(); // remove the references to the engine @@ -127,66 +110,53 @@ public class ScriptEngineHandler implements PluginInstallerListener // return engine; // } - public ArrayList<String> getEngineDeclaredImportClasses() - { + public ArrayList<String> getEngineDeclaredImportClasses() { return engineDeclaredImportClasses; } - public ArrayList<String> getEngineDeclaredImports() - { + public ArrayList<String> getEngineDeclaredImports() { return engineDeclaredImports; } - public HashMap<String, VariableType> getEngineFunctions() - { + public HashMap<String, VariableType> getEngineFunctions() { return engineFunctions; } - public HashMap<String, VariableType> getEngineVariables() - { + public HashMap<String, VariableType> getEngineVariables() { return engineVariables; } - public HashMap<Class<?>, ArrayList<ScriptFunctionCompletion>> getEngineTypesMethod() - { + public HashMap<Class<?>, ArrayList<ScriptFunctionCompletion>> getEngineTypesMethod() { return engineTypesMethod; } - public static ScriptEngineManager getEngineManager() - { + public static ScriptEngineManager getEngineManager() { return engineManager; } - private void findBindingMethodsPlugins() - { - ProgressFrame frame; - if (Icy.getMainInterface().isHeadLess()) - { + private void findBindingMethodsPlugins() { + final ProgressFrame frame; + if (Icy.getMainInterface().isHeadLess()) { frame = null; } - else - { + else { frame = new ProgressFrame("Loading functions..."); } - try - { - try - { + try { + try { allClasses.addAll(ClassUtil.findClassNamesInPackage("icy", true)); } - catch (IOException e) - { + catch (final IOException e) { + IcyExceptionHandler.showErrorMessage(e, true); } - if (getClass().getClassLoader() instanceof JarClassLoader) - { + if (getClass().getClassLoader() instanceof JarClassLoader) { // Collection<Class<?>> col = // PluginLoader.getLoadedClasses().values(); - Collection<Class<?>> col = PluginLoader.getLoadedClasses().values(); + final Collection<Class<?>> col = PluginLoader.getLoadedClasses().values(); if (frame != null) frame.setLength(col.size()); int i = 0; - for (Class<?> clazz : new ArrayList<Class<?>>(col)) - { + for (final Class<?> clazz : new ArrayList<>(col)) { findBindingsMethods(clazz); allClasses.add(clazz.getName()); ++i; @@ -194,15 +164,13 @@ public class ScriptEngineHandler implements PluginInstallerListener frame.setPosition(i); } } - else - { - ArrayList<PluginDescriptor> list = PluginLoader.getPlugins(); + else { + final ArrayList<PluginDescriptor> list = PluginLoader.getPlugins(); if (frame != null) frame.setLength(list.size()); int i = 0; - for (PluginDescriptor pd : list) - { - Class<?> clazz = pd.getPluginClass(); + for (final PluginDescriptor pd : list) { + final Class<?> clazz = pd.getPluginClass(); // System.out.println(pd); findBindingsMethods(clazz); allClasses.add(clazz.getName()); @@ -213,61 +181,55 @@ public class ScriptEngineHandler implements PluginInstallerListener } Collections.sort(allClasses); } - finally - { + finally { // chrono.displayInSeconds(); if (frame != null) frame.close(); } } - public void findBindingsMethods(Class<?> clazz) - { + public void findBindingsMethods(final Class<?> clazz) { if (clazz == null) return; // get the annotated methods - Method[] methods; - try - { + final Method[] methods; + try { methods = clazz.getDeclaredMethods(); } - catch (Error e) - { + catch (final Error e) { return; } - for (final Method method : methods) - { + for (final Method method : methods) { // make sure the method is public and annotated - int modifiers = method.getModifiers(); + final int modifiers = method.getModifiers(); if (!Modifier.isPublic(modifiers)) continue; // is it an annotated with BindingFunction? - BindingFunction blockFunction = method.getAnnotation(BindingFunction.class); + final BindingFunction blockFunction = method.getAnnotation(BindingFunction.class); if (blockFunction == null) continue; bindingFunctions.add(method); // Generate the function for the provider - ArrayList<Parameter> fParams = new ArrayList<Parameter>(); - Class<?>[] paramTypes = method.getParameterTypes(); + final ArrayList<Parameter> fParams = new ArrayList<>(); + final Class<?>[] paramTypes = method.getParameterTypes(); // get the parameters - String params = ""; - String functionName = blockFunction.value(); + StringBuilder params = new StringBuilder(); + final String functionName = blockFunction.value(); // get the parameters - for (int i = 0; i < paramTypes.length; ++i) - { + for (int i = 0; i < paramTypes.length; ++i) { fParams.add(new Parameter(IcyCompletionProvider.getType(paramTypes[i], true), "arg" + i)); - params += ",arg" + i; + params.append(",arg").append(i); } if (params.length() > 0) - params = params.substring(1); + params = new StringBuilder(params.substring(1)); // the object for the provider - ScriptFunctionCompletion sfc; + final ScriptFunctionCompletion sfc; if (Modifier.isStatic(method.getModifiers())) sfc = new ScriptFunctionCompletion(null, functionName, method); else @@ -276,21 +238,18 @@ public class ScriptEngineHandler implements PluginInstallerListener sfc.setParams(fParams); sfc.setRelevance(2); - if (engineFunctions != null) - { - Class<?> returnType = method.getReturnType(); + if (engineFunctions != null) { + final Class<?> returnType = method.getReturnType(); if (VariableType.isGeneric(returnType)) engineFunctions.put(functionName, new VariableType(returnType, VariableType.getType(method.getGenericReturnType().toString()))); else engineFunctions.put(functionName, new VariableType(returnType)); } - if (engineTypesMethod != null) - { + if (engineTypesMethod != null) { ArrayList<ScriptFunctionCompletion> methodsExisting = engineTypesMethod.get(clazz); if (methodsExisting == null) - methodsExisting = new ArrayList<ScriptFunctionCompletion>(); - if (methodsExisting.contains(sfc)) - methodsExisting.remove(sfc); + methodsExisting = new ArrayList<>(); + methodsExisting.remove(sfc); methodsExisting.add(sfc); engineTypesMethod.put(clazz, methodsExisting); } @@ -300,17 +259,14 @@ public class ScriptEngineHandler implements PluginInstallerListener /** * @return all methods */ - public ArrayList<Method> getFunctions() - { + public ArrayList<Method> getFunctions() { return bindingFunctions; } // FIXME Although this is defined, the listener is never added !! @Override - public void pluginInstalled(PluginDescriptor plugin, boolean success) - { - if (success) - { + public void pluginInstalled(final PluginDescriptor plugin, final boolean success) { + if (success) { bindingFunctions.clear(); engineFunctions.clear(); engineTypesMethod.clear(); @@ -325,10 +281,8 @@ public class ScriptEngineHandler implements PluginInstallerListener // FIXME Although this is defined, the listener is never added !! @Override - public void pluginRemoved(PluginDescriptor plugin, boolean success) - { - if (success) - { + public void pluginRemoved(final PluginDescriptor plugin, final boolean success) { + if (success) { bindingFunctions.clear(); engineFunctions.clear(); engineTypesMethod.clear(); @@ -339,22 +293,19 @@ public class ScriptEngineHandler implements PluginInstallerListener } /** - * @return all classes declared in plugins and icy. Language independant. + * @return all classes declared in plugins and icy. Language independent. */ - public static ArrayList<String> getAllClasses() - { + public static ArrayList<String> getAllClasses() { return allClasses; } /** + * @param factory the {@link ScriptEngineFactory} * @return the String language corresponding to the engine factory.<br> - * Ex: ECMAScript factory returns JavaScript. - * @param factory - * the {@link ScriptEngineFactory} + * Ex: ECMAScript factory returns JavaScript. */ - public static String getLanguageName(ScriptEngineFactory factory) - { - String languageName = factory.getLanguageName(); + public static String getLanguageName(final ScriptEngineFactory factory) { + final String languageName = factory.getLanguageName(); if (languageName.contentEquals("ECMAScript")) return "JavaScript"; if (languageName.contentEquals("python")) @@ -362,10 +313,8 @@ public class ScriptEngineHandler implements PluginInstallerListener return languageName; } - public static void clearEngines() - { - for (ScriptEngine engine : engines.values()) - { + public static void clearEngines() { + for (final ScriptEngine engine : engines.values()) { disposeEngine(engine); } engines.clear(); diff --git a/src/main/java/plugins/tprovoost/scripteditor/scriptinghandlers/ScriptEngineManager.java b/src/main/java/plugins/tprovoost/scripteditor/scriptinghandlers/ScriptEngineManager.java index 069e56360ef08f9c757293981ee005e405418263..36f550f8f36ff9a4fe3940a99ab44ee8eb75e7c4 100644 --- a/src/main/java/plugins/tprovoost/scripteditor/scriptinghandlers/ScriptEngineManager.java +++ b/src/main/java/plugins/tprovoost/scripteditor/scriptinghandlers/ScriptEngineManager.java @@ -2,7 +2,6 @@ package plugins.tprovoost.scripteditor.scriptinghandlers; import java.util.ArrayList; import java.util.Collections; -import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; import java.util.List; @@ -18,38 +17,43 @@ import icy.plugin.PluginLauncher; import icy.plugin.PluginLoader; import icy.plugin.interface_.PluginScriptFactory; -public class ScriptEngineManager -{ - /** Set of script engine factories discovered. */ - private HashSet<ScriptEngineFactory> engineSpis = new HashSet<>(); +public class ScriptEngineManager { + /** + * Set of script engine factories discovered. + */ + private final HashSet<ScriptEngineFactory> engineSpis = new HashSet<>(); - /** Map of engine name to script engine factory. */ - private HashMap<String, ScriptEngineFactory> nameAssociations = new HashMap<>(); + /** + * Map of engine name to script engine factory. + */ + private final HashMap<String, ScriptEngineFactory> nameAssociations = new HashMap<>(); - /** Map of script file extension to script engine factory. */ - private HashMap<String, ScriptEngineFactory> extensionAssociations = new HashMap<>(); + /** + * Map of script file extension to script engine factory. + */ + private final HashMap<String, ScriptEngineFactory> extensionAssociations = new HashMap<>(); - /** Map of script script MIME type to script engine factory. */ - private HashMap<String, ScriptEngineFactory> mimeTypeAssociations = new HashMap<>(); + /** + * Map of script MIME type to script engine factory. + */ + private final HashMap<String, ScriptEngineFactory> mimeTypeAssociations = new HashMap<>(); - /** Global bindings associated with script engines created by this manager. */ + /** + * Global bindings associated with script engines created by this manager. + */ private Bindings globalScope = new SimpleBindings(); - public ScriptEngineManager() - { + public ScriptEngineManager() { super(); - for (PluginDescriptor plugin : PluginLoader.getPlugins(PluginScriptFactory.class, true, false, false)) - { - try - { + for (final PluginDescriptor plugin : PluginLoader.getPlugins(PluginScriptFactory.class, true, false, false)) { + try { // create plugin instance - PluginScriptFactory psf = (PluginScriptFactory) PluginLauncher.create(plugin); + final PluginScriptFactory psf = (PluginScriptFactory) PluginLauncher.create(plugin); // get the factory and add it to the list engineSpis.add(psf.getScriptEngineFactory()); } - catch (Throwable t) - { + catch (final Throwable t) { System.err.println("Error while retrieving ScriptEngineFactory from " + plugin.getName() + ":"); System.err.println(t.getMessage()); } @@ -62,15 +66,11 @@ public class ScriptEngineManager * <code>Bindings</code> as global bindings for <code>ScriptEngine</code> * objects created by it. * - * @param bindings - * The specified <code>Bindings</code> - * @throws IllegalArgumentException - * if bindings is null. + * @param bindings The specified <code>Bindings</code> + * @throws IllegalArgumentException if bindings is null. */ - public void setBindings(Bindings bindings) - { - if (bindings == null) - { + public void setBindings(final Bindings bindings) { + if (bindings == null) { throw new IllegalArgumentException("Global scope cannot be null."); } @@ -84,37 +84,29 @@ public class ScriptEngineManager * * @return The globalScope field. */ - public Bindings getBindings() - { + public Bindings getBindings() { return globalScope; } /** * Sets the specified key/value pair in the Global Scope. - * - * @param key - * Key to set - * @param value - * Value to set. - * @throws NullPointerException - * if key is null. - * @throws IllegalArgumentException - * if key is empty string. + * + * @param key Key to set + * @param value Value to set. + * @throws NullPointerException if key is null. + * @throws IllegalArgumentException if key is empty string. */ - public void put(String key, Object value) - { + public void put(final String key, final Object value) { globalScope.put(key, value); } /** * Gets the value for the specified key in the Global Scope - * - * @param key - * The key whose value is to be returned. + * + * @param key The key whose value is to be returned. * @return The value for the specified key. */ - public Object get(String key) - { + public Object get(final String key) { return globalScope.get(key); } @@ -128,64 +120,49 @@ public class ScriptEngineManager * If one is not found, it searches the set of <code>ScriptEngineFactory</code> instances * stored by the constructor for one with the specified name. If a <code>ScriptEngineFactory</code> * is found by either method, it is used to create instance of <code>ScriptEngine</code>. - * - * @param shortName - * The short name of the <code>ScriptEngine</code> implementation. - * returned by the <code>getNames</code> method of its <code>ScriptEngineFactory</code>. + * + * @param shortName The short name of the <code>ScriptEngine</code> implementation. + * returned by the <code>getNames</code> method of its <code>ScriptEngineFactory</code>. * @return A <code>ScriptEngine</code> created by the factory located in the search. Returns null - * if no such factory was found. The <code>ScriptEngineManager</code> sets its own <code>globalScope</code> - * <code>Bindings</code> as the <code>GLOBAL_SCOPE</code> <code>Bindings</code> of the newly - * created <code>ScriptEngine</code>. - * @throws NullPointerException - * if shortName is null. + * if no such factory was found. The <code>ScriptEngineManager</code> sets its own <code>globalScope</code> + * <code>Bindings</code> as the <code>GLOBAL_SCOPE</code> <code>Bindings</code> of the newly + * created <code>ScriptEngine</code>. + * @throws NullPointerException if shortName is null. */ - public javax.script.ScriptEngine getEngineByName(String shortName) - { + public javax.script.ScriptEngine getEngineByName(final String shortName) { if (shortName == null) throw new NullPointerException(); // look for registered name first - Object obj; - if (null != (obj = nameAssociations.get(shortName))) - { - ScriptEngineFactory spi = (ScriptEngineFactory) obj; - try - { - ScriptEngine engine = spi.getScriptEngine(); + final ScriptEngineFactory obj = nameAssociations.get(shortName); + if (obj != null) { + try { + final ScriptEngine engine = obj.getScriptEngine(); engine.setBindings(getBindings(), ScriptContext.GLOBAL_SCOPE); return engine; } - catch (Exception exp) - { + catch (final Exception exp) { debugPrint(exp); } } - for (ScriptEngineFactory spi : engineSpis) - { + for (final ScriptEngineFactory spi : engineSpis) { List<String> names = null; - try - { + try { names = spi.getNames(); } - catch (Exception exp) - { + catch (final Exception exp) { debugPrint(exp); } - if (names != null) - { - for (String name : names) - { - if (shortName.equals(name)) - { - try - { - ScriptEngine engine = spi.getScriptEngine(); + if (names != null) { + for (final String name : names) { + if (shortName.equals(name)) { + try { + final ScriptEngine engine = spi.getScriptEngine(); engine.setBindings(getBindings(), ScriptContext.GLOBAL_SCOPE); return engine; } - catch (Exception exp) - { + catch (final Exception exp) { debugPrint(exp); } } @@ -201,60 +178,46 @@ public class ScriptEngineManager * used by <code>getEngineByName</code> is used except that the search starts * by looking for a <code>ScriptEngineFactory</code> registered to handle the * given extension using <code>registerEngineExtension</code>. - * - * @param extension - * The given extension + * + * @param extension The given extension * @return The engine to handle scripts with this extension. Returns <code>null</code> - * if not found. - * @throws NullPointerException - * if extension is null. + * if not found. + * @throws NullPointerException if extension is null. */ - public ScriptEngine getEngineByExtension(String extension) - { + public ScriptEngine getEngineByExtension(final String extension) { if (extension == null) throw new NullPointerException(); // look for registered extension first - Object obj; - if (null != (obj = extensionAssociations.get(extension))) - { - ScriptEngineFactory spi = (ScriptEngineFactory) obj; - try - { - ScriptEngine engine = spi.getScriptEngine(); + final ScriptEngineFactory obj = extensionAssociations.get(extension); + if (obj != null) { + try { + final ScriptEngine engine = obj.getScriptEngine(); engine.setBindings(getBindings(), ScriptContext.GLOBAL_SCOPE); return engine; } - catch (Exception exp) - { + catch (final Exception exp) { debugPrint(exp); } } - for (ScriptEngineFactory spi : engineSpis) - { + for (final ScriptEngineFactory spi : engineSpis) { List<String> exts = null; - try - { + try { exts = spi.getExtensions(); } - catch (Exception exp) - { + catch (final Exception exp) { debugPrint(exp); } if (exts == null) continue; - for (String ext : exts) - { - if (extension.equals(ext)) - { - try - { - ScriptEngine engine = spi.getScriptEngine(); + for (final String ext : exts) { + if (extension.equals(ext)) { + try { + final ScriptEngine engine = spi.getScriptEngine(); engine.setBindings(getBindings(), ScriptContext.GLOBAL_SCOPE); return engine; } - catch (Exception exp) - { + catch (final Exception exp) { debugPrint(exp); } } @@ -268,60 +231,46 @@ public class ScriptEngineManager * used by <code>getEngineByName</code> is used except that the search starts * by looking for a <code>ScriptEngineFactory</code> registered to handle the * given mime type using <code>registerEngineMimeType</code>. - * - * @param mimeType - * The given mime type + * + * @param mimeType The given mime type * @return The engine to handle scripts with this mime type. Returns <code>null</code> - * if not found. - * @throws NullPointerException - * if mimeType is null. + * if not found. + * @throws NullPointerException if mimeType is null. */ - public ScriptEngine getEngineByMimeType(String mimeType) - { + public ScriptEngine getEngineByMimeType(final String mimeType) { if (mimeType == null) throw new NullPointerException(); // look for registered types first - Object obj; - if (null != (obj = mimeTypeAssociations.get(mimeType))) - { - ScriptEngineFactory spi = (ScriptEngineFactory) obj; - try - { - ScriptEngine engine = spi.getScriptEngine(); + final ScriptEngineFactory obj = mimeTypeAssociations.get(mimeType); + if (obj != null) { + try { + final ScriptEngine engine = obj.getScriptEngine(); engine.setBindings(getBindings(), ScriptContext.GLOBAL_SCOPE); return engine; } - catch (Exception exp) - { + catch (final Exception exp) { debugPrint(exp); } } - for (ScriptEngineFactory spi : engineSpis) - { + for (final ScriptEngineFactory spi : engineSpis) { List<String> types = null; - try - { + try { types = spi.getMimeTypes(); } - catch (Exception exp) - { + catch (final Exception exp) { debugPrint(exp); } if (types == null) continue; - for (String type : types) - { - if (mimeType.equals(type)) - { - try - { - ScriptEngine engine = spi.getScriptEngine(); + for (final String type : types) { + if (mimeType.equals(type)) { + try { + final ScriptEngine engine = spi.getScriptEngine(); engine.setBindings(getBindings(), ScriptContext.GLOBAL_SCOPE); return engine; } - catch (Exception exp) - { + catch (final Exception exp) { debugPrint(exp); } } @@ -333,32 +282,24 @@ public class ScriptEngineManager /** * Returns a list whose elements are instances of all the <code>ScriptEngineFactory</code> classes * found by the discovery mechanism. - * + * * @return List of all discovered <code>ScriptEngineFactory</code>s. */ - public List<ScriptEngineFactory> getEngineFactories() - { - List<ScriptEngineFactory> res = new ArrayList<ScriptEngineFactory>(engineSpis.size()); - for (ScriptEngineFactory spi : engineSpis) - { - res.add(spi); - } + public List<ScriptEngineFactory> getEngineFactories() { + final List<ScriptEngineFactory> res = new ArrayList<>(engineSpis.size()); + res.addAll(engineSpis); return Collections.unmodifiableList(res); } /** * Registers a <code>ScriptEngineFactory</code> to handle a language * name. Overrides any such association found using the Discovery mechanism. - * - * @param name - * The name to be associated with the <code>ScriptEngineFactory</code>. - * @param factory - * The class to associate with the given name. - * @throws NullPointerException - * if any of the parameters is null. + * + * @param name The name to be associated with the <code>ScriptEngineFactory</code>. + * @param factory The class to associate with the given name. + * @throws NullPointerException if any of the parameters is null. */ - public void registerEngineName(String name, ScriptEngineFactory factory) - { + public void registerEngineName(final String name, final ScriptEngineFactory factory) { if (name == null || factory == null) throw new NullPointerException(); nameAssociations.put(name, factory); @@ -368,16 +309,12 @@ public class ScriptEngineManager * Registers a <code>ScriptEngineFactory</code> to handle a mime type. * Overrides any such association found using the Discovery mechanism. * - * @param type - * The mime type to be associated with the - * <code>ScriptEngineFactory</code>. - * @param factory - * The class to associate with the given mime type. - * @throws NullPointerException - * if any of the parameters is null. + * @param type The mime type to be associated with the + * <code>ScriptEngineFactory</code>. + * @param factory The class to associate with the given mime type. + * @throws NullPointerException if any of the parameters is null. */ - public void registerEngineMimeType(String type, ScriptEngineFactory factory) - { + public void registerEngineMimeType(final String type, final ScriptEngineFactory factory) { if (type == null || factory == null) throw new NullPointerException(); mimeTypeAssociations.put(type, factory); @@ -387,23 +324,18 @@ public class ScriptEngineManager * Registers a <code>ScriptEngineFactory</code> to handle an extension. * Overrides any such association found using the Discovery mechanism. * - * @param extension - * The extension type to be associated with the - * <code>ScriptEngineFactory</code>. - * @param factory - * The class to associate with the given extension. - * @throws NullPointerException - * if any of the parameters is null. + * @param extension The extension type to be associated with the + * <code>ScriptEngineFactory</code>. + * @param factory The class to associate with the given extension. + * @throws NullPointerException if any of the parameters is null. */ - public void registerEngineExtension(String extension, ScriptEngineFactory factory) - { + public void registerEngineExtension(final String extension, final ScriptEngineFactory factory) { if (extension == null || factory == null) throw new NullPointerException(); extensionAssociations.put(extension, factory); } - private static void debugPrint(Throwable exp) - { + private static void debugPrint(final Throwable exp) { exp.printStackTrace(); } } diff --git a/src/main/java/plugins/tprovoost/scripteditor/scriptinghandlers/ScriptVariable.java b/src/main/java/plugins/tprovoost/scripteditor/scriptinghandlers/ScriptVariable.java index 0299e2882e8f752a27417474be3ce1819c68007a..f1ebeac4937b21c4cb89b271aa254be21ac94453 100644 --- a/src/main/java/plugins/tprovoost/scripteditor/scriptinghandlers/ScriptVariable.java +++ b/src/main/java/plugins/tprovoost/scripteditor/scriptinghandlers/ScriptVariable.java @@ -2,113 +2,91 @@ package plugins.tprovoost.scripteditor.scriptinghandlers; import java.util.ArrayList; -public class ScriptVariable -{ - private ArrayList<ScriptVariableScope> variableScopes = new ArrayList<ScriptVariableScope>(); +public class ScriptVariable { + private final ArrayList<ScriptVariableScope> variableScopes = new ArrayList<>(); - public ScriptVariable() - { + public ScriptVariable() { } - public ScriptVariable(VariableType returnType) - { + public ScriptVariable(final VariableType returnType) { addType(0, returnType); } - public void addType(int offsetBegin, VariableType returnType) - { + public void addType(final int offsetBegin, final VariableType returnType) { addType(offsetBegin, -1, returnType); } - public void addType(int offsetBegin, int offsetEnd, VariableType returnType) - { - if (!variableScopes.isEmpty()) - { - ScriptVariableScope lastScope = variableScopes.get(variableScopes.size() - 1); + public void addType(final int offsetBegin, final int offsetEnd, final VariableType returnType) { + if (!variableScopes.isEmpty()) { + final ScriptVariableScope lastScope = variableScopes.get(variableScopes.size() - 1); if (lastScope.endScopeOffset == -1) lastScope.endScopeOffset = offsetBegin - 1; } variableScopes.add(new ScriptVariableScope(offsetBegin, offsetEnd, returnType)); } - public VariableType getVariableClassType(int offset) - { - for (ScriptVariableScope svc : variableScopes) - { - VariableType type = svc.getType(offset); + public VariableType getVariableClassType(final int offset) { + for (final ScriptVariableScope svc : variableScopes) { + final VariableType type = svc.getType(offset); if (type != null) return type; } return null; } - public VariableType getVariableLastClassType() - { - if (!variableScopes.isEmpty()) - { + public VariableType getVariableLastClassType() { + if (!variableScopes.isEmpty()) { return variableScopes.get(variableScopes.size() - 1).type; } return null; } - public class ScriptVariableScope - { + public class ScriptVariableScope { private int declarationOffset; private int endScopeOffset; - private VariableType type; + private final VariableType type; - public ScriptVariableScope(int declarationOffset, int endScopeOffset, Class<?> type) - { + public ScriptVariableScope(final int declarationOffset, final int endScopeOffset, final Class<?> type) { this(declarationOffset, endScopeOffset, new VariableType(type)); } - public ScriptVariableScope(int declarationOffset, int endScopeOffset, VariableType type) - { + public ScriptVariableScope(final int declarationOffset, final int endScopeOffset, final VariableType type) { this.declarationOffset = declarationOffset; this.endScopeOffset = endScopeOffset; this.type = type; variableScopes.add(this); } - public VariableType getType(int offset) - { + public VariableType getType(final int offset) { if (offset >= declarationOffset && (endScopeOffset == -1 || offset < endScopeOffset)) return type; return null; } - - public int getDeclarationOffset() - { - return declarationOffset; - } - - public int getEndScopeOffset() - { - return endScopeOffset; - } - - public void setDeclarationOffset(int declarationOffset) - { - this.declarationOffset = declarationOffset; - } - - public void setEndScopeOffset(int endScopeOffset) - { - this.endScopeOffset = endScopeOffset; - } + + public int getDeclarationOffset() { + return declarationOffset; + } + + public int getEndScopeOffset() { + return endScopeOffset; + } + + public void setDeclarationOffset(final int declarationOffset) { + this.declarationOffset = declarationOffset; + } + + public void setEndScopeOffset(final int endScopeOffset) { + this.endScopeOffset = endScopeOffset; + } } - - public ArrayList<ScriptVariableScope> getVariableScopes() - { - return variableScopes; - } - - public boolean isInScope(int offset) - { - for (ScriptVariableScope svc : variableScopes) - { - boolean inScope = offset >= svc.declarationOffset - && (svc.endScopeOffset == -1 || offset < svc.endScopeOffset); + + public ArrayList<ScriptVariableScope> getVariableScopes() { + return variableScopes; + } + + public boolean isInScope(final int offset) { + for (final ScriptVariableScope svc : variableScopes) { + final boolean inScope = offset >= svc.declarationOffset && (svc.endScopeOffset == -1 || offset < svc.endScopeOffset); if (inScope) return true; } diff --git a/src/main/java/plugins/tprovoost/scripteditor/scriptinghandlers/ScriptingErrors.java b/src/main/java/plugins/tprovoost/scripteditor/scriptinghandlers/ScriptingErrors.java index 9689c6ad54e850f5b838a653e54b42419c9b7775..fd81c00d96725d226c6cb95d61fd3f301480c2dc 100644 --- a/src/main/java/plugins/tprovoost/scripteditor/scriptinghandlers/ScriptingErrors.java +++ b/src/main/java/plugins/tprovoost/scripteditor/scriptinghandlers/ScriptingErrors.java @@ -13,144 +13,132 @@ import org.fife.ui.rtextarea.Gutter; /** * This class stores the errors and warnings found when parsing the files - * and also the runtime error that may have occured when running the script. - * - * @author tlecomte + * and also the runtime error that may have occurred when running the script. * + * @author tlecomte */ public class ScriptingErrors { - private static final IcyIcon ICON_ERROR_TOOLTIP = new IcyIcon(ImageUtil.load(PluginLoader - .getResourceAsStream("plugins/tprovoost/scripteditor/resources/icons/quickfix_warning_obj.gif")), 16, false); - - private static final IcyIcon ICON_ERROR = new IcyIcon(ImageUtil.load(PluginLoader - .getResourceAsStream("plugins/tprovoost/scripteditor/resources/icons/error.gif")), 15, false); - - /** - * {@link ArrayList} containing all the errors found when parsing the file. - */ - private final ArrayList<ScriptException> errors = new ArrayList<ScriptException>(); - /** - * {@link ArrayList} containing all the warnings found when parsing the file. - */ - private final ArrayList<ScriptException> warnings = new ArrayList<ScriptException>(); - /** - * The error that stopped the script, if any. - */ - private ScriptException runtimeError = null; - - public void displayOnGutter(Gutter gutter) { - // The parser may have found multiple errors/warnings on each line - // We walk the list to merge them. - ArrayList<Integer> lines = new ArrayList<Integer>(); - ArrayList<Boolean> areWarning = new ArrayList<Boolean>(); - ArrayList<String> messages = new ArrayList<String>(); - - if (runtimeError != null) - { - lines.add(runtimeError.getLineNumber()); - areWarning.add(false); - - // We will wrap the message in HTML to handle multiple errors on a single line - // so first make sure we have nothing that could break HTML in the raw messages - String normalizedMessage = runtimeError.getMessage().replaceAll("<", "").replaceAll(">", ""); - messages.add(normalizedMessage); - } - - for (ScriptException see : errors) - { - // We will wrap the message in HTML to handle multiple errors on a single line - // so first make sure we have nothing that could break HTML in the raw messages - String normalizedMessage = see.getMessage().replaceAll("<", "").replaceAll(">", ""); - - if (lines.contains(see.getLineNumber())) - { - // there was already an error on this line - int index = lines.indexOf(see.getLineNumber()); - String message = messages.get(index) + "<br>" + normalizedMessage; - messages.set(index, message); - // if there is an error, make it an error, not a warning - areWarning.set(index, false); - } - else - { - lines.add(see.getLineNumber()); - areWarning.add(false); - messages.add(normalizedMessage); - } - } - - for (ScriptException see : warnings) - { - // We will wrap the message in HTML to handle multiple errors on a single line - // so first make sure we have nothing that could break HTML in the raw messages - String normalizedMessage = see.getMessage().replaceAll("<", "").replaceAll(">", ""); - - if (lines.contains(see.getLineNumber())) - { - // there was already an error on this line - int index = lines.indexOf(see.getLineNumber()); - String message = messages.get(index) + "<br>" + normalizedMessage; - messages.set(index, message); - // no need to change areWarning here - } - else - { - lines.add(see.getLineNumber()); - areWarning.add(false); - messages.add(normalizedMessage); - } - } - - for (int i=0; i<lines.size(); i++) - { - IcyIcon icon; - if (areWarning.get(i)) - icon = ICON_ERROR_TOOLTIP; - else - icon = ICON_ERROR; - //wrap the tooltip in html to handle multi-lines - String tooltip = "<html>" + messages.get(i) + "</html>"; - // if (tooltip.length() > 127) - // { - // tooltip = tooltip.substring(0, 127) + "..."; - // } - - // Warning! The Gutter displays lines starting from 1, BUT its - // internal implementation is based on a JTextArea that expects - // the line numbers to be counted from 0. - int textAreaLineNumber = lines.get(i)-1; - - try - { - gutter.addLineTrackingIcon(textAreaLineNumber, icon, tooltip); - } catch (BadLocationException e) - { - e.printStackTrace(); - System.out.println(tooltip); - } - - gutter.repaint(); - } - } - - public void setRuntimeError(ScriptException e) { - runtimeError = e; - } - - public void cleanup() { - errors.clear(); - warnings.clear(); - runtimeError = null; - } - - public void addWarning(ScriptException se) { - warnings.add(se); - } - - public void addError(ScriptException se) { - errors.add(se); - } - - + private static final IcyIcon ICON_ERROR_TOOLTIP = new IcyIcon(ImageUtil.load(PluginLoader.getResourceAsStream("plugins/tprovoost/scripteditor/resources/icons/quickfix_warning_obj.gif")), 16, false); + + private static final IcyIcon ICON_ERROR = new IcyIcon(ImageUtil.load(PluginLoader.getResourceAsStream("plugins/tprovoost/scripteditor/resources/icons/error.gif")), 15, false); + + /** + * {@link ArrayList} containing all the errors found when parsing the file. + */ + private final ArrayList<ScriptException> errors = new ArrayList<>(); + /** + * {@link ArrayList} containing all the warnings found when parsing the file. + */ + private final ArrayList<ScriptException> warnings = new ArrayList<>(); + /** + * The error that stopped the script, if any. + */ + private ScriptException runtimeError = null; + + public void displayOnGutter(final Gutter gutter) { + // The parser may have found multiple errors/warnings on each line + // We walk the list to merge them. + final ArrayList<Integer> lines = new ArrayList<>(); + final ArrayList<Boolean> areWarning = new ArrayList<>(); + final ArrayList<String> messages = new ArrayList<>(); + + if (runtimeError != null) { + lines.add(runtimeError.getLineNumber()); + areWarning.add(false); + + // We will wrap the message in HTML to handle multiple errors on a single line + // so first make sure we have nothing that could break HTML in the raw messages + final String normalizedMessage = runtimeError.getMessage().replaceAll("<", "").replaceAll(">", ""); + messages.add(normalizedMessage); + } + + for (final ScriptException see : errors) { + // We will wrap the message in HTML to handle multiple errors on a single line + // so first make sure we have nothing that could break HTML in the raw messages + final String normalizedMessage = see.getMessage().replaceAll("<", "").replaceAll(">", ""); + + if (lines.contains(see.getLineNumber())) { + // there was already an error on this line + final int index = lines.indexOf(see.getLineNumber()); + final String message = messages.get(index) + "<br>" + normalizedMessage; + messages.set(index, message); + // if there is an error, make it an error, not a warning + areWarning.set(index, false); + } + else { + lines.add(see.getLineNumber()); + areWarning.add(false); + messages.add(normalizedMessage); + } + } + + for (final ScriptException see : warnings) { + // We will wrap the message in HTML to handle multiple errors on a single line + // so first make sure we have nothing that could break HTML in the raw messages + final String normalizedMessage = see.getMessage().replaceAll("<", "").replaceAll(">", ""); + + if (lines.contains(see.getLineNumber())) { + // there was already an error on this line + final int index = lines.indexOf(see.getLineNumber()); + final String message = messages.get(index) + "<br>" + normalizedMessage; + messages.set(index, message); + // no need to change areWarning here + } + else { + lines.add(see.getLineNumber()); + areWarning.add(false); + messages.add(normalizedMessage); + } + } + + for (int i = 0; i < lines.size(); i++) { + final IcyIcon icon; + if (areWarning.get(i)) + icon = ICON_ERROR_TOOLTIP; + else + icon = ICON_ERROR; + //wrap the tooltip in html to handle multi-lines + final String tooltip = "<html>" + messages.get(i) + "</html>"; + // if (tooltip.length() > 127) + // { + // tooltip = tooltip.substring(0, 127) + "..."; + // } + + // Warning! The Gutter displays lines starting from 1, BUT its + // internal implementation is based on a JTextArea that expects + // the line numbers to be counted from 0. + final int textAreaLineNumber = lines.get(i) - 1; + + try { + gutter.addLineTrackingIcon(textAreaLineNumber, icon, tooltip); + } + catch (final BadLocationException e) { + e.printStackTrace(); + System.out.println(tooltip); + } + + gutter.repaint(); + } + } + + public void setRuntimeError(final ScriptException e) { + runtimeError = e; + } + + public void cleanup() { + errors.clear(); + warnings.clear(); + runtimeError = null; + } + + public void addWarning(final ScriptException se) { + warnings.add(se); + } + + public void addError(final ScriptException se) { + errors.add(se); + } + + } diff --git a/src/main/java/plugins/tprovoost/scripteditor/scriptinghandlers/ScriptingHandler.java b/src/main/java/plugins/tprovoost/scripteditor/scriptinghandlers/ScriptingHandler.java index e8b964337c2673b0446d60608c99e5425e979305..cce2111f9f15c375558e93d74e7514c32e2a2d02 100644 --- a/src/main/java/plugins/tprovoost/scripteditor/scriptinghandlers/ScriptingHandler.java +++ b/src/main/java/plugins/tprovoost/scripteditor/scriptinghandlers/ScriptingHandler.java @@ -14,6 +14,7 @@ import java.util.ArrayList; import java.util.HashMap; import java.util.List; +import javax.annotation.Nonnull; import javax.script.ScriptException; import javax.swing.JTextArea; import javax.swing.Timer; @@ -23,6 +24,7 @@ import javax.swing.text.BadLocationException; import javax.swing.text.Document; import javax.swing.text.JTextComponent; +import icy.system.IcyExceptionHandler; import org.fife.ui.autocomplete.Completion; import org.fife.ui.autocomplete.DefaultCompletionProvider; import org.fife.ui.autocomplete.VariableCompletion; @@ -51,11 +53,10 @@ import plugins.tprovoost.scripteditor.scriptingconsole.BindingsScriptFrame; /** * This class is in charge of the compilation of the script. It mostly depends * on the provider. - * + * * @author Thomas Provoost */ -public abstract class ScriptingHandler implements KeyListener, PluginRepositoryLoaderListener, LinkGenerator -{ +public abstract class ScriptingHandler implements KeyListener, PluginRepositoryLoaderListener, LinkGenerator { /** * Reference to errors and warnings found when parsing or running the file. */ @@ -65,9 +66,11 @@ public abstract class ScriptingHandler implements KeyListener, PluginRepositoryL * List of the variable completions found when script was parsed. Functions * and classes are considered as Variables too. */ - protected ArrayList<Completion> variableCompletions = new ArrayList<Completion>(); + protected ArrayList<Completion> variableCompletions = new ArrayList<>(); - /** Reference to the provider used for the autocompletion. */ + /** + * Reference to the provider used for the autocompletion. + */ protected DefaultCompletionProvider provider; /** @@ -76,27 +79,37 @@ public abstract class ScriptingHandler implements KeyListener, PluginRepositoryL */ private boolean compilationOk = false; - /** Reference to the current engine. */ - - /** Reference to the {@link RSyntaxTextArea} this item works on. */ + /** + * Reference to the {@link RSyntaxTextArea} this item works on. + */ protected JTextComponent textArea; - /** Contains all declared variables in the script. */ + /** + * Contains all declared variables in the script. + */ protected HashMap<String, ScriptVariable> localVariables; - protected HashMap<String, ScriptVariable> externalVariables = new HashMap<String, ScriptVariable>(); + protected HashMap<String, ScriptVariable> externalVariables = new HashMap<>(); - /** Contains all declared variables in the script. */ - protected HashMap<String, VariableType> localFunctions = new HashMap<String, VariableType>(); + /** + * Contains all declared variables in the script. + */ + protected HashMap<String, VariableType> localFunctions = new HashMap<>(); - /** Contains all declared importPackages in the script. */ - protected ArrayList<String> scriptDeclaredImports = new ArrayList<String>(); + /** + * Contains all declared importPackages in the script. + */ + protected ArrayList<String> scriptDeclaredImports = new ArrayList<>(); - /** Contains all declared importClasses in the script. */ - protected ArrayList<String> scriptDeclaredImportClasses = new ArrayList<String>(); + /** + * Contains all declared importClasses in the script. + */ + protected ArrayList<String> scriptDeclaredImportClasses = new ArrayList<>(); - /** A specific offset contains an Function. */ - protected HashMap<Integer, IcyFunctionBlock> blockFunctions = new HashMap<Integer, IcyFunctionBlock>(); + /** + * A specific offset contains a Function. + */ + protected HashMap<Integer, IcyFunctionBlock> blockFunctions = new HashMap<>(); /** * This is where the warning / errors are displayed, contained in this @@ -104,16 +117,17 @@ public abstract class ScriptingHandler implements KeyListener, PluginRepositoryL */ protected ConsoleOutput errorOutput; - /** Reference to the textarea scrollpane gutter. */ - private Gutter gutter; + /** + * Reference to the textarea scrollpane gutter. + */ + private final Gutter gutter; - /** Filename of the script */ + /** + * Filename of the script + */ protected String fileName = "Untitled"; - /** for debug purposes: advance will be used to load or not all functions */ - private boolean advanced; - - private boolean forceRun = false; + private boolean forceRun; private boolean newEngine = true; private boolean strict = false; private boolean varInterpretation = false; @@ -123,12 +137,14 @@ public abstract class ScriptingHandler implements KeyListener, PluginRepositoryL */ public EvalThread thread; - private ArrayList<ScriptListener> listeners = new ArrayList<ScriptListener>(); + private final ArrayList<ScriptListener> listeners = new ArrayList<>(); - /** Turn to true if you need to display more information in the console. */ + /** + * Turn to true if you need to display more information in the console. + */ protected static final boolean DEBUG = false; - private AutoVerify autoverify = new AutoVerify(); + private final AutoVerify autoverify = new AutoVerify(); // Different relevance of items. Simplify code, but integer values can // always be used. @@ -136,34 +152,20 @@ public abstract class ScriptingHandler implements KeyListener, PluginRepositoryL public static final int RELEVANCE_LOW = 2; public static final int RELEVANCE_HIGH = 10; - private StringWriter sw = new StringWriter(); - private PrintWriter pw = new PrintWriter(sw, true) - { + private final StringWriter sw = new StringWriter(); + private final PrintWriter pw = new PrintWriter(sw, true) { @Override - public synchronized void write(final String s) - { - if (errorOutput != null) - { - EventQueue.invokeLater(new Runnable() - { - - @Override - public void run() - { - errorOutput.append(s); - } - }); + public synchronized void write(@Nonnull final String s) { + if (errorOutput != null) { + EventQueue.invokeLater(() -> errorOutput.append(s)); } - else - { + else { System.out.print(s); } } }; - public ScriptingHandler(DefaultCompletionProvider provider, String engineType, JTextComponent textArea, - Gutter gutter, boolean forceRun, ScriptingPanel scriptingPanel) - { + public ScriptingHandler(final DefaultCompletionProvider provider, final String engineType, final JTextComponent textArea, final Gutter gutter, final boolean forceRun, final ScriptingPanel scriptingPanel) { this.provider = provider; this.textArea = textArea; this.gutter = gutter; @@ -172,16 +174,14 @@ public abstract class ScriptingHandler implements KeyListener, PluginRepositoryL textArea.getDocument().addDocumentListener(autoverify); - if (textArea instanceof RSyntaxTextArea) - { + if (textArea instanceof RSyntaxTextArea) { ((RSyntaxTextArea) textArea).setLinkGenerator(this); } - localVariables = new HashMap<String, ScriptVariable>(); + localVariables = new HashMap<>(); - ScriptEngine engine = getEngine(); - if (engine == null) - { + final ScriptEngine engine = getEngine(); + if (engine == null) { return; } engine.setWriter(pw); @@ -189,72 +189,52 @@ public abstract class ScriptingHandler implements KeyListener, PluginRepositoryL } /** - * @param provider - * reference to the provider used by autocomplete. Cannot be - * null. - * @param engineType - * as of now, only "JavaScript" or "Python". - * @param textArea - * reference to the textArea. Cannot be null. - * @param gutter - * reference to the gutter attached to the scrollpane of the - * textArea. + * @param provider reference to the provider used by autocomplete. Cannot be + * null. + * @param engineType as of now, only "JavaScript" or "Python". + * @param textArea reference to the textArea. Cannot be null. + * @param gutter reference to the gutter attached to the scrollpane of the + * textArea. */ - public ScriptingHandler(DefaultCompletionProvider provider, String engineType, JTextComponent textArea, - Gutter gutter) - { + public ScriptingHandler(final DefaultCompletionProvider provider, final String engineType, final JTextComponent textArea, final Gutter gutter) { this(provider, engineType, textArea, gutter, false); } /** - * @param provider - * reference to the provider used by autocomplete. Cannot be null. - * @param engineType - * as of now, only "JavaScript" or "Python". - * @param textArea - * reference to the textArea. Cannot be null. - * @param gutter - * reference to the gutter attached to the scrollpane of the textArea. - * @param forceRun - * force immediate execution + * @param provider reference to the provider used by autocomplete. Cannot be null. + * @param engineType as of now, only "JavaScript" or "Python". + * @param textArea reference to the textArea. Cannot be null. + * @param gutter reference to the gutter attached to the scrollpane of the textArea. + * @param forceRun force immediate execution */ - public ScriptingHandler(DefaultCompletionProvider provider, String engineType, JTextComponent textArea, - Gutter gutter, boolean forceRun) - { + public ScriptingHandler(final DefaultCompletionProvider provider, final String engineType, final JTextComponent textArea, final Gutter gutter, final boolean forceRun) { this(provider, engineType, textArea, gutter, forceRun, null); } - public void setOutput(ConsoleOutput consoleOutput) - { + public void setOutput(final ConsoleOutput consoleOutput) { this.errorOutput = consoleOutput; } /** * Ex: script.py or script.js - * - * @param fileName - * the script filename + * + * @param fileName the script filename */ - public void setFileName(String fileName) - { + public void setFileName(final String fileName) { this.fileName = fileName; } /** * Set the language of the Handler. - * - * @param engineType - * the script engine id (language) + * + * @param engineType the script engine id (language) */ - private void setLanguage(String engineType) - { - try - { + private void setLanguage(final String engineType) { + try { installDefaultLanguageCompletions(engineType); } - catch (ScriptException e) - { + catch (final ScriptException e) { e.printStackTrace(); } } @@ -262,79 +242,65 @@ public abstract class ScriptingHandler implements KeyListener, PluginRepositoryL /** * @return a {@link HashMap} containing local functions */ - public HashMap<String, VariableType> getLocalFunctions() - { + public HashMap<String, VariableType> getLocalFunctions() { return localFunctions; } /** * @return a {@link HashMap} containing local variables */ - public HashMap<String, ScriptVariable> getLocalVariables() - { + public HashMap<String, ScriptVariable> getLocalVariables() { return localVariables; } /** * @return a {@link HashMap} containing block functions */ - public HashMap<Integer, IcyFunctionBlock> getBlockFunctions() - { + public HashMap<Integer, IcyFunctionBlock> getBlockFunctions() { return blockFunctions; } /** * @return a {@link HashMap} containing external variables */ - public HashMap<String, ScriptVariable> getExternalVariables() - { + public HashMap<String, ScriptVariable> getExternalVariables() { return externalVariables; } /** + * @param name variable name * @return the variable type - * @param name - * variable name */ - public VariableType getVariableDeclaration(String name) - { + public VariableType getVariableDeclaration(final String name) { return getVariableDeclaration(name, textArea.getCaretPosition()); } /** + * @param name variable name + * @param offset offset in the script to start looking for the variable * @return variable declaration according to a specific offset - * @param name - * variable name - * @param offset - * offset in the script to start looking for the variable */ - public VariableType getVariableDeclaration(String name, int offset) - { - boolean isArray = name.contains("["); - String originalName = name; - if (isArray) - { - name = name.substring(0, name.indexOf('[')); + public VariableType getVariableDeclaration(final String name, final int offset) { + String paramName = name; + final boolean isArray = paramName.contains("["); + if (isArray) { + paramName = paramName.substring(0, paramName.indexOf('[')); } - ScriptVariable sv = localVariables.get(name); + final ScriptVariable sv = localVariables.get(paramName); if (sv == null) return null; VariableType type = sv.getVariableClassType(offset); Class<?> typeC = null; - if (type == null) - { - ScriptEngineHandler engineHandler = ScriptEngineHandler.getEngineHandler(getEngine()); - type = engineHandler.getEngineVariables().get(name); + if (type == null) { + final ScriptEngineHandler engineHandler = ScriptEngineHandler.getEngineHandler(getEngine()); + type = engineHandler.getEngineVariables().get(paramName); } if (type != null) typeC = type.getClazz(); - if (typeC != null) - { - if (isArray) - { - int occ = originalName.split("\\[").length - 1; - for (int i = 0; i < occ; ++i) - { + if (typeC != null) { + if (isArray) { + final int occ = name.split("\\[").length - 1; + for (int i = 0; i < occ; ++i) { typeC = typeC.getComponentType(); } } @@ -347,151 +313,115 @@ public abstract class ScriptingHandler implements KeyListener, PluginRepositoryL // } // } } - if (type != null) - { - VariableType vt = new VariableType(typeC); + if (type != null) { + final VariableType vt = new VariableType(typeC); vt.setType(type.getType()); return vt; } - return new VariableType((Class<?>) typeC); + return new VariableType(typeC); } /** * Install the language completion - * - * @param language - * the language to install completion for - * @throws ScriptException - * if an error occurred + * + * @param language the language to install completion for + * @throws ScriptException if an error occurred */ - public abstract void installDefaultLanguageCompletions(String language) throws ScriptException; + public abstract void installDefaultLanguageCompletions(final String language) throws ScriptException; /** * Import all functions annotated with the {@link BindingFunction} * annotation. - * - * @throws ScriptException - * if an error occurred + * + * @throws ScriptException if an error occurred */ - public void importFunctions() throws ScriptException - { + public void importFunctions() throws ScriptException { if (!(provider instanceof IcyCompletionProvider)) return; - advanced = false; - if (advanced) - { - ThreadUtil.bgRun(new Runnable() - { - - @SuppressWarnings("deprecation") - @Override - public void run() - { - ProgressFrame frame = new ProgressFrame("Loading functions..."); - ((IcyCompletionProvider) provider).findAllMethods(getEngine(), frame); - frame.setVisible(false); - } - }); - } - else - { - // install functions from ScriptEngineHandler - ScriptEngineHandler handler = ScriptEngineHandler.getEngineHandler(getEngine()); - ArrayList<Method> functions = handler.getFunctions(); - - ((IcyCompletionProvider) provider).installMethods(functions); - installMethods(getEngine(), functions); - } + + // install functions from ScriptEngineHandler + final ScriptEngineHandler handler = ScriptEngineHandler.getEngineHandler(getEngine()); + final ArrayList<Method> functions = handler.getFunctions(); + + ((IcyCompletionProvider) provider).installMethods(functions); + installMethods(getEngine(), functions); } public abstract void installMethods(ScriptEngine engine, ArrayList<Method> functions); /** * Returns if should execute the code or not. - * + * * @return compilation state */ - public boolean isCompilationOk() - { + public boolean isCompilationOk() { return compilationOk; } /** * Sets if should execute the code or not. - * + * * @param compilationOk */ - private void setCompilationOk(boolean compilationOk) - { + private void setCompilationOk(final boolean compilationOk) { this.compilationOk = compilationOk; } /** * @return <code>true</code> if the engine has just be added */ - public boolean isNewEngine() - { + public boolean isNewEngine() { return newEngine; } /** * Set the 'new engine' state - * - * @param newEngine - * engine just added state + * + * @param newEngine engine just added state */ - public void setNewEngine(boolean newEngine) - { + public void setNewEngine(final boolean newEngine) { this.newEngine = newEngine; } /** * @return <code>true</code> if force run is active */ - public boolean isForceRun() - { + public boolean isForceRun() { return forceRun; } /** * Set the 'force run' state - * - * @param forceRun - * 'force run' state + * + * @param forceRun 'force run' state */ - public void setForceRun(boolean forceRun) - { + public void setForceRun(final boolean forceRun) { this.forceRun = forceRun; } /** * @return strict state */ - public boolean isStrict() - { + public boolean isStrict() { return strict; } /** * Set the 'strict' state - * - * @param strict - * 'strict' state + * + * @param strict 'strict' state */ - public void setStrict(boolean strict) - { + public void setStrict(final boolean strict) { this.strict = strict; } /** * Enable the variable interpretation - * - * @param varInterpretation - * variable interpretation state + * + * @param varInterpretation variable interpretation state */ - public void setVarInterpretation(boolean varInterpretation) - { + public void setVarInterpretation(final boolean varInterpretation) { this.varInterpretation = varInterpretation; } @@ -499,44 +429,33 @@ public abstract class ScriptingHandler implements KeyListener, PluginRepositoryL * Interpret the script. If <code>exec</code> is true, will try to run the * code if compile is successful. Be careful: a building code is not * necessary a functional running code. - * - * @param exec - * if true, runs the code after interpretation + * + * @param exec if true, runs the code after interpretation */ - public void interpret(boolean exec) - { + public void interpret(final boolean exec) { // use either selected text if any or all text String s = textArea.getSelectedText(); if (s == null) s = textArea.getText(); // interpret the code - if (exec && forceRun) - { + if (exec && forceRun) { run(); } - else - { + else { interpret(s); if (exec && (isCompilationOk())) run(); } } - protected void updateGutter() - { - ThreadUtil.invokeLater(new Runnable() - { + protected void updateGutter() { + ThreadUtil.invokeLater(() -> { + if (gutter == null || !(textArea instanceof JTextArea)) + return; + gutter.removeAllTrackingIcons(); - @Override - public void run() - { - if (gutter == null || !(textArea instanceof JTextArea)) - return; - gutter.removeAllTrackingIcons(); - - errors.displayOnGutter(gutter); - } + errors.displayOnGutter(gutter); }); } @@ -545,72 +464,61 @@ public abstract class ScriptingHandler implements KeyListener, PluginRepositoryL * user willing to immediately run the code or not). First, the code is * Parsed. If any error occurs, the line containing it will be highlighted * in the gutter. - * - * @param s - * the code to interpret. + * + * @param s the code to interpret. */ - protected void interpret(String s) - { - RTextArea textArea = new RTextArea(); + protected void interpret(final String s) { + final RTextArea textArea = new RTextArea(); textArea.setText(s); - try - { + try { clearScriptVariables(); registerImports(); - if (varInterpretation) - { + if (varInterpretation) { errors.cleanup(); detectVariables(s); } setCompilationOk(true); } - catch (ScriptException e) - { + catch (final ScriptException e) { errors.setRuntimeError(e); } // update the icons for warning/errors now that the script has been interpreted updateGutter(); } - protected void addExternalVariables() - { - for (String s : externalVariables.keySet()) - { - ScriptVariable sv = externalVariables.get(s); - String type = sv.getVariableClassType(0).toString(); - VariableCompletion c = new VariableCompletion(provider, s, type); + protected void addExternalVariables() { + for (final String s : externalVariables.keySet()) { + final ScriptVariable sv = externalVariables.get(s); + final String type = sv.getVariableClassType(0).toString(); + final VariableCompletion c = new VariableCompletion(provider, s, type); c.setRelevance(RELEVANCE_HIGH); variableCompletions.add(c); } localVariables.putAll(externalVariables); } - private synchronized void clearScriptVariables() - { + private synchronized void clearScriptVariables() { localVariables.clear(); localFunctions.clear(); scriptDeclaredImports.clear(); - for (String s : scriptDeclaredImportClasses) - { - try - { - BasicJavaClassCompletion c = new BasicJavaClassCompletion(provider, ClassUtil.findClass(s)); + for (String s : scriptDeclaredImportClasses) { + try { + final BasicJavaClassCompletion c = new BasicJavaClassCompletion(provider, ClassUtil.findClass(s)); s = c.getName(); - List<Completion> list = provider.getCompletionByInputText(s); + final List<Completion> list = provider.getCompletionByInputText(s); if (list == null) continue; - for (Completion c2 : new ArrayList<Completion>(list)) - { - if (c2 instanceof VariableCompletion) - { + for (final Completion c2 : new ArrayList<>(list)) { + if (c2 instanceof VariableCompletion) { if (((VariableCompletion) c2).getName().contentEquals(s)) provider.removeCompletion(c2); } } } - catch (ClassNotFoundException e) - { + catch (final ClassNotFoundException e) { + System.err.println("plugins.tprovoost.scripteditor.scriptinghandlers.ScriptingHandler.clearScriptVariables()"); + IcyExceptionHandler.showErrorMessage(e, false); } } scriptDeclaredImportClasses.clear(); @@ -619,14 +527,11 @@ public abstract class ScriptingHandler implements KeyListener, PluginRepositoryL /** * Execute the script */ - public void run() - { - ScriptEngine engine; - - if (isNewEngine()) - { - if (errorOutput != null) - { + public void run() { + final ScriptEngine engine; + + if (isNewEngine()) { + if (errorOutput != null) { // Graphics2D g = (Graphics2D) errorOutput.getGraphics(); // int chW = g.getFontMetrics().charWidth('_'); // int w = errorOutput.getWidth(); @@ -637,8 +542,7 @@ public abstract class ScriptingHandler implements KeyListener, PluginRepositoryL // errorOutput.append(str + "\n"); // errorOutput.append("New Engine created" + "\n"); // errorOutput.append(str + "\n"); - if (Preferences.getPreferences().isAutoClearOutputEnabled()) - { + if (Preferences.getPreferences().isAutoClearOutputEnabled()) { errorOutput.clear(); } // g.dispose(); @@ -646,8 +550,7 @@ public abstract class ScriptingHandler implements KeyListener, PluginRepositoryL engine = createNewEngine(); } - else - { + else { engine = getEngine(); } @@ -658,40 +561,36 @@ public abstract class ScriptingHandler implements KeyListener, PluginRepositoryL /** * Creates a new engine for the current language. Will delete the previous one. - * + * * @return the new created script engine */ - public ScriptEngine createNewEngine() - { - ScriptEngine oldEngine = getEngine(); + public ScriptEngine createNewEngine() { + final ScriptEngine oldEngine = getEngine(); - if (oldEngine != null) - { + if (oldEngine != null) { // retrieve the methods known to the old engine to transfert them to the new engine - ScriptEngineHandler engineHandler = ScriptEngineHandler.getEngineHandler(oldEngine); - ArrayList<Method> functions = engineHandler.getFunctions(); + final ScriptEngineHandler engineHandler = ScriptEngineHandler.getEngineHandler(oldEngine); + final ArrayList<Method> functions = engineHandler.getFunctions(); // unregister the old engine (will do the housekeeping) ScriptEngineHandler.disposeEngine(oldEngine); // create a new engine - String newEngineType = oldEngine.getName(); - ScriptEngine newEngine = ScriptEngineHandler.getEngine(newEngineType, true); + final String newEngineType = oldEngine.getName(); + final ScriptEngine newEngine = ScriptEngineHandler.getEngine(newEngineType, true); installMethods(newEngine, functions); - try - { + try { installDefaultLanguageCompletions(newEngineType); } - catch (ScriptException e) - { + catch (final ScriptException e) { + IcyExceptionHandler.showErrorMessage(e, true); } newEngine.setWriter(pw); newEngine.setErrorWriter(pw); return newEngine; } - else - { + else { // Failed to retrieve the current engine return null; } @@ -709,40 +608,32 @@ public abstract class ScriptingHandler implements KeyListener, PluginRepositoryL /** * This method will detect the variables and add them to the provider. - * - * @param s - * script content - * @throws ScriptException - * if an error occurred + * + * @param s script content + * @throws ScriptException if an error occurred */ protected abstract void detectVariables(String s) throws ScriptException; @Override - public void keyTyped(KeyEvent e) - { + public void keyTyped(final KeyEvent e) { // System.out.println("coucou"); } @Override - public void keyPressed(KeyEvent e) - { - switch (e.getKeyCode()) - { + public void keyPressed(final KeyEvent e) { + switch (e.getKeyCode()) { case KeyEvent.VK_F: - if (EventUtil.isControlDown(e) && EventUtil.isShiftDown(e)) - { + if (EventUtil.isControlDown(e) && EventUtil.isShiftDown(e)) { format(); } break; case KeyEvent.VK_ENTER: - if (EventUtil.isControlDown(e)) - { + if (EventUtil.isControlDown(e)) { interpret(false); e.consume(); break; } - else if (EventUtil.isShiftDown(e)) - { + else if (EventUtil.isShiftDown(e)) { break; } break; @@ -785,127 +676,96 @@ public abstract class ScriptingHandler implements KeyListener, PluginRepositoryL /** * Organize imports */ - public void organizeImports() - { + public void organizeImports() { organizeImports(textArea); } /** * Organize imports - * - * @param textArea - * component containing script text + * + * @param textArea component containing script text */ public abstract void organizeImports(JTextComponent textArea); @Override - public void keyReleased(KeyEvent e) - { + public void keyReleased(final KeyEvent e) { } /** * Returns the class corresponding to the type, depending on the imports:<br> * Javascript example: - * + * * <pre> * {@code * importPackage(Packages.javax.swing) * importClass(Packages.java.util.Math) * } * </pre> - * + * <p> * If the type asked is JButton, this will return javax.swing.JButton class. * If the type asked is Math, this will return java.util.Math class. - * - * @param type - * class name + * + * @param type class name * @return return the {@link Class} object corresponding to the specified class name */ - public Class<?> resolveClassDeclaration(String type) - { + public Class<?> resolveClassDeclaration(final String type) { // try with declared in the script importClass - for (String s : scriptDeclaredImportClasses) - { + for (final String s : scriptDeclaredImportClasses) { String className = ClassUtil.getSimpleClassName(s); - int idx = className.indexOf('$'); + final int idx = className.indexOf('$'); if (idx != -1) className = className.substring(idx + 1); if (className.contentEquals(type)) - try - { + try { return ClassUtil.findClass(s); } - catch (ClassNotFoundException e) - { - // System.out.println(e.getLocalizedMessage()); - } - catch (NoClassDefFoundError e2) - { + catch (final ClassNotFoundException | NoClassDefFoundError e) { + System.err.println("plugins.tprovoost.scripteditor.scriptinghandlers.ScriptingHandler.resolveClassDeclaration(String type)"); + IcyExceptionHandler.showErrorMessage(e, false); } - int idxDollar = type.indexOf("$"); + final int idxDollar = type.indexOf("$"); if (type.contains(className) && idxDollar != -1) - try - { + try { return ClassUtil.findClass(s + type.substring(idxDollar)); } - catch (ClassNotFoundException e) - { - // System.out.println(e.getLocalizedMessage()); - } - catch (NoClassDefFoundError e2) - { + catch (final ClassNotFoundException | NoClassDefFoundError e) { + IcyExceptionHandler.showErrorMessage(e, true); } } // try with declared in the script importPackage - for (String s : scriptDeclaredImports) - { - try - { + for (final String s : scriptDeclaredImports) { + try { return ClassUtil.findClass(s + "." + type); } - catch (ClassNotFoundException e) - { - } - catch (NoClassDefFoundError e2) - { + catch (final ClassNotFoundException | NoClassDefFoundError e) { + IcyExceptionHandler.showErrorMessage(e, true); } } - if (strict) - { + if (strict) { // declared in engine - ScriptEngineHandler engineHandler = ScriptEngineHandler.getEngineHandler(getEngine()); + final ScriptEngineHandler engineHandler = ScriptEngineHandler.getEngineHandler(getEngine()); // try with declared in the engine importClass - for (String s : engineHandler.getEngineDeclaredImportClasses()) - { + for (final String s : engineHandler.getEngineDeclaredImportClasses()) { if (ClassUtil.getSimpleClassName(s).contentEquals(type)) - try - { + try { return ClassUtil.findClass(s); } - catch (ClassNotFoundException e) - { - } - catch (NoClassDefFoundError e2) - { + catch (final ClassNotFoundException | NoClassDefFoundError e) { + IcyExceptionHandler.showErrorMessage(e, true); } } // try with declared in the script importPackage - for (String s : engineHandler.getEngineDeclaredImports()) - { - try - { + for (final String s : engineHandler.getEngineDeclaredImports()) { + try { return ClassUtil.findClass(s + "." + type); } - catch (ClassNotFoundException e) - { - } - catch (NoClassDefFoundError e2) - { + catch (final ClassNotFoundException | NoClassDefFoundError e) { + IcyExceptionHandler.showErrorMessage(e, true); } } } @@ -920,51 +780,42 @@ public abstract class ScriptingHandler implements KeyListener, PluginRepositoryL /** * @author thomasprovoost */ - private class AutoVerify extends FocusAdapter implements DocumentListener, ActionListener - { - - private Timer timer; + private class AutoVerify extends FocusAdapter implements DocumentListener, ActionListener { + private final Timer timer; private boolean lastChange; - public AutoVerify() - { + public AutoVerify() { timer = new Timer(1000, this); timer.setRepeats(false); } @Override - public void insertUpdate(DocumentEvent e) - { - try - { - Document doc = e.getDocument(); - int offset = e.getOffset(); - int len = e.getLength(); - if (doc.getText(offset, len).contentEquals(".")) - { + public void insertUpdate(final DocumentEvent e) { + try { + final Document doc = e.getDocument(); + final int offset = e.getOffset(); + final int len = e.getLength(); + if (doc.getText(offset, len).contentEquals(".")) { timer.stop(); lastChange = false; - String fullTxt = doc.getText(0, doc.getLength()); + final String fullTxt = doc.getText(0, doc.getLength()); String s = fullTxt.substring(0, offset); s += fullTxt.substring(offset + len, doc.getLength()); interpret(s); } } - catch (BadLocationException e1) - { - e1.printStackTrace(); + catch (final BadLocationException ex) { + ex.printStackTrace(); } } @Override - public void removeUpdate(DocumentEvent e) - { + public void removeUpdate(final DocumentEvent e) { } @Override - public void changedUpdate(DocumentEvent e) - { + public void changedUpdate(final DocumentEvent e) { lastChange = true; // System.out.println("changedUpdate"); if (Preferences.getPreferences().isAutoBuildEnabled()) @@ -972,55 +823,46 @@ public abstract class ScriptingHandler implements KeyListener, PluginRepositoryL } @Override - public void actionPerformed(ActionEvent e) - { + public void actionPerformed(final ActionEvent e) { lastChange = false; interpret(false); } @Override - public void focusLost(FocusEvent e) - { + public void focusLost(final FocusEvent e) { timer.stop(); } @Override - public void focusGained(FocusEvent e) - { + public void focusGained(final FocusEvent e) { if (lastChange) timer.restart(); } } - @SuppressWarnings("unchecked") @Override - public void pluginRepositeryLoaderChanged(PluginDescriptor plugin) - { + public void pluginRepositeryLoaderChanged(final PluginDescriptor plugin) { if (plugin == null) return; - Class<? extends Plugin> clazz; - try - { - clazz = (Class<? extends Plugin>) ClassUtil.findClass(plugin.getPluginClass().toString()); + final Class<? extends Plugin> clazz; + try { + // TODO: 11/04/2023 Check if cast works + //clazz = (Class<? extends Plugin>) ClassUtil.findClass(plugin.getPluginClass().toString()); + clazz = ClassUtil.findClass(plugin.getPluginClass().toString()).asSubclass(Plugin.class); } - catch (ClassNotFoundException e) - { + catch (final ClassNotFoundException e) { return; } - if (!plugin.isInstalled()) - { + if (!plugin.isInstalled()) { // uninstalled the plugin - ScriptEngineHandler engineHandler = ScriptEngineHandler.getEngineHandler(getEngine()); - HashMap<Class<?>, ArrayList<ScriptFunctionCompletion>> engineTypesMethod = engineHandler - .getEngineTypesMethod(); + final ScriptEngineHandler engineHandler = ScriptEngineHandler.getEngineHandler(getEngine()); + final HashMap<Class<?>, ArrayList<ScriptFunctionCompletion>> engineTypesMethod = engineHandler.getEngineTypesMethod(); engineTypesMethod.remove(clazz); } - else - { + else { // plugin installed - if (provider instanceof IcyCompletionProvider) - { + if (provider instanceof IcyCompletionProvider) { // ((IcyCompletionProvider) // provider).findBindingsMethods(engine, clazz); } @@ -1029,126 +871,99 @@ public abstract class ScriptingHandler implements KeyListener, PluginRepositoryL /** * Evaluate (execute) the specified script with the given {@link ScriptEngine} - * - * @param engine - * the {@link ScriptEngine} used to evaluate the script - * @param content - * script content - * @throws ScriptException - * if the script has error(s) + * + * @param engine the {@link ScriptEngine} used to evaluate the script + * @param content script content + * @throws ScriptException if the script has error(s) */ public abstract void evalEngine(ScriptEngine engine, String content) throws ScriptException; /** * @author Thomas Provoost */ - public class EvalThread extends Thread - { + public class EvalThread extends Thread { - private String s; - private ScriptEngine evalEngine; + private final String s; + private final ScriptEngine evalEngine; /** * Create a new script evaluator thread - * - * @param engine - * the {@link ScriptEngine} used to evaluate the script - * @param script - * script content + * + * @param engine the {@link ScriptEngine} used to evaluate the script + * @param script script content */ - public EvalThread(ScriptEngine engine, String script) - { + public EvalThread(final ScriptEngine engine, final String script) { this.evalEngine = engine; this.s = script; } @Override - public void run() - { + public void run() { fireEvaluationStarted(); - if (evalEngine != getEngine()) - { + if (evalEngine != getEngine()) { evalEngine.setWriter(pw); evalEngine.setErrorWriter(pw); } - try - { + try { evalEngine(evalEngine, s); - ScriptEngineHandler engineHandler = ScriptEngineHandler.getEngineHandler(getEngine()); + final ScriptEngineHandler engineHandler = ScriptEngineHandler.getEngineHandler(getEngine()); - for (String key : localVariables.keySet()) + for (final String key : localVariables.keySet()) engineHandler.getEngineVariables().put(key, localVariables.get(key).getVariableLastClassType()); engineHandler.getEngineFunctions().putAll(localFunctions); engineHandler.getEngineDeclaredImportClasses().addAll(scriptDeclaredImportClasses); engineHandler.getEngineDeclaredImports().addAll(scriptDeclaredImports); - BindingsScriptFrame frame = BindingsScriptFrame.getInstance(); + final BindingsScriptFrame frame = BindingsScriptFrame.getInstance(); frame.setEngine(evalEngine); frame.update(); } - catch (ThreadDeath td) - { + catch (final ThreadDeath td) { System.out.println("shutdown"); } - catch (final ScriptException e) - { - ThreadUtil.invokeLater(new Runnable() - { - - @Override - public void run() - { - errors.setRuntimeError(e); - updateGutter(); - } + catch (final ScriptException e) { + ThreadUtil.invokeLater(() -> { + errors.setRuntimeError(e); + updateGutter(); }); } - finally - { + finally { fireEvaluationOver(); thread = null; } } } - @SuppressWarnings("deprecation") /** * Try to interrupt the script execution */ - public void killScript() - { + public void killScript() { // Something is Running ! - if (thread != null) - { - thread.stop(); + if (thread != null) { + thread.interrupt(); thread = null; } } - public void fireEvaluationStarted() - { - for (ScriptListener listener : new ArrayList<ScriptListener>(listeners)) + public void fireEvaluationStarted() { + for (final ScriptListener listener : new ArrayList<>(listeners)) listener.evaluationStarted(); } - public void fireEvaluationOver() - { - for (ScriptListener listener : new ArrayList<ScriptListener>(listeners)) + public void fireEvaluationOver() { + for (final ScriptListener listener : new ArrayList<>(listeners)) listener.evaluationOver(); } - public boolean isRunning() - { + public boolean isRunning() { return thread != null; } - public void addScriptListener(ScriptListener listener) - { + public void addScriptListener(final ScriptListener listener) { listeners.add(listener); } - public void removeScriptListener(ScriptListener listener) - { + public void removeScriptListener(final ScriptListener listener) { listeners.remove(listener); } @@ -1157,37 +972,28 @@ public abstract class ScriptingHandler implements KeyListener, PluginRepositoryL */ public abstract void format(); - public void stopThreads() - { + public void stopThreads() { textArea.getDocument().removeDocumentListener(autoverify); killScript(); } - public static Method resolveMethod(Class<?> clazz, String name, Class<?>[] parameterTypes) - throws SecurityException, NoSuchMethodException - { - try - { + public static Method resolveMethod(final Class<?> clazz, final String name, final Class<?>[] parameterTypes) + throws SecurityException, NoSuchMethodException { + try { return clazz.getMethod(name, parameterTypes); } - catch (SecurityException e) - { - } - catch (NoSuchMethodException e) - { + catch (final SecurityException | NoSuchMethodException e) { + IcyExceptionHandler.showErrorMessage(e, true); } - L1: for (Method m : clazz.getMethods()) - { - Class<?>[] types = m.getParameterTypes(); - if (m.getName().contentEquals(name) && types.length == parameterTypes.length) - { + L1: + for (final Method m : clazz.getMethods()) { + final Class<?>[] types = m.getParameterTypes(); + if (m.getName().contentEquals(name) && types.length == parameterTypes.length) { // check types super etc - for (int i = 0; i < types.length; ++i) - { + for (int i = 0; i < types.length; ++i) { // if (types[i] == null || parameterTypes[i] == null || // !types[i].isAssignableFrom(parameterTypes[i])) - if (types[i] != null && parameterTypes[i] != null && !(parameterTypes[i].isAssignableFrom(types[i]) - || types[i].isAssignableFrom(parameterTypes[i]))) + if (types[i] != null && parameterTypes[i] != null && !(parameterTypes[i].isAssignableFrom(types[i]) || types[i].isAssignableFrom(parameterTypes[i]))) continue L1; } return m; @@ -1196,8 +1002,7 @@ public abstract class ScriptingHandler implements KeyListener, PluginRepositoryL return clazz.getMethod(name, parameterTypes); } - public void autoImport() - { + public void autoImport() { // default : do nothing } diff --git a/src/main/java/plugins/tprovoost/scripteditor/scriptinghandlers/VariableType.java b/src/main/java/plugins/tprovoost/scripteditor/scriptinghandlers/VariableType.java index 6ddae0e0d69487f147edc686361cb6be773ee5d8..58f78447eccb93686021fbb29c4a9f3460d97a88 100644 --- a/src/main/java/plugins/tprovoost/scripteditor/scriptinghandlers/VariableType.java +++ b/src/main/java/plugins/tprovoost/scripteditor/scriptinghandlers/VariableType.java @@ -8,81 +8,70 @@ import plugins.tprovoost.scripteditor.completion.IcyCompletionProvider; /** * Object containing the Class needed and if necessary the Type associated. Can * be extremely useful when the class is an Array. - * + * * @author Thomas Provoost */ -public class VariableType -{ - private Class<?> cType; - - // many places use getType().isEmpty(), which would give a NullPointerException - // if type is not initialized - private String type = ""; - - public VariableType(Class<?> cType) - { - this.cType = cType; - } - - public VariableType(Class<?> cType, String type) - { - this.cType = cType; - this.type = type; - } - - public Class<?> getClazz() - { - return cType; - } - - public void setClassType(Class<?> cType) - { - this.cType = cType; - } - - public String getType() - { - return type; - } - - public void setType(String type) - { - this.type = type; - } - - public String[] getTypeParameters() - { - String typeParams = type.toString(); - int idxB = typeParams.indexOf('<'); - int idxE = typeParams.indexOf('>'); - - typeParams.substring(idxB + 1, idxE); - return typeParams.split(","); - } - - @Override - public String toString() - { - String typeS = (type == null || type.contentEquals("")) ? "" : " of " + type; - if (cType == null) - return ""; - return IcyCompletionProvider.getType(cType, true) + typeS; - } - - public static boolean isGeneric(Class<?> clazz) - { - return clazz.getTypeParameters().length != 0; - } - - public static String getType(String s) - { - Pattern p = Pattern.compile("(\\w|_|\\.)*\\s*<(.*)>"); - Matcher m = p.matcher(s); - if (m.matches()) - { - return m.group(2); - } - return ""; - } +public class VariableType { + private Class<?> cType; + + // many places use getType().isEmpty(), which would give a NullPointerException + // if type is not initialized + private String type = ""; + + public VariableType(final Class<?> cType) { + this.cType = cType; + } + + public VariableType(final Class<?> cType, final String type) { + this.cType = cType; + this.type = type; + } + + public Class<?> getClazz() { + return cType; + } + + public void setClassType(final Class<?> cType) { + this.cType = cType; + } + + public String getType() { + return type; + } + + public void setType(final String type) { + this.type = type; + } + + public String[] getTypeParameters() { + final String typeParams = type; + final int idxB = typeParams.indexOf('<'); + final int idxE = typeParams.indexOf('>'); + + // TODO: 11/04/2023 Check, unused substring return value + typeParams.substring(idxB + 1, idxE); + return typeParams.split(","); + } + + @Override + public String toString() { + final String typeS = (type == null || type.contentEquals("")) ? "" : " of " + type; + if (cType == null) + return ""; + return IcyCompletionProvider.getType(cType, true) + typeS; + } + + public static boolean isGeneric(final Class<?> clazz) { + return clazz.getTypeParameters().length != 0; + } + + public static String getType(final String s) { + final Pattern p = Pattern.compile("(\\w|_|\\.)*\\s*<(.*)>"); + final Matcher m = p.matcher(s); + if (m.matches()) { + return m.group(2); + } + return ""; + } } diff --git a/src/main/java/plugins/tprovoost/scripteditor/scriptinghandlers/js/JSScriptEngine.java b/src/main/java/plugins/tprovoost/scripteditor/scriptinghandlers/js/JSScriptEngine.java index bb4d38cbbbbcbbf62bb576bfdd8815b6d3d181b3..6c1f0e117e99a0400c00a72b602fc1dbbae504cc 100644 --- a/src/main/java/plugins/tprovoost/scripteditor/scriptinghandlers/js/JSScriptEngine.java +++ b/src/main/java/plugins/tprovoost/scripteditor/scriptinghandlers/js/JSScriptEngine.java @@ -5,9 +5,9 @@ import icy.plugin.PluginLoader; import java.io.BufferedInputStream; import java.io.File; -import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; +import java.nio.file.Files; import java.util.HashMap; import javax.script.ScriptException; @@ -21,216 +21,182 @@ import org.mozilla.javascript.ScriptableObject; import plugins.tprovoost.scripteditor.scriptinghandlers.ScriptEngine; -public class JSScriptEngine extends ScriptEngine -{ - - public ScriptableObject scriptable; - public String lastFileName = ""; - - // used to tell Rhino that it should count the lines starting from 1, - // as in the GUI - private static int LINE_NUMBER_START = 1; - - public JSScriptEngine() - { - Context context = Context.enter(); - context.setApplicationClassLoader(PluginLoader.getLoader()); - scriptable = new IcyImporterTopLevel(context); - Context.exit(); - } - - @Override - public void eval(String s) throws ScriptException - { - // uses Context from Rhino integrated in JRE or impossibility - // to use already defined methods in ScriptEngine, such as println or - // getImage - Context context = Context.enter(); - context.setApplicationClassLoader(PluginLoader.getLoader()); - // context.setErrorReporter(errorReporter); - try - { - // ScriptableObject scriptable = new ImporterTopLevel(context); - // Bindings bs = engine.getBindings(ScriptContext.ENGINE_SCOPE); - // for (String key : bs.keySet()) - // { - // Object o = bs.get(key); - // scriptable.put(key, scriptable, o); - // } - Script script = context.compileString(s, "script", LINE_NUMBER_START, null); - script.exec(context, scriptable); - // for (Object o : scriptable.getIds()) - // { - // String key = (String) o; - // bs.put(key, scriptable.get(key, scriptable)); - // } - } catch (RhinoException e3) - { - getErrorWriter().write(e3.getMessage()); - throw (ScriptException) new ScriptException(e3.getMessage(), e3.sourceName(), e3.lineNumber(), e3.columnNumber()).initCause(e3); - } finally - { - bindings.clear(); - for (Object o : scriptable.getIds()) - { - bindings.put((String) o, scriptable.get(o)); - } - Context.exit(); - } - } - - public void evalFile(String fileName) throws ScriptException - { - this.lastFileName = fileName; - File f = new File(fileName); - if (!f.exists()) - { - throw new ScriptException("The script file could not be found, please check if it is correctly saved on the disk.", fileName, -1); - } - - byte[] bytes = null; - try - { - BufferedInputStream bis = new BufferedInputStream(new FileInputStream(f)); - bytes = new byte[bis.available()]; - bis.read(bytes); - bis.close(); - } catch (IOException e1) - { - throw new ScriptException(e1.getMessage(), fileName, -1); - } - String s = new String(bytes); - - Context context = Context.enter(); - context.setApplicationClassLoader(PluginLoader.getLoader()); - // context.setErrorReporter(errorReporter); - try - { - Script script = context.compileString(s, "script", LINE_NUMBER_START, null); - script.exec(context, scriptable); - } catch (RhinoException e3) - { - getErrorWriter().write(e3.getMessage()); - throw (ScriptException) new ScriptException(e3.getMessage(), e3.sourceName(), e3.lineNumber(), e3.columnNumber()).initCause(e3); - } finally - { - bindings.clear(); - for (Object o : scriptable.getIds()) - { - bindings.put((String) o, scriptable.get(o)); - } - lastFileName = ""; - Context.exit(); - } - } - - class IcyImporterTopLevel extends ImporterTopLevel - { - - /** - * - */ - private static final long serialVersionUID = 1L; - - public IcyImporterTopLevel(Context context) - { - super(context); - String[] names = { "println", "print", "eval" }; - defineFunctionProperties(names, IcyImporterTopLevel.class, ScriptableObject.DONTENUM); - } - - public void println(Object o) - { - getWriter().write(Context.toString(o) + "\n"); - } - - public void print(Object o) - { - getWriter().write(Context.toString(o)); - } - - public void eval(Object o) throws ScriptException, FileNotFoundException - { - File f; - if (o instanceof NativeJavaObject && ((NativeJavaObject) o).unwrap() instanceof File) - f = (File) ((NativeJavaObject) o).unwrap(); - else if (o instanceof String) - { - String s = (String) o; - f = new File(s); - if (!f.exists() && !s.contains(File.separator)) - { - if (!s.endsWith(".js")) - s += ".js"; - s = FileUtil.getDirectory(lastFileName) + File.separator + s; - f = new File(s); - } - } else - { - // getErrorWriter().write("Argument must be a file of a string."); - throw new FileNotFoundException("Argument must be a file of a string."); - } - BufferedInputStream bis = new BufferedInputStream(new FileInputStream(f)); - byte[] bytes = null; - try - { - bytes = new byte[bis.available()]; - bis.read(bytes); - bis.close(); - } catch (IOException e1) - { - // getErrorWriter().write(e1.getMessage()); - } - String s = new String(bytes); - Context context = Context.enter(); - context.setApplicationClassLoader(PluginLoader.getLoader()); - try - { - Script script = context.compileString(s, "script", LINE_NUMBER_START, null); - script.exec(context, scriptable); - } catch (RhinoException e3) - { - // getErrorWriter().write(e3.getMessage()); - throw (ScriptException) new ScriptException(e3.getMessage(), e3.sourceName(), e3.lineNumber(), e3.columnNumber()).initCause(e3); - } finally - { - Context.exit(); - } - } - } - - @Override - public String getName() - { - return "javascript"; - } - - @Override - public void clear() - { - HashMap<String, Object> bindings = getBindings(); - for (String s : bindings.keySet()) - { - bindings.put(s, null); - scriptable.delete(s); - } - } - - @Override - public HashMap<String, Object> getBindings() - { - return bindings; - } - - @Override - protected void putInRealEngine(String name, Object value) - { - scriptable.put(name, scriptable, value); - } - - @Override - protected void removeFromRealEngine(String name) - { - scriptable.delete(name); - } +public class JSScriptEngine extends ScriptEngine { + + public ScriptableObject scriptable; + public String lastFileName = ""; + + // used to tell Rhino that it should count the lines starting from 1, + // as in the GUI + private static final int LINE_NUMBER_START = 1; + + public JSScriptEngine() { + final Context context = Context.enter(); + context.setApplicationClassLoader(PluginLoader.getLoader()); + scriptable = new IcyImporterTopLevel(context); + Context.exit(); + } + + @Override + public void eval(final String s) throws ScriptException { + // uses Context from Rhino integrated in JRE or impossibility + // to use already defined methods in ScriptEngine, such as println or + // getImage + final Context context = Context.enter(); + context.setApplicationClassLoader(PluginLoader.getLoader()); + // context.setErrorReporter(errorReporter); + try { + // ScriptableObject scriptable = new ImporterTopLevel(context); + // Bindings bs = engine.getBindings(ScriptContext.ENGINE_SCOPE); + // for (String key : bs.keySet()) + // { + // Object o = bs.get(key); + // scriptable.put(key, scriptable, o); + // } + final Script script = context.compileString(s, "script", LINE_NUMBER_START, null); + script.exec(context, scriptable); + // for (Object o : scriptable.getIds()) + // { + // String key = (String) o; + // bs.put(key, scriptable.get(key, scriptable)); + // } + } + catch (final RhinoException e) { + getErrorWriter().write(e.getMessage()); + throw (ScriptException) new ScriptException(e.getMessage(), e.sourceName(), e.lineNumber(), e.columnNumber()).initCause(e); + } + finally { + bindings.clear(); + for (final Object o : scriptable.getIds()) { + bindings.put((String) o, scriptable.get(o)); + } + Context.exit(); + } + } + + @Override + public void evalFile(final String fileName) throws ScriptException { + this.lastFileName = fileName; + final File f = new File(fileName); + if (!f.exists()) { + throw new ScriptException("The script file could not be found, please check if it is correctly saved on the disk.", fileName, -1); + } + + final byte[] bytes; + try { + final BufferedInputStream bis = new BufferedInputStream(Files.newInputStream(f.toPath())); + bytes = new byte[bis.available()]; + bis.read(bytes); + bis.close(); + } + catch (final IOException e) { + throw new ScriptException(e.getMessage(), fileName, -1); + } + final String s = new String(bytes); + + final Context context = Context.enter(); + context.setApplicationClassLoader(PluginLoader.getLoader()); + // context.setErrorReporter(errorReporter); + try { + final Script script = context.compileString(s, "script", LINE_NUMBER_START, null); + script.exec(context, scriptable); + } + catch (final RhinoException e) { + getErrorWriter().write(e.getMessage()); + throw (ScriptException) new ScriptException(e.getMessage(), e.sourceName(), e.lineNumber(), e.columnNumber()).initCause(e); + } + finally { + bindings.clear(); + for (final Object o : scriptable.getIds()) { + bindings.put((String) o, scriptable.get(o)); + } + lastFileName = ""; + Context.exit(); + } + } + + class IcyImporterTopLevel extends ImporterTopLevel { + public IcyImporterTopLevel(final Context context) { + super(context); + final String[] names = {"println", "print", "eval"}; + defineFunctionProperties(names, IcyImporterTopLevel.class, ScriptableObject.DONTENUM); + } + + public void println(final Object o) { + getWriter().write(Context.toString(o) + "\n"); + } + + public void print(final Object o) { + getWriter().write(Context.toString(o)); + } + + public void eval(final Object o) throws ScriptException, FileNotFoundException { + File f; + if (o instanceof NativeJavaObject && ((NativeJavaObject) o).unwrap() instanceof File) + f = (File) ((NativeJavaObject) o).unwrap(); + else if (o instanceof String) { + String s = (String) o; + f = new File(s); + if (!f.exists() && !s.contains(File.separator)) { + if (!s.endsWith(".js")) + s += ".js"; + s = FileUtil.getDirectory(lastFileName) + File.separator + s; + f = new File(s); + } + } + else { + // getErrorWriter().write("Argument must be a file of a string."); + throw new FileNotFoundException("Argument must be a file of a string."); + } + final byte[] bytes; + try { + final BufferedInputStream bis = new BufferedInputStream(Files.newInputStream(f.toPath())); + bytes = new byte[bis.available()]; + bis.read(bytes); + bis.close(); + } + catch (final IOException e) { + throw new ScriptException(e.getMessage(), f.getName(), -1); + // getErrorWriter().write(e.getMessage()); + } + final String s = new String(bytes); + final Context context = Context.enter(); + context.setApplicationClassLoader(PluginLoader.getLoader()); + try { + final Script script = context.compileString(s, "script", LINE_NUMBER_START, null); + script.exec(context, scriptable); + } + catch (final RhinoException e) { + // getErrorWriter().write(e3.getMessage()); + throw (ScriptException) new ScriptException(e.getMessage(), e.sourceName(), e.lineNumber(), e.columnNumber()).initCause(e); + } + finally { + Context.exit(); + } + } + } + + @Override + public String getName() { + return "javascript"; + } + + @Override + public void clear() { + final HashMap<String, Object> bindings = getBindings(); + for (final String s : bindings.keySet()) { + bindings.put(s, null); + scriptable.delete(s); + } + } + + @Override + protected void putInRealEngine(final String name, final Object value) { + scriptable.put(name, scriptable, value); + } + + @Override + protected void removeFromRealEngine(final String name) { + scriptable.delete(name); + } } \ No newline at end of file diff --git a/src/main/java/plugins/tprovoost/scripteditor/scriptinghandlers/js/JSScriptingHandlerRhino.java b/src/main/java/plugins/tprovoost/scripteditor/scriptinghandlers/js/JSScriptingHandlerRhino.java index 4f47edf36456f79542a6e272bf251becaf793bd2..6b725312e6d5da07a21c371ecfad573d47dd49eb 100644 --- a/src/main/java/plugins/tprovoost/scripteditor/scriptinghandlers/js/JSScriptingHandlerRhino.java +++ b/src/main/java/plugins/tprovoost/scripteditor/scriptinghandlers/js/JSScriptingHandlerRhino.java @@ -25,6 +25,7 @@ import javax.swing.text.BadLocationException; import javax.swing.text.Caret; import javax.swing.text.JTextComponent; +import icy.system.IcyExceptionHandler; import org.fife.ui.autocomplete.BasicCompletion; import org.fife.ui.autocomplete.Completion; import org.fife.ui.autocomplete.DefaultCompletionProvider; @@ -88,42 +89,35 @@ import plugins.tprovoost.scripteditor.scriptinghandlers.ScriptVariable; import plugins.tprovoost.scripteditor.scriptinghandlers.ScriptingHandler; import plugins.tprovoost.scripteditor.scriptinghandlers.VariableType; -public class JSScriptingHandlerRhino extends ScriptingHandler -{ +public class JSScriptingHandlerRhino extends ScriptingHandler { private String currentText; // used to tell Rhino that it should count the lines starting from 1, // as in the GUI - private static int LINE_NUMBER_START = 1; + private static final int LINE_NUMBER_START = 1; /** * Registers all the warnings and errors that have been found by Rhino when * parsing */ - class Reporter implements ErrorReporter - { + class Reporter implements ErrorReporter { @Override - public void warning(String message, String sourceName, int line, String lineSource, int lineOffset) - { - ScriptException se = new ScriptException(message, sourceName, line, lineOffset); + public void warning(final String message, final String sourceName, final int line, final String lineSource, final int lineOffset) { + final ScriptException se = new ScriptException(message, sourceName, line, lineOffset); errors.addWarning(se); } @Override - public void error(String message, String sourceName, int line, String lineSource, int lineOffset) - { - ScriptException se = new ScriptException(message, sourceName, line, lineOffset); + public void error(final String message, final String sourceName, final int line, final String lineSource, final int lineOffset) { + final ScriptException se = new ScriptException(message, sourceName, line, lineOffset); errors.addError(se); } @Override - public EvaluatorException runtimeError(String message, String sourceName, int line, String lineSource, - int lineOffset) - { - System.out.println( - "runtimeError " + message + " " + sourceName + " " + line + " " + lineSource + " " + lineOffset); - ScriptException se = new ScriptException(message, sourceName, line, lineOffset); + public EvaluatorException runtimeError(final String message, final String sourceName, final int line, final String lineSource, final int lineOffset) { + System.out.println("runtimeError " + message + " " + sourceName + " " + line + " " + lineSource + " " + lineOffset); + final ScriptException se = new ScriptException(message, sourceName, line, lineOffset); errors.addError(se); return null; } @@ -139,28 +133,22 @@ public class JSScriptingHandlerRhino extends ScriptingHandler * Contains all functions created in * {@link #resolveCallType(AstNode, String, boolean)}. */ - private LinkedList<IcyFunctionBlock> functionBlocksToResolve = new LinkedList<IcyFunctionBlock>(); + private final LinkedList<IcyFunctionBlock> functionBlocksToResolve = new LinkedList<>(); /** * Create a new JavaScript scripting handler using specified parameters - * - * @param provider - * completion provider - * @param textArea - * {@link TextArea} component - * @param gutter - * gutter - * @param autocompilation - * auto compilation process + * + * @param provider completion provider + * @param textArea {@link TextArea} component + * @param gutter gutter + * @param autocompilation auto compilation process */ - public JSScriptingHandlerRhino(DefaultCompletionProvider provider, JTextComponent textArea, Gutter gutter, - boolean autocompilation) - { + public JSScriptingHandlerRhino(final DefaultCompletionProvider provider, final JTextComponent textArea, final Gutter gutter, final boolean autocompilation) { super(provider, "javascript", textArea, gutter, autocompilation); } - public void evalEngine(ScriptEngine engine, String s) throws ScriptException - { + @Override + public void evalEngine(final ScriptEngine engine, final String s) throws ScriptException { if (fileName == null || fileName.isEmpty() || fileName.contentEquals("Untitled")) engine.eval(s); else @@ -168,102 +156,90 @@ public class JSScriptingHandlerRhino extends ScriptingHandler } @Override - public void installDefaultLanguageCompletions(String language) - { - ScriptEngine engine = getEngine(); - if (engine == null) - { + public void installDefaultLanguageCompletions(final String language) { + final ScriptEngine engine = getEngine(); + if (engine == null) { if (DEBUG) System.out.println("Engine is null."); return; } - ScriptEngineHandler engineHandler = ScriptEngineHandler.getEngineHandler(getEngine()); - HashMap<String, VariableType> engineFunctions = engineHandler.getEngineFunctions(); - HashMap<String, VariableType> engineVariables = engineHandler.getEngineVariables(); + final ScriptEngineHandler engineHandler = ScriptEngineHandler.getEngineHandler(getEngine()); + final HashMap<String, VariableType> engineFunctions = engineHandler.getEngineFunctions(); + final HashMap<String, VariableType> engineVariables = engineHandler.getEngineVariables(); // IMPORT PACKAGES - try - { + try { importJavaScriptPackages(getEngine()); } - catch (ScriptException e1) - { + catch (final ScriptException e) { + IcyExceptionHandler.showErrorMessage(e, true); } // ArrayList<Parameter> params = new ArrayList<Parameter>(); // HARDCODED ITEMS, TO BE REMOVED OR ADDED IN AN XML - String mainInterface = MainInterface.class.getName(); - try - { + final String mainInterface = MainInterface.class.getName(); + try { engine.eval( "function getSequence() { return Packages.icy.main.Icy.getMainInterface().getFocusedSequence() }"); - if (provider != null) - { - FunctionCompletion c = new FunctionCompletion(provider, "getSequence", Sequence.class.getName()); + if (provider != null) { + final FunctionCompletion c = new FunctionCompletion(provider, "getSequence", Sequence.class.getName()); c.setDefinedIn(mainInterface); c.setReturnValueDescription("The focused sequence is returned."); c.setShortDescription("Returns the sequence under focus. Returns null if no sequence opened."); // check if does not exist already // if not, add it to provider - List<Completion> list = provider.getCompletionByInputText("gui"); + final List<Completion> list = provider.getCompletionByInputText("gui"); if (list == null || !IcyCompletionProvider.exists(c, list)) provider.addCompletion(c); } engineFunctions.put("getSequence", new VariableType(Sequence.class)); } - catch (ScriptException e) - { - System.out.println(e.getMessage()); + catch (final ScriptException e) { + IcyExceptionHandler.showErrorMessage(e, true); } - try - { + try { engine.eval("function getImage() { return Packages.icy.main.Icy.getMainInterface().getFocusedImage(); }"); - if (provider != null) - { - FunctionCompletion c = new FunctionCompletion(provider, "getImage", IcyBufferedImage.class.getName()); + if (provider != null) { + final FunctionCompletion c = new FunctionCompletion(provider, "getImage", IcyBufferedImage.class.getName()); c.setDefinedIn(mainInterface); c.setShortDescription("Returns the current image viewed in the focused sequence."); c.setReturnValueDescription("Returns the focused Image, returns null if no sequence opened"); // check if does not exist already // if not, add it to provider - List<Completion> list = provider.getCompletionByInputText("gui"); + final List<Completion> list = provider.getCompletionByInputText("gui"); if (list == null || !IcyCompletionProvider.exists(c, list)) provider.addCompletion(c); } engineFunctions.put("getImage", new VariableType(IcyBufferedImage.class)); } - catch (ScriptException e) - { - System.out.println(e.getMessage()); + catch (final ScriptException e) { + IcyExceptionHandler.showErrorMessage(e, true); } - try - { + try { engine.eval("gui = Packages.icy.main.Icy.getMainInterface()"); - if (provider != null) - { - VariableCompletion vc = new VariableCompletion(provider, "gui", mainInterface); + if (provider != null) { + final VariableCompletion vc = new VariableCompletion(provider, "gui", mainInterface); vc.setDefinedIn(mainInterface); vc.setShortDescription("Returns the sequence under focus. Returns null if no sequence opened."); // check if does not exist already // if not, add it to provider - List<Completion> list = provider.getCompletionByInputText("gui"); + final List<Completion> list = provider.getCompletionByInputText("gui"); if (list == null || !IcyCompletionProvider.exists(vc, list)) provider.addCompletion(vc); } engineVariables.put("gui", new VariableType(MainInterface.class)); } - catch (ScriptException e) - { - System.out.println(e.getMessage()); + catch (final ScriptException e) { + IcyExceptionHandler.showErrorMessage(e, true); } // ADD JS FUNCTIONS @@ -272,162 +248,139 @@ public class JSScriptingHandlerRhino extends ScriptingHandler engineFunctions.put("eval", new VariableType(void.class)); // IMPORT PLUGINS FUNCTIONS - try - { + try { importFunctions(); } - catch (ScriptException e) - { + catch (final ScriptException e) { e.printStackTrace(); } } - private void importJavaScriptPackages(ScriptEngine engine) throws ScriptException - { + private void importJavaScriptPackages(final ScriptEngine engine) throws ScriptException { // } @Override - public void installMethods(ScriptEngine engine, ArrayList<Method> methods) - { + public void installMethods(final ScriptEngine engine, final ArrayList<Method> methods) { // hardcoded functions, to remove in the future - try - { + try { engine.eval( "function getSequence() { return Packages.icy.main.Icy.getMainInterface().getFocusedSequence() }"); } - catch (ScriptException e1) - { + catch (final ScriptException e) { + IcyExceptionHandler.showErrorMessage(e, true); } - try - { + try { engine.eval("function getImage() { return Packages.icy.main.Icy.getMainInterface().getFocusedImage(); }"); } - catch (ScriptException e1) - { + catch (final ScriptException e) { + IcyExceptionHandler.showErrorMessage(e, true); } - try - { + try { engine.eval("gui = Packages.icy.main.Icy.getMainInterface()"); } - catch (ScriptException e1) - { + catch (final ScriptException e) { + IcyExceptionHandler.showErrorMessage(e, true); } - for (Method method : methods) - { + for (final Method method : methods) { // is it an annotated with BindingFunction? - BindingFunction blockFunction = method.getAnnotation(BindingFunction.class); + final BindingFunction blockFunction = method.getAnnotation(BindingFunction.class); if (blockFunction == null) continue; // Generate the function for the provider - ArrayList<Parameter> fParams = new ArrayList<Parameter>(); - Class<?>[] paramTypes = method.getParameterTypes(); + final ArrayList<Parameter> fParams = new ArrayList<>(); + final Class<?>[] paramTypes = method.getParameterTypes(); // get the parameters - String params = ""; - String functionName = blockFunction.value(); + StringBuilder params = new StringBuilder(); + final String functionName = blockFunction.value(); // get the parameters - for (int i = 0; i < paramTypes.length; ++i) - { + for (int i = 0; i < paramTypes.length; ++i) { fParams.add(new Parameter(IcyCompletionProvider.getType(paramTypes[i], true), "arg" + i)); - params += ",arg" + i; + params.append(",arg").append(i); } if (params.length() > 0) - params = params.substring(1); + params = new StringBuilder(params.substring(1)); // the object for the provider - ScriptFunctionCompletion sfc; + final ScriptFunctionCompletion sfc; if (Modifier.isStatic(method.getModifiers())) sfc = new ScriptFunctionCompletion(null, functionName, method); else sfc = new ScriptFunctionCompletion(null, method.getName(), method); - try - { + try { // FIXME? // if (engine instanceof RhinoScriptEngine) // { - if (method.getReturnType() == void.class) - { + if (method.getReturnType() == void.class) { engine.eval("function " + functionName + " (" + params + ") {\n\t" + sfc.getMethodCall() + "\n}"); } - else - { - engine.eval("function " + functionName + " (" + params + ") {\n\treturn " + sfc.getMethodCall() - + "\n}"); + else { + engine.eval("function " + functionName + " (" + params + ") {\n\treturn " + sfc.getMethodCall() + "\n}"); } // } } - catch (ScriptException e) - { - e.printStackTrace(); + catch (final ScriptException e) { + IcyExceptionHandler.showErrorMessage(e, true); } } } @Override - public void registerImports() - { - String s = textArea.getText(); - Pattern patternClasses = Pattern.compile("importClass\\(\\s*(Packages\\.|)((\\w|\\.|\\$)+)\\s*\\)"); + public void registerImports() { + final String s = textArea.getText(); + final Pattern patternClasses = Pattern.compile("importClass\\(\\s*(Packages\\.|)((\\w|\\.|\\$)+)\\s*\\)"); Matcher m = patternClasses.matcher(s); int offset = 0; - while (m.find(offset)) - { - String foundString = m.group(0); - String imported = m.group(2); + while (m.find(offset)) { + final String foundString = m.group(0); + final String imported = m.group(2); scriptDeclaredImportClasses.add(imported); - PluginDescriptor plugindesc = PluginRepositoryLoader.getPlugin(imported); - if (plugindesc != null) - { + final PluginDescriptor plugindesc = PluginRepositoryLoader.getPlugin(imported); + if (plugindesc != null) { // method is in the exact plugin if (!plugindesc.isInstalled()) PluginInstaller.install(plugindesc, false); } - else - { + else { // class around plugin - for (PluginDescriptor pd : PluginRepositoryLoader.getPlugins()) - { + for (final PluginDescriptor pd : PluginRepositoryLoader.getPlugins()) { if (pd.getClassName().startsWith(imported) && !pd.isInstalled()) PluginInstaller.install(pd, false); } } - try - { - if (provider != null && (provider.getCompletionByInputText(imported)) == null) - { + try { + if (provider != null && (provider.getCompletionByInputText(imported)) == null) { provider.addCompletion(new BasicJavaClassCompletion(provider, ClassUtil.findClass(imported))); } } - catch (ClassNotFoundException e) - { + catch (final ClassNotFoundException e) { + IcyExceptionHandler.showErrorMessage(e, true); } - int idxString = s.indexOf(foundString, offset); + final int idxString = s.indexOf(foundString, offset); if (idxString == -1) break; offset = idxString + foundString.length(); } - Pattern patternPackages = Pattern.compile("importPackage\\((Packages\\.|)((\\w|\\.)+)\\)"); + final Pattern patternPackages = Pattern.compile("importPackage\\((Packages\\.|)((\\w|\\.)+)\\)"); m = patternPackages.matcher(s); offset = 0; - while (m.find(offset)) - { - String foundString = m.group(0); - String imported = m.group(2); + while (m.find(offset)) { + final String foundString = m.group(0); + final String imported = m.group(2); scriptDeclaredImports.add(imported); - for (PluginDescriptor pd : PluginRepositoryLoader.getPlugins()) - { + for (final PluginDescriptor pd : PluginRepositoryLoader.getPlugins()) { if (pd.getClassName().startsWith(imported) && !pd.isInstalled()) PluginInstaller.install(pd, false); } - int idxString = s.indexOf(foundString, offset); + final int idxString = s.indexOf(foundString, offset); if (idxString == -1) break; offset = idxString + foundString.length(); @@ -435,81 +388,71 @@ public class JSScriptingHandlerRhino extends ScriptingHandler } @Override - public void organizeImports(JTextComponent tc) - { + public void organizeImports(final JTextComponent tc) { organizeImportsStatic(tc); } /** * Static because of the call in the autocomplete. FIXME - * + * * @param tc */ - private static void organizeImportsStatic(JTextComponent tc) - { - ArrayList<String> listImportsClass = new ArrayList<String>(); - ArrayList<String> listImportsPackages = new ArrayList<String>(); + private static void organizeImportsStatic(final JTextComponent tc) { + final ArrayList<String> listImportsClass = new ArrayList<>(); + final ArrayList<String> listImportsPackages = new ArrayList<>(); boolean errorHappened = false; - String originalText = tc.getText(); - String text = ""; - while ((text = tc.getText()).contains("importClass(") && !errorHappened) - { - int idxStart = text.indexOf("importClass("); + final String originalText = tc.getText(); + String text; + while ((text = tc.getText()).contains("importClass(") && !errorHappened) { + final int idxStart = text.indexOf("importClass("); if (idxStart == -1) // should never happen because of the contains continue; - int idxStop = text.indexOf(')', idxStart); - if (idxStop == -1) - { // something weird happened in the code, stop. + final int idxStop = text.indexOf(')', idxStart); + if (idxStop == -1) { // something weird happened in the code, stop. errorHappened = true; break; } - Caret c = tc.getCaret(); + final Caret c = tc.getCaret(); c.setDot(idxStart); c.moveDot(idxStop + 1); listImportsClass.add(tc.getSelectedText()); tc.replaceSelection(""); } - while ((text = tc.getText()).contains("importPackage(") && !errorHappened) - { - int idxStart = text.indexOf("importPackage("); + while ((text = tc.getText()).contains("importPackage(") && !errorHappened) { + final int idxStart = text.indexOf("importPackage("); if (idxStart == -1) // should never happen because of the contains continue; - int idxStop = text.indexOf(')', idxStart); - if (idxStop == -1) - { // something weird happened in the code, stop. + final int idxStop = text.indexOf(')', idxStart); + if (idxStop == -1) { // something weird happened in the code, stop. errorHappened = true; break; } - Caret c = tc.getCaret(); + final Caret c = tc.getCaret(); c.setDot(idxStart); c.moveDot(idxStop + 1); listImportsPackages.add(tc.getSelectedText()); tc.replaceSelection(""); } - if (errorHappened) - { + if (errorHappened) { tc.setText(originalText); } - else - { - String result = ""; + else { + final StringBuilder result = new StringBuilder(); Collections.sort(listImportsClass); Collections.sort(listImportsPackages); - for (int i = 0; i < listImportsClass.size(); ++i) - { + for (int i = 0; i < listImportsClass.size(); ++i) { if (i == 0) - result += listImportsClass.get(i); + result.append(listImportsClass.get(i)); else - result += "\n" + listImportsClass.get(i); + result.append("\n").append(listImportsClass.get(i)); } - for (int i = 0; i < listImportsPackages.size(); ++i) - { + for (int i = 0; i < listImportsPackages.size(); ++i) { if (i == 0) - result += "\n\n" + listImportsPackages.get(i); + result.append("\n\n").append(listImportsPackages.get(i)); else - result += "\n" + listImportsPackages.get(i); + result.append("\n").append(listImportsPackages.get(i)); } String leftText = tc.getText(); char c; @@ -520,55 +463,48 @@ public class JSScriptingHandlerRhino extends ScriptingHandler } @Override - public void autoDownloadPlugins() - { - String s = textArea.getText(); - Pattern patternClasses = Pattern.compile("importClass\\((Packages\\.|)((\\w|\\.)+)\\)"); + public void autoDownloadPlugins() { + final String s = textArea.getText(); + final Pattern patternClasses = Pattern.compile("importClass\\((Packages\\.|)((\\w|\\.)+)\\)"); Matcher m = patternClasses.matcher(s); int offset = 0; - while (m.find(offset)) - { - String foundString = m.group(0); - String imported = m.group(2); - - PluginDescriptor plugindesc = PluginRepositoryLoader.getPlugin(imported); - if (plugindesc != null) - { + while (m.find(offset)) { + final String foundString = m.group(0); + final String imported = m.group(2); + + final PluginDescriptor plugindesc = PluginRepositoryLoader.getPlugin(imported); + if (plugindesc != null) { // method is in the exact plugin if (!plugindesc.isInstalled()) PluginInstaller.install(plugindesc, false); } - else - { + else { // class around plugin - for (PluginDescriptor pd : PluginRepositoryLoader.getPlugins()) - { + for (final PluginDescriptor pd : PluginRepositoryLoader.getPlugins()) { if (pd.getClassName().startsWith(imported) && !pd.isInstalled()) PluginInstaller.install(pd, false); } } - int idxString = s.indexOf(foundString, offset); + final int idxString = s.indexOf(foundString, offset); if (idxString == -1) break; offset = idxString + foundString.length(); } - Pattern patternPackages = Pattern.compile("importPackage\\((Packages\\.|)((\\w|\\.)+)\\)"); + final Pattern patternPackages = Pattern.compile("importPackage\\((Packages\\.|)((\\w|\\.)+)\\)"); m = patternPackages.matcher(s); offset = 0; - while (m.find(offset)) - { - String foundString = m.group(0); - String imported = m.group(2); + while (m.find(offset)) { + final String foundString = m.group(0); + final String imported = m.group(2); - for (PluginDescriptor pd : PluginRepositoryLoader.getPlugins()) - { + for (final PluginDescriptor pd : PluginRepositoryLoader.getPlugins()) { if (pd.getClassName().startsWith(imported) && !pd.isInstalled()) PluginInstaller.install(pd, false); } - int idxString = s.indexOf(foundString, offset); + final int idxString = s.indexOf(foundString, offset); if (idxString == -1) break; offset = idxString + foundString.length(); @@ -581,11 +517,9 @@ public class JSScriptingHandlerRhino extends ScriptingHandler // -------------------------------------------------------------------- // -------------------------------------------------------------------- @Override - protected void detectVariables(String s) throws ScriptException - { + protected void detectVariables(final String s) throws ScriptException { Context.enter(); - try - { + try { currentText = s; final CompilerEnvirons comp = CompilerEnvirons.ideEnvirons(); // report errors and warnings through our own reporter class @@ -593,23 +527,20 @@ public class JSScriptingHandlerRhino extends ScriptingHandler // do not complain about missing commas when they are not strictly needed comp.setStrictMode(false); final Parser parser = new Parser(comp); - AstRoot root = null; + final AstRoot root; - try - { + try { root = parser.parse(s, fileName, LINE_NUMBER_START); } - catch (RhinoException e) - { + catch (final RhinoException e) { throw new ScriptException(e.getMessage(), e.sourceName(), e.lineNumber(), e.columnNumber()); } if (root == null || !root.hasChildren()) return; // no issue, removes variables - if (provider != null) - { - for (Completion c : variableCompletions) + if (provider != null) { + for (final Completion c : variableCompletions) provider.removeCompletion(c); } variableCompletions.clear(); @@ -630,42 +561,35 @@ public class JSScriptingHandlerRhino extends ScriptingHandler if (provider != null) provider.addCompletions(variableCompletions); } - finally - { + finally { Context.exit(); } } /** * Register all variables in the successfully compiled script. - * + * * @param n * @param root * @throws ScriptException */ - private void registerVariables(AstNode n, AstRoot root, String text) throws ScriptException - { + private void registerVariables(final AstNode n, final AstRoot root, final String text) throws ScriptException { if (n == null) return; if (DEBUG) System.out.println("current node: " + typeToName(n.getType())); // register current - for (Completion c : generateCompletion(n, root, text)) - { - if (c != null) - { + for (final Completion c : generateCompletion(n, root, text)) { + if (c != null) { boolean alreadyExists = false; - if (c instanceof VariableCompletion) - { - ScriptVariable vc = localVariables.get(((VariableCompletion) c).getName()); + if (c instanceof VariableCompletion) { + final ScriptVariable vc = localVariables.get(((VariableCompletion) c).getName()); if (vc != null && !vc.isInScope(textArea.getCaretPosition())) alreadyExists = true; } - for (int i = 0; i < variableCompletions.size() && !alreadyExists; ++i) - { - if (variableCompletions.get(i).compareTo(c) == 0) - { + for (int i = 0; i < variableCompletions.size() && !alreadyExists; ++i) { + if (variableCompletions.get(i).compareTo(c) == 0) { if (textArea.getCaret().getDot() > n.getAbsolutePosition()) variableCompletions.remove(i); else @@ -677,11 +601,9 @@ public class JSScriptingHandlerRhino extends ScriptingHandler } } // recursive call on children (if any) - if (n.hasChildren()) - { + if (n.hasChildren()) { AstNode child = (AstNode) n.getFirstChild(); - while (child != null) - { + while (child != null) { registerVariables(child, root, text); child = (AstNode) child.getNext(); } @@ -690,57 +612,50 @@ public class JSScriptingHandlerRhino extends ScriptingHandler /** * Automatically generates the completion for javascript: variable or function. - * + * * @param n * @param root - * @param commandStartOffset - * @param commandEndOffset * @return * @throws ScriptException */ - private List<Completion> generateCompletion(AstNode n, AstRoot root, String text) throws ScriptException - { - List<Completion> toReturn = new ArrayList<Completion>(); + private List<Completion> generateCompletion(final AstNode n, final AstRoot root, final String text) throws ScriptException { + final List<Completion> toReturn = new ArrayList<>(); AstNode expression = null; - switch (n.getType()) - { + switch (n.getType()) { case Token.VAR: - VariableDeclaration var = (VariableDeclaration) n; - List<VariableInitializer> listVars = var.getVariables(); + final VariableDeclaration var = (VariableDeclaration) n; + final List<VariableInitializer> listVars = var.getVariables(); // listVars cannot be null, and contains // all variables declared after the keyword "var" - for (VariableInitializer v : listVars) - { - AstNode target = v.getTarget(); - AstNode init = v.getInitializer(); + for (final VariableInitializer v : listVars) { + final AstNode target = v.getTarget(); + final AstNode init = v.getInitializer(); // only use variable declaration with names, // not with Literals. - if (target.getType() == Token.NAME) - { + if (target.getType() == Token.NAME) { VariableType type = null; if (init != null) type = getRealType(init); String typeString = ""; if (type != null) typeString = type.toString(); - VariableCompletion c = new VariableCompletion(provider, target.getString(), typeString); + final VariableCompletion c = new VariableCompletion(provider, target.getString(), typeString); c.setSummary("variable"); c.setDefinedIn("script"); c.setRelevance(RELEVANCE_HIGH); - int pos = n.getAbsolutePosition(); + final int pos = n.getAbsolutePosition(); addVariableDeclaration(c.getName(), type, pos, pos + var.getParent().getLength()); toReturn.add(c); } } break; case Token.EXPR_VOID: - if (n instanceof LabeledStatement) - { - LabeledStatement labelSt = (LabeledStatement) n; - for (Label label : labelSt.getLabels()) + if (n instanceof LabeledStatement) { + final LabeledStatement labelSt = (LabeledStatement) n; + for (final Label label : labelSt.getLabels()) toReturn.add(new BasicCompletion(provider, label.getName(), "Label")); break; } @@ -749,22 +664,18 @@ public class JSScriptingHandlerRhino extends ScriptingHandler case Token.ASSIGN: if (expression == null) expression = n; - if (expression instanceof Assignment) - { - AstNode left = ((Assignment) expression).getLeft(); - AstNode right = ((Assignment) expression).getRight(); - VariableType type = getRealType(right); - if (type != null && type.getClazz() == void.class) - { - throw new ScriptException("This method returns \"void\" and cannot be assigned", fileName, - n.getLineno(), -1); + if (expression instanceof Assignment) { + final AstNode left = ((Assignment) expression).getLeft(); + final AstNode right = ((Assignment) expression).getRight(); + final VariableType type = getRealType(right); + if (type != null && type.getClazz() == void.class) { + throw new ScriptException("This method returns \"void\" and cannot be assigned", fileName, n.getLineno(), -1); } String typeString = ""; if (type != null) typeString = type.toString(); - if (left.getType() == Token.NAME) - { - VariableCompletion c = new VariableCompletion(provider, left.getString(), typeString); + if (left.getType() == Token.NAME) { + final VariableCompletion c = new VariableCompletion(provider, left.getString(), typeString); c.setSummary("variable"); c.setDefinedIn("script"); c.setRelevance(RELEVANCE_HIGH); @@ -772,41 +683,33 @@ public class JSScriptingHandlerRhino extends ScriptingHandler toReturn.add(c); } } - else if (expression instanceof FunctionCall) - { - AstNode target = ((FunctionCall) expression).getTarget(); - if (!(target.getType() == Token.NAME && (target.getString().contentEquals("importClass") - || target.getString().contentEquals("importPackage")))) - { - VariableType vt = resolveCallType(expression, text, false); + else if (expression instanceof FunctionCall) { + final AstNode target = ((FunctionCall) expression).getTarget(); + if (!(target.getType() == Token.NAME && (target.getString().contentEquals("importClass") || target.getString().contentEquals("importPackage")))) { + final VariableType vt = resolveCallType(expression, text, false); if (vt == null) updateGutter(); } } - else if (expression instanceof PropertyGet) - { + else if (expression instanceof PropertyGet) { // Do nothing } break; case Token.BLOCK: - if (n instanceof Block) - { - Block scope = (Block) n; + if (n instanceof Block) { + final Block scope = (Block) n; AstNode child = (AstNode) scope.getFirstChild(); - while (child != null) - { + while (child != null) { registerVariables(child, root, text); child = (AstNode) child.getNext(); } } - else if (n instanceof Scope) - { - Scope scope = (Scope) n; + else if (n instanceof Scope) { + final Scope scope = (Scope) n; AstNode child = (AstNode) scope.getFirstChild(); - while (child != null) - { + while (child != null) { registerVariables(child, root, text); child = (AstNode) child.getNext(); } @@ -818,12 +721,11 @@ public class JSScriptingHandlerRhino extends ScriptingHandler break; case Token.FUNCTION: - FunctionNode fn = (FunctionNode) n; - FunctionCompletion fc = new FunctionCompletion(provider, fn.getName(), ""); - List<AstNode> paramsFn = fn.getParams(); - ArrayList<Parameter> params = new ArrayList<Parameter>(); - for (AstNode param : paramsFn) - { + final FunctionNode fn = (FunctionNode) n; + final FunctionCompletion fc = new FunctionCompletion(provider, fn.getName(), ""); + final List<AstNode> paramsFn = fn.getParams(); + final ArrayList<Parameter> params = new ArrayList<>(); + for (final AstNode param : paramsFn) { params.add(new Parameter("", param.toSource())); } fc.setParams(params); @@ -835,21 +737,18 @@ public class JSScriptingHandlerRhino extends ScriptingHandler break; case Token.IF: - IfStatement nIf = (IfStatement) n; + final IfStatement nIf = (IfStatement) n; registerVariables(nIf.getThenPart(), root, text); registerVariables(nIf.getElsePart(), root, text); break; case Token.DO: - case Token.FOR: - { - if (n instanceof ForInLoop) - { - ForInLoop fl = (ForInLoop) n; + case Token.FOR: { + if (n instanceof ForInLoop) { + final ForInLoop fl = (ForInLoop) n; registerVariables(fl.getIterator(), root, text); } - if (n instanceof ForLoop) - { - ForLoop fl = (ForLoop) n; + if (n instanceof ForLoop) { + final ForLoop fl = (ForLoop) n; registerVariables(fl.getInitializer(), root, text); } } @@ -857,10 +756,8 @@ public class JSScriptingHandlerRhino extends ScriptingHandler registerVariables(((Loop) n).getBody(), root, text); break; case Token.SWITCH: - for (SwitchCase c : ((SwitchStatement) n).getCases()) - { - for (AstNode statement : c.getStatements()) - { + for (final SwitchCase c : ((SwitchStatement) n).getCases()) { + for (final AstNode statement : c.getStatements()) { registerVariables(statement, root, text); } } @@ -869,30 +766,26 @@ public class JSScriptingHandlerRhino extends ScriptingHandler return toReturn; } - // 22/03/13 1608 - private VariableType resolveCallType(AstNode n, String text, boolean noerror) - { - VariableType toReturn = null; - ScriptEngineHandler engineHandler = ScriptEngineHandler.getEngineHandler(getEngine()); - int offset = n.getAbsolutePosition(); + private VariableType resolveCallType(final AstNode n, final String text, final boolean noerror) { + VariableType toReturn; + final ScriptEngineHandler engineHandler = ScriptEngineHandler.getEngineHandler(getEngine()); + final int offset = n.getAbsolutePosition(); String s = buildFunction2(n); // System.out.println(s); - boolean containsNew = s.contains("new "); - if (containsNew) - { + final boolean containsNew = s.contains("new "); + if (containsNew) { s = s.substring("new ".length()); } // create a regex pattern - Pattern p = Pattern.compile("\\w(\\w|\\.|\\[|\\])*\\((\\w|\\.|\\[|,|\\]|\\(|\\)| )*\\)"); - Matcher match = p.matcher(s); + final Pattern p = Pattern.compile("\\w(\\w|\\.|\\[|])*\\((\\w|\\.|\\[|,|]|\\(|\\)| )*\\)"); + final Matcher match = p.matcher(s); - int idxP1 = 0; + int idxP1; int idxP2; int decal = 0; boolean isField = false; - if (match.find(0)) - { + if (match.find(0)) { // TODO handle spot.points String firstCall = match.group(0); idxP1 = firstCall.indexOf('('); @@ -909,40 +802,33 @@ public class JSScriptingHandlerRhino extends ScriptingHandler else if (idxP1 != -1) classNameOrFunctionNameOrVariable = firstCall.substring(0, idxP1); else - classNameOrFunctionNameOrVariable = firstCall.substring(0); + classNameOrFunctionNameOrVariable = firstCall; - if (classNameOrFunctionNameOrVariable.contains(".")) - { + if (classNameOrFunctionNameOrVariable.contains(".")) { // is it a class? - Class<?> clazz = resolveClassDeclaration(classNameOrFunctionNameOrVariable); + final Class<?> clazz = resolveClassDeclaration(classNameOrFunctionNameOrVariable); if (clazz != null) vt = new VariableType(clazz); - else - { - String res[] = classNameOrFunctionNameOrVariable.split("\\."); + else { + final String[] res = classNameOrFunctionNameOrVariable.split("\\."); classNameOrFunctionNameOrVariable = res[0]; isField = true; - for (int i = 1; i < res.length; ++i) - { + for (int i = 1; i < res.length; ++i) { lastDot = classNameOrFunctionNameOrVariable.length() + 1; decal = classNameOrFunctionNameOrVariable.length() + 1; } } } - if (vt == null) - { + if (vt == null) { // -------------------------- // TEST IF IS FUNCTION BINDED // -------------------------- vt = localFunctions.get(classNameOrFunctionNameOrVariable); } - if (vt == null) - { - vt = ScriptEngineHandler.getEngineHandler(getEngine()).getEngineFunctions() - .get(classNameOrFunctionNameOrVariable); - if (classNameOrFunctionNameOrVariable.contentEquals("println") - || classNameOrFunctionNameOrVariable.contentEquals("print")) + if (vt == null) { + vt = ScriptEngineHandler.getEngineHandler(getEngine()).getEngineFunctions().get(classNameOrFunctionNameOrVariable); + if (classNameOrFunctionNameOrVariable.contentEquals("println") || classNameOrFunctionNameOrVariable.contentEquals("print")) vt = new VariableType(void.class); } @@ -959,18 +845,15 @@ public class JSScriptingHandlerRhino extends ScriptingHandler vt = engineHandler.getEngineVariables().get(classNameOrFunctionNameOrVariable); // is it a class? - if (vt == null) - { - Class<?> clazz = resolveClassDeclaration(classNameOrFunctionNameOrVariable); + if (vt == null) { + final Class<?> clazz = resolveClassDeclaration(classNameOrFunctionNameOrVariable); if (clazz != null) vt = new VariableType(clazz); } // unknown type - if (vt == null) - { - errors.addWarning(new ScriptException("Unknown field or method: " + classNameOrFunctionNameOrVariable, - null, n.getLineno())); + if (vt == null) { + errors.addWarning(new ScriptException("Unknown field or method: " + classNameOrFunctionNameOrVariable, null, n.getLineno())); return null; } @@ -980,7 +863,7 @@ public class JSScriptingHandlerRhino extends ScriptingHandler if (returnType == null) return null; - String call; + final String call; if (decal < idxP1) call = firstCall.substring(lastDot + 1); else @@ -988,102 +871,75 @@ public class JSScriptingHandlerRhino extends ScriptingHandler // FIND THE CORRESPONDING METHOD String genericType = vt.getType(); - if (lastDot != -1) - { - if (!isField) - { - try - { + if (lastDot != -1) { + if (!isField) { + try { // generate the Class<?> arguments - Class<?> clazzes[]; + Class<?>[] clazzes; // get the arguments - String argsString = firstCall.substring(idxP1 + 1, idxP2); + final String argsString = firstCall.substring(idxP1 + 1, idxP2); // separate arguments - String[] args = argsString.split(","); + final String[] args = argsString.split(","); - if (argsString.isEmpty()) - { + if (argsString.isEmpty()) { clazzes = new Class<?>[0]; } - else - { + else { clazzes = new Class<?>[args.length]; for (int i = 0; i < clazzes.length; ++i) clazzes[i] = resolveClassDeclaration(args[i]); clazzes = getGenericNumberTypes(text, n, vt.getClazz(), firstCall.substring(lastDot + 1, idxP1), clazzes); } - Method m = resolveMethod(returnType, call, clazzes); - - String genericReturnType = m.getGenericReturnType().toString(); - if (Pattern.matches("(\\[*)E", genericReturnType) && !genericType.isEmpty()) - { - try - { - // TOOD array + final Method m = resolveMethod(returnType, call, clazzes); + + final String genericReturnType = m.getGenericReturnType().toString(); + if (Pattern.matches("(\\[*)E", genericReturnType) && !genericType.isEmpty()) { + try { + // TODO array returnType = ClassUtil.findClass(genericType); genericType = ""; } - catch (ClassNotFoundException e) - { + catch (final ClassNotFoundException e) { + IcyExceptionHandler.showErrorMessage(e, true); } } - else - { + else { // set the new return type. returnType = m.getReturnType(); - if (returnType.getTypeParameters().length > 0) - { + if (returnType.getTypeParameters().length > 0) { genericType = VariableType.getType(m.getGenericReturnType().toString()); } } } - catch (SecurityException e1) - { + catch (final SecurityException e) { + IcyExceptionHandler.showErrorMessage(e, true); } - catch (NoSuchMethodException e1) - { - try - { - Field f = returnType.getField(call); + catch (final NoSuchMethodException ex) { + try { + final Field f = returnType.getField(call); returnType = f.getType(); } - catch (SecurityException e) - { - errors.addWarning( - new ScriptException("Unknown field or method: " + call, null, n.getLineno())); - return null; - } - catch (NoSuchFieldException e) - { - errors.addWarning( - new ScriptException("Unknown field or method: " + call, null, n.getLineno())); + catch (final SecurityException | NoSuchFieldException e) { + errors.addWarning(new ScriptException("Unknown field or method: " + call, null, n.getLineno())); return null; } } } - else - { + else { // TODO // System.out.println("not a method"); - Field f; - try - { + final Field f; + try { String next = firstCall.substring(decal); next = next.substring(0, next.indexOf('.')); decal += next.length(); f = returnType.getField(next); returnType = f.getType(); } - catch (SecurityException e) - { - errors.addWarning(new ScriptException("Unknown field or method: " + call, null, n.getLineno())); - return null; - } - catch (NoSuchFieldException e) - { + catch (final SecurityException | NoSuchFieldException e) { errors.addWarning(new ScriptException("Unknown field or method: " + call, null, n.getLineno())); return null; } @@ -1099,109 +955,88 @@ public class JSScriptingHandlerRhino extends ScriptingHandler fb.setReturnType(toReturn); if (DEBUG) - System.out.println( - "function edited: (" + (fb.getStartOffset() + n.getPosition()) + ") " + text.substring(offset)); + System.out.println("function edited: (" + (fb.getStartOffset() + n.getPosition()) + ") " + text.substring(offset)); // Add the function block to the index of blockFunctions. blockFunctions.put(fb.getStartOffset(), fb); // iterate over the next functions, based on the returnType - while (match.find(decal) && !(firstCall = match.group()).isEmpty()) - { - if (returnType == void.class) - { - System.out - .println("Void return, impossible to call something else on it. at line:" + +n.getLineno()); + while (match.find(decal) && !(firstCall = match.group()).isEmpty()) { + if (returnType == void.class) { + System.out.println("Void return, impossible to call something else on it. at line:" + n.getLineno()); } idxP1 = firstCall.indexOf('('); idxP2 = firstCall.indexOf(')'); decal += idxP2 + 2; // account for ) and . - String argsString = firstCall.substring(idxP1 + 1, idxP2); - String[] args = argsString.split(","); + final String argsString = firstCall.substring(idxP1 + 1, idxP2); + final String[] args = argsString.split(","); Class<?>[] clazzes; - if (argsString.isEmpty()) - { + if (argsString.isEmpty()) { clazzes = new Class<?>[0]; } - else - { + else { clazzes = new Class<?>[args.length]; for (int i = 0; i < clazzes.length; ++i) clazzes[i] = resolveClassDeclaration(args[i]); lastDot = firstCall.substring(0, idxP1).lastIndexOf('.'); - if (lastDot < 0) - { + if (lastDot < 0) { lastDot = -1; // in case of new for instance. } clazzes = getGenericNumberTypes(text, n, returnType, firstCall.substring(lastDot + 1, idxP1), clazzes); } - String call2; + final String call2; // if (lastDot != -1) // call2 = firstCall.substring(lastDot + 1, idxP1); // else call2 = firstCall.substring(0, idxP1); - if (call2.contentEquals("newInstance")) - { - try - { + if (call2.contentEquals("newInstance")) { + try { returnType.getConstructor(clazzes); } - catch (SecurityException e) - { - } - catch (NoSuchMethodException e) - { + catch (final SecurityException | NoSuchMethodException e) { + IcyExceptionHandler.showErrorMessage(e, true); } } - else - { - Method m; - try - { + else { + final Method m; + try { m = resolveMethod(returnType, firstCall.substring(0, idxP1), clazzes); // Check if the return type is E or [E or [[E, etc. That // means that 'E' // corresponds // to the previous generic Type. - String genericReturnType = m.getGenericReturnType().toString(); - if (Pattern.matches("(\\[*)E", genericReturnType) && !genericType.isEmpty()) - { - try - { - // TOOD array + final String genericReturnType = m.getGenericReturnType().toString(); + if (Pattern.matches("(\\[*)E", genericReturnType) && !genericType.isEmpty()) { + try { + // TODO array returnType = ClassUtil.findClass(genericType); genericType = ""; } - catch (ClassNotFoundException e) - { + catch (final ClassNotFoundException e) { + IcyExceptionHandler.showErrorMessage(e, true); } } - else - { + else { // set the new return type. returnType = m.getReturnType(); - if (returnType.getTypeParameters().length > 0) - { + if (returnType.getTypeParameters().length > 0) { genericType = VariableType.getType(m.getGenericReturnType().toString()); } } } - catch (SecurityException e1) - { + catch (final SecurityException e) { + IcyExceptionHandler.showErrorMessage(e, true); } - catch (NoSuchMethodException e1) - { - try - { - Field f = returnType.getField(call); + catch (final NoSuchMethodException ex) { + try { + final Field f = returnType.getField(call); returnType = f.getType(); } - catch (SecurityException e) - { + catch (final SecurityException e) { + IcyExceptionHandler.showErrorMessage(e, true); } - catch (NoSuchFieldException e) - { + catch (final NoSuchFieldException e) { return null; } } @@ -1226,36 +1061,32 @@ public class JSScriptingHandlerRhino extends ScriptingHandler return null; } - @SuppressWarnings("unused") - private VariableType resolveCallTypeOld(AstNode n, String text, boolean noerror) - { - VariableType toReturn = null; - ScriptEngineHandler engineHandler = ScriptEngineHandler.getEngineHandler(getEngine()); - int offset = n.getAbsolutePosition(); + private VariableType resolveCallTypeOld(final AstNode n, final String text, final boolean noerror) { + VariableType toReturn; + final ScriptEngineHandler engineHandler = ScriptEngineHandler.getEngineHandler(getEngine()); + final int offset = n.getAbsolutePosition(); String s = buildFunction2(n); // System.out.println(s); - boolean containsNew = s.contains("new "); - if (containsNew) - { + final boolean containsNew = s.contains("new "); + if (containsNew) { s = s.substring("new ".length()); } // create a regex pattern - Pattern p = Pattern.compile("\\w(\\w|\\.|\\[|\\])*\\((\\w|\\.|\\[|,|\\]|\\(|\\)| )*\\)"); - Matcher match = p.matcher(s); + final Pattern p = Pattern.compile("\\w(\\w|\\.|\\[|])*\\((\\w|\\.|\\[|,|]|\\(|\\)| )*\\)"); + final Matcher match = p.matcher(s); - int idxP1 = 0; + int idxP1; int idxP2; int decal = 0; - if (match.find(0)) - { + if (match.find(0)) { // TODO handle spot.points String firstCall = match.group(0); idxP1 = firstCall.indexOf('('); idxP2 = firstCall.indexOf(')'); decal += idxP2 + 1; int lastDot = firstCall.substring(0, idxP1).lastIndexOf('.'); - VariableType vt = null; + VariableType vt; // get the className (or binding function name if it is the // case) @@ -1265,20 +1096,17 @@ public class JSScriptingHandlerRhino extends ScriptingHandler else if (idxP1 != -1) classNameOrFunctionNameOrVariable = firstCall.substring(0, idxP1); else - classNameOrFunctionNameOrVariable = firstCall.substring(0); + classNameOrFunctionNameOrVariable = firstCall; - if (classNameOrFunctionNameOrVariable.contains(".")) - { + if (classNameOrFunctionNameOrVariable.contains(".")) { // is it a class? - Class<?> clazz = resolveClassDeclaration(classNameOrFunctionNameOrVariable); + final Class<?> clazz = resolveClassDeclaration(classNameOrFunctionNameOrVariable); if (clazz != null) vt = new VariableType(clazz); - else - { - String res[] = classNameOrFunctionNameOrVariable.split("\\."); + else { + final String[] res = classNameOrFunctionNameOrVariable.split("\\."); classNameOrFunctionNameOrVariable = res[0]; - for (int i = 1; i < res.length; ++i) - { + for (int i = 1; i < res.length; ++i) { lastDot = classNameOrFunctionNameOrVariable.length() + 1; decal = classNameOrFunctionNameOrVariable.length() + 1; } @@ -1295,12 +1123,9 @@ public class JSScriptingHandlerRhino extends ScriptingHandler // TEST IF IS FUNCTION BINDED // -------------------------- vt = localFunctions.get(classNameOrFunctionNameOrVariable); - if (vt == null) - { - vt = ScriptEngineHandler.getEngineHandler(getEngine()).getEngineFunctions() - .get(classNameOrFunctionNameOrVariable); - if (classNameOrFunctionNameOrVariable.contentEquals("println") - || classNameOrFunctionNameOrVariable.contentEquals("print")) + if (vt == null) { + vt = ScriptEngineHandler.getEngineHandler(getEngine()).getEngineFunctions().get(classNameOrFunctionNameOrVariable); + if (classNameOrFunctionNameOrVariable.contentEquals("println") || classNameOrFunctionNameOrVariable.contentEquals("print")) vt = new VariableType(void.class); } @@ -1317,28 +1142,24 @@ public class JSScriptingHandlerRhino extends ScriptingHandler vt = engineHandler.getEngineVariables().get(classNameOrFunctionNameOrVariable); // is it a class? - if (vt == null) - { - Class<?> clazz = resolveClassDeclaration(classNameOrFunctionNameOrVariable); + if (vt == null) { + final Class<?> clazz = resolveClassDeclaration(classNameOrFunctionNameOrVariable); if (clazz != null) vt = new VariableType(clazz); } // unknown type - if (vt == null) - { + if (vt == null) { System.out.println("Unknown: " + classNameOrFunctionNameOrVariable + " at line: " + n.getLineno()); return null; } // generate the Class<?> arguments - Class<?> clazzes[]; - if (argsString.isEmpty()) - { + Class<?>[] clazzes; + if (argsString.isEmpty()) { clazzes = new Class<?>[0]; } - else - { + else { clazzes = new Class<?>[args.length]; for (int i = 0; i < clazzes.length; ++i) clazzes[i] = resolveClassDeclaration(args[i]); @@ -1349,7 +1170,7 @@ public class JSScriptingHandlerRhino extends ScriptingHandler // the first type! Class<?> returnType = vt.getClazz(); - String call; + final String call; if (decal < idxP1) call = firstCall.substring(lastDot + 1); else @@ -1357,50 +1178,41 @@ public class JSScriptingHandlerRhino extends ScriptingHandler // FIND THE CORRESPONDING METHOD String genericType = vt.getType(); - if (lastDot != -1) - { - try - { - Method m = resolveMethod(returnType, call, clazzes); - - String genericReturnType = m.getGenericReturnType().toString(); - if (Pattern.matches("(\\[*)E", genericReturnType) && !genericType.isEmpty()) - { - try - { - // TOOD array + if (lastDot != -1) { + try { + final Method m = resolveMethod(returnType, call, clazzes); + + final String genericReturnType = m.getGenericReturnType().toString(); + if (Pattern.matches("(\\[*)E", genericReturnType) && !genericType.isEmpty()) { + try { + // TODO array returnType = ClassUtil.findClass(genericType); genericType = ""; } - catch (ClassNotFoundException e) - { + catch (final ClassNotFoundException e) { + IcyExceptionHandler.showErrorMessage(e, true); } } - else - { + else { // set the new return type. returnType = m.getReturnType(); - if (returnType.getTypeParameters().length > 0) - { + if (returnType.getTypeParameters().length > 0) { genericType = VariableType.getType(m.getGenericReturnType().toString()); } } } - catch (SecurityException e1) - { + catch (final SecurityException e) { + IcyExceptionHandler.showErrorMessage(e, true); } - catch (NoSuchMethodException e1) - { - try - { - Field f = returnType.getField(call); + catch (final NoSuchMethodException ex) { + try { + final Field f = returnType.getField(call); returnType = f.getType(); } - catch (SecurityException e) - { + catch (final SecurityException e) { + IcyExceptionHandler.showErrorMessage(e, true); } - catch (NoSuchFieldException e) - { + catch (final NoSuchFieldException e) { return null; } } @@ -1420,101 +1232,81 @@ public class JSScriptingHandlerRhino extends ScriptingHandler blockFunctions.put(fb.getStartOffset(), fb); // iterate over the next functions, based on the returnType - while (match.find(decal) && !(firstCall = match.group()).isEmpty()) - { - if (returnType == void.class) - { - System.out - .println("Void return, impossible to call something else on it. at line:" + +n.getLineno()); + while (match.find(decal) && !(firstCall = match.group()).isEmpty()) { + if (returnType == void.class) { + System.out.println("Void return, impossible to call something else on it. at line:" + n.getLineno()); } idxP1 = firstCall.indexOf('('); idxP2 = firstCall.indexOf(')'); decal += idxP2 + 2; // account for ) and . argsString = firstCall.substring(idxP1 + 1, idxP2); args = argsString.split(","); - if (argsString.isEmpty()) - { + if (argsString.isEmpty()) { clazzes = new Class<?>[0]; } - else - { + else { clazzes = new Class<?>[args.length]; for (int i = 0; i < clazzes.length; ++i) clazzes[i] = resolveClassDeclaration(args[i]); lastDot = firstCall.substring(0, idxP1).lastIndexOf('.'); - if (lastDot < 0) - { + if (lastDot < 0) { lastDot = -1; // in case of new for instance. } clazzes = getGenericNumberTypes(text, n, returnType, firstCall.substring(lastDot + 1, idxP1), clazzes); } - String call2; + final String call2; // if (lastDot != -1) // call2 = firstCall.substring(lastDot + 1, idxP1); // else call2 = firstCall.substring(0, idxP1); - if (call2.contentEquals("newInstance")) - { - try - { + if (call2.contentEquals("newInstance")) { + try { returnType.getConstructor(clazzes); } - catch (SecurityException e) - { - } - catch (NoSuchMethodException e) - { + catch (final SecurityException | NoSuchMethodException e) { + IcyExceptionHandler.showErrorMessage(e, true); } } - else - { - Method m; - try - { + else { + final Method m; + try { m = resolveMethod(returnType, firstCall.substring(0, idxP1), clazzes); // Check if the return type is E or [E or [[E, etc. That // means that 'E' // corresponds // to the previous generic Type. - String genericReturnType = m.getGenericReturnType().toString(); - if (Pattern.matches("(\\[*)E", genericReturnType) && !genericType.isEmpty()) - { - try - { - // TOOD array + final String genericReturnType = m.getGenericReturnType().toString(); + if (Pattern.matches("(\\[*)E", genericReturnType) && !genericType.isEmpty()) { + try { + // TODO array returnType = ClassUtil.findClass(genericType); genericType = ""; } - catch (ClassNotFoundException e) - { + catch (final ClassNotFoundException e) { + IcyExceptionHandler.showErrorMessage(e, true); } } - else - { + else { // set the new return type. returnType = m.getReturnType(); - if (returnType.getTypeParameters().length > 0) - { + if (returnType.getTypeParameters().length > 0) { genericType = VariableType.getType(m.getGenericReturnType().toString()); } } } - catch (SecurityException e1) - { + catch (final SecurityException e) { + IcyExceptionHandler.showErrorMessage(e, true); } - catch (NoSuchMethodException e1) - { - try - { - Field f = returnType.getField(call); + catch (final NoSuchMethodException ex) { + try { + final Field f = returnType.getField(call); returnType = f.getType(); } - catch (SecurityException e) - { + catch (final SecurityException e) { + IcyExceptionHandler.showErrorMessage(e, true); } - catch (NoSuchFieldException e) - { + catch (final NoSuchFieldException e) { return null; } } @@ -1527,8 +1319,7 @@ public class JSScriptingHandlerRhino extends ScriptingHandler fb.setReturnType(toReturn); if (DEBUG) - System.out.println("function edited: (" + (fb.getStartOffset() + n.getPosition()) + ") " - + text.substring(offset)); + System.out.println("function edited: (" + (fb.getStartOffset() + n.getPosition()) + ") " + text.substring(offset)); // add the Function Block to the index of blockFunctions. blockFunctions.put(fb.getStartOffset(), fb); @@ -1540,62 +1331,51 @@ public class JSScriptingHandlerRhino extends ScriptingHandler /** * Fix: Issue with same name functions, will always use the first one. - * + * * @param clazz * @param function * @param argsClazzes - * @param commandStartOffset - * @param commandEndOffset * @return */ - private static Class<?>[] getGenericNumberTypes(String text, AstNode n, Class<?> clazz, String function, - Class<?>[] argsClazzes) - { - Class<?>[] toReturn = new Class<?>[argsClazzes.length]; - int offset = n.getAbsolutePosition(); - String fullCommand = text.substring(offset, offset + n.getLength()); - int idxStart = fullCommand.indexOf(function); + private static Class<?>[] getGenericNumberTypes(final String text, final AstNode n, final Class<?> clazz, final String function, final Class<?>[] argsClazzes) { + final Class<?>[] toReturn = new Class<?>[argsClazzes.length]; + final int offset = n.getAbsolutePosition(); + final String fullCommand = text.substring(offset, offset + n.getLength()); + final int idxStart = fullCommand.indexOf(function); if (idxStart == -1) return argsClazzes; - int idxP1 = fullCommand.indexOf('(', idxStart); - int idxP2 = fullCommand.indexOf(')', idxStart); + final int idxP1 = fullCommand.indexOf('(', idxStart); + final int idxP2 = fullCommand.indexOf(')', idxStart); if (idxP1 == -1 || idxP2 == -1) return argsClazzes; - String argumentsChained = fullCommand.substring(idxP1 + 1, idxP2); - String[] args = argumentsChained.split(","); + final String argumentsChained = fullCommand.substring(idxP1 + 1, idxP2); + final String[] args = argumentsChained.split(","); if (args.length != argsClazzes.length) return argsClazzes; // FIXME here boolean hasNumber = false; - for (int i = 0; i < argsClazzes.length; ++i) - { + for (int i = 0; i < argsClazzes.length; ++i) { if (argsClazzes[i] == Number.class) hasNumber = true; toReturn[i] = argsClazzes[i]; } - if (hasNumber) - { - for (Method m : clazz.getMethods()) - { - if (m.getName().contentEquals(function)) - { - Class<?> params[] = m.getParameterTypes(); - if (params.length == argsClazzes.length) - { - for (int i = 0; i < params.length; ++i) - { + if (hasNumber) { + for (final Method m : clazz.getMethods()) { + if (m.getName().contentEquals(function)) { + final Class<?>[] params = m.getParameterTypes(); + if (params.length == argsClazzes.length) { + for (int i = 0; i < params.length; ++i) { if (params[i] == null || argsClazzes[i] == null) break; if (params[i].isAssignableFrom(argsClazzes[i])) toReturn[i] = params[i]; - else if (params[i].isPrimitive()) - { + else if (params[i].isPrimitive()) { if (!(params[i] == float.class || params[i] == double.class) && !args[i].contains(".")) toReturn[i] = params[i]; else if (params[i] == float.class || params[i] == double.class) @@ -1609,10 +1389,8 @@ public class JSScriptingHandlerRhino extends ScriptingHandler } } } - return toReturn; } - else - return toReturn; + return toReturn; } // private Class<?> resolveRight(AstNode right, String text) throws @@ -1690,41 +1468,33 @@ public class JSScriptingHandlerRhino extends ScriptingHandler // return null; // } - private Class<?> resolveArrayItemTypeComponent(AstNode node) - { - int type = node.getType(); - if (type == Token.NAME) - { - String varname = node.getString(); - VariableType clazz = getVariableDeclaration(varname, node.getAbsolutePosition()); + private Class<?> resolveArrayItemTypeComponent(final AstNode node) { + final int type = node.getType(); + if (type == Token.NAME) { + final String varname = node.getString(); + final VariableType clazz = getVariableDeclaration(varname, node.getAbsolutePosition()); return clazz == null ? null : clazz.getClazz(); } - else if (type == Token.GETELEM) - { + else if (type == Token.GETELEM) { return resolveArrayItemTypeComponent(((ElementGet) node).getTarget()); } return null; } - private Class<?> createArrayItemType(Class<?> clazz, AstNode node) - { - int type = node.getType(); - if (type == Token.GETELEM) - { + private Class<?> createArrayItemType(final Class<?> clazz, final AstNode node) { + final int type = node.getType(); + if (type == Token.GETELEM) { return createArrayItemType(clazz.getComponentType(), ((ElementGet) node).getTarget()); } - else if (type == Token.NAME) - { - clazz = clazz.getComponentType(); + else if (type == Token.NAME) { + return clazz.getComponentType(); } return clazz; } - protected void addVariableDeclaration(String name, VariableType type, int offset) - { + protected void addVariableDeclaration(final String name, final VariableType type, final int offset) { ScriptVariable vc = localVariables.get(name); - if (vc == null) - { + if (vc == null) { vc = new ScriptVariable(); localVariables.put(name, vc); } @@ -1732,11 +1502,9 @@ public class JSScriptingHandlerRhino extends ScriptingHandler } // TODO use for variables with Token.VAR variables. - protected void addVariableDeclaration(String name, VariableType type, int offsetBegin, int offsetEnd) - { + protected void addVariableDeclaration(final String name, final VariableType type, final int offsetBegin, final int offsetEnd) { ScriptVariable vc = localVariables.get(name); - if (vc == null) - { + if (vc == null) { vc = new ScriptVariable(); localVariables.put(name, vc); } @@ -1744,39 +1512,35 @@ public class JSScriptingHandlerRhino extends ScriptingHandler } @Override - public Class<?> resolveClassDeclaration(String type) - { + public Class<?> resolveClassDeclaration(final String type) { Class<?> toReturn = null; int arraySize = 0; - while (type.endsWith("[]")) - { - type = type.substring(0, type.length() - 2); + String s = type; + while (s.endsWith("[]")) { + s = s.substring(0, s.length() - 2); arraySize++; } // try absolute - if (type.contentEquals("Array")) - { + if (s.contentEquals("Array")) { return NativeArray.class; } - else if (type.contentEquals("String")) - { + else if (s.contentEquals("String")) { return String.class; } - try - { - if (type.startsWith("Packages.")) - type = type.substring("Packages.".length()); - toReturn = ClassUtil.findClass(type); + try { + if (s.startsWith("Packages.")) + s = s.substring("Packages.".length()); + toReturn = ClassUtil.findClass(s); } - catch (ClassNotFoundException e) - { + catch (final ClassNotFoundException e) { + System.err.println("plugins.tprovoost.scripteditor.scriptinghandlers.js.JSScriptingHandlerRhino.resolveClassDeclaration(String type)"); + IcyExceptionHandler.showErrorMessage(e, false); } if (toReturn == null) - toReturn = super.resolveClassDeclaration(type); + toReturn = super.resolveClassDeclaration(s); if (toReturn == null) - toReturn = getNativeJSTypes(type); - while (toReturn != null && arraySize > 0) - { + toReturn = getNativeJSTypes(s); + while (toReturn != null && arraySize > 0) { toReturn = Array.newInstance(toReturn, 1).getClass(); arraySize--; } @@ -1784,26 +1548,23 @@ public class JSScriptingHandlerRhino extends ScriptingHandler } // FIXME + /** * This is a workaround for JS functions and their Java equivalent. However, * this doesn't work properly, as those Classes have different methods (Java * String and JS String have different methods for instance). - * + * * @param type * @return */ - private Class<?> getNativeJSTypes(String type) - { - if (type.contentEquals("Math")) - { + private Class<?> getNativeJSTypes(final String type) { + if (type.contentEquals("Math")) { return Math.class; } - else if (type.contentEquals("File")) - { + else if (type.contentEquals("File")) { return File.class; } - else if (type.contentEquals("String")) - { + else if (type.contentEquals("String")) { return String.class; } return null; @@ -1811,30 +1572,23 @@ public class JSScriptingHandlerRhino extends ScriptingHandler /** * Specific constructor not important, just the type - * - * @param n - * : current node. - * @param toReturn - * : text that will be returned in the end. + * + * @param n : current node. + * @param s : text that will be returned in the end. * @return */ - private String generateClassName(Node n, String toReturn) - { - - if (n != null) - { - if (n.getType() == Token.GETPROP) - { - String left = generateClassName(((PropertyGet) n).getLeft(), toReturn); - String right = generateClassName(((PropertyGet) n).getRight(), toReturn); + private String generateClassName(final Node n, final String s) { + String toReturn = s; + if (n != null) { + if (n.getType() == Token.GETPROP) { + final String left = generateClassName(((PropertyGet) n).getLeft(), toReturn); + final String right = generateClassName(((PropertyGet) n).getRight(), toReturn); toReturn += left + (left.contentEquals("") ? "" : ".") + right; } - else if (n.getType() == Token.NAME) - { + else if (n.getType() == Token.NAME) { return n.getString(); } - else if (n.getType() == Token.GETELEM) - { + else if (n.getType() == Token.GETELEM) { return generateClassName(((ElementGet) n).getTarget(), toReturn); } } @@ -1845,25 +1599,20 @@ public class JSScriptingHandlerRhino extends ScriptingHandler * Given the fact that the text can be different from {@link #textArea} * .getText(), this method returns the offset in the original text, * corresponding to the commandStartOffset in the modified text. - * - * @param text - * : text with or without line modifications - * @param offset - * : the offset wanted + * + * @param text : text with or without line modifications + * @param offset : the offset wanted * @return : Returns the same offset if textArea is not a JTextArea, returns the - * correct one if it is. - * @throws BadLocationException - * : An exception is raised of the offset does not - * exist in the original text, which should never - * happen. + * correct one if it is. + * @throws BadLocationException : An exception is raised of the offset does not + * exist in the original text, which should never + * happen. */ - public int getTextAreaOffset(String text, int offset) throws BadLocationException - { - if (textArea instanceof JTextArea) - { - JTextArea txtTmp = new JTextArea(text); - int line = txtTmp.getLineOfOffset(offset); - int offsetFromLine = offset - txtTmp.getLineStartOffset(line); + public int getTextAreaOffset(final String text, final int offset) throws BadLocationException { + if (textArea instanceof JTextArea) { + final JTextArea txtTmp = new JTextArea(text); + final int line = txtTmp.getLineOfOffset(offset); + final int offsetFromLine = offset - txtTmp.getLineStartOffset(line); return ((JTextArea) textArea).getLineStartOffset(line) + offsetFromLine; } else @@ -1871,54 +1620,51 @@ public class JSScriptingHandlerRhino extends ScriptingHandler } /** - * Dump the whole tree in the cconsole. - * + * Dump the whole tree in the console. + * * @param n * @param root - * @param commandIdx + * @param cIdx * @param decal */ - private void dumpTree(Node n, AstRoot root, int commandIdx, String decal) - { + private void dumpTree(final Node n, final AstRoot root, final int cIdx, final String decal) { if (n == null) return; + int commandIdx = cIdx; System.out.print(commandIdx + ": " + decal + typeToName(n.getType())); - switch (n.getType()) - { + final int level; + switch (n.getType()) { case Token.EXPR_RESULT: System.out.println(); - AstNode expression = ((ExpressionStatement) n).getExpression(); - if (expression instanceof Assignment) - { - Node left = ((Assignment) expression).getLeft(); - Node right = ((Assignment) expression).getRight(); - System.out.println(""); - int level = commandIdx + 1; + final AstNode expression = ((ExpressionStatement) n).getExpression(); + if (expression instanceof Assignment) { + final Node left = ((Assignment) expression).getLeft(); + final Node right = ((Assignment) expression).getRight(); + System.out.println(); + level = commandIdx + 1; dumpTree(left, root, level, "-" + decal); dumpTree(right, root, level, "-" + decal); } - else if (expression instanceof FunctionCall) - { - List<AstNode> args = ((FunctionCall) expression).getArguments(); + else if (expression instanceof FunctionCall) { + final List<AstNode> args = ((FunctionCall) expression).getArguments(); dumpTree(((FunctionCall) expression).getTarget(), root, commandIdx, "-" + decal); - for (AstNode arg : args) - { + for (final AstNode arg : args) { dumpTree(arg, root, commandIdx, "-" + decal); } } break; case Token.GETPROP: - Node propLeft = ((PropertyGet) n).getLeft(); - Node propRight = ((PropertyGet) n).getRight(); + final Node propLeft = ((PropertyGet) n).getLeft(); + final Node propRight = ((PropertyGet) n).getRight(); System.out.println(":"); - int level = commandIdx + 1; + level = commandIdx + 1; dumpTree(propLeft, root, level, "-" + decal); dumpTree(propRight, root, level, "-" + decal); break; case Token.BINDNAME: // System.out.println("bindname"); case Token.STRING: - StringLiteral str = (StringLiteral) n; + final StringLiteral str = (StringLiteral) n; System.out.println(": " + str.getValue()); break; case Token.NAME: @@ -1930,45 +1676,40 @@ public class JSScriptingHandlerRhino extends ScriptingHandler case Token.CALL: System.out.println(); level = commandIdx + 1; - FunctionCall fn = ((FunctionCall) n); - for (AstNode arg : fn.getArguments()) - { + final FunctionCall fn = ((FunctionCall) n); + for (final AstNode arg : fn.getArguments()) { dumpTree(arg, root, level, decal); } dumpTree(fn.getTarget(), root, level, "-" + decal); break; case Token.FUNCTION: - FunctionNode fn2 = (FunctionNode) n; + final FunctionNode fn2 = (FunctionNode) n; System.out.print(" " + fn2.getName()); dumpTree(fn2.getBody(), root, commandIdx + 1, "-" + decal); break; case Token.IF: System.out.println(); - IfStatement nIf = (IfStatement) n; + final IfStatement nIf = (IfStatement) n; level = commandIdx + 1; dumpTree(nIf.getThenPart(), root, level, "-" + decal); dumpTree(nIf.getElsePart(), root, level, "-" + decal); break; case Token.BLOCK: System.out.println(); - if (n instanceof Block) - { - Block scope = (Block) n; + if (n instanceof Block) { + final Block scope = (Block) n; Node child = scope.getFirstChild(); level = commandIdx + 1; - while (child != null) - { + while (child != null) { dumpTree(child, root, level, "-" + decal); child = child.getNext(); } } - else if (n instanceof Scope) - { - Scope scope = (Scope) n; + else if (n instanceof Scope) { + final Scope scope = (Scope) n; Node child = scope.getFirstChild(); level = commandIdx + 1; - while (child != null) - { + while (child != null) { dumpTree(child, root, level, "-" + decal); child = child.getNext(); } @@ -1977,7 +1718,7 @@ public class JSScriptingHandlerRhino extends ScriptingHandler case Token.GETELEM: System.out.println(); level = commandIdx + 1; - ElementGet get = (ElementGet) n; + final ElementGet get = (ElementGet) n; dumpTree(get.getElement(), root, level, "-" + decal); dumpTree(get.getTarget(), root, level, "-" + decal); break; @@ -1990,10 +1731,8 @@ public class JSScriptingHandlerRhino extends ScriptingHandler break; case Token.SWITCH: level = commandIdx + 1; - for (SwitchCase c : ((SwitchStatement) n).getCases()) - { - for (AstNode statement : c.getStatements()) - { + for (final SwitchCase c : ((SwitchStatement) n).getCases()) { + for (final AstNode statement : c.getStatements()) { dumpTree(statement, root, commandIdx + 1, decal); } } @@ -2001,15 +1740,12 @@ public class JSScriptingHandlerRhino extends ScriptingHandler default: System.out.println(); } - if (n.hasChildren()) - { + if (n.hasChildren()) { Node child = n.getFirstChild(); - while (child != null) - { + while (child != null) { dumpTree(child, root, commandIdx, "-" + decal); child = child.getNext(); - if (n == root) - { + if (n == root) { ++commandIdx; System.out.println(); } @@ -2017,13 +1753,11 @@ public class JSScriptingHandlerRhino extends ScriptingHandler } } - private String buildFunction2(AstNode n) - { + private String buildFunction2(final AstNode n) { String callName = ""; callName = buildFunctionRecursive(callName, n); - if (!callName.isEmpty()) - { + if (!callName.isEmpty()) { // removes the last dot if (callName.startsWith(".")) callName = callName.substring(1); @@ -2039,93 +1773,80 @@ public class JSScriptingHandlerRhino extends ScriptingHandler /** * Recursive version */ - private String buildFunctionRecursive(String elem, AstNode n) - { - if (n != null) - { - int type; - if ((type = n.getType()) == Token.GETPROP) - { - AstNode propLeft = ((PropertyGet) n).getLeft(); - AstNode propRight = ((PropertyGet) n).getRight(); - - String left = buildFunctionRecursive(elem, propLeft); - String right = buildFunctionRecursive(elem, propRight); + private String buildFunctionRecursive(final String s, final AstNode n) { + String elem = s; + if (n != null) { + final int type; + if ((type = n.getType()) == Token.GETPROP) { + final AstNode propLeft = ((PropertyGet) n).getLeft(); + final AstNode propRight = ((PropertyGet) n).getRight(); + + final String left = buildFunctionRecursive(elem, propLeft); + final String right = buildFunctionRecursive(elem, propRight); return left + right + elem; } - else if (type == Token.CALL) - { - FunctionCall fn = ((FunctionCall) n); - String args = ""; - args += "("; + else if (type == Token.CALL) { + final FunctionCall fn = ((FunctionCall) n); + final StringBuilder args = new StringBuilder("("); int i = 0; - for (AstNode arg : fn.getArguments()) - { + for (final AstNode arg : fn.getArguments()) { if (i != 0) - args += ","; - VariableType typeC = getRealType(arg); + args.append(","); + final VariableType typeC = getRealType(arg); if (typeC != null && typeC.getClazz() != null) - args += typeC.getClazz().getName(); + args.append(typeC.getClazz().getName()); else - args += "unknown"; + args.append("unknown"); i++; } - args += ")"; + args.append(")"); String functionName = ""; - AstNode target = fn.getTarget(); - String toReturn; - int targetType = target.getType(); - if (targetType == Token.NAME) - { + final AstNode target = fn.getTarget(); + final String toReturn; + final int targetType = target.getType(); + if (targetType == Token.NAME) { functionName = target.getString(); toReturn = functionName + args; } - else if (targetType == Token.GETPROP) - { + else if (targetType == Token.GETPROP) { functionName = ((PropertyGet) target).getRight().getString(); toReturn = buildFunctionRecursive(elem, ((PropertyGet) target).getLeft()) + "." + functionName + args; } - else if (targetType == Token.GETELEM) - { - ElementGet get = (ElementGet) target; + else if (targetType == Token.GETELEM) { + final ElementGet get = (ElementGet) target; elem = buildFunctionRecursive("", get.getElement()); functionName = elem.substring(0, elem.indexOf('(')); - String targetName = buildFunctionRecursive("", get.getTarget()); + final String targetName = buildFunctionRecursive("", get.getTarget()); toReturn = targetName + "." + elem; } else toReturn = elem; int rp = fn.getRp(); - if (rp != -1) - { + if (rp != -1) { rp = n.getAbsolutePosition() + rp + 1; if (DEBUG) System.out.println("function found:" + functionName); - IcyFunctionBlock fb = new IcyFunctionBlock(functionName, rp, null); + final IcyFunctionBlock fb = new IcyFunctionBlock(functionName, rp, null); functionBlocksToResolve.add(fb); } return toReturn; } - else if (type == Token.NAME) - { + else if (type == Token.NAME) { // if (functionNext) // callName = "." + n.getString() + "()" + callName; // else return "." + n.getString(); // return buildFunctionRecursive(callName, n.getFirstChild()); } - else if (type == Token.NUMBER) - { + else if (type == Token.NUMBER) { return Number.class.getName(); } - else if (type == Token.STRING) - { + else if (type == Token.STRING) { return ((StringLiteral) n).getValue(); } - else if (type == Token.GETELEM) - { - Class<?> clazz = resolveArrayItemTypeComponent(n); + else if (type == Token.GETELEM) { + final Class<?> clazz = resolveArrayItemTypeComponent(n); if (clazz != null) return clazz.getCanonicalName(); } @@ -2135,26 +1856,21 @@ public class JSScriptingHandlerRhino extends ScriptingHandler /** * Get the type of a variable definition. - * + * * @param n - * @param commandStartOffset - * @param commandEndOffset * @return * @throws ScriptException */ - private VariableType getRealType(AstNode n) - { + private VariableType getRealType(final AstNode n) { if (n == null) return null; - switch (n.getType()) - { + switch (n.getType()) { case Token.ADD: // test if string - InfixExpression expr = (InfixExpression) n; - VariableType typeLeft = getRealType(expr.getLeft()); - VariableType typeRight = getRealType(expr.getRight()); - if ((typeLeft != null && typeLeft.getClazz() == String.class) - || (typeRight != null && typeRight.getClazz() == String.class)) + final InfixExpression expr = (InfixExpression) n; + final VariableType typeLeft = getRealType(expr.getLeft()); + final VariableType typeRight = getRealType(expr.getRight()); + if ((typeLeft != null && typeLeft.getClazz() == String.class) || (typeRight != null && typeRight.getClazz() == String.class)) return new VariableType(String.class); case Token.DIV: case Token.SUB: @@ -2168,41 +1884,35 @@ public class JSScriptingHandlerRhino extends ScriptingHandler return new VariableType(boolean.class); case Token.NAME: return getVariableDeclaration(n.getString(), n.getAbsolutePosition()); - case Token.CALL: - { - VariableType vt = resolveCallType(n, currentText, false); - if (vt == null) - { + case Token.CALL: { + final VariableType vt = resolveCallType(n, currentText, false); + if (vt == null) { updateGutter(); } return vt; } case Token.FUNCTION: return new VariableType(Void.class); - case Token.GETPROP: - { + case Token.GETPROP: { // class wanted - AstNode target = ((PropertyGet) n).getTarget(); - if (target.getType() == Token.GETELEM) - { + final AstNode target = ((PropertyGet) n).getTarget(); + if (target.getType() == Token.GETELEM) { // array - String rightStr = generateClassName(n, ""); + final String rightStr = generateClassName(n, ""); // Class<?> clazz = resolveArrayItemTypeComponent(target); // clazz = createArrayItemType(clazz, target); if (rightStr.contentEquals("length")) return new VariableType(int.class); } - else - { + else { // class - String className = generateClassName(n, ""); + final String className = generateClassName(n, ""); Class<?> clazz = resolveClassDeclaration(className); if (clazz != null) return new VariableType(clazz); // try if it is an enum - int idx = className.lastIndexOf('.'); - if (idx != -1) - { + final int idx = className.lastIndexOf('.'); + if (idx != -1) { clazz = resolveClassDeclaration(className.substring(0, idx)); return clazz == null ? null : new VariableType(clazz); } @@ -2211,23 +1921,20 @@ public class JSScriptingHandlerRhino extends ScriptingHandler } case Token.ARRAYLIT: return new VariableType(Object[].class); - case Token.NEW: - { - NewExpression nexp = (NewExpression) n; - AstNode target = nexp.getTarget(); - if (target != null) - { - String className = generateClassName(target, ""); - Class<?> clazz = resolveClassDeclaration(className); + case Token.NEW: { + final NewExpression nexp = (NewExpression) n; + final AstNode target = nexp.getTarget(); + if (target != null) { + final String className = generateClassName(target, ""); + final Class<?> clazz = resolveClassDeclaration(className); return clazz == null ? null : new VariableType(clazz); } } - case Token.GETELEM: - { + case Token.GETELEM: { // access a table - ElementGet get = (ElementGet) n; + final ElementGet get = (ElementGet) n; // AstNode index = get.getElement(); - AstNode target = get.getTarget(); + final AstNode target = get.getTarget(); Class<?> clazz = resolveArrayItemTypeComponent(target); if (clazz != null) clazz = createArrayItemType(clazz, target); @@ -2238,18 +1945,15 @@ public class JSScriptingHandlerRhino extends ScriptingHandler } /** - * <i>Extracted from rhino for debugging puproses.</i><br/> + * <i>Extracted from rhino for debugging purposes.</i><br/> * Always returns a human-readable string for the token name. For instance, - * {@link #FINALLY} has the name "FINALLY". - * - * @param token - * the token code + * {@link Token#FINALLY} has the name "FINALLY". + * + * @param token the token code * @return the actual name for the token code */ - private String typeToName(int token) - { - switch (token) - { + private String typeToName(final int token) { + switch (token) { case Token.EOF: return "EOF"; case Token.EOL: @@ -2551,17 +2255,14 @@ public class JSScriptingHandlerRhino extends ScriptingHandler } /** - * <i>Extracted from rhino for debugging puproses.</i> Convert a keyword token + * <i>Extracted from rhino for debugging purposes.</i> Convert a keyword token * to a name string for use with the {@link Context#FEATURE_RESERVED_KEYWORD_AS_IDENTIFIER} feature. - * - * @param token - * A token + * + * @param token A token * @return the corresponding name string */ - public static String keywordToName(int token) - { - switch (token) - { + public static String keywordToName(final int token) { + switch (token) { case Token.BREAK: return "break"; case Token.CASE: @@ -2624,28 +2325,24 @@ public class JSScriptingHandlerRhino extends ScriptingHandler } @Override - public void format() - { + public void format() { /* * This formatter uses beautify.js by Einar Lielmanis, <einar@jsbeautifier.org> * http://jsbeautifier.org/ */ - InputStream is = PluginLoader - .getResourceAsStream("plugins/tprovoost/scripteditor/resources/beautify/beautify.js"); - Reader reader = new BufferedReader(new InputStreamReader(is)); - Context context = Context.enter(); + final InputStream is = PluginLoader.getResourceAsStream("plugins/tprovoost/scripteditor/resources/beautify/beautify.js"); + final Reader reader = new BufferedReader(new InputStreamReader(is)); + final Context context = Context.enter(); context.setLanguageVersion(Context.VERSION_1_6); - org.mozilla.javascript.ScriptableObject scope = context.initStandardObjects(); + final org.mozilla.javascript.ScriptableObject scope = context.initStandardObjects(); - try - { + try { context.evaluateReader(scope, reader, "Beautify", 1, null); } - catch (IOException e) - { + catch (final IOException e) { return; } - Function fct = (Function) scope.get("js_beautify", scope); + final Function fct = (Function) scope.get("js_beautify", scope); // boolean preserveNewLines = // JSBeautifyOptions.getInstance().getOption("preserveNewLines", @@ -2664,34 +2361,29 @@ public class JSScriptingHandlerRhino extends ScriptingHandler // String braceStyle = // JSBeautifyOptions.getInstance().getOption("braceStyle", "collapse"); - boolean preserveNewLines = true; - boolean useTabs = true; - boolean spaceBeforeConditional = true; - boolean jslintHappy = false; - boolean indentCase = false; - int indentSize = 1; - String braceStyle = "collapse"; + final boolean preserveNewLines = true; + final boolean useTabs = true; + final boolean spaceBeforeConditional = true; + final boolean jslintHappy = false; + final boolean indentCase = false; + final int indentSize = 1; + final String braceStyle = "collapse"; - NativeObject properties = new NativeObject(); + final NativeObject properties = new NativeObject(); - if (useTabs) - { + if (useTabs) { properties.defineProperty("indent_char", "\t", NativeObject.READONLY); properties.defineProperty("indent_size", 1, NativeObject.READONLY); } - else - { + else { int size = 4; - if (indentSize == 0) - { + if (indentSize == 0) { size = 2; } - else if (indentSize == 1) - { + else if (indentSize == 1) { size = 4; } - else - { + else { size = 8; } properties.defineProperty("indent_size", size, NativeObject.READONLY); @@ -2705,36 +2397,31 @@ public class JSScriptingHandlerRhino extends ScriptingHandler properties.defineProperty("brace_style", braceStyle, NativeObject.READONLY); - Object result = fct.call(context, scope, scope, new Object[] {textArea.getText(), properties}); + final Object result = fct.call(context, scope, scope, new Object[]{textArea.getText(), properties}); - String finalText = result.toString(); - int caretPos = textArea.getCaretPosition(); + final String finalText = result.toString(); + final int caretPos = textArea.getCaretPosition(); textArea.setText(finalText); if (caretPos > 0 && caretPos < finalText.length()) textArea.setCaretPosition(caretPos); } @Override - public ScriptEngine getEngine() - { + public ScriptEngine getEngine() { return ScriptEngineHandler.getEngine("javascript"); } @Override - public LinkGeneratorResult isLinkAtOffset(RSyntaxTextArea textArea, int offs) - { + public LinkGeneratorResult isLinkAtOffset(final RSyntaxTextArea textArea, final int offs) { return null; } @Override - public void autoImport() - { - try - { + public void autoImport() { + try { detectVariables(currentText); } - catch (ScriptException e) - { + catch (final ScriptException e) { errors.setRuntimeError(e); } } diff --git a/src/main/java/plugins/tprovoost/scripteditor/scriptinghandlers/py/PyScriptEngine.java b/src/main/java/plugins/tprovoost/scripteditor/scriptinghandlers/py/PyScriptEngine.java index c77dd0930c21eb0ae1e6d3ce51fde54439aaf853..646826df8858a5773dbae06f025b04a9873deb38 100644 --- a/src/main/java/plugins/tprovoost/scripteditor/scriptinghandlers/py/PyScriptEngine.java +++ b/src/main/java/plugins/tprovoost/scripteditor/scriptinghandlers/py/PyScriptEngine.java @@ -18,175 +18,157 @@ import org.python.util.PythonInterpreter; import plugins.tprovoost.scripteditor.scriptinghandlers.ScriptEngine; -public class PyScriptEngine extends ScriptEngine -{ - private static boolean initialized = false; - private PythonInterpreter py; - - public PyScriptEngine() - { - if (!initialized) - { - initializer(); - initialized = true; - } - - // Set __name__ == "__main__" (useful for python scripting) - // Without this, it is "__builtin__" - PyStringMap dict = new PyStringMap(); - dict.__setitem__("__name__", new PyString("__main__")); - - // start with a fresh PySystemState - PySystemState sys = new PySystemState(); - - py = new PythonInterpreter(dict, sys); - } - - @Override - public void eval(String s) throws ScriptException - { - for (String s2 : bindings.keySet()) - { - py.set(s2, bindings.get(s2)); - } - py.setOut(getWriter()); - py.setErr(getErrorWriter()); - try - { - py.exec(s); - PyStringMap locals = (PyStringMap) py.getLocals(); - Object[] values = locals.values().toArray(); - Object[] keys = locals.keys().toArray(); - bindings.clear(); - for (int i = 0; i < keys.length; ++i) - { - bindings.put((String) keys[i], values[i]); - } - } catch (PyException pe) - { - getErrorWriter().write(pe.toString()); - getErrorWriter().flush(); - // Re-throw the exception so that it can be handled by the GUI - // Warning! PyException is a subclass of RuntimeException, so - // it is an unchecked exception !! - // We convert it to a checked exception. - throw scriptException(pe); - } - } - - public void evalFile(String s) throws ScriptException - { - for (String s2 : bindings.keySet()) - { - py.set(s2, bindings.get(s2)); - } - py.setOut(getWriter()); - py.setErr(getErrorWriter()); - try - { - py.execfile(s); - PyStringMap locals = (PyStringMap) py.getLocals(); - Object[] values = locals.values().toArray(); - Object[] keys = locals.keys().toArray(); - bindings.clear(); - for (int i = 0; i < keys.length; ++i) - { - bindings.put((String) keys[i], values[i]); - } - } catch (PyException pe) - { - getErrorWriter().write(pe.toString()); - getErrorWriter().flush(); - // Re-throw the exception so that it can be handled by the GUI - // Warning! PyException is a subclass of RuntimeException, so - // it is an unchecked exception !! - // We convert it to a checked exception. - throw scriptException(pe); - } - } - - /** - * Initialize the python interpreter state (paths, etc.) - */ - public static void initializer() - { - // Get preProperties postProperties, and System properties - Properties postProps = new Properties(); - Properties sysProps = System.getProperties(); - - // put System properties (those set with -D on the command line) in - // postProps - Enumeration<?> e = sysProps.propertyNames(); - while (e.hasMoreElements()) - { - String name = (String) e.nextElement(); - if (name.startsWith("python.")) - postProps.put(name, System.getProperty(name)); - } - - // Here's the initialization step - PythonInterpreter.initialize(sysProps, postProps, null); - } - - @Override - public String getName() - { - return "python"; - } - - @Override - public void clear() - { - HashMap<String, Object> bindings = getBindings(); - for (String s : bindings.keySet()) - { - bindings.put(s, null); - py.set(s, null); - } - - // let Jython do its housekeeping - py.cleanup(); - } - - @Override - protected void putInRealEngine(String name, Object value) - { - py.set(name, value); - } - - @Override - protected void removeFromRealEngine(String name) - { - py.set(name, null); - } - - public PythonInterpreter getPythonInterpreter() - { - return py; - } - - /** - * Convert from PyException (subclass of RuntimeException, unchecked) - * to ScriptException (checked!). - * - * This function is taken from org.python.jsr223.PyScriptEngine.scriptException - * - * @param pye The Python runtime exception - * @return a ScriptException wrapping up the PyException as closely as possible - */ - public static ScriptException scriptException(PyException pye) { - ScriptException se = null; +public class PyScriptEngine extends ScriptEngine { + private static boolean initialized = false; + private final PythonInterpreter py; + + public PyScriptEngine() { + if (!initialized) { + initializer(); + initialized = true; + } + + // Set __name__ == "__main__" (useful for python scripting) + // Without this, it is "__builtin__" + final PyStringMap dict = new PyStringMap(); + dict.__setitem__("__name__", new PyString("__main__")); + + // start with a fresh PySystemState + final PySystemState sys = new PySystemState(); + + py = new PythonInterpreter(dict, sys); + } + + @Override + public void eval(final String s) throws ScriptException { + for (final String s2 : bindings.keySet()) { + py.set(s2, bindings.get(s2)); + } + py.setOut(getWriter()); + py.setErr(getErrorWriter()); + try { + py.exec(s); + final PyStringMap locals = (PyStringMap) py.getLocals(); + final Object[] values = locals.values().toArray(); + final Object[] keys = locals.keys().toArray(); + bindings.clear(); + for (int i = 0; i < keys.length; ++i) { + bindings.put((String) keys[i], values[i]); + } + } + catch (final PyException pe) { + getErrorWriter().write(pe.toString()); + getErrorWriter().flush(); + // Re-throw the exception so that it can be handled by the GUI + // Warning! PyException is a subclass of RuntimeException, so + // it is an unchecked exception !! + // We convert it to a checked exception. + throw scriptException(pe); + } + } + + @Override + public void evalFile(final String s) throws ScriptException { + for (final String s2 : bindings.keySet()) { + py.set(s2, bindings.get(s2)); + } + py.setOut(getWriter()); + py.setErr(getErrorWriter()); + try { + py.execfile(s); + final PyStringMap locals = (PyStringMap) py.getLocals(); + final Object[] values = locals.values().toArray(); + final Object[] keys = locals.keys().toArray(); + bindings.clear(); + for (int i = 0; i < keys.length; ++i) { + bindings.put((String) keys[i], values[i]); + } + } + catch (final PyException pe) { + getErrorWriter().write(pe.toString()); + getErrorWriter().flush(); + // Re-throw the exception so that it can be handled by the GUI + // Warning! PyException is a subclass of RuntimeException, so + // it is an unchecked exception !! + // We convert it to a checked exception. + throw scriptException(pe); + } + } + + /** + * Initialize the python interpreter state (paths, etc.) + */ + public static void initializer() { + // Get preProperties postProperties, and System properties + final Properties postProps = new Properties(); + final Properties sysProps = System.getProperties(); + + // put System properties (those set with -D on the command line) in + // postProps + final Enumeration<?> e = sysProps.propertyNames(); + while (e.hasMoreElements()) { + final String name = (String) e.nextElement(); + if (name.startsWith("python.")) + postProps.put(name, System.getProperty(name)); + } + + // Here's the initialization step + PythonInterpreter.initialize(sysProps, postProps, null); + } + + @Override + public String getName() { + return "python"; + } + + @Override + public void clear() { + final HashMap<String, Object> bindings = getBindings(); + for (final String s : bindings.keySet()) { + bindings.put(s, null); + py.set(s, null); + } + + // let Jython do its housekeeping + py.cleanup(); + } + + @Override + protected void putInRealEngine(final String name, final Object value) { + py.set(name, value); + } + + @Override + protected void removeFromRealEngine(final String name) { + py.set(name, null); + } + + public PythonInterpreter getPythonInterpreter() { + return py; + } + + /** + * Convert from PyException (subclass of RuntimeException, unchecked) + * to ScriptException (checked!). + * <p> + * This function is taken from org.python.jsr223.PyScriptEngine.scriptException + * + * @param pye The Python runtime exception + * @return a ScriptException wrapping up the PyException as closely as possible + */ + public static ScriptException scriptException(final PyException pye) { + ScriptException se; try { pye.normalize(); - PyObject type = pye.type; + final PyObject type = pye.type; PyObject value = pye.value; - PyTraceback tb = pye.traceback; + final PyTraceback tb = pye.traceback; if (__builtin__.isinstance(value, Py.SyntaxError)) { - PyObject filename = value.__findattr__("filename"); - PyObject lineno = value.__findattr__("lineno"); - PyObject offset = value.__findattr__("offset"); + final PyObject filename = value.__findattr__("filename"); + final PyObject lineno = value.__findattr__("lineno"); + final PyObject offset = value.__findattr__("offset"); value = value.__findattr__("msg"); se = new ScriptException( @@ -194,25 +176,29 @@ public class PyScriptEngine extends ScriptEngine filename == null ? "<script>" : filename.toString(), lineno == null ? 0 : lineno.asInt(), offset == null ? 0 : offset.asInt()); - } else if (tb != null) { - String filename; + } + else if (tb != null) { + final String filename; if (tb.tb_frame == null || tb.tb_frame.f_code == null) { filename = null; - } else { + } + else { filename = tb.tb_frame.f_code.co_filename; } se = new ScriptException( Py.formatException(type, value), filename, tb.tb_lineno); - } else { + } + else { se = new ScriptException(Py.formatException(type, value)); } se.initCause(pye); return se; - } catch (PyException ee) { - // we failed to convert cleanly... so wrap up the exception - // in the most straightforward way possible... + } + catch (final PyException e) { + // we failed to convert cleanly... so wrap up the exception + // in the most straightforward way possible... se = new ScriptException(pye); } return se; diff --git a/src/main/java/plugins/tprovoost/scripteditor/scriptinghandlers/py/PythonScriptingHandler.java b/src/main/java/plugins/tprovoost/scripteditor/scriptinghandlers/py/PythonScriptingHandler.java index 9bed1b92a8d6649f17ea99b2c25fb36f0a4d5133..7ccd0dec4263cf3db4b4fc3fb4688e22cbcf75a8 100644 --- a/src/main/java/plugins/tprovoost/scripteditor/scriptinghandlers/py/PythonScriptingHandler.java +++ b/src/main/java/plugins/tprovoost/scripteditor/scriptinghandlers/py/PythonScriptingHandler.java @@ -1,6 +1,7 @@ package plugins.tprovoost.scripteditor.scriptinghandlers.py; import icy.file.FileUtil; +import icy.system.IcyExceptionHandler; import icy.util.ClassUtil; import java.io.File; @@ -63,962 +64,853 @@ import plugins.tprovoost.scripteditor.scriptinghandlers.ScriptVariable; import plugins.tprovoost.scripteditor.scriptinghandlers.ScriptingHandler; import plugins.tprovoost.scripteditor.scriptinghandlers.VariableType; -public class PythonScriptingHandler extends ScriptingHandler -{ +public class PythonScriptingHandler extends ScriptingHandler { private static InteractiveInterpreter interpreter; - private LinkedList<IcyFunctionBlock> functionBlocksToResolve = new LinkedList<IcyFunctionBlock>(); - private HashMap<String, String> aliases = new HashMap<String, String>(); + private final LinkedList<IcyFunctionBlock> functionBlocksToResolve = new LinkedList<>(); + private final HashMap<String, String> aliases = new HashMap<>(); // private String currentText; - private HashMap<String, File> modules = new HashMap<String, File>(); + private final HashMap<String, File> modules = new HashMap<>(); - public PythonScriptingHandler(DefaultCompletionProvider provider, JTextComponent textArea, Gutter gutter, boolean autocompilation) - { - super(provider, "Python", textArea, gutter, autocompilation); + public PythonScriptingHandler(final DefaultCompletionProvider provider, final JTextComponent textArea, final Gutter gutter, final boolean autocompilation) { + super(provider, "Python", textArea, gutter, autocompilation); } @Override - public void evalEngine(ScriptEngine engine, String s) throws ScriptException - { - if (fileName == null || fileName.isEmpty() || fileName.contentEquals("Untitled") || fileName.contentEquals("Untitled")) - engine.eval(s); - else - engine.evalFile(fileName); + public void evalEngine(final ScriptEngine engine, final String s) throws ScriptException { + if (fileName == null || fileName.isEmpty() || fileName.contentEquals("Untitled") || fileName.contentEquals("Untitled")) + engine.eval(s); + else + engine.evalFile(fileName); } - public static void setInterpreter(InteractiveInterpreter interpreter) - { - PythonScriptingHandler.interpreter = interpreter; + public static void setInterpreter(final InteractiveInterpreter interpreter) { + PythonScriptingHandler.interpreter = interpreter; } - public static PythonInterpreter getInterpreter() - { - return interpreter; + public static PythonInterpreter getInterpreter() { + return interpreter; } @Override - public void installDefaultLanguageCompletions(String language) throws ScriptException - { - importPythonPackages(getEngine()); - - // IMPORT PLUGINS FUNCTIONS - importFunctions(); - - HashMap<String, VariableType> engineFunctions = ScriptEngineHandler.getEngineHandler(getEngine()).getEngineFunctions(); - engineFunctions.put("range", new VariableType(Object[].class)); - engineFunctions.put("isinstance", new VariableType(Boolean.class)); - engineFunctions.put("len", new VariableType(Number.class)); - engineFunctions.put("zip", new VariableType(PyList.class)); - } + public void installDefaultLanguageCompletions(final String language) throws ScriptException { + importPythonPackages(getEngine()); + + // IMPORT PLUGINS FUNCTIONS + importFunctions(); - public void importPythonPackages(ScriptEngine engine) throws ScriptException - { + final HashMap<String, VariableType> engineFunctions = ScriptEngineHandler.getEngineHandler(getEngine()).getEngineFunctions(); + engineFunctions.put("range", new VariableType(Object[].class)); + engineFunctions.put("isinstance", new VariableType(Boolean.class)); + engineFunctions.put("len", new VariableType(Number.class)); + engineFunctions.put("zip", new VariableType(PyList.class)); } + public void importPythonPackages(final ScriptEngine engine) {} + @Override - public void autoDownloadPlugins() - { + public void autoDownloadPlugins() { } @Override - protected void detectVariables(String s) throws ScriptException - { - // currentText = s; - - final CompilerFlags cflags = Py.getCompilerFlags(0, false); - if (provider != null) - { - for (Completion c : variableCompletions) - provider.removeCompletion(c); - } - variableCompletions.clear(); - - // register external variables prior to detection. - // Otherwise, references to external variables will not - // be detected. - addExternalVariables(); - - // avoid SyntaxErrors due to encoding declarations - s = mangleCodingDeclaration(s); - - mod node; - try - { - // parsing the code may raise a PyException, for syntax errors for example - node = ParserFacade.parseExpressionOrModule(new StringReader(s), fileName, cflags); - } - catch (PyException pye) - { - throw PyScriptEngine.scriptException(pye); - } - - if (node.getChildren() == null) - return; - if (DEBUG) - dumpTree(node, ""); - registerImports(node); - registerVariables(node); - - // add the completions - if (provider != null) - { - provider.addCompletions(variableCompletions); - } + protected void detectVariables(final String s) throws ScriptException { + String currentText = s; + + final CompilerFlags cflags = Py.getCompilerFlags(0, false); + if (provider != null) { + for (final Completion c : variableCompletions) + provider.removeCompletion(c); + } + variableCompletions.clear(); + + // register external variables prior to detection. + // Otherwise, references to external variables will not + // be detected. + addExternalVariables(); + + // avoid SyntaxErrors due to encoding declarations + currentText = mangleCodingDeclaration(currentText); + + final mod node; + try { + // parsing the code may raise a PyException, for syntax errors for example + node = ParserFacade.parseExpressionOrModule(new StringReader(currentText), fileName, cflags); + } + catch (final PyException pye) { + throw PyScriptEngine.scriptException(pye); + } + + if (node.getChildren() == null) + return; + if (DEBUG) + dumpTree(node, ""); + registerImports(node); + registerVariables(node); + + // add the completions + if (provider != null) { + provider.addCompletions(variableCompletions); + } } - private static String mangleCodingDeclaration(String s) - { - // Mangle coding definitions on first two lines of the string. - // Otherwise we get a SyntaxError when parsing a script that begins - // with a coding declaration such as: - // # -*- coding: utf-8 -*- - String[] parts = s.split("\n", 3); - StringBuilder builder = new StringBuilder(); - - for (int i=0; i<parts.length-1; i++) { - // replace the coding declaration with something harmless - builder.append(parts[i].replaceFirst("coding[:=]\\s*([-\\w.]+)", "coding declaration")); - builder.append("\n"); - } - builder.append(parts[parts.length-1]); // lines 3 and below - return builder.toString(); + private static String mangleCodingDeclaration(final String s) { + // Mangle coding definitions on first two lines of the string. + // Otherwise we get a SyntaxError when parsing a script that begins + // with a coding declaration such as: + // # -*- coding: utf-8 -*- + final String[] parts = s.split("\n", 3); + final StringBuilder builder = new StringBuilder(); + + for (int i = 0; i < parts.length - 1; i++) { + // replace the coding declaration with something harmless + builder.append(parts[i].replaceFirst("coding[:=]\\s*([-\\w.]+)", "coding declaration")); + builder.append("\n"); + } + builder.append(parts[parts.length - 1]); // lines 3 and below + return builder.toString(); } - public void registerVariables(PythonTree node) - { - if (node == null) - return; - for (Completion c : generateCompletion(node)) - { - if (c != null) - { - boolean alreadyExists = false; - if (c instanceof VariableCompletion) - { - ScriptVariable vc = localVariables.get(((VariableCompletion) c).getName()); - if (vc != null && !vc.isInScope(textArea.getCaretPosition())) - alreadyExists = true; - } - for (int i = 0; i < variableCompletions.size() && !alreadyExists; ++i) - { - if (variableCompletions.get(i).compareTo(c) == 0) - { - if (textArea.getCaret().getDot() > node.getCharStartIndex()) - variableCompletions.remove(i); - else - alreadyExists = true; - } - } - if (!alreadyExists) - variableCompletions.add(c); - } - } - // recursive call on children (if any) - if (node.getChildCount() > 0) - { - for (PythonTree tree : node.getChildren()) - { - registerVariables(tree); - } - } + public void registerVariables(final PythonTree node) { + if (node == null) + return; + for (final Completion c : generateCompletion(node)) { + if (c != null) { + boolean alreadyExists = false; + if (c instanceof VariableCompletion) { + final ScriptVariable vc = localVariables.get(((VariableCompletion) c).getName()); + if (vc != null && !vc.isInScope(textArea.getCaretPosition())) + alreadyExists = true; + } + for (int i = 0; i < variableCompletions.size() && !alreadyExists; ++i) { + if (variableCompletions.get(i).compareTo(c) == 0) { + if (textArea.getCaret().getDot() > node.getCharStartIndex()) + variableCompletions.remove(i); + else + alreadyExists = true; + } + } + if (!alreadyExists) + variableCompletions.add(c); + } + } + // recursive call on children (if any) + if (node.getChildCount() > 0) { + for (final PythonTree tree : node.getChildren()) { + registerVariables(tree); + } + } } - private ArrayList<Completion> generateCompletion(PythonTree node) - { - ArrayList<Completion> toReturn = new ArrayList<Completion>(); - - if (node instanceof Assign) - { - // assign - Assign assign = (Assign) node; - expr target = assign.getInternalTargets().get(0); - expr value = assign.getInternalValue(); - - if (target instanceof org.python.antlr.ast.List) - { - for (int i = 0; i < target.getChildCount(); ++i) - { - PythonTree child = target.getChild(i); - String name = child.getText(); - VariableType type = new VariableType(Object.class); - VariableCompletion c = new VariableCompletion(provider, name, type == null || type.getClazz() == null ? "" : type.toString()); - c.setDefinedIn(fileName); - c.setSummary("variable"); - c.setRelevance(ScriptingHandler.RELEVANCE_HIGH); - toReturn.add(c); - addVariableDeclaration(c.getName(), type, node.getCharStartIndex()); - } - } else - { - String name = target.getText(); - VariableType type = resolveType(value); - VariableCompletion c = new VariableCompletion(provider, name, type == null || type.getClazz() == null ? "" : type.toString()); - c.setDefinedIn(fileName); - c.setSummary("variable"); - c.setRelevance(ScriptingHandler.RELEVANCE_HIGH); - toReturn.add(c); - addVariableDeclaration(c.getName(), type, node.getCharStartIndex()); - } - } else if (node instanceof Call) - { - // resolveCallType(node, currentText, false); - } else if (node instanceof FunctionDef) - { - FunctionDef fn = (FunctionDef) node; - String name = fn.getName().toString(); - localFunctions.put(name, null); - - FunctionCompletion fc = new FunctionCompletion(provider, name, ""); - String shortDesc = ""; - - List<stmt> body = fn.getInternalBody(); - if (body.size() > 0) - { - PythonTree child = body.get(0); - if (child instanceof Expr && child.getChildCount() > 0) - { - PythonTree childchild = child.getChild(0); - if (childchild instanceof Str) - { - shortDesc = ((Str) childchild).getInternalS().toString(); - } - } - } - fc.setDefinedIn(FileUtil.getFileName(fileName, true)); - fc.setShortDescription(shortDesc); - fc.setRelevance(ScriptingHandler.RELEVANCE_HIGH); - toReturn.add(fc); - } else if (node instanceof For) - { - // String name = ((Name) ((For) node).getTarget()).getInternalId(); - // VariableType type = resolveType((PythonTree) ((For) - // node).getIter()); - // String typeS = ""; - // if (type != null) - // { - // Class<?> clazz = type.getClazz(); - // if (clazz != null) - // { - // if (clazz.isArray()) - // { - // type = new VariableType(clazz.getComponentType()); - // } - // typeS = type.toString(); - // } - // } - // addVariableDeclaration(name, null, node.getCharStartIndex()); - // localVariables.get(name).getVariableScopes().get(0).setEndScopeOffset(node.getCharStopIndex()); - // VariableCompletion c = new VariableCompletion(provider, name, - // typeS); - // c.setDefinedIn(fileName); - // c.setRelevance(ScriptingHandler.RELEVANCE_HIGH); - // toReturn.add(c); - } - return toReturn; + private ArrayList<Completion> generateCompletion(final PythonTree node) { + final ArrayList<Completion> toReturn = new ArrayList<>(); + + if (node instanceof Assign) { + // assign + final Assign assign = (Assign) node; + final expr target = assign.getInternalTargets().get(0); + final expr value = assign.getInternalValue(); + + if (target instanceof org.python.antlr.ast.List) { + for (int i = 0; i < target.getChildCount(); ++i) { + final PythonTree child = target.getChild(i); + final String name = child.getText(); + final VariableType type = new VariableType(Object.class); + final VariableCompletion c = new VariableCompletion(provider, name, type == null || type.getClazz() == null ? "" : type.toString()); + c.setDefinedIn(fileName); + c.setSummary("variable"); + c.setRelevance(ScriptingHandler.RELEVANCE_HIGH); + toReturn.add(c); + addVariableDeclaration(c.getName(), type, node.getCharStartIndex()); + } + } + else { + final String name = target.getText(); + final VariableType type = resolveType(value); + final VariableCompletion c = new VariableCompletion(provider, name, type == null || type.getClazz() == null ? "" : type.toString()); + c.setDefinedIn(fileName); + c.setSummary("variable"); + c.setRelevance(ScriptingHandler.RELEVANCE_HIGH); + toReturn.add(c); + addVariableDeclaration(c.getName(), type, node.getCharStartIndex()); + } + } + else if (node instanceof Call) { + // resolveCallType(node, currentText, false); + } + else if (node instanceof FunctionDef) { + final FunctionDef fn = (FunctionDef) node; + final String name = fn.getName().toString(); + localFunctions.put(name, null); + + final FunctionCompletion fc = new FunctionCompletion(provider, name, ""); + String shortDesc = ""; + + final List<stmt> body = fn.getInternalBody(); + if (body.size() > 0) { + final PythonTree child = body.get(0); + if (child instanceof Expr && child.getChildCount() > 0) { + final PythonTree childchild = child.getChild(0); + if (childchild instanceof Str) { + shortDesc = ((Str) childchild).getInternalS().toString(); + } + } + } + fc.setDefinedIn(FileUtil.getFileName(fileName, true)); + fc.setShortDescription(shortDesc); + fc.setRelevance(ScriptingHandler.RELEVANCE_HIGH); + toReturn.add(fc); + } + else if (node instanceof For) { + // String name = ((Name) ((For) node).getTarget()).getInternalId(); + // VariableType type = resolveType((PythonTree) ((For) + // node).getIter()); + // String typeS = ""; + // if (type != null) + // { + // Class<?> clazz = type.getClazz(); + // if (clazz != null) + // { + // if (clazz.isArray()) + // { + // type = new VariableType(clazz.getComponentType()); + // } + // typeS = type.toString(); + // } + // } + // addVariableDeclaration(name, null, node.getCharStartIndex()); + // localVariables.get(name).getVariableScopes().get(0).setEndScopeOffset(node.getCharStopIndex()); + // VariableCompletion c = new VariableCompletion(provider, name, + // typeS); + // c.setDefinedIn(fileName); + // c.setRelevance(ScriptingHandler.RELEVANCE_HIGH); + // toReturn.add(c); + } + return toReturn; } - protected void addVariableDeclaration(String name, VariableType type, int offset) - { - ScriptVariable vc = localVariables.get(name); - if (vc == null) - { - vc = new ScriptVariable(); - localVariables.put(name, vc); - } - vc.addType(offset, type); + protected void addVariableDeclaration(final String name, final VariableType type, final int offset) { + ScriptVariable vc = localVariables.get(name); + if (vc == null) { + vc = new ScriptVariable(); + localVariables.put(name, vc); + } + vc.addType(offset, type); } - private VariableType resolveType(PythonTree child) - { - if (child instanceof Call) - // return resolveCallType(child, currentText, false); - return null; - else if (child instanceof Num) - return new VariableType(Number.class); - - else if (child instanceof Str) - return new VariableType(String.class); - else if (child instanceof BinOp) - { - PyObject left = ((BinOp) child).getLeft(); - return resolveType((PythonTree) left); - } else if (child instanceof Name) - { - return getVariableDeclaration(child.getText(), child.getCharStartIndex()); - } else if (child instanceof Assign) - { - // TODO - } else if (child instanceof org.python.antlr.ast.List) - { - // TODO - } else if (child instanceof ListComp) - { - // TODO - } - if (DEBUG) - System.out.println("TODO handle: " + child.getClass()); - return null; + private VariableType resolveType(final PythonTree child) { + if (child instanceof Call) + // return resolveCallType(child, currentText, false); + return null; + else if (child instanceof Num) + return new VariableType(Number.class); + + else if (child instanceof Str) + return new VariableType(String.class); + else if (child instanceof BinOp) { + final PyObject left = ((BinOp) child).getLeft(); + return resolveType((PythonTree) left); + } + else if (child instanceof Name) { + return getVariableDeclaration(child.getText(), child.getCharStartIndex()); + } + else if (child instanceof Assign) { + // TODO + } + else if (child instanceof org.python.antlr.ast.List) { + // TODO + } + else if (child instanceof ListComp) { + // TODO + } + if (DEBUG) + System.out.println("TODO handle: " + child.getClass()); + return null; } - @SuppressWarnings("unused") - private VariableType resolveCallType(PythonTree child, String text, boolean noerror) - { - VariableType toReturn = null; - ScriptEngineHandler engineHandler = ScriptEngineHandler.getEngineHandler(getEngine()); - int offset = child.getCharStartIndex(); - String s = buildFunction(child); - if (DEBUG) - System.out.println("Built function : " + s); - // create a regex pattern - Pattern p = Pattern.compile("\\w(\\w|\\.|\\[|\\])*\\((\\w|\\.|\\[|,|\\]|\\(|\\)| )*\\)"); - Matcher match = p.matcher(s); - - int idxP1 = 0; - int idxP2; - int decal = 0; - boolean isField = false; - if (match.find(0)) - { - // TODO handle spot.points - String firstCall = match.group(0); - idxP1 = firstCall.indexOf('('); - idxP2 = firstCall.indexOf(')'); - decal += idxP2 + 1; - int lastDot = firstCall.substring(0, idxP1).lastIndexOf('.'); - VariableType vt = null; - - // get the className (or binding function name if it is the - // case) - String classNameOrFunctionNameOrVariable; - if (lastDot != -1) - classNameOrFunctionNameOrVariable = firstCall.substring(0, lastDot); - else if (idxP1 != -1) - classNameOrFunctionNameOrVariable = firstCall.substring(0, idxP1); - else - classNameOrFunctionNameOrVariable = firstCall.substring(0); - - // is it a class? - Class<?> clazz = resolveClassDeclaration(classNameOrFunctionNameOrVariable); - if (clazz != null) - vt = new VariableType(clazz); - else if (classNameOrFunctionNameOrVariable.contains(".")) - { - String res[] = classNameOrFunctionNameOrVariable.split("\\."); - classNameOrFunctionNameOrVariable = res[0]; - isField = true; - for (int i = 1; i < res.length; ++i) - { - lastDot = classNameOrFunctionNameOrVariable.length() + 1; - decal = classNameOrFunctionNameOrVariable.length() + 1; - } - } - - if (vt == null) - { - // -------------------------- - // TEST IF IS FUNCTION BINDED - // -------------------------- - vt = localFunctions.get(classNameOrFunctionNameOrVariable); - } - if (vt == null) - { - vt = ScriptEngineHandler.getEngineHandler(getEngine()).getEngineFunctions().get(classNameOrFunctionNameOrVariable); - if (classNameOrFunctionNameOrVariable.contentEquals("println") || classNameOrFunctionNameOrVariable.contentEquals("print")) - vt = new VariableType(void.class); - } - - // ------------------------------------------- - // IT IS SOMETHING ELSE, PERFORM VARIOUS TESTS - // ------------------------------------------- - - // is it a script defined variable? - if (vt == null) - vt = getVariableDeclaration(classNameOrFunctionNameOrVariable, offset); - - // is it an engine variable? - if (vt == null) - vt = engineHandler.getEngineVariables().get(classNameOrFunctionNameOrVariable); - - // is it a class? - if (vt == null) - { - clazz = resolveClassDeclaration(classNameOrFunctionNameOrVariable); - if (clazz != null) - vt = new VariableType(clazz); - } - // unknown type - if (vt == null) - { - String moduleName = classNameOrFunctionNameOrVariable + ".py"; - String currentDirectory = FileUtil.getDirectory(fileName); - } - // unknown type - if (vt == null) - { - System.out.println("Error while parsing code: cannot find type of: " + classNameOrFunctionNameOrVariable + " at line: " + child.getLine()); - return null; - } - - // the first type! - Class<?> returnType = vt.getClazz(); - - if (returnType == null) - return null; - - String call; - if (decal < idxP1) - call = firstCall.substring(lastDot + 1); - else - call = firstCall.substring(lastDot + 1, idxP1); - - // FIND THE CORRESPONDING METHOD - String genericType = vt.getType(); - if (lastDot != -1) - { - if (!isField) - { - try - { - // generate the Class<?> arguments - Class<?> clazzes[]; - - // get the arguments - String argsString = firstCall.substring(idxP1 + 1, idxP2); - - // separate arguments - String[] args = argsString.split(","); - - if (argsString.isEmpty()) - { - clazzes = new Class<?>[0]; - } else - { - clazzes = new Class<?>[args.length]; - for (int i = 0; i < clazzes.length; ++i) - clazzes[i] = resolveClassDeclaration(args[i]); - clazzes = getGenericNumberTypes(text, child, vt.getClazz(), firstCall.substring(lastDot + 1, idxP1), clazzes); - } - Method m = resolveMethod(returnType, call, clazzes); - - String genericReturnType = m.getGenericReturnType().toString(); - if (Pattern.matches("(\\[*)E", genericReturnType) && !genericType.isEmpty()) - { - try - { - // TOOD array - returnType = ClassUtil.findClass(genericType); - genericType = ""; - } catch (ClassNotFoundException e) - { - } - } else - { - // set the new return type. - returnType = m.getReturnType(); - if (returnType.getTypeParameters().length > 0) - { - genericType = VariableType.getType(m.getGenericReturnType().toString()); - } - } - } catch (SecurityException e1) - { - } catch (NoSuchMethodException e1) - { - try - { - Field f = returnType.getField(call); - returnType = f.getType(); - } catch (SecurityException e) - { - } catch (NoSuchFieldException e) - { - return null; - } - } - } else - { - // TODO - // System.out.println("not a method"); - Field f; - try - { - String next = firstCall.substring(decal); - next = next.substring(0, next.indexOf('.')); - decal += next.length(); - f = returnType.getField(next); - returnType = f.getType(); - } catch (SecurityException e) - { - } catch (NoSuchFieldException e) - { - } - } - - } - - // Create the VariableType containing the result. - toReturn = new VariableType(returnType, genericType); - - // Pop the function Block and set its type. - if (functionBlocksToResolve.isEmpty()) - { - System.out.println("No function to resolve."); - return null; - } - IcyFunctionBlock fb = functionBlocksToResolve.pop(); - fb.setReturnType(toReturn); - - if (DEBUG) - System.out.println("function edited: (" + (child.getCharStartIndex()) + ") " + text.substring(offset)); - - // Add the function block to the index of blockFunctions. - blockFunctions.put(fb.getStartOffset(), fb); - - // iterate over the next functions, based on the returnType - while (match.find(decal) && !(firstCall = match.group()).isEmpty()) - { - if (returnType == void.class) - { - System.out.println("Void return, impossible to call something else on it. at line:" + child.getLine()); - } - idxP1 = firstCall.indexOf('('); - idxP2 = firstCall.indexOf(')'); - decal += idxP2 + 2; // account for ) and . - String argsString = firstCall.substring(idxP1 + 1, idxP2); - String[] args = argsString.split(","); - Class<?>[] clazzes; - if (argsString.isEmpty()) - { - clazzes = new Class<?>[0]; - } else - { - clazzes = new Class<?>[args.length]; - for (int i = 0; i < clazzes.length; ++i) - clazzes[i] = resolveClassDeclaration(args[i]); - lastDot = firstCall.substring(0, idxP1).lastIndexOf('.'); - if (lastDot < 0) - { - lastDot = -1; // in case of new for instance. - } - clazzes = getGenericNumberTypes(text, child, returnType, firstCall.substring(lastDot + 1, idxP1), clazzes); - } - String call2; - // if (lastDot != -1) - // call2 = firstCall.substring(lastDot + 1, idxP1); - // else - call2 = firstCall.substring(0, idxP1); - if (call2.contentEquals("newInstance")) - { - try - { - returnType.getConstructor(clazzes); - } catch (SecurityException e) - { - } catch (NoSuchMethodException e) - { - } - } else - { - Method m; - try - { - m = resolveMethod(returnType, firstCall.substring(0, idxP1), clazzes); - // Check if the return type is E or [E or [[E, etc. That - // means that 'E' - // corresponds - // to the previous generic Type. - String genericReturnType = m.getGenericReturnType().toString(); - if (Pattern.matches("(\\[*)E", genericReturnType) && !genericType.isEmpty()) - { - try - { - // TOOD array - returnType = ClassUtil.findClass(genericType); - genericType = ""; - } catch (ClassNotFoundException e) - { - } - } else - { - // set the new return type. - returnType = m.getReturnType(); - if (returnType.getTypeParameters().length > 0) - { - genericType = VariableType.getType(m.getGenericReturnType().toString()); - } - } - } catch (SecurityException e1) - { - } catch (NoSuchMethodException e1) - { - try - { - Field f = returnType.getField(call); - returnType = f.getType(); - } catch (SecurityException e) - { - } catch (NoSuchFieldException e) - { - return null; - } - } - - } - if (functionBlocksToResolve.isEmpty()) - return null; - // get the last function block to resolve and set its type - fb = functionBlocksToResolve.pop(); - toReturn = new VariableType(returnType, genericType); - fb.setReturnType(toReturn); - - if (DEBUG) - System.out.println("function edited: (" + (fb.getStartOffset() + child.getCharStartIndex() - fb.getStartOffset()) + ") " + text.substring(offset)); - - // add the Function Block to the index of blockFunctions. - blockFunctions.put(fb.getStartOffset(), fb); - } - return toReturn; - } - return null; + private VariableType resolveCallType(final PythonTree child, final String text, final boolean noerror) { + VariableType toReturn; + final ScriptEngineHandler engineHandler = ScriptEngineHandler.getEngineHandler(getEngine()); + final int offset = child.getCharStartIndex(); + final String s = buildFunction(child); + if (DEBUG) + System.out.println("Built function : " + s); + // create a regex pattern + final Pattern p = Pattern.compile("\\w(\\w|\\.|\\[|])*\\((\\w|\\.|\\[|,|]|\\(|\\)| )*\\)"); + final Matcher match = p.matcher(s); + + int idxP1; + int idxP2; + int decal = 0; + boolean isField = false; + if (match.find(0)) { + // TODO handle spot.points + String firstCall = match.group(0); + idxP1 = firstCall.indexOf('('); + idxP2 = firstCall.indexOf(')'); + decal += idxP2 + 1; + int lastDot = firstCall.substring(0, idxP1).lastIndexOf('.'); + VariableType vt = null; + + // get the className (or binding function name if it is the + // case) + String classNameOrFunctionNameOrVariable; + if (lastDot != -1) + classNameOrFunctionNameOrVariable = firstCall.substring(0, lastDot); + else if (idxP1 != -1) + classNameOrFunctionNameOrVariable = firstCall.substring(0, idxP1); + else + classNameOrFunctionNameOrVariable = firstCall; + + // is it a class? + Class<?> clazz = resolveClassDeclaration(classNameOrFunctionNameOrVariable); + if (clazz != null) + vt = new VariableType(clazz); + else if (classNameOrFunctionNameOrVariable.contains(".")) { + final String[] res = classNameOrFunctionNameOrVariable.split("\\."); + classNameOrFunctionNameOrVariable = res[0]; + isField = true; + for (int i = 1; i < res.length; ++i) { + lastDot = classNameOrFunctionNameOrVariable.length() + 1; + decal = classNameOrFunctionNameOrVariable.length() + 1; + } + } + + if (vt == null) { + // -------------------------- + // TEST IF IS FUNCTION BINDED + // -------------------------- + vt = localFunctions.get(classNameOrFunctionNameOrVariable); + } + if (vt == null) { + vt = ScriptEngineHandler.getEngineHandler(getEngine()).getEngineFunctions().get(classNameOrFunctionNameOrVariable); + if (classNameOrFunctionNameOrVariable.contentEquals("println") || classNameOrFunctionNameOrVariable.contentEquals("print")) + vt = new VariableType(void.class); + } + + // ------------------------------------------- + // IT IS SOMETHING ELSE, PERFORM VARIOUS TESTS + // ------------------------------------------- + + // is it a script defined variable? + if (vt == null) + vt = getVariableDeclaration(classNameOrFunctionNameOrVariable, offset); + + // is it an engine variable? + if (vt == null) + vt = engineHandler.getEngineVariables().get(classNameOrFunctionNameOrVariable); + + // is it a class? + if (vt == null) { + clazz = resolveClassDeclaration(classNameOrFunctionNameOrVariable); + if (clazz != null) + vt = new VariableType(clazz); + } + // unknown type + if (vt == null) { + final String moduleName = classNameOrFunctionNameOrVariable + ".py"; + final String currentDirectory = FileUtil.getDirectory(fileName); + } + // unknown type + if (vt == null) { + System.out.println("Error while parsing code: cannot find type of: " + classNameOrFunctionNameOrVariable + " at line: " + child.getLineno()); + return null; + } + + // the first type! + Class<?> returnType = vt.getClazz(); + + if (returnType == null) + return null; + + final String call; + if (decal < idxP1) + call = firstCall.substring(lastDot + 1); + else + call = firstCall.substring(lastDot + 1, idxP1); + + // FIND THE CORRESPONDING METHOD + String genericType = vt.getType(); + if (lastDot != -1) { + if (!isField) { + try { + // generate the Class<?> arguments + Class<?>[] clazzes; + + // get the arguments + final String argsString = firstCall.substring(idxP1 + 1, idxP2); + + // separate arguments + final String[] args = argsString.split(","); + + if (argsString.isEmpty()) { + clazzes = new Class<?>[0]; + } + else { + clazzes = new Class<?>[args.length]; + for (int i = 0; i < clazzes.length; ++i) + clazzes[i] = resolveClassDeclaration(args[i]); + clazzes = getGenericNumberTypes(text, child, vt.getClazz(), firstCall.substring(lastDot + 1, idxP1), clazzes); + } + final Method m = resolveMethod(returnType, call, clazzes); + + final String genericReturnType = m.getGenericReturnType().toString(); + if (Pattern.matches("(\\[*)E", genericReturnType) && !genericType.isEmpty()) { + try { + // TODO array + returnType = ClassUtil.findClass(genericType); + genericType = ""; + } + catch (final ClassNotFoundException e) { + IcyExceptionHandler.showErrorMessage(e, true); + } + } + else { + // set the new return type. + returnType = m.getReturnType(); + if (returnType.getTypeParameters().length > 0) { + genericType = VariableType.getType(m.getGenericReturnType().toString()); + } + } + } + catch (final SecurityException e) { + IcyExceptionHandler.showErrorMessage(e, true); + } + catch (final NoSuchMethodException ex) { + try { + final Field f = returnType.getField(call); + returnType = f.getType(); + } + catch (final SecurityException e) { + IcyExceptionHandler.showErrorMessage(e, true); + } + catch (final NoSuchFieldException e) { + return null; + } + } + } + else { + // TODO + // System.out.println("not a method"); + final Field f; + try { + String next = firstCall.substring(decal); + next = next.substring(0, next.indexOf('.')); + decal += next.length(); + f = returnType.getField(next); + returnType = f.getType(); + } + catch (final SecurityException | NoSuchFieldException e) { + IcyExceptionHandler.showErrorMessage(e, true); + } + } + + } + + // Create the VariableType containing the result. + toReturn = new VariableType(returnType, genericType); + + // Pop the function Block and set its type. + if (functionBlocksToResolve.isEmpty()) { + System.out.println("No function to resolve."); + return null; + } + IcyFunctionBlock fb = functionBlocksToResolve.pop(); + fb.setReturnType(toReturn); + + if (DEBUG) + System.out.println("function edited: (" + (child.getCharStartIndex()) + ") " + text.substring(offset)); + + // Add the function block to the index of blockFunctions. + blockFunctions.put(fb.getStartOffset(), fb); + + // iterate over the next functions, based on the returnType + while (match.find(decal) && !(firstCall = match.group()).isEmpty()) { + if (returnType == void.class) { + System.out.println("Void return, impossible to call something else on it. at line:" + child.getLineno()); + } + idxP1 = firstCall.indexOf('('); + idxP2 = firstCall.indexOf(')'); + decal += idxP2 + 2; // account for ) and . + final String argsString = firstCall.substring(idxP1 + 1, idxP2); + final String[] args = argsString.split(","); + Class<?>[] clazzes; + if (argsString.isEmpty()) { + clazzes = new Class<?>[0]; + } + else { + clazzes = new Class<?>[args.length]; + for (int i = 0; i < clazzes.length; ++i) + clazzes[i] = resolveClassDeclaration(args[i]); + lastDot = firstCall.substring(0, idxP1).lastIndexOf('.'); + if (lastDot < 0) { + lastDot = -1; // in case of new for instance. + } + clazzes = getGenericNumberTypes(text, child, returnType, firstCall.substring(lastDot + 1, idxP1), clazzes); + } + final String call2; + // if (lastDot != -1) + // call2 = firstCall.substring(lastDot + 1, idxP1); + // else + call2 = firstCall.substring(0, idxP1); + if (call2.contentEquals("newInstance")) { + try { + returnType.getConstructor(clazzes); + } + catch (final SecurityException | NoSuchMethodException e) { + IcyExceptionHandler.showErrorMessage(e, true); + } + } + else { + final Method m; + try { + m = resolveMethod(returnType, firstCall.substring(0, idxP1), clazzes); + // Check if the return type is E or [E or [[E, etc. That + // means that 'E' + // corresponds + // to the previous generic Type. + final String genericReturnType = m.getGenericReturnType().toString(); + if (Pattern.matches("(\\[*)E", genericReturnType) && !genericType.isEmpty()) { + try { + // TODO array + returnType = ClassUtil.findClass(genericType); + genericType = ""; + } + catch (final ClassNotFoundException e) { + IcyExceptionHandler.showErrorMessage(e, true); + } + } + else { + // set the new return type. + returnType = m.getReturnType(); + if (returnType.getTypeParameters().length > 0) { + genericType = VariableType.getType(m.getGenericReturnType().toString()); + } + } + } + catch (final SecurityException e) { + IcyExceptionHandler.showErrorMessage(e, true); + } + catch (final NoSuchMethodException ex) { + try { + final Field f = returnType.getField(call); + returnType = f.getType(); + } + catch (final SecurityException e) { + IcyExceptionHandler.showErrorMessage(e, true); + } + catch (final NoSuchFieldException e) { + return null; + } + } + + } + if (functionBlocksToResolve.isEmpty()) + return null; + // get the last function block to resolve and set its type + fb = functionBlocksToResolve.pop(); + toReturn = new VariableType(returnType, genericType); + fb.setReturnType(toReturn); + + if (DEBUG) + System.out.println("function edited: (" + (fb.getStartOffset() + child.getCharStartIndex() - fb.getStartOffset()) + ") " + text.substring(offset)); + + // add the Function Block to the index of blockFunctions. + blockFunctions.put(fb.getStartOffset(), fb); + } + return toReturn; + } + return null; } - private String buildFunction(PythonTree child) - { - String callName = ""; - - callName = buildFunctionRecursive(callName, child); - if (!callName.isEmpty()) - { - // removes the last dot - if (callName.startsWith(".")) - callName = callName.substring(1); - } - if (callName.endsWith(".")) - callName = callName.substring(0, callName.length() - 1); - return callName; + private String buildFunction(final PythonTree child) { + String callName = ""; + + callName = buildFunctionRecursive(callName, child); + if (!callName.isEmpty()) { + // removes the last dot + if (callName.startsWith(".")) + callName = callName.substring(1); + } + if (callName.endsWith(".")) + callName = callName.substring(0, callName.length() - 1); + return callName; } - private String buildFunctionRecursive(String callName, PythonTree n) - { - if (n != null) - { - // int type = n.getAntlrType(); - if (n instanceof Call) - { - Call fn = ((Call) n); - String args = ""; - args += "("; - int i = 0; - for (expr exp : fn.getInternalArgs()) - { - if (i != 0) - args += ","; - VariableType typeC = resolveType(exp); - if (typeC != null && typeC.getClazz() != null) - args += typeC.getClazz().getName(); - else - args += "unknown"; - i++; - } - args += ")"; - String functionName = ""; - PyObject target = fn.getFunc(); - String toReturn = ""; - if (target instanceof Attribute) - { - Attribute att = ((Attribute) target); - functionName = att.getAttr().toString(); - toReturn = functionName + args + "." + callName; - toReturn = buildFunctionRecursive(toReturn, (PythonTree) (att.getValue())); - } else if (target instanceof Name) - { - functionName = ((Name) target).getInternalId(); - toReturn = functionName + args + "." + callName; - } - // if (targetType == Token.NAME) - // { - // functionName = target.getString(); - // toReturn = functionName + args; - // } - // else if (targetType == Token.GETPROP) - // { - // functionName = ((PropertyGet) target).getRight().getString(); - // toReturn = buildFunctionRecursive(elem, ((PropertyGet) - // target).getLeft()) + "." + - // functionName - // + args; - // } - // else if (targetType == Token.GETELEM) - // { - // ElementGet get = (ElementGet) target; - // elem = buildFunctionRecursive("", get.getElement()); - // functionName = elem.substring(0, elem.indexOf('(')); - // String targetName = buildFunctionRecursive("", - // get.getTarget()); - // toReturn = targetName + "." + elem; - // } - // else - // toReturn = elem; - int rp = fn.getCharStopIndex(); - if (DEBUG) - System.out.println("function found:" + functionName); - IcyFunctionBlock fb = new IcyFunctionBlock(functionName, rp, null); - functionBlocksToResolve.add(fb); - return toReturn; - } else if (n instanceof Name) - { - callName = ((Name) n).getInternalId() + "." + callName; - } - - } - return callName; + private String buildFunctionRecursive(String callName, final PythonTree n) { + if (n != null) { + // int type = n.getAntlrType(); + if (n instanceof Call) { + final Call fn = ((Call) n); + final StringBuilder args = new StringBuilder("("); + int i = 0; + for (final expr exp : fn.getInternalArgs()) { + if (i != 0) + args.append(","); + final VariableType typeC = resolveType(exp); + if (typeC != null && typeC.getClazz() != null) + args.append(typeC.getClazz().getName()); + else + args.append("unknown"); + i++; + } + args.append(")"); + String functionName = ""; + final PyObject target = fn.getFunc(); + String toReturn = ""; + if (target instanceof Attribute) { + final Attribute att = ((Attribute) target); + functionName = att.getAttr().toString(); + toReturn = functionName + args + "." + callName; + toReturn = buildFunctionRecursive(toReturn, (PythonTree) (att.getValue())); + } + else if (target instanceof Name) { + functionName = ((Name) target).getInternalId(); + toReturn = functionName + args + "." + callName; + } + // if (targetType == Token.NAME) + // { + // functionName = target.getString(); + // toReturn = functionName + args; + // } + // else if (targetType == Token.GETPROP) + // { + // functionName = ((PropertyGet) target).getRight().getString(); + // toReturn = buildFunctionRecursive(elem, ((PropertyGet) + // target).getLeft()) + "." + + // functionName + // + args; + // } + // else if (targetType == Token.GETELEM) + // { + // ElementGet get = (ElementGet) target; + // elem = buildFunctionRecursive("", get.getElement()); + // functionName = elem.substring(0, elem.indexOf('(')); + // String targetName = buildFunctionRecursive("", + // get.getTarget()); + // toReturn = targetName + "." + elem; + // } + // else + // toReturn = elem; + final int rp = fn.getCharStopIndex(); + if (DEBUG) + System.out.println("function found:" + functionName); + final IcyFunctionBlock fb = new IcyFunctionBlock(functionName, rp, null); + functionBlocksToResolve.add(fb); + return toReturn; + } + else if (n instanceof Name) { + callName = ((Name) n).getInternalId() + "." + callName; + } + + } + return callName; } - public void dumpTree(PythonTree node, String decal) - { - if (node == null) - return; - System.out.println(decal + node.getType().getName()); - List<PythonTree> children = node.getChildren(); - if (children == null) - return; - for (PythonTree child : children) - { - dumpTree(child, decal + "\t"); - } + public void dumpTree(final PythonTree node, final String decal) { + if (node == null) + return; + System.out.println(decal + node.getType().getName()); + final List<PythonTree> children = node.getChildren(); + if (children == null) + return; + for (final PythonTree child : children) { + dumpTree(child, decal + "\t"); + } } @Override - public void registerImports() - { - aliases.clear(); - modules.clear(); + public void registerImports() { + aliases.clear(); + modules.clear(); } - private void registerImports(PythonTree node) - { - if (node instanceof Import) - { - registerImportsTree((Import) node); - } else if (node instanceof ImportFrom) - { - registerImportsTree((ImportFrom) node); - } - List<PythonTree> children = node.getChildren(); - if (children != null) - { - for (PythonTree child : children) - registerImports(child); - } + private void registerImports(final PythonTree node) { + if (node instanceof Import) { + registerImportsTree((Import) node); + } + else if (node instanceof ImportFrom) { + registerImportsTree((ImportFrom) node); + } + final List<PythonTree> children = node.getChildren(); + if (children != null) { + for (final PythonTree child : children) + registerImports(child); + } } - private void registerImportsTree(Import tree) - { - // TODO handle modules - List<alias> imports = tree.getInternalNames(); - for (alias a : imports) - { - String alias = a.getInternalAsname(); - String classOrModule = a.getName().toString(); - File moduleFile; - if (alias == null && !classOrModule.contains(".") && (moduleFile = isModule(classOrModule)) != null) - { - // insert modle TODO - modules.put(classOrModule, moduleFile); - - // int pos = currentText.indexOf(classOrModule); - - PythonModuleCompletion mc = new PythonModuleCompletion(provider, classOrModule); - mc.setRelevance(RELEVANCE_HIGH); - variableCompletions.add(mc); - - if (DEBUG) - System.out.println("Module found : " + classOrModule); - } else - { - if (alias != null) - aliases.put(a.getInternalAsname().toString(), classOrModule); - scriptDeclaredImportClasses.add(classOrModule); - } - } + private void registerImportsTree(final Import tree) { + // TODO handle modules + final List<alias> imports = tree.getInternalNames(); + for (final alias a : imports) { + final String alias = a.getInternalAsname(); + final String classOrModule = a.getName().toString(); + final File moduleFile; + if (alias == null && !classOrModule.contains(".") && (moduleFile = isModule(classOrModule)) != null) { + // TODO: insert module + modules.put(classOrModule, moduleFile); + + // int pos = currentText.indexOf(classOrModule); + + final PythonModuleCompletion mc = new PythonModuleCompletion(provider, classOrModule); + mc.setRelevance(RELEVANCE_HIGH); + variableCompletions.add(mc); + + if (DEBUG) + System.out.println("Module found : " + classOrModule); + } + else { + if (alias != null) + aliases.put(a.getInternalAsname(), classOrModule); + scriptDeclaredImportClasses.add(classOrModule); + } + } } - private File isModule(String value) - { - // Look into the current folder - File f = new File(FileUtil.getDirectory(fileName) + value + ".py"); - if (f.exists()) - return f; - - // Look into the sys.path - PyList paths = ((PyScriptEngine) getEngine()).getPythonInterpreter().getSystemState().path; - for (PyObject o : paths.getArray()) - { - String path = o.toString(); - if (!path.startsWith("_")) - { - f = new File(path + File.separator + value + ".py"); - if (f.exists()) - return f; - } - } - return null; + private File isModule(final String value) { + // Look into the current folder + File f = new File(FileUtil.getDirectory(fileName) + value + ".py"); + if (f.exists()) + return f; + + // Look into the sys.path + final PyList paths = ((PyScriptEngine) getEngine()).getPythonInterpreter().getSystemState().path; + for (final PyObject o : paths.getArray()) { + final String path = o.toString(); + if (!path.startsWith("_")) { + f = new File(path + File.separator + value + ".py"); + if (f.exists()) + return f; + } + } + return null; } - private void registerImportsTree(ImportFrom tree) - { - List<PythonTree> children = tree.getChildren(); - String sPackage = ""; - for (PythonTree child : children) - { - if (!sPackage.isEmpty()) - sPackage += "."; - sPackage += child.getText(); - } - - List<alias> imports = tree.getInternalNames(); - for (alias a : imports) - { - String alias = a.getInternalAsname(); - scriptDeclaredImportClasses.add(a.getName().toString()); - if (alias != null) - aliases.put(sPackage + "." + a.getInternalAsname().toString(), a.getName().toString()); - } + private void registerImportsTree(final ImportFrom tree) { + final List<PythonTree> children = tree.getChildren(); + final StringBuilder sPackage = new StringBuilder(); + for (final PythonTree child : children) { + if (sPackage.length() > 0) + sPackage.append("."); + sPackage.append(child.getText()); + } + + final List<alias> imports = tree.getInternalNames(); + for (final alias a : imports) { + final String alias = a.getInternalAsname(); + scriptDeclaredImportClasses.add(a.getName().toString()); + if (alias != null) + aliases.put(sPackage + "." + a.getInternalAsname(), a.getName().toString()); + } } @Override - public void organizeImports(JTextComponent textArea2) - { - } + public void organizeImports(final JTextComponent textArea2) {} @Override - public void format() - { - // TODO + public void format() { + // TODO } @Override - public void installMethods(ScriptEngine engine, ArrayList<Method> functions) - { - } + public void installMethods(final ScriptEngine engine, final ArrayList<Method> functions) {} @Override - public ScriptEngine getEngine() - { - return ScriptEngineHandler.getEngine("python"); + public ScriptEngine getEngine() { + return ScriptEngineHandler.getEngine("python"); } /** * Fix: Issue with same name functions, will always use the first one. - * + * * @param clazz * @param function * @param argsClazzes - * @param commandStartOffset - * @param commandEndOffset * @return */ - private static Class<?>[] getGenericNumberTypes(String text, PythonTree child, Class<?> clazz, String function, Class<?>[] argsClazzes) - { - Class<?>[] toReturn = new Class<?>[argsClazzes.length]; - String fullCommand = text.substring(child.getCharStartIndex(), child.getCharStopIndex()); - int idxStart = fullCommand.indexOf(function); - - if (idxStart == -1) - return argsClazzes; - - int idxP1 = fullCommand.indexOf('(', idxStart); - int idxP2 = fullCommand.indexOf(')', idxStart); - - if (idxP1 == -1 || idxP2 == -1) - return argsClazzes; - - String argumentsChained = fullCommand.substring(idxP1 + 1, idxP2); - String[] args = argumentsChained.split(","); - - if (args.length != argsClazzes.length) - return argsClazzes; - - // FIXME here - boolean hasNumber = false; - for (int i = 0; i < argsClazzes.length; ++i) - { - if (argsClazzes[i] == Number.class) - hasNumber = true; - toReturn[i] = argsClazzes[i]; - } - if (hasNumber) - { - for (Method m : clazz.getMethods()) - { - if (m.getName().contentEquals(function)) - { - Class<?> params[] = m.getParameterTypes(); - if (params.length == argsClazzes.length) - { - for (int i = 0; i < params.length; ++i) - { - if (params[i] == null || argsClazzes[i] == null) - break; - if (params[i].isAssignableFrom(argsClazzes[i])) - toReturn[i] = params[i]; - else if (params[i].isPrimitive()) - { - if (!(params[i] == float.class || params[i] == double.class) && !args[i].contains(".")) - toReturn[i] = params[i]; - else if (params[i] == float.class || params[i] == double.class) - toReturn[i] = params[i]; - else - break; - } else - break; - } - } - } - } - return toReturn; - } else - return toReturn; + private static Class<?>[] getGenericNumberTypes(final String text, final PythonTree child, final Class<?> clazz, final String function, final Class<?>[] argsClazzes) { + final Class<?>[] toReturn = new Class<?>[argsClazzes.length]; + final String fullCommand = text.substring(child.getCharStartIndex(), child.getCharStopIndex()); + final int idxStart = fullCommand.indexOf(function); + + if (idxStart == -1) + return argsClazzes; + + final int idxP1 = fullCommand.indexOf('(', idxStart); + final int idxP2 = fullCommand.indexOf(')', idxStart); + + if (idxP1 == -1 || idxP2 == -1) + return argsClazzes; + + final String argumentsChained = fullCommand.substring(idxP1 + 1, idxP2); + final String[] args = argumentsChained.split(","); + + if (args.length != argsClazzes.length) + return argsClazzes; + + // FIXME here + boolean hasNumber = false; + for (int i = 0; i < argsClazzes.length; ++i) { + if (argsClazzes[i] == Number.class) + hasNumber = true; + toReturn[i] = argsClazzes[i]; + } + if (hasNumber) { + for (final Method m : clazz.getMethods()) { + if (m.getName().contentEquals(function)) { + final Class<?>[] params = m.getParameterTypes(); + if (params.length == argsClazzes.length) { + for (int i = 0; i < params.length; ++i) { + if (params[i] == null || argsClazzes[i] == null) + break; + if (params[i].isAssignableFrom(argsClazzes[i])) + toReturn[i] = params[i]; + else if (params[i].isPrimitive()) { + if (!(params[i] == float.class || params[i] == double.class) && !args[i].contains(".")) + toReturn[i] = params[i]; + else if (params[i] == float.class || params[i] == double.class) + toReturn[i] = params[i]; + else + break; + } + else + break; + } + } + } + } + } + return toReturn; } - public HashMap<String, File> getModules() - { - return modules; + public HashMap<String, File> getModules() { + return modules; } @Override - public LinkGeneratorResult isLinkAtOffset(final RSyntaxTextArea textArea, int offs) - { - for (String s : modules.keySet()) - { - final String currentS = s; - final int offsetMod = textArea.getText().indexOf(s); - if (offs >= offsetMod && offs <= offsetMod + s.length()) - { - return new LinkGeneratorResult() - { - - @Override - public int getSourceOffset() - { - return offsetMod; - } - - @Override - public HyperlinkEvent execute() - { - String path = modules.get(currentS).getAbsolutePath(); - try - { - return new HyperlinkEvent(textArea, EventType.ACTIVATED, new URL(path), path); - } catch (MalformedURLException e) - { - return new HyperlinkEvent(textArea, EventType.ACTIVATED, null, path); - } - } - }; - } - } - return null; + public LinkGeneratorResult isLinkAtOffset(final RSyntaxTextArea textArea, final int offs) { + for (final String s : modules.keySet()) { + final int offsetMod = textArea.getText().indexOf(s); + if (offs >= offsetMod && offs <= offsetMod + s.length()) { + return new LinkGeneratorResult() { + + @Override + public int getSourceOffset() { + return offsetMod; + } + + @Override + public HyperlinkEvent execute() { + final String path = modules.get(s).getAbsolutePath(); + try { + return new HyperlinkEvent(textArea, EventType.ACTIVATED, new URL(path), path); + } + catch (final MalformedURLException e) { + return new HyperlinkEvent(textArea, EventType.ACTIVATED, null, path); + } + } + }; + } + } + return null; } } diff --git a/src/main/java/plugins/tprovoost/scripteditor/search/OnlineScriptProvider.java b/src/main/java/plugins/tprovoost/scripteditor/search/OnlineScriptProvider.java index 888e72866db525967a9e56bab7ce4ac4f9b13324..d2599a761624b0144c70c6bf23d07bea9547c683 100644 --- a/src/main/java/plugins/tprovoost/scripteditor/search/OnlineScriptProvider.java +++ b/src/main/java/plugins/tprovoost/scripteditor/search/OnlineScriptProvider.java @@ -6,17 +6,14 @@ import icy.plugin.interface_.PluginSearchProvider; import icy.search.SearchResultProducer; import plugins.tprovoost.scripteditor.main.ScriptEditorPlugin; -public class OnlineScriptProvider extends Plugin implements PluginSearchProvider, PluginBundled -{ +public class OnlineScriptProvider extends Plugin implements PluginSearchProvider, PluginBundled { @Override - public Class<? extends SearchResultProducer> getSearchProviderClass() - { + public Class<? extends SearchResultProducer> getSearchProviderClass() { return ScriptProvider.class; } @Override - public String getMainPluginClassName() - { + public String getMainPluginClassName() { return ScriptEditorPlugin.class.getName(); } } diff --git a/src/main/java/plugins/tprovoost/scripteditor/search/ScriptDescriptor.java b/src/main/java/plugins/tprovoost/scripteditor/search/ScriptDescriptor.java index 944ffceb0aec08383779b4d3558d78ca7cdbc90b..9c8365c24633f0ebbdae68d8e6189c073ce54ae4 100644 --- a/src/main/java/plugins/tprovoost/scripteditor/search/ScriptDescriptor.java +++ b/src/main/java/plugins/tprovoost/scripteditor/search/ScriptDescriptor.java @@ -10,103 +10,86 @@ import org.w3c.dom.Node; import plugins.tprovoost.scripteditor.main.ScriptEditorPlugin; -public class ScriptDescriptor implements XMLPersistent -{ - private String name; - private String description; - private String author; - private String url; - private String fileurl; - private String extension; - private String version; - - public ScriptDescriptor(Node node) - { - loadFromXML(node); - } - - public ScriptDescriptor(String name, String url) - { - this.name = name; - this.url = url; - } - - public String getName() - { - return name; - } - - public String getDescription() - { - return description; - } - - public String getExtension() - { - return extension; - } - - public String getAuthor() - { - return author; - } - - public String getVersion() - { - return version; - } - - public String getUrl() - { - return url; - } - - public String getFileUrl() - { - return fileurl; - } - - public void setName(String name) - { - this.name = name; - } - - public void setDescription(String description) - { - this.description = description; - } - - public void setAuthor(String author) - { - this.author = author; - } - - public void setUrl(String url) - { - this.url = url; - } - - @Override - public boolean loadFromXML(Node node) - { - this.name = XMLUtil.getValue(XMLUtil.getElement(node, "name"), "No name"); - this.author = XMLUtil.getValue(XMLUtil.getElement(node, "author"), "No author"); - this.url = XMLUtil.getValue(XMLUtil.getElement(node, "url"), ""); - this.fileurl = XMLUtil.getValue(XMLUtil.getElement(node, "fileurl"), ""); - this.description = XMLUtil.getValue(XMLUtil.getElement(node, "shortDescription"), "No description"); - this.extension = XMLUtil.getValue(XMLUtil.getElement(node, "language"), "js"); - this.version = XMLUtil.getValue(XMLUtil.getElement(node, "version"), "1"); - return true; - } - - @Override - public boolean saveToXML(Node node) - { - return false; - } - - public ImageIcon getIcon() - { - return PluginLoader.getPlugin(ScriptEditorPlugin.class.getName()).getIcon(); - } +public class ScriptDescriptor implements XMLPersistent { + private String name; + private String description; + private String author; + private String url; + private String fileurl; + private String extension; + private String version; + + public ScriptDescriptor(final Node node) { + loadFromXML(node); + } + + public ScriptDescriptor(final String name, final String url) { + this.name = name; + this.url = url; + } + + public String getName() { + return name; + } + + public String getDescription() { + return description; + } + + public String getExtension() { + return extension; + } + + public String getAuthor() { + return author; + } + + public String getVersion() { + return version; + } + + public String getUrl() { + return url; + } + + public String getFileUrl() { + return fileurl; + } + + public void setName(final String name) { + this.name = name; + } + + public void setDescription(final String description) { + this.description = description; + } + + public void setAuthor(final String author) { + this.author = author; + } + + public void setUrl(final String url) { + this.url = url; + } + + @Override + public boolean loadFromXML(final Node node) { + this.name = XMLUtil.getValue(XMLUtil.getElement(node, "name"), "No name"); + this.author = XMLUtil.getValue(XMLUtil.getElement(node, "author"), "No author"); + this.url = XMLUtil.getValue(XMLUtil.getElement(node, "url"), ""); + this.fileurl = XMLUtil.getValue(XMLUtil.getElement(node, "fileurl"), ""); + this.description = XMLUtil.getValue(XMLUtil.getElement(node, "shortDescription"), "No description"); + this.extension = XMLUtil.getValue(XMLUtil.getElement(node, "language"), "js"); + this.version = XMLUtil.getValue(XMLUtil.getElement(node, "version"), "1"); + return true; + } + + @Override + public boolean saveToXML(final Node node) { + return false; + } + + public ImageIcon getIcon() { + return PluginLoader.getPlugin(ScriptEditorPlugin.class.getName()).getIcon(); + } } diff --git a/src/main/java/plugins/tprovoost/scripteditor/search/ScriptProvider.java b/src/main/java/plugins/tprovoost/scripteditor/search/ScriptProvider.java index 7b38f30339e1480bd3b91c9cb10d2ec5ff30daae..61570a6c8b0156e72940cef15681cb2e224e3093 100644 --- a/src/main/java/plugins/tprovoost/scripteditor/search/ScriptProvider.java +++ b/src/main/java/plugins/tprovoost/scripteditor/search/ScriptProvider.java @@ -24,50 +24,53 @@ import icy.util.StringUtil; import icy.util.XMLUtil; import plugins.tprovoost.scripteditor.main.ScriptEditorPlugin; -public class ScriptProvider extends SearchResultProducer -{ +public class ScriptProvider extends SearchResultProducer { private static final String SEARCH_URL = NetworkUtil.WEBSITE_URL + "search/search.php?search="; private static final String ID_SEARCH_RESULT = "searchresult"; private static final String ID_SCRIPT = "script"; private static final String ID_TEXT = "string"; - private final long REQUEST_INTERVAL = 400; - @Override - public String getName() - { + public String getName() { return "Scripts"; } @Override - public String getTooltipText() - { + public String getTooltipText() { return "Result(s) from online scripts"; } @Override - public void doSearch(String[] words, SearchResultConsumer consumer) - { - String request = SEARCH_URL; + @SuppressWarnings("deprecation") + public void doSearch(final String[] words, final SearchResultConsumer consumer) { + final StringBuilder request = new StringBuilder(SEARCH_URL); if (words.length > 0) - request += words[0].replace("+", "%2B").replace("&", "%26").replace("@", "%40").replace("<", "%3C") - .replace(">", "%3E"); - if (words.length > 1) - { + request.append( + words[0].replace("+", "%2B") + .replace("&", "%26") + .replace("@", "%40") + .replace("<", "%3C") + .replace(">", "%3E") + ); + if (words.length > 1) { for (int i = 1; i < words.length; i++) - request += "%20" + words[i].replace("+", "%2B").replace("&", "%26").replace("@", "%40") - .replace("<", "%3C").replace(">", "%3E"); + request.append("%20").append( + words[i].replace("+", "%2B") + .replace("&", "%26") + .replace("@", "%40") + .replace("<", "%3C") + .replace(">", "%3E") + ); } final long startTime = System.currentTimeMillis(); // wait interval elapsed before sending request (avoid website request // spam) - while ((System.currentTimeMillis() - startTime) < REQUEST_INTERVAL) - { - ThreadUtil.sleep(10); + while ((System.currentTimeMillis() - startTime) < 400L) { + ThreadUtil.sleep(10L); // abort if (hasWaitingSearch()) return; @@ -77,11 +80,9 @@ public class ScriptProvider extends SearchResultProducer int retry = 0; // let's 10 try to get the result - while ((doc == null) && (retry < 10)) - { - // we use an online request as website can search in plugin - // documention - doc = XMLUtil.loadDocument(URLUtil.getURL(request), false); + while ((doc == null) && (retry < 10)) { + // we use an online request as website can search in plugin documentation + doc = XMLUtil.loadDocument(URLUtil.getURL(request.toString()), false); // abort if (hasWaitingSearch()) @@ -89,7 +90,7 @@ public class ScriptProvider extends SearchResultProducer // error ? --> wait a bit before retry if (doc == null) - ThreadUtil.sleep(100); + ThreadUtil.sleep(100L); retry++; } @@ -98,8 +99,7 @@ public class ScriptProvider extends SearchResultProducer if (doc == null) return; - if (hasWaitingSearch()) - { + if (hasWaitingSearch()) { return; } @@ -109,10 +109,9 @@ public class ScriptProvider extends SearchResultProducer if (resultElement == null) return; - final ArrayList<SearchResult> tmpResults = new ArrayList<SearchResult>(); + final ArrayList<SearchResult> tmpResults = new ArrayList<>(); - for (Element script : XMLUtil.getElements(resultElement, ID_SCRIPT)) - { + for (final Element script : XMLUtil.getElements(resultElement, ID_SCRIPT)) { // abort if (getClass().getClassLoader() != SystemUtil.getSystemClassLoader() && hasWaitingSearch()) return; @@ -127,63 +126,54 @@ public class ScriptProvider extends SearchResultProducer consumer.resultsChanged(this); } - private OnlineScriptResult getResult(Element scriptNode, String words[]) - { + private OnlineScriptResult getResult(final Element scriptNode, final String[] words) { final String text = XMLUtil.getElementValue(scriptNode, ID_TEXT, ""); - ScriptDescriptor script = new ScriptDescriptor(scriptNode); + final ScriptDescriptor script = new ScriptDescriptor(scriptNode); return new OnlineScriptResult(this, script, text, words); } - private class OnlineScriptResult extends SearchResult - { + private static class OnlineScriptResult extends SearchResult { - private ScriptDescriptor script; + private final ScriptDescriptor script; private String description; - public OnlineScriptResult(ScriptProvider scriptProvider, ScriptDescriptor script, String text, - String[] searchWords) - { + public OnlineScriptResult(final ScriptProvider scriptProvider, final ScriptDescriptor script, final String text, final String[] searchWords) { super(scriptProvider); this.script = script; int wi = 0; description = ""; - while (StringUtil.isEmpty(description) && (wi < searchWords.length)) - { + while (StringUtil.isEmpty(description) && (wi < searchWords.length)) { // no more than 80 characters... description = StringUtil.trunc(text, searchWords[wi], 80); wi++; } - if (!StringUtil.isEmpty(description)) - { + if (!StringUtil.isEmpty(description)) { // remove carriage return description = description.replace("\n", ""); // highlight search keywords (only for more than 2 characters // search) - if ((searchWords.length > 1) || (searchWords[0].length() > 2)) - { + if ((searchWords.length > 1) || (searchWords[0].length() > 2)) { // highlight search keywords - for (String word : searchWords) + for (final String word : searchWords) description = StringUtil.htmlBoldSubstring(description, word, true); } } } @Override - public String getTitle() - { + public String getTitle() { return script.getName(); } @Override - public Image getImage() - { - ImageIcon icon = script.getIcon(); + public Image getImage() { + final ImageIcon icon = script.getIcon(); if (icon != null) return icon.getImage(); @@ -191,65 +181,44 @@ public class ScriptProvider extends SearchResultProducer } @Override - public String getDescription() - { + public String getDescription() { return description; } @Override - public String getTooltip() - { + public String getTooltip() { return "Left click: Open - Right click: Online documentation"; } @Override - public void execute() - { - ThreadUtil.bgRun(new Runnable() - { - @Override - public void run() - { - final String name = script.getName() + " v" + script.getVersion() + "." + script.getExtension(); - final DownloadFrame frameDownload = new DownloadFrame(name); - try - { - byte[] data = NetworkUtil.download(new URL(script.getFileUrl()), frameDownload, true); - - if (data != null) - { - final String s = new String(data); - ThreadUtil.invokeLater(new Runnable() - { - @Override - public void run() - { - ScriptEditorPlugin.openInScriptEditor(s, name); - } - }); - } - } - catch (MalformedURLException e1) - { - new FailedAnnounceFrame("Could not load the script :" + e1.getMessage()); - } - finally - { - frameDownload.close(); + public void execute() { + ThreadUtil.bgRun(() -> { + final String name = script.getName() + " v" + script.getVersion() + "." + script.getExtension(); + final DownloadFrame frameDownload = new DownloadFrame(name); + try { + final byte[] data = NetworkUtil.download(new URL(script.getFileUrl()), frameDownload, true); + + if (data != null) { + final String s = new String(data); + ThreadUtil.invokeLater(() -> ScriptEditorPlugin.openInScriptEditor(s, name)); } } + catch (final MalformedURLException e) { + new FailedAnnounceFrame("Could not load the script :" + e.getMessage()); + } + finally { + frameDownload.close(); + } }); } @Override - public void executeAlternate() - { + public void executeAlternate() { NetworkUtil.openBrowser(script.getUrl()); } @Override - public RichTooltip getRichToolTip() - { + public RichTooltip getRichToolTip() { return new ScriptRichToolTip(script); } } diff --git a/src/main/java/plugins/tprovoost/scripteditor/search/ScriptRichToolTip.java b/src/main/java/plugins/tprovoost/scripteditor/search/ScriptRichToolTip.java index fbdd7c8403224f15da961473bee213c2247f5e8c..6a73832f8c5d2835306432dd2b6f5702f93ecbcc 100644 --- a/src/main/java/plugins/tprovoost/scripteditor/search/ScriptRichToolTip.java +++ b/src/main/java/plugins/tprovoost/scripteditor/search/ScriptRichToolTip.java @@ -7,11 +7,9 @@ import javax.swing.ImageIcon; import org.pushingpixels.flamingo.api.common.RichTooltip; -public class ScriptRichToolTip extends RichTooltip -{ +public class ScriptRichToolTip extends RichTooltip { - public ScriptRichToolTip(ScriptDescriptor script) - { + public ScriptRichToolTip(final ScriptDescriptor script) { final String name = script.getName(); final String description = script.getDescription(); final String website = script.getUrl(); @@ -23,9 +21,8 @@ public class ScriptRichToolTip extends RichTooltip if (plugIcon != PluginDescriptor.DEFAULT_ICON) setMainImage(plugIcon.getImage()); - if (!StringUtil.isEmpty(description)) - { - for (String str : description.split("\n")) + if (!StringUtil.isEmpty(description)) { + for (final String str : description.split("\n")) if (!StringUtil.isEmpty(str)) addDescriptionSection(str); } diff --git a/src/main/java/plugins/tprovoost/scripteditor/uitools/filedialogs/FileDialog.java b/src/main/java/plugins/tprovoost/scripteditor/uitools/filedialogs/FileDialog.java index 5b95551a6897ed93d89308ba382722458745223d..901ced61bca135669fb273f7f866b1c757adf934 100644 --- a/src/main/java/plugins/tprovoost/scripteditor/uitools/filedialogs/FileDialog.java +++ b/src/main/java/plugins/tprovoost/scripteditor/uitools/filedialogs/FileDialog.java @@ -9,189 +9,160 @@ import java.io.File; import javax.swing.JFileChooser; import javax.swing.filechooser.FileNameExtensionFilter; -public class FileDialog -{ - - public static File open() - { - return open(null); - } - - public static File open(String currentDirectory) - { - return open(currentDirectory, "", new String[0]); - } - - public static File open(String currentDirectory, String filterDesc, String... ext) - { - FileDialogAWT fcawt = new FileDialogAWT(false, currentDirectory, filterDesc, ext); - while (!fcawt.isReady()) - ThreadUtil.sleep(100); - JFileChooser fc = fcawt.fc; - int res = fcawt.result; - - if (res == JFileChooser.APPROVE_OPTION) - return fc.getSelectedFile(); - - return null; - } - - public static File openFolder() - { - return openFolder(""); - } - - public static File openFolder(String currentDirectory) - { - FileDialogAWT fcawt = new FileDialogAWT(false, currentDirectory, "", new String[0]); - fcawt.setFolderOnly(true); - while (!fcawt.isReady()) - ThreadUtil.sleep(100); - JFileChooser fc = fcawt.fc; - int res = fcawt.result; - - if (res == JFileChooser.APPROVE_OPTION) - return fc.getSelectedFile(); - - return null; - } - - public static File[] openMulti() - { - return openMulti(null); - } - - public static File[] openMulti(String currentDirectory) - { - return openMulti(currentDirectory, "", new String[0]); - } - - public static File[] openMulti(String currentDirectory, String filterDesc, String... ext) - { - FileDialogAWT fcawt = new FileDialogAWT(false, true, currentDirectory, filterDesc, ext); - while (!fcawt.isReady()) - ThreadUtil.sleep(100); - JFileChooser fc = fcawt.fc; - int res = fcawt.result; - - if (res == JFileChooser.APPROVE_OPTION) - return fc.getSelectedFiles(); - - return null; - } - - public static File save() - { - return save(null); - } - - public static File save(String currentDirectory) - { - return save(currentDirectory, "", new String[0]); - } - - public static File save(final String currentDirectory, final String filterDesc, final String... ext) - { - FileDialogAWT fcawt = new FileDialogAWT(true, currentDirectory, filterDesc, ext); - while (!fcawt.isReady()) - ThreadUtil.sleep(100); - JFileChooser fc = fcawt.fc; - int res = fcawt.result; - - if (res == JFileChooser.APPROVE_OPTION) - { - String s = fc.getSelectedFile().getAbsolutePath(); - if (FileUtil.getFileExtension(s, false).isEmpty() && ext != null && ext.length > 0) - { - new File(s + "." + ext[0]); - } else - { - return fc.getSelectedFile(); - } - } - return null; - } - - public static File saveFolder() - { - return saveFolder(null); - } - - public static File saveFolder(String currentDirectory) - { - FileDialogAWT fcawt = new FileDialogAWT(true, currentDirectory, "", new String[0]); - fcawt.setFolderOnly(true); - while (!fcawt.isReady()) - ThreadUtil.sleep(100); - JFileChooser fc = fcawt.fc; - int res = fcawt.result; - - if (res == JFileChooser.APPROVE_OPTION) - return fc.getSelectedFile(); - return null; - } - - private static class FileDialogAWT - { - private JFileChooser fc; - private int result; - private boolean ready; - private boolean folderOnly = false; - - public FileDialogAWT(final boolean save, final String currentDirectory, final String filterDesc, final String... ext) - { - this(save, false, currentDirectory, filterDesc, ext); - } - - public void setFolderOnly(boolean folderOnly) - { - this.folderOnly = folderOnly; - } - - public FileDialogAWT(final boolean save, final boolean multi, final String currentDirectory, final String filterDesc, final String[] ext) - { - setReady(false); - ThreadUtil.invokeLater(new Runnable() - { - @Override - public void run() - { - fc = new JFileChooser(currentDirectory); - if (folderOnly) - { - fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); - } else - { - if (ext != null && ext.length > 0) - fc.setFileFilter(new FileNameExtensionFilter(filterDesc, ext)); - fc.setMultiSelectionEnabled(multi); - } - if (save) - result = fc.showSaveDialog(Icy.getMainInterface().getMainFrame()); - else - result = fc.showOpenDialog(Icy.getMainInterface().getMainFrame()); - setReady(true); - } - }); - } - - /** - * @return the ready - */ - private boolean isReady() - { - return ready; - } - - /** - * @param ready - * the ready to set - */ - private void setReady(boolean ready) - { - this.ready = ready; - } - - } +public class FileDialog { + + public static File open() { + return open(null); + } + + public static File open(final String currentDirectory) { + return open(currentDirectory, ""); + } + + public static File open(final String currentDirectory, final String filterDesc, final String... ext) { + final FileDialogAWT fcawt = new FileDialogAWT(false, currentDirectory, filterDesc, ext); + while (!fcawt.isReady()) + ThreadUtil.sleep(100L); + final JFileChooser fc = fcawt.fc; + final int res = fcawt.result; + + if (res == JFileChooser.APPROVE_OPTION) + return fc.getSelectedFile(); + + return null; + } + + public static File openFolder() { + return openFolder(""); + } + + public static File openFolder(final String currentDirectory) { + final FileDialogAWT fcawt = new FileDialogAWT(false, currentDirectory, ""); + fcawt.setFolderOnly(true); + while (!fcawt.isReady()) + ThreadUtil.sleep(100L); + final JFileChooser fc = fcawt.fc; + final int res = fcawt.result; + + if (res == JFileChooser.APPROVE_OPTION) + return fc.getSelectedFile(); + + return null; + } + + public static File[] openMulti() { + return openMulti(null); + } + + public static File[] openMulti(final String currentDirectory) { + return openMulti(currentDirectory, ""); + } + + public static File[] openMulti(final String currentDirectory, final String filterDesc, final String... ext) { + final FileDialogAWT fcawt = new FileDialogAWT(false, true, currentDirectory, filterDesc, ext); + while (!fcawt.isReady()) + ThreadUtil.sleep(100L); + final JFileChooser fc = fcawt.fc; + final int res = fcawt.result; + + if (res == JFileChooser.APPROVE_OPTION) + return fc.getSelectedFiles(); + + return null; + } + + public static File save() { + return save(null); + } + + public static File save(final String currentDirectory) { + return save(currentDirectory, ""); + } + + public static File save(final String currentDirectory, final String filterDesc, final String... ext) { + final FileDialogAWT fcawt = new FileDialogAWT(true, currentDirectory, filterDesc, ext); + while (!fcawt.isReady()) + ThreadUtil.sleep(100L); + final JFileChooser fc = fcawt.fc; + final int res = fcawt.result; + + if (res == JFileChooser.APPROVE_OPTION) { + final String s = fc.getSelectedFile().getAbsolutePath(); + if (FileUtil.getFileExtension(s, false).isEmpty() && ext != null && ext.length > 0) { + new File(s + "." + ext[0]); + } + else { + return fc.getSelectedFile(); + } + } + return null; + } + + public static File saveFolder() { + return saveFolder(null); + } + + public static File saveFolder(final String currentDirectory) { + final FileDialogAWT fcawt = new FileDialogAWT(true, currentDirectory, ""); + fcawt.setFolderOnly(true); + while (!fcawt.isReady()) + ThreadUtil.sleep(100L); + final JFileChooser fc = fcawt.fc; + final int res = fcawt.result; + + if (res == JFileChooser.APPROVE_OPTION) + return fc.getSelectedFile(); + return null; + } + + private static class FileDialogAWT { + private JFileChooser fc; + private int result; + private boolean ready; + private boolean folderOnly = false; + + public FileDialogAWT(final boolean save, final String currentDirectory, final String filterDesc, final String... ext) { + this(save, false, currentDirectory, filterDesc, ext); + } + + public void setFolderOnly(final boolean folderOnly) { + this.folderOnly = folderOnly; + } + + public FileDialogAWT(final boolean save, final boolean multi, final String currentDirectory, final String filterDesc, final String[] ext) { + setReady(false); + ThreadUtil.invokeLater(() -> { + fc = new JFileChooser(currentDirectory); + if (folderOnly) { + fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); + } + else { + if (ext != null && ext.length > 0) + fc.setFileFilter(new FileNameExtensionFilter(filterDesc, ext)); + fc.setMultiSelectionEnabled(multi); + } + if (save) + result = fc.showSaveDialog(Icy.getMainInterface().getMainFrame()); + else + result = fc.showOpenDialog(Icy.getMainInterface().getMainFrame()); + setReady(true); + }); + } + + /** + * @return the ready + */ + private boolean isReady() { + return ready; + } + + /** + * @param ready the ready to set + */ + private void setReady(final boolean ready) { + this.ready = ready; + } + + } } diff --git a/src/main/java/plugins/tprovoost/scripteditor/uitools/userdialogs/Dialog.java b/src/main/java/plugins/tprovoost/scripteditor/uitools/userdialogs/Dialog.java index 0ff7c57192b26a988e0555c5223983ef48be9cf2..2f7532a17bfe6f2b550437dbacfbaf2f4a85df7d 100644 --- a/src/main/java/plugins/tprovoost/scripteditor/uitools/userdialogs/Dialog.java +++ b/src/main/java/plugins/tprovoost/scripteditor/uitools/userdialogs/Dialog.java @@ -4,8 +4,6 @@ import icy.main.Icy; import icy.system.thread.ThreadUtil; import java.awt.BorderLayout; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; import java.util.ArrayList; import java.util.LinkedList; @@ -16,249 +14,173 @@ import javax.swing.JButton; import javax.swing.JDialog; import javax.swing.JPanel; -public class Dialog -{ +public class Dialog { private static final int DEFAULT_COLUMN_SIZE = 8; - private ArrayList<Item> listItems = new ArrayList<Item>(); + private final ArrayList<Item> listItems = new ArrayList<>(); - private LinkedList<Item> listNumbers = new LinkedList<Item>(); - private LinkedList<Item> listStrings = new LinkedList<Item>(); - private LinkedList<Item> listcboxes = new LinkedList<Item>(); - private LinkedList<Item> listChoices = new LinkedList<Item>(); + private final LinkedList<Item> listNumbers = new LinkedList<>(); + private final LinkedList<Item> listStrings = new LinkedList<>(); + private final LinkedList<Item> listcboxes = new LinkedList<>(); + private final LinkedList<Item> listChoices = new LinkedList<>(); private boolean ok = false; private JDialog dialog; private boolean working; - public Dialog(final String name) - { - ThreadUtil.invokeLater(new Runnable() - { - - @Override - public void run() - { - dialog = new JDialog(Icy.getMainInterface().getMainFrame(), name); - } - }); + public Dialog(final String name) { + ThreadUtil.invokeLater(() -> dialog = new JDialog(Icy.getMainInterface().getMainFrame(), name)); } - public void addNumber(String label, double defaultValue) - { + public void addNumber(final String label, final double defaultValue) { addNumber(label, defaultValue, DEFAULT_COLUMN_SIZE, ""); } - public void addNumber(final String label, final double defaultValue, final int columns, final String unit) - { - ThreadUtil.invokeLater(new Runnable() - { - - @Override - public void run() - { - ItemNumber item = new ItemNumber(label, defaultValue, columns, unit); - listItems.add(item); - listNumbers.add(item); - } + public void addNumber(final String label, final double defaultValue, final int columns, final String unit) { + ThreadUtil.invokeLater(() -> { + final ItemNumber item = new ItemNumber(label, defaultValue, columns, unit); + listItems.add(item); + listNumbers.add(item); }); } - public void show() - { + public void show() { if (isWorking()) return; setWorking(true); - ThreadUtil.invokeLater(new Runnable() - { - @Override - public void run() - { - // generate the UI - dialog.setModal(true); - - // MIDDLE PANEL - JPanel panelMiddle = new JPanel(); - panelMiddle.setLayout(new BoxLayout(panelMiddle, BoxLayout.Y_AXIS)); - - for (Item item : listItems) - panelMiddle.add(item); - - // SOUTH PANEL - JPanel panelSouth = new JPanel(); - panelSouth.setLayout(new BoxLayout(panelSouth, BoxLayout.X_AXIS)); - - JButton btnOK = new JButton("OK"); - btnOK.addActionListener(new ActionListener() - { - - @Override - public void actionPerformed(ActionEvent e) - { - ok = true; - dialog.setVisible(false); - } - }); - - JButton btnCancel = new JButton("Cancel"); - btnCancel.addActionListener(new ActionListener() - { - - @Override - public void actionPerformed(ActionEvent e) - { - ok = false; - dialog.setVisible(false); - } - }); - - panelSouth.add(Box.createHorizontalGlue()); - panelSouth.add(btnOK); - panelSouth.add(Box.createHorizontalStrut(4)); - panelSouth.add(btnCancel); - - // CREATE CONTENT PANE - JPanel contentPane = new JPanel(new BorderLayout()); - contentPane.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10)); - contentPane.add(panelMiddle, BorderLayout.CENTER); - contentPane.add(panelSouth, BorderLayout.SOUTH); - - dialog.setContentPane(contentPane); - dialog.pack(); - dialog.setLocationRelativeTo(Icy.getMainInterface().getMainFrame()); - dialog.setVisible(true); - dialog = null; - - setWorking(false); - } + ThreadUtil.invokeLater(() -> { + // generate the UI + dialog.setModal(true); + + // MIDDLE PANEL + final JPanel panelMiddle = new JPanel(); + panelMiddle.setLayout(new BoxLayout(panelMiddle, BoxLayout.Y_AXIS)); + + for (final Item item : listItems) + panelMiddle.add(item); + + // SOUTH PANEL + final JPanel panelSouth = new JPanel(); + panelSouth.setLayout(new BoxLayout(panelSouth, BoxLayout.X_AXIS)); + + final JButton btnOK = new JButton("OK"); + btnOK.addActionListener(e -> { + ok = true; + dialog.setVisible(false); + }); + + final JButton btnCancel = new JButton("Cancel"); + btnCancel.addActionListener(e -> { + ok = false; + dialog.setVisible(false); + }); + + panelSouth.add(Box.createHorizontalGlue()); + panelSouth.add(btnOK); + panelSouth.add(Box.createHorizontalStrut(4)); + panelSouth.add(btnCancel); + + // CREATE CONTENT PANE + final JPanel contentPane = new JPanel(new BorderLayout()); + contentPane.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10)); + contentPane.add(panelMiddle, BorderLayout.CENTER); + contentPane.add(panelSouth, BorderLayout.SOUTH); + + dialog.setContentPane(contentPane); + dialog.pack(); + dialog.setLocationRelativeTo(Icy.getMainInterface().getMainFrame()); + dialog.setVisible(true); + dialog = null; + + setWorking(false); }); } - public boolean getResult() - { + public boolean getResult() { while (isWorking()) ThreadUtil.sleep(100); return ok; } - public void addMessage(String label) - { + public void addMessage(final String label) { listItems.add(new ItemMessage(label)); } - public void addString(final String label, final String initialText) - { - ThreadUtil.invokeLater(new Runnable() - { - @Override - public void run() - { - Item item = new ItemString(label, initialText); - listItems.add(item); - listStrings.add(item); - } + public void addString(final String label, final String initialText) { + ThreadUtil.invokeLater(() -> { + final Item item = new ItemString(label, initialText); + listItems.add(item); + listStrings.add(item); }); } - public void addString(final String label, final String initialText, final int columns) - { - ThreadUtil.invokeLater(new Runnable() - { - @Override - public void run() - { - Item item = new ItemString(label, initialText, columns); - listItems.add(item); - listStrings.add(item); - } + public void addString(final String label, final String initialText, final int columns) { + ThreadUtil.invokeLater(() -> { + final Item item = new ItemString(label, initialText, columns); + listItems.add(item); + listStrings.add(item); }); } - public void addSlider(final String label, final int min, final int max, final int defaultValue) - { - ThreadUtil.invokeLater(new Runnable() - { - @Override - public void run() - { - Item item = new ItemSlider(label, min, max, defaultValue); - listItems.add(item); - listNumbers.add(item); - } + public void addSlider(final String label, final int min, final int max, final int defaultValue) { + ThreadUtil.invokeLater(() -> { + final Item item = new ItemSlider(label, min, max, defaultValue); + listItems.add(item); + listNumbers.add(item); }); } - public void addCheckbox(final String label, final boolean defaultValue) - { - ThreadUtil.invokeLater(new Runnable() - { - @Override - public void run() - { - Item item = new ItemCheckbox(label, defaultValue); - listItems.add(item); - listcboxes.add(item); - } + public void addCheckbox(final String label, final boolean defaultValue) { + ThreadUtil.invokeLater(() -> { + final Item item = new ItemCheckbox(label, defaultValue); + listItems.add(item); + listcboxes.add(item); }); } - public void addChoice(String label, String[] items) - { + public void addChoice(final String label, final String[] items) { addChoice(label, items, items[0]); } - public void addChoice(final String label, final String[] items, final String defaultValue) - { - ThreadUtil.invokeLater(new Runnable() - { - @Override - public void run() - { - Item item = new ItemCombo(label, items, defaultValue); - listItems.add(item); - listChoices.add(item); - } + public void addChoice(final String label, final String[] items, final String defaultValue) { + ThreadUtil.invokeLater(() -> { + final Item item = new ItemCombo(label, items, defaultValue); + listItems.add(item); + listChoices.add(item); }); } - public Number getNumber() - { + public Number getNumber() { return (Number) listNumbers.pop().getValue(); } - public String getString() - { + public String getString() { return (String) listStrings.pop().getValue(); } - public Boolean getCheckBox() - { + public Boolean getCheckBox() { return (Boolean) listcboxes.pop().getValue(); } - public String getChoice() - { + public String getChoice() { return (String) listChoices.pop().getValue(); } /** * Returns if the current Dialog is being displayed. - * + * * @return working */ - private boolean isWorking() - { + private boolean isWorking() { return working; } /** * Synchronized setter. - * - * @param working - * the working to set + * + * @param working the working to set */ - private synchronized void setWorking(boolean working) - { + private synchronized void setWorking(final boolean working) { this.working = working; } } diff --git a/src/main/java/plugins/tprovoost/scripteditor/uitools/userdialogs/Item.java b/src/main/java/plugins/tprovoost/scripteditor/uitools/userdialogs/Item.java index 6327212ac44e55478ff24f101f60df130bc28236..cb545a562f02a986853aff91a6ee806bc5124fcf 100644 --- a/src/main/java/plugins/tprovoost/scripteditor/uitools/userdialogs/Item.java +++ b/src/main/java/plugins/tprovoost/scripteditor/uitools/userdialogs/Item.java @@ -3,12 +3,8 @@ package plugins.tprovoost.scripteditor.uitools.userdialogs; import javax.swing.BorderFactory; import javax.swing.JPanel; -public abstract class Item extends JPanel -{ - private static final long serialVersionUID = 1L; - - public Item() - { +public abstract class Item extends JPanel { + public Item() { setBorder(BorderFactory.createEmptyBorder(4, 4, 4, 4)); } diff --git a/src/main/java/plugins/tprovoost/scripteditor/uitools/userdialogs/ItemCheckbox.java b/src/main/java/plugins/tprovoost/scripteditor/uitools/userdialogs/ItemCheckbox.java index 72c6af618b74ea6867dd4c81243efd1dd245f073..69e78d07604c7a6c1d85d62ae8abc9b53835a9b0 100644 --- a/src/main/java/plugins/tprovoost/scripteditor/uitools/userdialogs/ItemCheckbox.java +++ b/src/main/java/plugins/tprovoost/scripteditor/uitools/userdialogs/ItemCheckbox.java @@ -5,13 +5,10 @@ import javax.swing.BoxLayout; import javax.swing.JCheckBox; import javax.swing.JLabel; -public class ItemCheckbox extends Item -{ - private static final long serialVersionUID = 1L; - private JCheckBox cbox; +public class ItemCheckbox extends Item { + private final JCheckBox cbox; - public ItemCheckbox(String name, boolean defaultValue) - { + public ItemCheckbox(final String name, final boolean defaultValue) { setLayout(new BoxLayout(this, BoxLayout.X_AXIS)); cbox = new JCheckBox(); cbox.setSelected(defaultValue); @@ -22,9 +19,7 @@ public class ItemCheckbox extends Item } @Override - public Boolean getValue() - { + public Boolean getValue() { return cbox.isSelected(); } - } diff --git a/src/main/java/plugins/tprovoost/scripteditor/uitools/userdialogs/ItemCombo.java b/src/main/java/plugins/tprovoost/scripteditor/uitools/userdialogs/ItemCombo.java index b7fb91fa034fcf20397baf5bf99e4ed057b919d6..be958c3cdaa98608468f8de0297ccf75e5285b39 100644 --- a/src/main/java/plugins/tprovoost/scripteditor/uitools/userdialogs/ItemCombo.java +++ b/src/main/java/plugins/tprovoost/scripteditor/uitools/userdialogs/ItemCombo.java @@ -5,20 +5,16 @@ import javax.swing.BoxLayout; import javax.swing.JComboBox; import javax.swing.JLabel; -public class ItemCombo extends Item -{ - private static final long serialVersionUID = 1L; - private JComboBox combo; +public class ItemCombo extends Item { + private final JComboBox<String> combo; - public ItemCombo(String name, String[] items) - { + public ItemCombo(final String name, final String[] items) { this(name, items, items[0]); } - public ItemCombo(String name, String[] items, String defaultValue) - { + public ItemCombo(final String name, final String[] items, final String defaultValue) { setLayout(new BoxLayout(this, BoxLayout.X_AXIS)); - combo = new JComboBox(items); + combo = new JComboBox<>(items); combo.setSelectedItem(defaultValue); add(new JLabel(name)); add(Box.createHorizontalStrut(4)); @@ -27,9 +23,7 @@ public class ItemCombo extends Item } @Override - public String getValue() - { + public String getValue() { return (String) combo.getSelectedItem(); } - } diff --git a/src/main/java/plugins/tprovoost/scripteditor/uitools/userdialogs/ItemMessage.java b/src/main/java/plugins/tprovoost/scripteditor/uitools/userdialogs/ItemMessage.java index 7b2e2033973b4ebf60d1c8da4192ef60dc2b26ff..6256f6350b4b006335e8f015631a9cb16b474fa7 100644 --- a/src/main/java/plugins/tprovoost/scripteditor/uitools/userdialogs/ItemMessage.java +++ b/src/main/java/plugins/tprovoost/scripteditor/uitools/userdialogs/ItemMessage.java @@ -4,21 +4,15 @@ import javax.swing.Box; import javax.swing.BoxLayout; import javax.swing.JLabel; -public class ItemMessage extends Item -{ - private static final long serialVersionUID = 1L; - - public ItemMessage(String name) - { +public class ItemMessage extends Item { + public ItemMessage(final String name) { setLayout(new BoxLayout(this, BoxLayout.X_AXIS)); add(new JLabel(name)); add(Box.createHorizontalGlue()); } @Override - public String getValue() - { + public String getValue() { return ""; } - } diff --git a/src/main/java/plugins/tprovoost/scripteditor/uitools/userdialogs/ItemNumber.java b/src/main/java/plugins/tprovoost/scripteditor/uitools/userdialogs/ItemNumber.java index 404c17094d9fa8679a6e5e1b3bae51a44cc7b551..75e05e608b7976c050af8c91defec662052e2434 100644 --- a/src/main/java/plugins/tprovoost/scripteditor/uitools/userdialogs/ItemNumber.java +++ b/src/main/java/plugins/tprovoost/scripteditor/uitools/userdialogs/ItemNumber.java @@ -5,17 +5,14 @@ import javax.swing.BoxLayout; import javax.swing.JLabel; import javax.swing.JTextField; -public class ItemNumber extends Item -{ - private static final long serialVersionUID = 1L; - private JTextField tf; +public class ItemNumber extends Item { + private final JTextField tf; - public ItemNumber(final String name, final double valueDefault, final int columns, final String unit) - { + public ItemNumber(final String name, final double valueDefault, final int columns, final String unit) { setLayout(new BoxLayout(ItemNumber.this, BoxLayout.X_AXIS)); tf = new JTextField(columns); - tf.setText("" + valueDefault); + tf.setText(String.valueOf(valueDefault)); add(new JLabel(name)); add(Box.createHorizontalStrut(4)); @@ -26,9 +23,7 @@ public class ItemNumber extends Item } @Override - public Double getValue() - { + public Double getValue() { return Double.parseDouble(tf.getText()); } - } diff --git a/src/main/java/plugins/tprovoost/scripteditor/uitools/userdialogs/ItemSlider.java b/src/main/java/plugins/tprovoost/scripteditor/uitools/userdialogs/ItemSlider.java index 3973914ecd19a46c13dc652b4d5c3d1e4ca5b418..e1ec5d20a2b5108c7349a2d096dc693d6df7140f 100644 --- a/src/main/java/plugins/tprovoost/scripteditor/uitools/userdialogs/ItemSlider.java +++ b/src/main/java/plugins/tprovoost/scripteditor/uitools/userdialogs/ItemSlider.java @@ -6,37 +6,29 @@ import javax.swing.JSlider; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; -public class ItemSlider extends Item -{ - private static final long serialVersionUID = 1L; - private JSlider spinner; - private JLabel lblValue; +public class ItemSlider extends Item { + private final JSlider spinner; + private final JLabel lblValue; - public ItemSlider(String name, int min, int max, int defaultValue) - { + public ItemSlider(final String name, final int min, final int max, final int defaultValue) { setLayout(new BoxLayout(this, BoxLayout.X_AXIS)); add(new JLabel(name)); spinner = new JSlider(min, max, defaultValue); - spinner.addChangeListener(new ChangeListener() - { - + spinner.addChangeListener(new ChangeListener() { @Override - public void stateChanged(ChangeEvent e) - { - lblValue.setText("" + spinner.getValue()); + public void stateChanged(final ChangeEvent e) { + lblValue.setText(String.valueOf(spinner.getValue())); } }); add(spinner); - lblValue = new JLabel("" + defaultValue); + lblValue = new JLabel(String.valueOf(defaultValue)); add(lblValue); } @Override - public Integer getValue() - { + public Integer getValue() { return spinner.getValue(); } - } diff --git a/src/main/java/plugins/tprovoost/scripteditor/uitools/userdialogs/ItemString.java b/src/main/java/plugins/tprovoost/scripteditor/uitools/userdialogs/ItemString.java index 7b8c855fbe7401e17119a6f60d586a3a97d3550d..bcdc6950d8ef836cda25dae730ed74377c2efd80 100644 --- a/src/main/java/plugins/tprovoost/scripteditor/uitools/userdialogs/ItemString.java +++ b/src/main/java/plugins/tprovoost/scripteditor/uitools/userdialogs/ItemString.java @@ -5,13 +5,10 @@ import javax.swing.BoxLayout; import javax.swing.JLabel; import javax.swing.JTextField; -public class ItemString extends Item -{ - private static final long serialVersionUID = 1L; - private JTextField tf; +public class ItemString extends Item { + private final JTextField tf; - public ItemString(final String name, final String initialText) - { + public ItemString(final String name, final String initialText) { setLayout(new BoxLayout(ItemString.this, BoxLayout.X_AXIS)); add(new JLabel(name)); add(Box.createHorizontalStrut(4)); @@ -20,19 +17,17 @@ public class ItemString extends Item add(Box.createHorizontalGlue()); } - public ItemString(String name, String initialText, int columns) - { + public ItemString(final String name, final String initialText, final int columns) { setLayout(new BoxLayout(this, BoxLayout.X_AXIS)); add(new JLabel(name)); add(Box.createHorizontalStrut(4)); - add(new JTextField(initialText, columns)); + tf = new JTextField(initialText, columns); + add(tf); add(Box.createHorizontalGlue()); } @Override - public String getValue() - { + public String getValue() { return tf.getText(); } - }