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

The following examples show how to use com.intellij.openapi.ui.Messages#CANCEL . 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 File: CreateDirectoryOrPackageHandler.java    From consulo with Apache License 2.0 6 votes vote down vote up
@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 2
Source File: JBMacMessages.java    From consulo with 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 3
Source File: WindowsDefenderFixAction.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Override
public void actionPerformed(@Nonnull AnActionEvent e, @Nonnull Notification notification) {
  int rc = Messages.showDialog(e.getProject(), DiagnosticBundle
                                       .message("virus.scanning.fix.explanation", ApplicationNamesInfo.getInstance().getFullProductName(), WindowsDefenderChecker.getInstance().getConfigurationInstructionsUrl()),
                               DiagnosticBundle.message("virus.scanning.fix.title"),
                               new String[]{DiagnosticBundle.message("virus.scanning.fix.automatically"), DiagnosticBundle.message("virus.scanning.fix.manually"),
                                       CommonBundle.getCancelButtonText()}, 0, null);

  switch (rc) {
    case Messages.OK:
      notification.expire();
      ApplicationManager.getApplication().executeOnPooledThread(() -> {
        if (WindowsDefenderChecker.getInstance().runExcludePathsCommand(e.getProject(), myPaths)) {
          UIUtil.invokeLaterIfNeeded(() -> {
            Notifications.Bus.notifyAndHide(new Notification("System Health", "", DiagnosticBundle.message("virus.scanning.fix.success.notification"), NotificationType.INFORMATION), e.getProject());
          });
        }
      });

      break;
    case Messages.CANCEL:
      BrowserUtil.browse(WindowsDefenderChecker.getInstance().getConfigurationInstructionsUrl());
      break;
  }
}
 
Example 4
Source File: BlazeAndroidBinaryRunConfigurationHandler.java    From intellij with Apache License 2.0 5 votes vote down vote up
private String choiceToString(int choice) {
  if (choice == Messages.YES) {
    return "yes";
  } else if (choice == Messages.NO) {
    return "not_now";
  } else if (choice == Messages.CANCEL) {
    return "never_for_project";
  } else {
    return "unknown";
  }
}
 
Example 5
Source File: InplaceChangeSignature.java    From consulo with Apache License 2.0 5 votes vote down vote up
public InplaceChangeSignature(Project project, Editor editor, @Nonnull PsiElement element) {
  myDocumentManager = PsiDocumentManager.getInstance(project);
  myProject = project;
  try {
    myMarkAction = StartMarkAction.start(editor, project, ChangeSignatureHandler.REFACTORING_NAME);
  }
  catch (StartMarkAction.AlreadyStartedException e) {
    final int exitCode = Messages.showYesNoDialog(myProject, e.getMessage(), ChangeSignatureHandler.REFACTORING_NAME, "Navigate to Started", "Cancel", Messages.getErrorIcon());
    if (exitCode == Messages.CANCEL) return;
    PsiElement method = myStableChange.getMethod();
    VirtualFile virtualFile = PsiUtilCore.getVirtualFile(method);
    new OpenFileDescriptor(project, virtualFile, method.getTextOffset()).navigate(true);
    return;
  }


  myEditor = editor;
  myDetector = LanguageChangeSignatureDetectors.INSTANCE.forLanguage(element.getLanguage());
  myStableChange = myDetector.createInitialChangeInfo(element);
  myInitialSignature = myDetector.extractSignature(myStableChange);
  myInitialName = DescriptiveNameUtil.getDescriptiveName(myStableChange.getMethod());
  TextRange highlightingRange = myDetector.getHighlightingRange(myStableChange);

  HighlightManager highlightManager = HighlightManager.getInstance(myProject);
  TextAttributes attributes = EditorColorsManager.getInstance().getGlobalScheme().getAttributes(EditorColors.LIVE_TEMPLATE_ATTRIBUTES);
  highlightManager.addRangeHighlight(editor, highlightingRange.getStartOffset(), highlightingRange.getEndOffset(), attributes, false, myHighlighters);
  for (RangeHighlighter highlighter : myHighlighters) {
    highlighter.setGreedyToRight(true);
    highlighter.setGreedyToLeft(true);
  }
  myEditor.getDocument().addDocumentListener(this);
  myEditor.putUserData(INPLACE_CHANGE_SIGNATURE, this);
  myPreview = InplaceRefactoring.createPreviewComponent(project, myDetector.getFileType());
  showBalloon();
}
 
Example 6
Source File: FileUtils.java    From EasyCode with 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 7
Source File: BlazeAndroidBinaryRunConfigurationHandler.java    From intellij with Apache License 2.0 4 votes vote down vote up
/**
 * Maybe shows the mobile-install optin dialog, and migrates project as appropriate.
 *
 * <p>Will only be shown once per project in a 20 hour window, with the ability to permanently
 * dismiss for this project.
 *
 * <p>If the user selects "Yes", all BlazeAndroidBinaryRunConfigurations in this project will be
 * migrated to use mobile-install.
 *
 * @return true if dialog was shown and user migrated, otherwise false
 */
private boolean maybeShowMobileInstallOptIn(
    Project project, BlazeCommandRunConfiguration configuration) {
  long lastPrompt = PropertiesComponent.getInstance(project).getOrInitLong(MI_LAST_PROMPT, 0L);
  boolean neverAsk =
      PropertiesComponent.getInstance(project).getBoolean(MI_NEVER_ASK_AGAIN, false);
  if (neverAsk || (System.currentTimeMillis() - lastPrompt) < MI_TIMEOUT_MS) {
    return false;
  }
  // Add more logging on why the MI opt-in dialog is shown.  There exists a bug there a user
  // is shown the mobile-install opt-in dialog every time they switch clients. The only way for
  // this to happen is if a new target is created or if the timeouts are not behaving as expected.
  // TODO Remove once b/130327673 is resolved.
  LOG.info(
      "Showing mobile install opt-in dialog.\n"
          + "Run target: "
          + configuration.getSingleTarget()
          + "\n"
          + "Time since last prompt: "
          + (System.currentTimeMillis() - lastPrompt));
  PropertiesComponent.getInstance(project)
      .setValue(MI_LAST_PROMPT, String.valueOf(System.currentTimeMillis()));
  int choice =
      Messages.showYesNoCancelDialog(
          project,
          "Blaze mobile-install (go/blaze-mi) introduces fast, incremental builds and deploys "
              + "for Android development.\nBlaze mobile-install is the default for new Android "
              + "Studio projects, but you're still using Blaze build.\n\nSwitch all run "
              + "configurations in this project to use Blaze mobile-install?",
          "Switch to Blaze mobile-install?",
          "Yes",
          "Not now",
          "Never ask again for this project",
          Messages.getQuestionIcon());
  if (choice == Messages.YES) {
    Messages.showInfoMessage(
        String.format(
            "Successfully migrated %d run configuration(s) to mobile-install",
            doMigrate(project)),
        "Success!");
  } else if (choice == Messages.NO) {
    // Do nothing, dialog will not be shown until the wait period has elapsed
  } else if (choice == Messages.CANCEL) {
    PropertiesComponent.getInstance(project).setValue(MI_NEVER_ASK_AGAIN, true);
  }
  EventLoggingService.getInstance()
      .logEvent(
          getClass(), "mi_migrate_prompt", ImmutableMap.of("choice", choiceToString(choice)));
  return choice == Messages.YES;
}
 
Example 8
Source File: MindMapDialogProvider.java    From netbeans-mmd-plugin with Apache License 2.0 4 votes vote down vote up
@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 9
Source File: InstallPluginAction.java    From consulo with Apache License 2.0 4 votes vote down vote up
private static boolean suggestToEnableInstalledPlugins(final InstalledPluginsTableModel pluginsModel,
                                                       final Set<PluginDescriptor> disabled,
                                                       final Set<PluginDescriptor> disabledDependants,
                                                       final List<PluginDescriptor> list) {
  if (!disabled.isEmpty() || !disabledDependants.isEmpty()) {
    String message = "";
    if (disabled.size() == 1) {
      message += "Updated plugin '" + disabled.iterator().next().getName() + "' is disabled.";
    }
    else if (!disabled.isEmpty()) {
      message += "Updated plugins " + StringUtil.join(disabled, PluginDescriptor::getName, ", ") + " are disabled.";
    }

    if (!disabledDependants.isEmpty()) {
      message += "<br>";
      message += "Updated plugin" + (list.size() > 1 ? "s depend " : " depends ") + "on disabled";
      if (disabledDependants.size() == 1) {
        message += " plugin '" + disabledDependants.iterator().next().getName() + "'.";
      }
      else {
        message += " plugins " + StringUtil.join(disabledDependants, PluginDescriptor::getName, ", ") + ".";
      }
    }
    message += " Disabled plugins and plugins which depends on disabled plugins won't be activated after restart.";

    int result;
    if (!disabled.isEmpty() && !disabledDependants.isEmpty()) {
      result = Messages.showYesNoCancelDialog(XmlStringUtil.wrapInHtml(message), CommonBundle.getWarningTitle(), "Enable all", "Enable updated plugin" + (disabled.size() > 1 ? "s" : ""),
                                              CommonBundle.getCancelButtonText(), Messages.getQuestionIcon());
      if (result == Messages.CANCEL) return false;
    }
    else {
      message += "<br>Would you like to enable ";
      if (!disabled.isEmpty()) {
        message += "updated plugin" + (disabled.size() > 1 ? "s" : "");
      }
      else {
        //noinspection SpellCheckingInspection
        message += "plugin dependenc" + (disabledDependants.size() > 1 ? "ies" : "y");
      }
      message += "?</body></html>";
      result = Messages.showYesNoDialog(message, CommonBundle.getWarningTitle(), Messages.getQuestionIcon());
      if (result == Messages.NO) return false;
    }

    if (result == Messages.YES) {
      disabled.addAll(disabledDependants);
      pluginsModel.enableRows(disabled.toArray(new PluginDescriptor[disabled.size()]), true);
    }
    else if (result == Messages.NO && !disabled.isEmpty()) {
      pluginsModel.enableRows(disabled.toArray(new PluginDescriptor[disabled.size()]), true);
    }
    return true;
  }
  return false;
}
 
Example 10
Source File: InplaceRefactoring.java    From consulo with Apache License 2.0 4 votes vote down vote up
protected boolean buildTemplateAndStart(final Collection<PsiReference> refs,
                                        final Collection<Pair<PsiElement, TextRange>> stringUsages,
                                        final PsiElement scope,
                                        final PsiFile containingFile) {
  final PsiElement context = InjectedLanguageManager.getInstance(containingFile.getProject()).getInjectionHost(containingFile);
  myScope = context != null ? context.getContainingFile() : scope;
  final TemplateBuilderImpl builder = new TemplateBuilderImpl(myScope);

  PsiElement nameIdentifier = getNameIdentifier();
  int offset = myEditor.getCaretModel().getOffset();
  PsiElement selectedElement = getSelectedInEditorElement(nameIdentifier, refs, stringUsages, offset);

  boolean subrefOnPrimaryElement = false;
  boolean hasReferenceOnNameIdentifier = false;
  for (PsiReference ref : refs) {
    if (isReferenceAtCaret(selectedElement, ref)) {
      builder.replaceElement(ref, PRIMARY_VARIABLE_NAME, createLookupExpression(selectedElement), true);
      subrefOnPrimaryElement = true;
      continue;
    }
    addVariable(ref, selectedElement, builder, offset);
    hasReferenceOnNameIdentifier |= isReferenceAtCaret(nameIdentifier, ref);
  }
  if (nameIdentifier != null) {
    hasReferenceOnNameIdentifier |= selectedElement.getTextRange().contains(nameIdentifier.getTextRange());
    if (!subrefOnPrimaryElement || !hasReferenceOnNameIdentifier){
      addVariable(nameIdentifier, selectedElement, builder);
    }
  }
  for (Pair<PsiElement, TextRange> usage : stringUsages) {
    addVariable(usage.first, usage.second, selectedElement, builder);
  }
  addAdditionalVariables(builder);
  try {
    myMarkAction = startRename();
  }
  catch (final StartMarkAction.AlreadyStartedException e) {
    final Document oldDocument = e.getDocument();
    if (oldDocument != myEditor.getDocument()) {
      final int exitCode = Messages.showYesNoCancelDialog(myProject, e.getMessage(), getCommandName(),
                                                          "Navigate to Started", "Cancel Started", "Cancel", Messages.getErrorIcon());
      if (exitCode == Messages.CANCEL) return true;
      navigateToAlreadyStarted(oldDocument, exitCode);
      return true;
    }
    else {

      if (!ourRenamersStack.isEmpty() && ourRenamersStack.peek() == this) {
        ourRenamersStack.pop();
        if (!ourRenamersStack.empty()) {
          myOldName = ourRenamersStack.peek().myOldName;
        }
      }

      revertState();
      final TemplateState templateState = TemplateManagerImpl.getTemplateState(InjectedLanguageUtil.getTopLevelEditor(myEditor));
      if (templateState != null) {
        templateState.gotoEnd(true);
      }
    }
    return false;
  }

  beforeTemplateStart();

  new WriteCommandAction(myProject, getCommandName()) {
    @Override
    protected void run(com.intellij.openapi.application.Result result) throws Throwable {
      startTemplate(builder);
    }
  }.execute();

  if (myBalloon == null) {
    showBalloon();
  }
  return true;
}
 
Example 11
Source File: MacMessagesImpl.java    From consulo with Apache License 2.0 4 votes vote down vote up
@Messages.YesNoCancelResult
public static int showAlertDialog(@Nonnull String title,
                                  @Nonnull String defaultText,
                                  @Nullable final String alternateText,
                                  @Nullable final String otherText,
                                  final String message,
                                  @Nullable consulo.ui.Window window,
                                  final boolean errorStyle,
                                  @Nullable final DialogWrapper.DoNotAskOption doNotAskDialogOption) {

  Map<Enum, Object> params  = new HashMap<Enum, Object> ();

  ID pool = invoke(invoke("NSAutoreleasePool", "alloc"), "init");
  try {
    params.put(COMMON_DIALOG_PARAM_TYPE.title, nsString(title));
    params.put(ALERT_DIALOG_PARAM_TYPE.defaultText, nsString(UIUtil.removeMnemonic(defaultText)));
    params.put(ALERT_DIALOG_PARAM_TYPE.alternateText, nsString(otherText == null ? "-1" : UIUtil.removeMnemonic(otherText)));
    params.put(ALERT_DIALOG_PARAM_TYPE.otherText, nsString(alternateText == null ? "-1" : UIUtil.removeMnemonic(alternateText)));
    // replace % -> %% to avoid formatted parameters (causes SIGTERM)
    params.put(COMMON_DIALOG_PARAM_TYPE.message, nsString(StringUtil.stripHtml(message == null ? "" : message, true).replace("%", "%%")));
    params.put(COMMON_DIALOG_PARAM_TYPE.errorStyle, nsString(errorStyle ? "error" : "-1"));
    params.put(COMMON_DIALOG_PARAM_TYPE.doNotAskDialogOption1, nsString(doNotAskDialogOption == null || !doNotAskDialogOption.canBeHidden()
                                                                        // TODO: state=!doNotAsk.shouldBeShown()
                                                                        ? "-1"
                                                                        : doNotAskDialogOption.getDoNotShowMessage()));
    params.put(COMMON_DIALOG_PARAM_TYPE.doNotAskDialogOption2, nsString(doNotAskDialogOption != null
                                                                        && !doNotAskDialogOption.isToBeShown() ? "checked" : "-1"));
    MessageResult result = resultsFromDocumentRoot.remove(
            showDialog(window, "showSheet:", new DialogParamsWrapper(DialogParamsWrapper.DialogType.alert, params)));

    int convertedResult = convertReturnCodeFromNativeAlertDialog(result.myReturnCode, alternateText);

    if (doNotAskDialogOption != null && doNotAskDialogOption.canBeHidden()) {
      boolean operationCanceled = convertedResult == Messages.CANCEL;
      if (!operationCanceled || doNotAskDialogOption.shouldSaveOptionsOnCancel()) {
        doNotAskDialogOption.setToBeShown(!result.mySuppress, convertedResult);
      }
    }

    return convertedResult;
  }
  finally {
    invoke(pool, "release");
  }
}
 
Example 12
Source File: MacMessagesImpl.java    From consulo with Apache License 2.0 4 votes vote down vote up
@Messages.YesNoCancelResult
private static int convertReturnCodeFromNativeAlertDialog(int returnCode, String alternateText) {
  // DEFAULT = 1
  // ALTERNATE = 0
  // OTHER = -1 (cancel)

  int cancelCode;
  int code;
  if (alternateText != null) {
    // DEFAULT = 0
    // ALTERNATE = 1
    // CANCEL = 2

    cancelCode = Messages.CANCEL;

    switch (returnCode) {
      case 1:
        code = Messages.YES;
        break;
      case 0:
        code = Messages.NO;
        break;
      case -1: // cancel
      default:
        code = Messages.CANCEL;
        break;
    }
  }
  else {
    // DEFAULT = 0
    // CANCEL = 1

    cancelCode = 1;

    switch (returnCode) {
      case 1:
        code = Messages.YES;
        break;
      case -1: // cancel
      default:
        code = Messages.NO;
        break;
    }
  }

  if (cancelCode == code) {
    code = Messages.CANCEL;
  }
  LOG.assertTrue(code == Messages.YES || code == Messages.NO || code == Messages.CANCEL, code);
  return code;
}