Java Code Examples for com.intellij.openapi.ui.Messages#YES

The following examples show how to use com.intellij.openapi.ui.Messages#YES . These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: consulo   File: JBMacMessages.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public int showYesNoCancelDialog(@Nonnull String title,
                                 String message,
                                 @Nonnull String defaultButton,
                                 String alternateButton,
                                 String otherButton,
                                 @Nullable consulo.ui.Window window,
                                 @Nullable DialogWrapper.DoNotAskOption doNotAskOption) {
  if (window == null) {
    window = getForemostWindow(null);
  }
  SheetMessage sheetMessage = new SheetMessage(window, title, message, UIUtil.getQuestionIcon(),
                                               new String [] {defaultButton, alternateButton, otherButton}, null, defaultButton, alternateButton);
  String resultString = sheetMessage.getResult();
  int result = resultString.equals(defaultButton) ? Messages.YES : resultString.equals(alternateButton) ? Messages.NO : Messages.CANCEL;
  if (doNotAskOption != null) {
    doNotAskOption.setToBeShown(sheetMessage.toBeShown(), result);
  }
  return result;
}
 
Example 2
public int exportProjectScheme() {
  String name = Messages.showInputDialog("Enter new scheme name:", "Copy Project Scheme to Global List", Messages.getQuestionIcon());
  if (name != null && !CodeStyleSchemesModel.PROJECT_SCHEME_NAME.equals(name)) {
    CodeStyleScheme newScheme = mySchemesModel.exportProjectScheme(name);
    updateSchemes();
    int switchToGlobal = Messages
      .showYesNoDialog("Project scheme was copied to global scheme list as '" + newScheme.getName() + "'.\n" +
                       "Switch to this created scheme?",
                       "Copy Project Scheme to Global List", Messages.getQuestionIcon());
    if (switchToGlobal == Messages.YES) {
      mySchemesModel.setUsePerProjectSettings(false);
      mySchemesModel.selectScheme(newScheme, null);
    }
    int row = 0;
    for (CodeStyleScheme scheme : mySchemes) {
      if (scheme == newScheme) {
        fireTableRowsInserted(row, row);
        return switchToGlobal == 0 ? row : -1;
      }
      row++;
    }
  }
  return -1;
}
 
Example 3
Source Project: consulo   File: RemoveChangeListAction.java    License: Apache License 2.0 6 votes vote down vote up
private static boolean askIfShouldRemoveChangeLists(@Nonnull List<? extends LocalChangeList> lists, Project project) {
  boolean activeChangelistSelected = lists.stream().anyMatch(LocalChangeList::isDefault);
  boolean haveNoChanges = lists.stream().allMatch(l -> l.getChanges().isEmpty());

  if (activeChangelistSelected) {
    return confirmActiveChangeListRemoval(project, lists, haveNoChanges);
  }

  String message = lists.size() == 1
                   ? VcsBundle.message("changes.removechangelist.warning.text", lists.get(0).getName())
                   : VcsBundle.message("changes.removechangelist.multiple.warning.text", lists.size());

  return haveNoChanges ||
         Messages.YES ==
         Messages
                 .showYesNoDialog(project, message, VcsBundle.message("changes.removechangelist.warning.title"), Messages.getQuestionIcon());
}
 
Example 4
public void deleteWorkspaceWithProgress(final Workspace selectedWorkspace) {
    logger.info("Deleting workspace " + selectedWorkspace.getName());
    // confirm with the user the deletion
    if (Messages.showYesNoDialog(project, TfPluginBundle.message(TfPluginBundle.KEY_TFVC_MANAGE_WORKSPACES_DELETE_CONFIRM_MSG, selectedWorkspace.getName()),
            TfPluginBundle.message(TfPluginBundle.KEY_TFVC_MANAGE_WORKSPACES_DELETE_CONFIRM_TITLE), Messages.getWarningIcon()) != Messages.YES) {
        logger.info("User cancelled workspace delete");
        return;
    }

    try {
        VcsUtil.runVcsProcessWithProgress(new VcsRunnable() {
            public void run() throws VcsException {
                deleteWorkspace(selectedWorkspace);
            }
        }, TfPluginBundle.message(TfPluginBundle.KEY_TFVC_MANAGE_WORKSPACES_DELETE_MSG, selectedWorkspace.getName()), true, project);
    } catch (VcsException e) {
        logger.warn("Exception while trying to delete workspace", e);
        Messages.showErrorDialog(project, e.getMessage(),
                TfPluginBundle.message(TfPluginBundle.KEY_TFVC_MANAGE_WORKSPACES_DELETE_ERROR_TITLE));
    } finally {
        // always refresh list
        setChangedAndNotify(REFRESH_WORKSPACE);
    }
}
 
Example 5
@Nullable
@Override
public Project openProject(@NotNull VirtualFile projectFile, @Nullable Project projectToClose, boolean forceOpenInNewFrame) {
  if (isAlreadyOpen(projectFile)) return null;

  switch (shouldOpenExistingProject(projectFile, projectToClose)) {
    case Messages.NO:
      Project project = importPantsProject(projectFile);
      OpenProjectTask task = openTask(projectToClose, project, forceOpenInNewFrame);
      return PlatformProjectOpenProcessor.openExistingProject(Paths.get(projectFile.getPath()), projectDir(projectFile), task);
    case Messages.YES:
      return PlatformProjectOpenProcessor.getInstance().doOpenProject(projectFile, projectToClose, forceOpenInNewFrame);
    default:
      return null;
  }
}
 
Example 6
/**
 * Synchronously shows a yes/no dialog. This method must not be called from a write safe context
 * as it needs to be executed synchronously and AWT actions are not allowed from a write safe
 * context.
 *
 * @param project the project used as a reference to generate and position the dialog
 * @param message the text displayed as the message of the dialog
 * @param title the text displayed as the title of the dialog
 * @return <code>true</code> if {@link Messages#YES} is chosen or <code>false</code> if {@link
 *     Messages#NO} is chosen or the dialog is closed
 * @throws IllegalAWTContextException if the calling thread is currently inside a write safe
 *     context
 * @throws IllegalStateException if no response value was received from the dialog or the response
 *     was not {@link Messages#YES} or {@link Messages#NO}.
 */
public static boolean showYesNoDialog(Project project, final String message, final String title)
    throws IllegalAWTContextException {

  if (application.isWriteAccessAllowed()) {
    throw new IllegalAWTContextException("AWT events are not allowed inside write actions.");
  }

  log.info("Showing yes/no dialog: " + title + " - " + message);

  Integer result =
      EDTExecutor.invokeAndWait(
          (Computable<Integer>)
              () -> Messages.showYesNoDialog(project, message, title, Messages.getQuestionIcon()),
          ModalityState.defaultModalityState());

  switch (result) {
    case Messages.YES:
      return true;
    case Messages.NO:
      return false;
    default:
      throw new IllegalStateException("Encountered unknown dialog answer " + result);
  }
}
 
Example 7
@Nullable
private Boolean suggestCreatingFileInstead(String subDirName) {
  Boolean createFile = false;
  if (StringUtil.countChars(subDirName, '.') == 1 && Registry.is("ide.suggest.file.when.creating.filename.like.directory")) {
    FileType fileType = findFileTypeBoundToName(subDirName);
    if (fileType != null) {
      String message = "The name you entered looks like a file name. Do you want to create a file named " + subDirName + " instead?";
      int ec = Messages.showYesNoCancelDialog(myProject, message, "File Name Detected", "&Yes, create file", "&No, create " + (myIsDirectory ? "directory" : "packages"),
                                              CommonBundle.getCancelButtonText(), TargetAWT.to(fileType.getIcon()));
      if (ec == Messages.CANCEL) {
        createFile = null;
      }
      if (ec == Messages.YES) {
        createFile = true;
      }
    }
  }
  return createFile;
}
 
Example 8
@Override
public void actionPerformed(final AnActionEvent e) {
  final Project project = e.getData(CommonDataKeys.PROJECT);
  if (project == null) {
    return;
  }
  final int result = Messages
    .showYesNoDialog(project, VcsBundle.message("delete.all.already.unshelved.confirmation"), myText,
                     Messages.getWarningIcon());
  if (result == Messages.YES) {
    final ShelveChangesManager manager = ShelveChangesManager.getInstance(project);
    manager.clearRecycled();
  }
}
 
Example 9
private boolean isClearAppData() {
    String clearDataString = model.getClearData();

    boolean clearData = (MuleRunnerEditor.CLEAR_DATA_ALWAYS.equals(clearDataString));

    if (!clearData) {
        if (MuleRunnerEditor.CLEAR_DATA_PROMPT.equals(clearDataString)) {
            int result = Messages.showYesNoDialog("Clear the application data (caches, object stores) before the launch?", "Clear Application Data", AllIcons.General.QuestionDialog);
            clearData = (result == Messages.YES);
        }
    }

    return clearData;
}
 
Example 10
Source Project: PackageTemplates   File: ImportHelper.java    License: Apache License 2.0 5 votes vote down vote up
private static File getCurrentRootDir(Context ctx) {
    if (FileTemplateHelper.isDefaultScheme(ctx.project)) {
        return PackageTemplateHelper.getRootDir();
    }

    int resultCode = Messages.showYesNoDialog(
            ctx.project,
            Localizer.get("title.ImportPackageTemplate"),
            Localizer.get("text.WhereToSave"),
            Localizer.get("action.ToDefaultDir"),
            Localizer.get("action.ToProjectDir"),
            Messages.getQuestionIcon()
    );
    //To Default
    if (resultCode == Messages.YES) {
        ctx.newFileTemplateSource = FileTemplateSource.DEFAULT_ONLY;
        return PackageTemplateHelper.getRootDir();
    } else {
        //To Project
        ctx.newFileTemplateSource = FileTemplateSource.PROJECT_ONLY;
        String rootDirPath = PackageTemplateHelper.getProjectRootDirPath(ctx.project);
        if (rootDirPath == null) {
            return null;
        }

        File file = new File(rootDirPath);
        FileWriter.createDirectories(file.toPath());
        return file;
    }
}
 
Example 11
Source Project: consulo   File: ProjectOrModuleNameStep.java    License: Apache License 2.0 5 votes vote down vote up
private boolean validateNameAndPath(@Nonnull NewModuleWizardContext context) throws WizardStepValidationException {
  final String name = myNamePathComponent.getNameValue();
  if (name.length() == 0) {
    final ApplicationInfo info = ApplicationInfo.getInstance();
    throw new WizardStepValidationException(IdeBundle.message("prompt.new.project.file.name", info.getVersionName(), context.getTargetId()));
  }

  final String projectFileDirectory = myNamePathComponent.getPath();
  if (projectFileDirectory.length() == 0) {
    throw new WizardStepValidationException(IdeBundle.message("prompt.enter.project.file.location", context.getTargetId()));
  }

  final boolean shouldPromptCreation = myNamePathComponent.isPathChangedByUser();
  if (!ProjectWizardUtil.createDirectoryIfNotExists(IdeBundle.message("directory.project.file.directory", context.getTargetId()), projectFileDirectory, shouldPromptCreation)) {
    return false;
  }

  final File file = new File(projectFileDirectory);
  if (file.exists() && !file.canWrite()) {
    throw new WizardStepValidationException(String.format("Directory '%s' is not writable!\nPlease choose another project location.", projectFileDirectory));
  }

  boolean shouldContinue = true;
  final File projectDir = new File(myNamePathComponent.getPath(), Project.DIRECTORY_STORE_FOLDER);
  if (projectDir.exists()) {
    int answer = Messages
            .showYesNoDialog(IdeBundle.message("prompt.overwrite.project.folder", projectDir.getAbsolutePath(), context.getTargetId()), IdeBundle.message("title.file.already.exists"), Messages.getQuestionIcon());
    shouldContinue = (answer == Messages.YES);
  }

  return shouldContinue;
}
 
Example 12
/**
 * Deletes the passwords/contexts from the table only but not permanently
 */
public void deletePasswords() {
    final ListSelectionModel selectionModel = getTableSelectionModel();
    if (!selectionModel.isSelectionEmpty()) {
        if (Messages.showYesNoDialog(project, TfPluginBundle.message(TfPluginBundle.KEY_SETTINGS_PASSWORD_MGT_DIALOG_DELETE_MSG), TfPluginBundle.message(TfPluginBundle.KEY_SETTINGS_PASSWORD_MGT_DIALOG_DELETE_TITLE), Messages.getQuestionIcon()) == Messages.YES) {
            // only delete contexts from the table at the moment and not for good (when Apply is used that is when we actually delete the contexts in deleteContexts)
            deleteContexts.addAll(tableModel.getSelectedContexts());
            populateContextTable();
        }
    } else {
        Messages.showWarningDialog(project, TfPluginBundle.message(TfPluginBundle.KEY_SETTINGS_PASSWORD_MGT_NO_ROWS_SELECTED), TfPluginBundle.message(TfPluginBundle.KEY_SETTINGS_PASSWORD_MGT_DIALOG_DELETE_TITLE));
    }
}
 
Example 13
Source Project: consulo   File: JBMacMessages.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public int showYesNoDialog(@Nonnull String title,
                           String message,
                           @Nonnull String yesButton,
                           @Nonnull String noButton,
                           @Nullable consulo.ui.Window window) {
  if (window == null) {
    window = getForemostWindow(null);
  }
  SheetMessage sheetMessage = new SheetMessage(window, title, message, UIUtil.getQuestionIcon(),
                                               new String [] {yesButton, noButton}, null, yesButton, noButton);
  return sheetMessage.getResult().equals(yesButton) ? Messages.YES : Messages.NO;
}
 
Example 14
Source Project: consulo   File: ModulesConfigurator.java    License: Apache License 2.0 5 votes vote down vote up
private boolean doRemoveModule(@Nonnull ModuleEditor selectedEditor) {

    String question;
    if (myModuleEditors.size() == 1) {
      question = ProjectBundle.message("module.remove.last.confirmation");
    }
    else {
      question = ProjectBundle.message("module.remove.confirmation", selectedEditor.getModule().getName());
    }
    int result = Messages.showYesNoDialog(myProject, question, ProjectBundle.message("module.remove.confirmation.title"), Messages.getQuestionIcon());
    if (result != Messages.YES) {
      return false;
    }
    // do remove
    myModuleEditors.remove(selectedEditor);

    // destroyProcess removed module
    final Module moduleToRemove = selectedEditor.getModule();
    // remove all dependencies on the module that is about to be removed
    List<ModifiableRootModel> modifiableRootModels = new ArrayList<>();
    for (final ModuleEditor moduleEditor : myModuleEditors) {
      final ModifiableRootModel modifiableRootModel = moduleEditor.getModifiableRootModelProxy();
      modifiableRootModels.add(modifiableRootModel);
    }

    // destroyProcess editor
    ModuleDeleteProvider.removeModule(moduleToRemove, null, modifiableRootModels, myModuleModel);
    processModuleCountChanged();
    Disposer.dispose(selectedEditor);

    return true;
  }
 
Example 15
Source Project: EasyCode   File: FileUtils.java    License: MIT License 4 votes vote down vote up
/**
 * 写入文件
 *
 * @param saveFile 需要保存的文件对象
 */
public void write(SaveFile saveFile) {
    // 校验目录是否存在
    PsiManager psiManager = PsiManager.getInstance(saveFile.getProject());
    PsiDirectory psiDirectory;
    VirtualFile directory = LocalFileSystem.getInstance().findFileByPath(saveFile.getPath());
    if (directory == null) {
        // 尝试创建目录
        if (saveFile.isOperateTitle() && !MessageDialogBuilder.yesNo(MsgValue.TITLE_INFO, "Directory " + saveFile.getPath() + " Not Found, Confirm Create?").isYes()) {
            return;
        }
        psiDirectory = WriteCommandAction.runWriteCommandAction(saveFile.getProject(), (Computable<PsiDirectory>) () -> {
            try {
                VirtualFile dir = VfsUtil.createDirectoryIfMissing(saveFile.getPath());
                LOG.assertTrue(dir != null);
                // 重载文件,防止发生IndexNotReadyException异常
                FileDocumentManager.getInstance().reloadFiles(dir);
                return psiManager.findDirectory(dir);
            } catch (IOException e) {
                LOG.error("path " + saveFile.getPath() + " error");
                ExceptionUtil.rethrow(e);
                return null;
            }
        });
    } else {
        psiDirectory = psiManager.findDirectory(directory);
    }
    if (psiDirectory == null) {
        return;
    }
    // 保存或替换文件
    PsiFile oldFile = psiDirectory.findFile(saveFile.getFile().getName());
    PsiDocumentManager psiDocumentManager = PsiDocumentManager.getInstance(saveFile.getProject());
    FileDocumentManager fileDocumentManager = FileDocumentManager.getInstance();
    if (saveFile.isOperateTitle() && oldFile != null) {
        MessageDialogBuilder.YesNoCancel yesNoCancel = MessageDialogBuilder.yesNoCancel(MsgValue.TITLE_INFO, "File " + saveFile.getFile().getName() + " Exists, Select Operate Mode?");
        yesNoCancel.yesText("Cover");
        yesNoCancel.noText("Compare");
        yesNoCancel.cancelText("Cancel");
        int result = yesNoCancel.show();
        switch (result) {
            case Messages.YES:
                break;
            case Messages.NO:
                // 对比代码时也格式化代码
                if (saveFile.isReformat()) {
                    // 保留旧文件内容,用新文件覆盖旧文件执行格式化,然后再还原旧文件内容
                    String oldText = oldFile.getText();
                    WriteCommandAction.runWriteCommandAction(saveFile.getProject(), () -> psiDocumentManager.getDocument(oldFile).setText(saveFile.getFile().getText()));
                    // 提交所有改动,并非VCS中的提交文件
                    PsiDocumentManager.getInstance(saveFile.getProject()).commitAllDocuments();
                    reformatFile(saveFile.getProject(), Collections.singletonList(oldFile));
                    // 提交所有改动,并非VCS中的提交文件
                    PsiDocumentManager.getInstance(saveFile.getProject()).commitAllDocuments();
                    String newText = oldFile.getText();
                    WriteCommandAction.runWriteCommandAction(saveFile.getProject(), () -> psiDocumentManager.getDocument(oldFile).setText(oldText));
                    // 提交所有改动,并非VCS中的提交文件
                    PsiDocumentManager.getInstance(saveFile.getProject()).commitAllDocuments();
                    saveFile.setVirtualFile(new LightVirtualFile(saveFile.getFile().getName(), saveFile.getFile().getFileType(), newText));
                }
                CompareFileUtils.showCompareWindow(saveFile.getProject(), fileDocumentManager.getFile(psiDocumentManager.getDocument(oldFile)), saveFile.getVirtualFile());
                return;
            case Messages.CANCEL:
            default:
                return;
        }
    }
    PsiDirectory finalPsiDirectory = psiDirectory;
    PsiFile finalFile = WriteCommandAction.runWriteCommandAction(saveFile.getProject(), (Computable<PsiFile>) () -> {
        if (oldFile == null) {
            // 提交所有改动,并非VCS中的提交文件
            PsiDocumentManager.getInstance(saveFile.getProject()).commitAllDocuments();
            return (PsiFile) finalPsiDirectory.add(saveFile.getFile());
        } else {
            // 对旧文件进行替换操作
            Document document = psiDocumentManager.getDocument(oldFile);
            LOG.assertTrue(document != null);
            document.setText(saveFile.getFile().getText());
            return oldFile;
        }
    });
    // 判断是否需要进行代码格式化操作
    if (saveFile.isReformat()) {
        reformatFile(saveFile.getProject(), Collections.singletonList(finalFile));
    }
    // 提交所有改动,并非VCS中的提交文件
    PsiDocumentManager.getInstance(saveFile.getProject()).commitAllDocuments();
}
 
Example 16
@Override
public boolean msgConfirmYesNo(@Nullable final Component parentComponent, @Nonnull final String title, @Nonnull final String text) {
  return Messages.showYesNoDialog(this.project, text, title, Messages.getQuestionIcon()) == Messages.YES;
}
 
Example 17
@Override
public Boolean msgConfirmYesNoCancel(@Nullable final Component parentComponent, @Nonnull final String title, @Nonnull final String text) {
  final int result = Messages.showYesNoCancelDialog(this.project, text, title, Messages.getQuestionIcon());
  return result == Messages.CANCEL ? null : result == Messages.YES;
}
 
Example 18
Source Project: consulo   File: RollbackAction.java    License: Apache License 2.0 4 votes vote down vote up
private static void rollbackModifiedWithoutEditing(final Project project, final LinkedHashSet<VirtualFile> modifiedWithoutEditing) {
  final String operationName = StringUtil.decapitalize(UIUtil.removeMnemonic(RollbackUtil.getRollbackOperationName(project)));
  String message = (modifiedWithoutEditing.size() == 1)
                   ? VcsBundle.message("rollback.modified.without.editing.confirm.single",
                                       operationName, modifiedWithoutEditing.iterator().next().getPresentableUrl())
                   : VcsBundle.message("rollback.modified.without.editing.confirm.multiple",
                                       operationName, modifiedWithoutEditing.size());
  int rc = showYesNoDialog(project, message, VcsBundle.message("changes.action.rollback.title", operationName), getQuestionIcon());
  if (rc != Messages.YES) {
    return;
  }
  final List<VcsException> exceptions = new ArrayList<>();

  final ProgressManager progressManager = ProgressManager.getInstance();
  final Runnable action = new Runnable() {
    public void run() {
      final ProgressIndicator indicator = progressManager.getProgressIndicator();
      try {
        ChangesUtil.processVirtualFilesByVcs(project, modifiedWithoutEditing, (vcs, items) -> {
          final RollbackEnvironment rollbackEnvironment = vcs.getRollbackEnvironment();
          if (rollbackEnvironment != null) {
            if (indicator != null) {
              indicator.setText(vcs.getDisplayName() +
                                ": performing " + UIUtil.removeMnemonic(rollbackEnvironment.getRollbackOperationName()).toLowerCase() + "...");
              indicator.setIndeterminate(false);
            }
            rollbackEnvironment
                    .rollbackModifiedWithoutCheckout(items, exceptions, new RollbackProgressModifier(items.size(), indicator));
            if (indicator != null) {
              indicator.setText2("");
            }
          }
        });
      }
      catch (ProcessCanceledException e) {
        // for files refresh
      }
      if (!exceptions.isEmpty()) {
        AbstractVcsHelper.getInstance(project).showErrors(exceptions, VcsBundle.message("rollback.modified.without.checkout.error.tab",
                                                                                        operationName));
      }

      VfsUtil.markDirty(true, false, VfsUtilCore.toVirtualFileArray(modifiedWithoutEditing));

      VirtualFileManager.getInstance().asyncRefresh(new Runnable() {
        public void run() {
          for (VirtualFile virtualFile : modifiedWithoutEditing) {
            VcsDirtyScopeManager.getInstance(project).fileDirty(virtualFile);
          }
        }
      });
    }
  };
  progressManager.runProcessWithProgressSynchronously(action, operationName, true, project);
}
 
Example 19
Source Project: consulo   File: ReplaceInProjectManager.java    License: Apache License 2.0 4 votes vote down vote up
public boolean showReplaceAllConfirmDialog(@Nonnull String usagesCount, @Nonnull String stringToFind, @Nonnull String filesCount, @Nonnull String stringToReplace) {
  return Messages.YES ==
         MessageDialogBuilder.yesNo(FindBundle.message("find.replace.all.confirmation.title"), FindBundle
                 .message("find.replace.all.confirmation", usagesCount, StringUtil.escapeXmlEntities(stringToFind), filesCount, StringUtil.escapeXmlEntities(stringToReplace))).yesText(FindBundle.message("find.replace.command")).project(myProject).noText(Messages.CANCEL_BUTTON).show();
}
 
Example 20
public static void shutdownOrRestartApp(String title) {
  final ApplicationEx app = (ApplicationEx)Application.get();
  int response = app.isRestartCapable() ? showRestartIDEADialog(title) : showShutDownIDEADialog(title);
  if (response == Messages.YES) app.restart(true);
}