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

The following examples show how to use com.intellij.openapi.ui.Messages#NO . 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: PantsOpenProjectProvider.java    From intellij-pants-plugin with Apache License 2.0 6 votes vote down vote up
@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 2
Source File: PantsOpenProjectProvider.java    From intellij-pants-plugin with Apache License 2.0 6 votes vote down vote up
private int shouldOpenExistingProject(VirtualFile file, Project projectToClose) {
  VirtualFile rootFile = PantsUtil.findBuildRoot(file).orElse(null);
  if(rootFile == null) return Messages.NO;

  ProjectOpenProcessor openProcessor = PlatformProjectOpenProcessor.getInstance();
  if (!openProcessor.canOpenProject(rootFile)) return Messages.NO;

  VirtualFile dotIdeaFile = rootFile.findChild(Project.DIRECTORY_STORE_FOLDER);
  if (dotIdeaFile == null || !dotIdeaFile.exists()) return Messages.NO;

  Application application = ApplicationManager.getApplication();
  if (application.isHeadlessEnvironment()) return Messages.YES;

  return Messages.showYesNoCancelDialog(
    projectToClose,
    JavaUiBundle.message("project.import.open.existing", "an existing project", rootFile.getPath(), file.getName()),
    IdeBundle.message("title.open.project"),
    JavaUiBundle.message("project.import.open.existing.openExisting"),
    JavaUiBundle.message("project.import.open.existing.reimport"),
    CommonBundle.getCancelButtonText(),
    Messages.getQuestionIcon()
  );
}
 
Example 3
Source File: SafeDialogUtils.java    From saros with GNU General Public License v2.0 6 votes vote down vote up
/**
 * 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 4
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 5
Source File: JBMacMessages.java    From consulo with Apache License 2.0 6 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,
                           @Nullable DialogWrapper.DoNotAskOption doNotAskDialogOption) {
  if (window == null) {
    window = getForemostWindow(null);
  }
  SheetMessage sheetMessage = new SheetMessage(window, title, message, UIUtil.getQuestionIcon(),
                                               new String [] {yesButton, noButton}, doNotAskDialogOption, yesButton, noButton);
  int result = sheetMessage.getResult().equals(yesButton) ? Messages.YES : Messages.NO;
  if (doNotAskDialogOption != null) {
    doNotAskDialogOption.setToBeShown(sheetMessage.toBeShown(), result);
  }
  return result;
}
 
Example 6
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 7
Source File: NewProjectAction.java    From consulo with Apache License 2.0 5 votes vote down vote up
@RequiredUIAccess
private static void generateProjectAsync(Project project, @Nonnull NewProjectPanel panel) {
  // leave current step
  panel.finish();

  NewModuleWizardContext context = panel.getWizardContext();

  final File location = new File(context.getPath());
  final int childCount = location.exists() ? location.list().length : 0;
  if (!location.exists() && !location.mkdirs()) {
    Messages.showErrorDialog(project, "Cannot create directory '" + location + "'", "Create Project");
    return;
  }

  final VirtualFile baseDir = WriteAction.compute(() -> LocalFileSystem.getInstance().refreshAndFindFileByIoFile(location));
  baseDir.refresh(false, true);

  if (childCount > 0) {
    int rc = Messages.showYesNoDialog(project, "The directory '" + location + "' is not empty. Continue?", "Create New Project", Messages.getQuestionIcon());
    if (rc == Messages.NO) {
      return;
    }
  }

  RecentProjectsManager.getInstance().setLastProjectCreationLocation(location.getParent());

  UIAccess uiAccess = UIAccess.current();
  ProjectManager.getInstance().openProjectAsync(baseDir, uiAccess).doWhenDone((openedProject) -> {
    uiAccess.give(() -> NewOrImportModuleUtil.doCreate(panel, openedProject, baseDir));
  });
}
 
Example 8
Source File: JBMacMessages.java    From consulo with 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 9
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 10
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 11
Source File: BlazeAndroidDeviceSelector.java    From intellij with Apache License 2.0 4 votes vote down vote up
private boolean promptAndKillSession(
    Executor executor, Project project, AndroidSessionInfo info) {
  String previousExecutor = info.getExecutorId();
  String currentExecutor = executor.getId();

  if (ourKillLaunchOption.isToBeShown()) {
    String msg;
    String noText;
    if (previousExecutor.equals(currentExecutor)) {
      msg =
          String.format(
              "Restart App?\nThe app is already running. "
                  + "Would you like to kill it and restart the session?");
      noText = "Cancel";
    } else {
      msg =
          String.format(
              "To switch from %1$s to %2$s, the app has to restart. Continue?",
              previousExecutor, currentExecutor);
      noText = "Cancel " + currentExecutor;
    }

    String targetName = info.getExecutionTarget().getDisplayName();
    String title = "Launching " + targetName;
    String yesText = "Restart " + targetName;
    if (Messages.NO
        == Messages.showYesNoDialog(
            project,
            msg,
            title,
            yesText,
            noText,
            AllIcons.General.QuestionDialog,
            ourKillLaunchOption)) {
      return false;
    }
  }

  LOG.info("Disconnecting existing session of the same launch configuration");
  info.getProcessHandler().detachProcess();
  return true;
}
 
Example 12
Source File: KeymapPanel.java    From consulo with Apache License 2.0 4 votes vote down vote up
private void addMouseShortcut(Shortcut shortcut, ShortcutRestrictions restrictions) {
  String actionId = myActionsTree.getSelectedActionId();
  if (actionId == null) {
    return;
  }

  if (!createKeymapCopyIfNeeded()) return;

  MouseShortcut mouseShortcut = shortcut instanceof MouseShortcut ? (MouseShortcut)shortcut : null;

  MouseShortcutDialog dialog = new MouseShortcutDialog(this, mouseShortcut, mySelectedKeymap, actionId, myActionsTree.getMainGroup(), restrictions);
  dialog.show();
  if (!dialog.isOK()) {
    return;
  }

  mouseShortcut = dialog.getMouseShortcut();

  if (mouseShortcut == null) {
    return;
  }

  String[] actionIds = mySelectedKeymap.getActionIds(mouseShortcut);
  if (actionIds.length > 1 || (actionIds.length == 1 && !actionId.equals(actionIds[0]))) {
    int result = Messages.showYesNoCancelDialog(this, KeyMapBundle.message("conflict.shortcut.dialog.message"),
                                                KeyMapBundle.message("conflict.shortcut.dialog.title"),
                                                KeyMapBundle.message("conflict.shortcut.dialog.remove.button"),
                                                KeyMapBundle.message("conflict.shortcut.dialog.leave.button"),
                                                KeyMapBundle.message("conflict.shortcut.dialog.cancel.button"), Messages.getWarningIcon());

    if (result == Messages.YES) {
      for (String id : actionIds) {
        mySelectedKeymap.removeShortcut(id, mouseShortcut);
      }
    }
    else if (result != Messages.NO) {
      return;
    }
  }

  // if shortcut is aleady registered to this action, just select it in the list

  Shortcut[] shortcuts = mySelectedKeymap.getShortcuts(actionId);
  for (Shortcut shortcut1 : shortcuts) {
    if (shortcut1.equals(mouseShortcut)) {
      return;
    }
  }

  mySelectedKeymap.addShortcut(actionId, mouseShortcut);
  if (StringUtil.startsWithChar(actionId, '$')) {
    mySelectedKeymap.addShortcut(KeyMapBundle.message("editor.shortcut", actionId.substring(1)), mouseShortcut);
  }

  repaintLists();
  processCurrentKeymapChanged(getCurrentQuickListIds());
}
 
Example 13
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 14
Source File: MacMessagesImpl.java    From consulo with Apache License 2.0 4 votes vote down vote up
@Override
@Messages.YesNoResult
public int showYesNoDialog(@Nonnull String title, String message, @Nonnull String yesButton, @Nonnull String noButton, @Nullable consulo.ui.Window window) {
  return showAlertDialog(title, yesButton, null, noButton, message, window) == Messages.YES ? Messages.YES : Messages.NO;
}
 
Example 15
Source File: MacMessagesImpl.java    From consulo with Apache License 2.0 4 votes vote down vote up
@Override
@Messages.YesNoResult
public int showYesNoDialog(@Nonnull String title, String message, @Nonnull String yesButton, @Nonnull String noButton, @Nullable consulo.ui.Window window,
                           @Nullable DialogWrapper.DoNotAskOption doNotAskDialogOption) {
  return showAlertDialog(title, yesButton, null, noButton, message, window, false, doNotAskDialogOption) == Messages.YES ? Messages.YES : Messages.NO;
}
 
Example 16
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;
}