# Scripts

All configurable beans on the [Installer->Screens & Actions](../beans/screensAndActions.md) step have script properties that allow you to customize their behavior, such as executing some code when a button is clicked or a custom initialization of a text field. Also, control flow in the screen and action system is done with scripts and expressions.

### Design-time JDK

By default, install4j uses the [bundled JRE](jreBundles.md) for compiling scripts up to the Java major version that install4j runs with itself. For JRE bundles with higher Java major versions, install4j uses the current JRE instead.

For special requirements, you can invoke "Settings->Java Editor Settings" in the script editor and select a different JDK for that purpose. The list of available design-time JDKs is saved globally for your entire install4j installation and not for the current project. The only information saved in your project is the name of the JDK configuration. In this way, you can bind a suitable JDK on other installations and on other platforms.

![](../images/ui/scripts_jdk_selection.png)

The design-time JDK is used for the following purposes:

- **Code completion** — The Java code editor will show completion proposals for classes and methods in the JDK runtime library from the design-time JDK.
- **Context-sensitive Javadoc help** — If the design-time JDK from the bundled JRE configuration is used, the corresponding Javadoc from the Oracle website is shown.   If you manually configure a design-time JDK, you can enter a Javadoc directory to get context-sensitive Javadoc help in the code editor for all classes in the JDK runtime library. By default, context-sensitive Javadoc help is only available for the [install4j API](../../reference/api.md).
- **Code compilation** — install4j uses a bundled eclipse compiler, so it does not use the compiler from the design-time JDK. However, it needs a runtime library against which scripts entered in the [installer configuration](screensAndActions.md) are compiled. The version of that JDK should correspond to the minimum Java version for the project. This is automatically the case if the design-time JDK from the bundled JRE configuration is used. For a manually selected design-time JRE, if its minimum Java version is higher than the minimum Java version of the project, runtime errors can occur if you accidentally use newer classes and method.

### The code editor

The Java code editor is shown for script properties on the [Installer->Screens & Actions](../beans/screensAndActions.md) step for any configurable bean including screens, actions, form components and groups, or when you edit the code for static fields and methods on the [Installer->Screens & Actions->Custom Code](../beans/customCode.md) step.

![](../images/ui/scripts_editor.png)

The box above the text editor shows the available parameters as well as the required return type. If parameters or return types are classes, and not primitive types, they will be shown as hyperlinks. Clicking on such a hyperlink opens the Javadoc in the external browser.

To get more information on classes from the `com.install4j.*` packages, choose **Help → Show API Documentation** from the menu and read the [help topic for the install4j API](../api/installer.md).

A number of packages can be used without using fully qualified class names. Those packages are:

- java.util.*
- java.io.*
- javax.swing.*
- com.install4j.api.*
- com.install4j.api.beans.*
- com.install4j.api.context.*
- com.install4j.api.events.*
- com.install4j.api.screens.*
- com.install4j.api.actions.*
- com.install4j.api.formcomponents.*
- com.install4j.api.update.*
- com.install4j.api.windows.*
- com.install4j.api.unix.*

You can put a number of import statements as the first lines in the text area to avoid using fully qualified class names. For example:

```
import java.awt.Color;
import java.awt.EventQueue;

EventQueue.invokeLater(() -> {
  JTextField textField = (JTextField)formEnvironment.getFormComponentById("12").getConfigurationObject();
  textField.setBackground(Color.RED);
});
```

If the gutter icon in the top right corner of the dialog is green, your script is going to compile unless you have disabled error analysis in the Java editor settings that are accessible in the menu of the script editor dialog.

In some situations, you may want to try the actual compilation. Choosing **Code → Test Compile** from the menu will compile the script and display any errors in a separate dialog. Saving your script with the `OK` button will not test the syntactic correctness of the script. When your install4j project is compiled, the script will also be compiled and errors will be reported.

### Expressions or scripts

Java code properties can either be expressions or scripts. install4j automatically detects whether you have entered an expression or a script.

An expression does not have a trailing semicolon and evaluates to the required return type. For example:

```
!context.isUnattended() && !context.isConsole()
```

The above example would work as the condition expression of an action and skip the action for unattended or console installations.

A script consists of a series of Java statements with a return statement of the required return type as the last statement. For example:

```
if (!context.getBooleanVariable("enterDetails")) {
  context.goForward(2, true, true);
}
return true;
```

The above example would work as the validation expression of a screen. If the variable with name "enterDetails" is not set to `true`, it would skip two screens forward, checking the conditions of the target screen as well as executing the actions of the current screen.

### Script parameters

The primary interface to interact with the installer or uninstaller is the **context** which is nearly always among the available parameters. The context provides information about the current installation and gives access to variables, screens, actions and other elements of the installation or uninstallation. The parameter is of type

- `com.install4j.api.context.InstallerContext` for screens and actions in the installation mode
- `com.install4j.api.context.UninstallerContext` for screens and actions in the uninstallation mode
- `com.install4j.api.context.Context` for form components.

Apart from the context, the available parameters include the action, screen or form component to which the Java code property belongs. If you know the implementation class, you can cast to it and modify the object as needed.

Many other useful static methods are also contained in the class `com.install4j.api.Util`, for example, OS detection methods or methods to display messages in a way that works for all installer modes:

```
if (Util.isMacOS()) {
    Util.showWarningMessage("This warning is only shown on macOS");
}
```

### Editor features

The Java editor offers the following code assistance powered by the eclipse platform:

- **Code completion** — **Code → Complete Code** or the corresponding keyboard shortcut brings up a popup with code completion proposals. Also, typing any character shows this popup if the "Show suggestions as you type" setting is enabled and completions are available.    While the popup is displayed, you can continue to type or delete characters with `Backspace` and the popup will be updated accordingly. "Camel-hump completion" is supported, meaning typing NPE and invoking code completion will propose `NullPointerException` among other classes. If you accept a class that is not automatically imported, the fully qualified name will be inserted unless the "Auto-import classes during code completion" setting is enabled, in which case an import statement will be added at the top if required.   The completion popup can suggest:    ![](../images/completion_variable.svg) Variables and default parameters. Default parameters are displayed in bold font.   ![](../images/completion_package.svg) Packages (when typing an import statement).   ![](../images/completion_class.svg) Classes. When a constructor for an abstract class is completed, method stubs are inserted if the "Insert method" stubs setting is enabled.   ![](../images/completion_field.svg) Fields (when the context is a class).   ![](../images/completion_method.svg) Methods (when the context is a class or the parameter list of a method).   Code templates that expand when the `TAB` key is pressed. An example is "serr" or "syserr" for writing to stderr with `System.err.println()`.   Static methods in special utility classes like `com.install4j.api.Util`, `com.install4j.api.SystemInfo` or others. For example, if you start typing "show", then the `com.install4j.api.Util.showMessage(...)` methods will be suggested.    You can configure code completion behavior in the Java editor settings.
- **Parameter info** — When the caret is in the arguments of a method call, **Code → Parameter Info** or the corresponding keyboard shortcut brings up a popup with information about the various overloaded signatures. The argument at the caret is shown in bold font. If you just performed code completion, the selected signature will be selected in the popup.
- **Caret highlighting** — Other usages of the element at the caret are highlighted in the editor with corresponding markers in the gutter. Write and read occurrences of fields and variables are colored differently.
- **Code-sensitive selection** — With **Edit → Extend Selection** and **Edit → Shrink Selection** or their corresponding keyboard shortcuts you can select containing code blocks. Invoke the actions repeatedly to cycle through larger and smaller blocks.
- **Problem analysis** — The code that you enter is analyzed on the fly and checked for errors and warning conditions. Errors are shown with red underlines in the editor and with red stripes in the right gutter. Warnings, such as unused variable declarations, are shown with yellow underlines in the editor and with yellow stripes in the right gutter. Hovering the mouse over an error or warning in the editor as well as hovering the mouse over a stripe in the gutter area displays the error or warning message.   The status indicator at the top of the right gutter is green if there are no warnings or errors, yellow if there are warnings but no errors and red if there are errors. In the latter case, the code will not compile and the installer cannot be generated. You can configure the threshold for problem analysis in the Java editor settings.   For moving between problems, the actions **Code → Navigate to Previous Highlighted Problem** and **Code → Navigate to Next Highlighted Problem** with separate keyboard shortcuts are available.   When the caret is on a problem location, **quick fixes** may become available and can be invoked with **Code → Quick Fix** or the corresponding keyboard shortcut. A popup will be displayed with possible actions to fix the problem. When using the mouse, you can click on the floating lightbulb to show the popup.    Quick fixes include:   Removing invalid or unused imports Terminating unterminated strings Declaring unresolved variables Adding imports for unresolved types Fixing type mismatches Adding missing return statements Fixing instance access to static members Correcting visibility of overridden methods Correcting invalid modifiers Fixing invalid abstract methods Adding unimplemented methods Removing unused local variables Removing unnecessary casts Removing dead code
- **Context-sensitive Javadoc** — **Help → Show Javadoc** or the corresponding keyboard shortcut opens the browser with the Javadoc page that describes the element at the cursor position. Javadoc for the Java runtime library can only be displayed if a design-time JDK is configured and a valid Javadoc location is specified in the design-time JDK configuration.
- **Code formatting** — **Code → Complete Code** or the corresponding keyboard shortcut reformats the selected code or the entire code if no code is selected. The code style for reformatting can be configured in the Java editor settings by supplying an Eclipse formatting profile. Eclipse XML profile files are supported by Eclipse, IntelliJ IDEA and the RedHat Java plugin of VS Code. To export them from your favorite IDE, perform the steps below:    In the Eclipse IDE, under **Preferences → Java Code Style Formatter**, edit the profile and click on "Export" next to the profile name.   In the IntelliJ IDEA settings, under **Editor → Code Style**, open the action menu next to the scheme and choose **Export → Export Eclipse XML File**.   In VS Code, if you use the RedHat Java plugin, the Eclipse XML file is the way formatting settings are configured, and you can use the same one as specified in the plugin settings.    If the file contains multiple profiles, the first one will be used. The tab size setting from the code formatting will be ignored because it is a separate option in the Java editor settings. In the install4j code editor, tabs are always converted to spaces.   When you are typing a closing brace, the corresponding block will be reformatted. You can disable this behavior with the "Format block when entering a closing brace" option in the Java editor settings.
- **Import organization** — With **Code → Organize Imports** or the corresponding keyboard shortcut you can clean up the imports at the top of the script.
- **Refactorings** — The context-dependent set of available refactorings is invoked with **Code → Refactor** or the corresponding keyboard shortcut.    A wide range of local refactorings is available including   Extracting and inlining variables Converting between lambdas and anonymous classes Converting between var and explicit types Adding static imports Converting to enhanced for loops Surrounding with try-catch Adding explicit lambda parameters Changing between lambda expression and lambda block Converting lambdas to method references Converting string concatenations to MessageFormat, StringBuilder or String.format() constructs or to text blocks Converting switch statements to switch expressions Joining and splitting variable declarations with variable definitions Inverting calls to Object.equals()   The **rename refactoring** has its own action **Code → Rename** with a separate keyboard shortcut. It is active whenever the element at the caret can be renamed.

### Key bindings

All key bindings in the Java code editor are configurable. The keymap editor is displayed by choosing **Settings → Keymap** from the menu in the Java code editor dialog. On macOS, that menu is shown as a "hamburger" menu on the right side of the toolbar.

![](../images/ui/scripts_keymap_settings.png)

The active keymap controls all key bindings in the editor. When you use the code editor for the first time, you can select which general-purpose IDE you are most familiar with, and the default keymap will be selected accordingly. The default keymaps cannot be edited directly. To customize key bindings, you first have to copy them. Except for the default keymaps, the name of a keymap can be edited by double-clicking on it.

When assigning new keystrokes or removing existing keystrokes from a copied map, the changes to the base keymap will be shown as "overridden" in the list of bindings. The keymap editor also features search functionality for locating bindings as well a conflict resolution mechanism.

Key bindings are saved in the file `$CONFIG_DIR/install4j/v11/keymap.xml` where `$CONFIG_DIR` is `%USERPROFILE%\AppData\Local` on Windows, `$HOME/.config` on Linux and `$HOME/Library/Application Support` on macOS. This file only exists if a keymap has been selected. When migrating an install4j installation to a different computer, you can copy this file to keep your keymaps.

### Code gallery

The Java code editor offers a code gallery containing useful snippets that show you how to get started with using the install4j API. The code gallery is displayed with the "Code gallery" toolbar button in the script editor.

![](../images/ui/scripts_gallery.png)

You can either copy a portion of the script with `CTRL-C` or click `OK` to insert the entire script at the current cursor position.

Not all code snippets are directly usable in the script that you are editing. Also, some script properties have special code snippets that are only shown for this property. If such code snippets exist, they are displayed in bold in a separate category with the name of the script property.

### Installer variables and scripts

Screens, actions and form components are wired together with installer variables that can be set and retrieved with little code snippets that make use of the context parameter that is available for most scripts. Any object can be used as the value for a variable, for a condition you can use boolean values. In a "Run script" action, you could set a boolean variable like this:

```
boolean myCondition = ...
context.setVariable("myCondition", myCondition);
```

Instead of calling `setVariable` in a "Run script" action, you can also use a "Set a variable" action where the return value of the script is saved to an installer variable.

Getting installer variables is done with the `context.getVariable(String variableName)` method. The convenience method `context.getBooleanVariable(String variableName)` makes it easier to check conditions and write them as expressions without a return value:

```
context.getBooleanVariable("myCondition")
```

To use installer variables with a string value in text properties of actions, screens and form components, write them as `${installer:myVariableName}` or use the variable selector button that inserts them with the correct syntax.
