Example usage for com.intellij.openapi.fileChooser FileSaverDialog save

List of usage examples for com.intellij.openapi.fileChooser FileSaverDialog save

Introduction

In this page you can find the example usage for com.intellij.openapi.fileChooser FileSaverDialog save.

Prototype

@Nullable
    VirtualFileWrapper save(@Nullable VirtualFile baseDir, @Nullable String filename);

Source Link

Usage

From source file:com.android.tools.idea.actions.ConvertToNinePatchAction.java

License:Apache License

@Override
public void actionPerformed(AnActionEvent e) {
    final VirtualFile pngFile = CommonDataKeys.VIRTUAL_FILE.getData(e.getDataContext());
    if (!isPngFile(pngFile)) {
        return;/*  w  ww  . ja  v  a2s. c  o m*/
    }

    FileSaverDescriptor descriptor = new FileSaverDescriptor(
            AndroidBundle.message("android.9patch.creator.save.title"), "", SdkConstants.EXT_PNG);
    FileSaverDialog saveFileDialog = FileChooserFactory.getInstance().createSaveFileDialog(descriptor,
            (Project) null);
    VirtualFileWrapper fileWrapper = saveFileDialog.save(pngFile.getParent(),
            pngFile.getNameWithoutExtension().concat(SdkConstants.DOT_9PNG));
    if (fileWrapper == null) {
        return;
    }

    final File patchFile = fileWrapper.getFile();
    new Task.Modal(null, "Creating 9-Patch File", false) {
        private IOException myException;

        @Override
        public void run(@NotNull ProgressIndicator indicator) {
            indicator.setIndeterminate(true);
            try {
                BufferedImage pngImage = ImageIO.read(VfsUtilCore.virtualToIoFile(pngFile));
                BufferedImage patchImage = ImageUtils.addMargin(pngImage, 1);
                ImageIO.write(patchImage, SdkConstants.EXT_PNG, patchFile);
                LocalFileSystem.getInstance().refreshAndFindFileByIoFile(patchFile);
            } catch (IOException e) {
                myException = e;
            }
        }

        @Override
        public void onSuccess() {
            if (myException != null) {
                Messages.showErrorDialog(
                        AndroidBundle.message("android.9patch.creator.error", myException.getMessage()),
                        AndroidBundle.message("android.9patch.creator.error.title"));
            }
        }
    }.queue();
}

From source file:com.android.tools.idea.ddms.screenshot.ScreenshotViewer.java

License:Apache License

@Override
protected void doOKAction() {
    FileSaverDescriptor descriptor = new FileSaverDescriptor(
            AndroidBundle.message("android.ddms.screenshot.save.title"), "", SdkConstants.EXT_PNG);
    FileSaverDialog saveFileDialog = FileChooserFactory.getInstance().createSaveFileDialog(descriptor,
            myProject);/*from www.  jav a2 s .  c o m*/
    VirtualFile baseDir = ourLastSavedFolder != null ? ourLastSavedFolder : myProject.getBaseDir();
    VirtualFileWrapper fileWrapper = saveFileDialog.save(baseDir, getDefaultFileName());
    if (fileWrapper == null) {
        return;
    }

    myScreenshotFile = fileWrapper.getFile();
    try {
        ImageIO.write(myDisplayedImageRef.get(), SdkConstants.EXT_PNG, myScreenshotFile);
    } catch (IOException e) {
        Messages.showErrorDialog(myProject, AndroidBundle.message("android.ddms.screenshot.save.error", e),
                AndroidBundle.message("android.ddms.actions.screenshot"));
        return;
    }

    VirtualFile virtualFile = fileWrapper.getVirtualFile();
    if (virtualFile != null) {
        //noinspection AssignmentToStaticFieldFromInstanceMethod
        ourLastSavedFolder = virtualFile.getParent();
    }

    super.doOKAction();
}

From source file:com.microsoft.intellij.ui.NewCertificateDialog.java

License:Open Source License

private ActionListener getFileSaverListener(final TextFieldWithBrowseButton field,
        final TextFieldWithBrowseButton fieldToUpdate, final String suffixToReplace, final String suffix) {
    return new ActionListener() {
        @Override/*  w w  w  . j a va2  s  .c om*/
        public void actionPerformed(ActionEvent e) {
            final FileSaverDialog dialog = FileChooserFactory.getInstance().createSaveFileDialog(
                    new FileSaverDescriptor(message("newCertDlgBrwFldr"), "", suffixToReplace), field);
            final VirtualFile baseDir = myProject.getBaseDir();
            final VirtualFileWrapper save = dialog.save(baseDir, "");
            if (save != null) {
                field.setText(FileUtil.toSystemDependentName(save.getFile().getAbsolutePath()));
                if (fieldToUpdate.getText().isEmpty()) {
                    fieldToUpdate.setText(Utils.replaceLastSubString(field.getText(), suffixToReplace, suffix));
                }
            }
        }
    };
}

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 w  w.  j  a v a  2 s. co  m*/
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;
}

From source file:org.cdv.intellij.ui.CDVIDEAFileSaveChooser.java

License:Open Source License

public File choose(String message, String suffix) {
    final FileSaverDialog dialog = FileChooserFactory.getInstance()
            .createSaveFileDialog(new FileSaverDescriptor(message, "", suffix), project);
    final VirtualFile baseDir = project.getBaseDir();
    final VirtualFileWrapper save = dialog.save(baseDir, "");
    if (save != null) {
        return save.getFile();
        //            field.setText(FileUtil.toSystemDependentName(save.getFile().getAbsolutePath()));
        //            if (fieldToUpdate.getText().isEmpty()) {
        //                fieldToUpdate.setText(Utils.replaceLastSubString(field.getText(), suffixToReplace, suffix));
        //            }
    }//from   ww w  .  j a  v  a  2s  .  c  om
    return null;
}

From source file:org.jetbrains.android.util.SaveFileListener.java

License:Apache License

@Override
public void actionPerformed(ActionEvent e) {
    String path = myTextField.getText().trim();
    if (path.length() == 0) {
        String defaultLocation = getDefaultLocation();
        path = defaultLocation != null && defaultLocation.length() > 0 ? defaultLocation
                : SystemProperties.getUserHome();
    }/*from w ww. j a v  a2s .com*/
    File file = new File(path);
    if (!file.exists()) {
        path = SystemProperties.getUserHome();
    }
    FileSaverDescriptor descriptor = new FileSaverDescriptor(myDialogTitle, "Save as *." + myExtension,
            myExtension);
    FileSaverDialog saveFileDialog = FileChooserFactory.getInstance().createSaveFileDialog(descriptor,
            myContentPanel);

    VirtualFile vf = LocalFileSystem.getInstance().findFileByIoFile(file.exists() ? file : new File(path));
    if (vf == null) {
        vf = VfsUtil.getUserHomeDir();
    }

    VirtualFileWrapper result = saveFileDialog.save(vf, null);

    if (result == null || result.getFile() == null) {
        return;
    }

    myTextField.setText(result.getFile().getPath());
}

From source file:org.jetbrains.idea.svn.treeConflict.ApplyPatchSaveToFileExecutor.java

License:Apache License

@Override
public void apply(MultiMap<VirtualFile, FilePatchInProgress> patchGroups, LocalChangeList localList,
        String fileName,//  w w w  .  ja v a  2s .c  om
        TransparentlyFailedValueI<Map<String, Map<String, CharSequence>>, PatchSyntaxException> additionalInfo) {
    final FileSaverDialog dialog = FileChooserFactory.getInstance()
            .createSaveFileDialog(new FileSaverDescriptor("Save patch to", ""), myProject);
    final VirtualFile baseDir = myProject.getBaseDir();
    final VirtualFileWrapper save = dialog.save(baseDir, "TheirsChanges.patch");
    if (save != null) {
        final CommitContext commitContext = new CommitContext();

        final VirtualFile baseForPatch = myBaseForPatch == null ? baseDir : myBaseForPatch;
        try {
            final List<FilePatch> textPatches = patchGroupsToOneGroup(patchGroups, baseForPatch);
            commitContext.putUserData(BaseRevisionTextPatchEP.ourPutBaseRevisionTextKey, false);
            PatchWriter.writePatches(myProject, save.getFile().getPath(), textPatches, commitContext,
                    CharsetToolkit.UTF8_CHARSET);
        } catch (final IOException e) {
            LOG.info(e);
            WaitForProgressToShow.runOrInvokeLaterAboveProgress(new Runnable() {
                public void run() {
                    Messages.showErrorDialog(myProject,
                            VcsBundle.message("create.patch.error.title", e.getMessage()),
                            CommonBundle.getErrorTitle());
                }
            }, null, myProject);
        }
    }
}