Example usage for com.intellij.openapi.fileChooser FileSaverDescriptor withShowHiddenFiles

List of usage examples for com.intellij.openapi.fileChooser FileSaverDescriptor withShowHiddenFiles

Introduction

In this page you can find the example usage for com.intellij.openapi.fileChooser FileSaverDescriptor withShowHiddenFiles.

Prototype

public FileChooserDescriptor withShowHiddenFiles(boolean showHiddenFiles) 

Source Link

Usage

From source file:net.happybrackets.intellij_plugin.IntelliJPluginGUIManager.java

License:Apache License

/**
 * Make Configuration/Known devices pane.
 * @param fileType 0 == configuration, 1 == known devices.
 */// w ww. j  a v a2  s .  c om
private Pane makeConfigurationPane(final int fileType) {
    final TextArea configField = new TextArea();
    final String label = fileType == 0 ? "Configuration" : "Known Devices";
    final String setting = fileType == 0 ? "controllerConfigPath" : "knownDevicesPath";

    //configField.setPrefSize(400, 250);
    configField.setMinHeight(minTextAreaHeight);
    // Load initial config into text field.
    if (fileType == 0) {
        configField.setText(HappyBracketsToolWindow.getCurrentConfigString());
    } else {
        StringBuilder map = new StringBuilder();
        deviceConnection.getKnownDevices().forEach((hostname, id) -> map.append(hostname + " " + id + "\n"));
        configField.setText(map.toString());
    }
    configField.textProperty().addListener((observable, oldValue, newValue) -> {
        configApplyButton[fileType].setDisable(false);
    });

    Button loadButton = new Button("Load");
    loadButton.setTooltip(new Tooltip("Load a new " + label.toLowerCase() + " file."));
    loadButton.setOnMouseClicked(event -> {
        //select a file
        final FileChooserDescriptor descriptor = FileChooserDescriptorFactory.createSingleFileDescriptor()
                .withShowHiddenFiles(true);
        descriptor.setTitle("Select " + label.toLowerCase() + " file");

        String currentFile = HappyBracketsToolWindow.getSettings().getString(setting);
        VirtualFile vfile = currentFile == null ? null
                : LocalFileSystem.getInstance().findFileByPath(currentFile.replace(File.separatorChar, '/'));

        //needs to run in Swing event dispatch thread, and then back again to JFX thread!!
        SwingUtilities.invokeLater(() -> {
            VirtualFile[] virtualFile = FileChooser.chooseFiles(descriptor, null, vfile);
            if (virtualFile != null && virtualFile.length > 0 && virtualFile[0] != null) {
                Platform.runLater(() -> {
                    loadConfigFile(virtualFile[0].getCanonicalPath(), label, configField, setting, loadButton,
                            event);
                });
            }
        });
    });

    Button saveButton = new Button("Save");
    saveButton.setTooltip(new Tooltip("Save these " + label.toLowerCase() + " settings to a file."));
    saveButton.setOnMouseClicked(event -> {
        //select a file
        FileSaverDescriptor fsd = new FileSaverDescriptor("Select " + label.toLowerCase() + " file to save to.",
                "Select " + label.toLowerCase() + " file to save to.");
        fsd.withShowHiddenFiles(true);
        final FileSaverDialog dialog = FileChooserFactory.getInstance().createSaveFileDialog(fsd, project);

        String currentFilePath = HappyBracketsToolWindow.getSettings().getString(setting);
        File currentFile = currentFilePath != null
                ? new File(HappyBracketsToolWindow.getSettings().getString(setting))
                : null;
        VirtualFile baseDir = null;
        String currentName = null;
        if (currentFile != null && currentFile.exists()) {
            baseDir = LocalFileSystem.getInstance().findFileByPath(
                    currentFile.getParentFile().getAbsolutePath().replace(File.separatorChar, '/'));
            currentName = currentFile.getName();
        } else {
            baseDir = LocalFileSystem.getInstance().findFileByPath(HappyBracketsToolWindow.getPluginLocation());
            currentName = fileType == 0 ? "controller-config.json" : "known_devices";
        }
        final VirtualFile baseDirFinal = baseDir;
        final String currentNameFinal = currentName;

        //needs to run in Swing event dispatch thread, and then back again to JFX thread!!
        SwingUtilities.invokeLater(() -> {
            final VirtualFileWrapper wrapper = dialog.save(baseDirFinal, currentNameFinal);

            if (wrapper != null) {
                Platform.runLater(() -> {
                    File configFile = wrapper.getFile();

                    // Check for overwrite of default config files (this doesn't apply to deployed plugin so disabling for now.)
                    //if ((new File(HappyBracketsToolWindow.getDefaultControllerConfigPath())).getAbsolutePath().equals(configFile.getAbsolutePath()) ||
                    //      (new File(HappyBracketsToolWindow.getDefaultKnownDevicesPath())).getAbsolutePath().equals(configFile.getAbsolutePath())) {
                    //   showPopup("Error saving " + label.toLowerCase() + ": cannot overwrite default configuration files.", saveButton, 5, event);
                    //}

                    try (PrintWriter out = new PrintWriter(configFile.getAbsolutePath())) {
                        out.print(configField.getText());

                        HappyBracketsToolWindow.getSettings().set(setting, configFile.getAbsolutePath());
                    } catch (Exception ex) {
                        showPopup("Error saving " + label.toLowerCase() + ": " + ex.getMessage(), saveButton, 5,
                                event);
                    }
                });
            }
        });
    });

    Button resetButton = new Button("Reset");
    resetButton.setTooltip(new Tooltip("Reset these " + label.toLowerCase() + " settings to their defaults."));
    resetButton.setOnMouseClicked(event -> {
        HappyBracketsToolWindow.getSettings().clear(setting);

        if (fileType == 0) {
            loadConfigFile(HappyBracketsToolWindow.getDefaultControllerConfigPath(), label, configField,
                    setting, resetButton, event);
            applyConfig(configField.getText());
        } else {
            loadConfigFile(HappyBracketsToolWindow.getDefaultKnownDevicesPath(), label, configField, setting,
                    resetButton, event);
            applyKnownDevices(configField.getText());
        }
    });

    configApplyButton[fileType] = new Button("Apply");
    configApplyButton[fileType].setTooltip(new Tooltip("Apply these " + label.toLowerCase() + " settings."));
    configApplyButton[fileType].setDisable(true);
    configApplyButton[fileType].setOnMouseClicked(event -> {
        configApplyButton[fileType].setDisable(true);

        if (fileType == 0) {
            applyConfig(configField.getText());
        } else {
            applyKnownDevices(configField.getText());
        }
    });

    FlowPane buttons = new FlowPane(defaultElementSpacing, defaultElementSpacing);
    buttons.setAlignment(Pos.TOP_LEFT);
    buttons.getChildren().addAll(loadButton, saveButton, resetButton, configApplyButton[fileType]);

    // If this is the main configuration pane, include buttons to set preferred IP version.
    FlowPane ipvButtons = null;
    if (fileType == 0) {
        // Set IP version buttons.
        ipvButtons = new FlowPane(defaultElementSpacing, defaultElementSpacing);
        ipvButtons.setAlignment(Pos.TOP_LEFT);

        for (int ipv = 4; ipv <= 6; ipv += 2) {
            final int ipvFinal = ipv;

            Button setIPv = new Button("Set IntelliJ to prefer IPv" + ipv);
            String currentSetting = System.getProperty("java.net.preferIPv" + ipv + "Addresses");

            if (currentSetting != null && currentSetting.toLowerCase().equals("true")) {
                setIPv.setDisable(true);
            }

            setIPv.setTooltip(new Tooltip("Set the JVM used by IntelliJ to prefer IPv" + ipv
                    + " addresses by default.\nThis can help resolve IPv4/Ipv6 incompatibility issues in some cases."));
            setIPv.setOnMouseClicked(event -> {
                // for the 32 and 64 bit versions of the options files.
                for (String postfix : new String[] { "", "64" }) {
                    String postfix2 = "";
                    String filename = "/idea" + postfix + postfix2 + ".vmoptions";
                    // If this (Linux (and Mac?)) version of the file doesn't exist, try the Windows version.
                    if (!Paths.get(PathManager.getBinPath() + filename).toFile().exists()) {
                        postfix2 = ".exe";
                        filename = "/idea" + postfix + postfix2 + ".vmoptions";

                        if (!Paths.get(PathManager.getBinPath() + filename).toFile().exists()) {
                            showPopup("An error occurred: could not find default configuration file.", setIPv,
                                    5, event);
                            return;
                        }
                    }

                    // Create custom options files if they don't already exist.
                    File custOptsFile = new File(PathManager.getCustomOptionsDirectory() + "/idea" + postfix
                            + postfix2 + ".vmoptions");
                    if (!custOptsFile.exists()) {
                        // Create copy of default.
                        try {
                            Files.copy(Paths.get(PathManager.getBinPath() + filename), custOptsFile.toPath());
                        } catch (IOException e) {
                            logger.error("Error creating custom options file.", e);
                            showPopup("Error creating custom options file: " + e.getMessage(), setIPv, 5,
                                    event);
                            return;
                        }
                    }

                    if (custOptsFile.exists()) {
                        StringBuilder newOpts = new StringBuilder();
                        try (Stream<String> stream = Files.lines(custOptsFile.toPath())) {
                            stream.forEach((line) -> {
                                // Remove any existing preferences.
                                if (!line.contains("java.net.preferIPv")) {
                                    newOpts.append(line + "\n");
                                }
                            });
                            // Add new preference to end.
                            newOpts.append("-Djava.net.preferIPv" + ipvFinal + "Addresses=true");
                        } catch (IOException e) {
                            logger.error("Error creating custom options file.", e);
                            showPopup("Error creating custom options file: " + e.getMessage(), setIPv, 5,
                                    event);
                            return;
                        }

                        // Write new options to file.
                        try (PrintWriter out = new PrintWriter(custOptsFile.getAbsolutePath())) {
                            out.println(newOpts);
                        } catch (FileNotFoundException e) {
                            // This totally shouldn't happen.
                        }
                    }
                }

                showPopup("You must restart IntelliJ for the changes to take effect.", setIPv, 5, event);
            });

            ipvButtons.getChildren().add(setIPv);
        }
    }

    VBox configPane = new VBox(defaultElementSpacing);
    configPane.setAlignment(Pos.TOP_LEFT);
    configPane.getChildren().addAll(makeTitle(label), configField, buttons);
    if (ipvButtons != null) {
        configPane.getChildren().add(ipvButtons);
    }

    return configPane;
}