Example usage for com.intellij.openapi.ui Messages showOkCancelDialog

List of usage examples for com.intellij.openapi.ui Messages showOkCancelDialog

Introduction

In this page you can find the example usage for com.intellij.openapi.ui Messages showOkCancelDialog.

Prototype

@OkCancelResult
@Deprecated
public static int showOkCancelDialog(@NotNull Component parent, String message,
        @Nls(capitalization = Nls.Capitalization.Title) String title, Icon icon) 

Source Link

Usage

From source file:com.intellij.ui.tabs.impl.DragHelper.java

License:Apache License

@Override
protected void processDragFinish(MouseEvent event, boolean willDragOutStart) {
    super.processDragFinish(event, willDragOutStart);

    endDrag(willDragOutStart);/*from   w w  w  .  j  a va  2s  .  c o m*/

    final JBTabsPosition position = myTabs.getTabsPosition();

    if (!willDragOutStart && myTabs.isAlphabeticalMode() && position != JBTabsPosition.top
            && position != JBTabsPosition.bottom) {
        Point p = new Point(event.getPoint());
        p = SwingUtilities.convertPoint(event.getComponent(), p, myTabs);
        if (myTabs.getVisibleRect().contains(p)
                && myPressedOnScreenPoint.distance(new RelativePoint(event).getScreenPoint()) > 15) {
            final int answer = Messages.showOkCancelDialog(myTabs,
                    IdeBundle.message("alphabetical.mode.is.on.warning"), IdeBundle.message("title.warning"),
                    Messages.getQuestionIcon());
            if (answer == Messages.OK) {
                JBEditorTabs.setAlphabeticalMode(false);
                myTabs.relayout(true, false);
                myTabs.revalidate();
            }
        }
    }
}

From source file:com.jetbrains.lang.dart.ide.actions.DartSortMembersAction.java

License:Apache License

protected void runOverFiles(@NotNull final Project project, @NotNull final List<VirtualFile> dartFiles) {
    if (dartFiles.isEmpty()) {
        Messages.showInfoMessage(project, DartBundle.message("dart.sort.members.files.no.dart.files"),
                DartBundle.message("dart.sort.members.action.name"));
        return;/*from   www. ja v  a2  s  .c  o  m*/
    }

    if (Messages.showOkCancelDialog(project,
            DartBundle.message("dart.sort.members.files.dialog.question", dartFiles.size()),
            DartBundle.message("dart.sort.members.action.name"), null) != Messages.OK) {
        return;
    }

    final Map<VirtualFile, SourceFileEdit> fileToFileEditMap = Maps.newHashMap();

    final Runnable runnable = () -> {
        double fraction = 0.0;
        for (final VirtualFile virtualFile : dartFiles) {
            fraction += 1.0;
            final ProgressIndicator indicator = ProgressManager.getInstance().getProgressIndicator();
            if (indicator != null) {
                indicator.checkCanceled();
                indicator.setFraction(fraction / dartFiles.size());
                indicator.setText2(FileUtil.toSystemDependentName(virtualFile.getPath()));
            }

            final String path = virtualFile.getPath();
            final SourceFileEdit fileEdit = DartAnalysisServerService.getInstance(project)
                    .edit_sortMembers(path);
            if (fileEdit != null) {
                fileToFileEditMap.put(virtualFile, fileEdit);
            }
        }
    };

    DartAnalysisServerService.getInstance(project).updateFilesContent();

    final boolean ok = ApplicationManagerEx.getApplicationEx().runProcessWithProgressSynchronously(runnable,
            DartBundle.message("dart.sort.members.action.name"), true, project);

    if (ok) {
        final Runnable onSuccessRunnable = () -> {
            CommandProcessor.getInstance().markCurrentCommandAsGlobal(project);

            for (Map.Entry<VirtualFile, SourceFileEdit> entry : fileToFileEditMap.entrySet()) {
                final VirtualFile file = entry.getKey();
                final Document document = FileDocumentManager.getInstance().getDocument(file);
                final SourceFileEdit fileEdit = entry.getValue();
                if (document != null) {
                    AssistUtils.applySourceEdits(project, file, document, fileEdit.getEdits(),
                            Collections.emptySet());
                }
            }
        };

        ApplicationManager.getApplication()
                .runWriteAction(() -> CommandProcessor.getInstance().executeCommand(project, onSuccessRunnable,
                        DartBundle.message("dart.sort.members.action.name"), null));
    }
}

From source file:com.maddyhome.idea.copyright.actions.GenerateCopyrightAction.java

License:Apache License

public void actionPerformed(AnActionEvent event) {
    DataContext context = event.getDataContext();
    Project project = CommonDataKeys.PROJECT.getData(context);
    assert project != null;
    Module module = LangDataKeys.MODULE.getData(context);
    PsiDocumentManager.getInstance(project).commitAllDocuments();

    PsiFile file = getFile(context, project);
    assert file != null;
    if (CopyrightManager.getInstance(project).getCopyrightOptions(file) == null) {
        if (Messages.showOkCancelDialog(project,
                "No copyright configured for current file. Would you like to edit copyright settings?",
                "No Copyright Available", Messages.getQuestionIcon()) == DialogWrapper.OK_EXIT_CODE) {
            ShowSettingsUtil.getInstance().showSettingsDialog(project,
                    new CopyrightProjectConfigurable(project).getDisplayName());
        } else {//  ww w .  java2 s  .  c o m
            return;
        }
    }
    new UpdateCopyrightProcessor(project, module, file).run();
}

From source file:com.mediaworx.intellij.opencmsplugin.sync.OpenCmsSyncer.java

License:Open Source License

/**
 * Analyzes the given file list using the {@link SyncFileAnalyzer} and triggers the sync to/from OpenCms using
 * the {@link SyncJob}//from w  ww  .  ja v a 2  s  . c o m
 * @param syncFiles list of local files (and folders) that are used as starting point for the sync
 */
public void syncFiles(List<File> syncFiles) {

    SyncFileAnalyzer analyzer;

    try {
        analyzer = new SyncFileAnalyzer(plugin, syncFiles, pullMetaDataOnly);
    } catch (CmsConnectionException e) {
        Messages.showDialog(e.getMessage(), "Error", new String[] { "Ok" }, 0, Messages.getErrorIcon());
        return;
    }

    ProgressManager.getInstance().runProcessWithProgressSynchronously(analyzer,
            "Analyzing local and VFS syncFiles and folders ...", true, plugin.getProject());

    if (!analyzer.isExecuteSync()) {
        return;
    }

    int numSyncEntities = analyzer.getSyncList().size();

    boolean proceed = numSyncEntities > 0;
    LOG.info("proceed? " + proceed);

    StringBuilder message = new StringBuilder();
    if (analyzer.hasWarnings()) {
        message.append("Infos/Warnings during file analysis:\n").append(analyzer.getWarnings().append("\n"));
    }
    if (proceed) {
        SyncJob syncJob = new SyncJob(plugin, analyzer.getSyncList());
        if (showConfirmDialog && !pullMetaDataOnly
                && ((numSyncEntities == 1 && message.length() > 0) || numSyncEntities > 1)) {
            assembleConfirmMessage(message, syncJob.getSyncList());
            int dlgStatus = Messages.showOkCancelDialog(plugin.getProject(), message.toString(),
                    "Start OpenCms VFS Sync?", Messages.getQuestionIcon());
            proceed = dlgStatus == 0;
        }
        if (proceed) {
            plugin.showConsole();
            new Thread(syncJob).start();
        }
    } else {
        message.append("Nothing to sync");
        Messages.showMessageDialog(message.toString(), "OpenCms VFS Sync", Messages.getInformationIcon());
    }
}

From source file:com.ritesh.idea.plugin.ui.action.ShowReviewBoard.java

License:Apache License

@Override
public void actionPerformed(final AnActionEvent e) {
    try {//  w  w w . j  a v a 2 s. co m
        final Project project = e.getProject();
        final IVcsDiffProvider vcsDiffProvider = VcsDiffProviderFactory.getVcsDiffProvider(project,
                ReviewDataProvider.getConfiguration(project));
        ApplicationManager.getApplication().runWriteAction(new Runnable() {
            public void run() {
                FileDocumentManager.getInstance().saveAllDocuments();
            }
        });
        if (vcsDiffProvider == null) {
            Notifications.Bus.notify(new Notification("ReviewBoard",
                    PluginBundle.message(PluginBundle.UNSUPPORTED_VCS_TITLE),
                    PluginBundle.message(PluginBundle.UNSUPPORTED_VCS_MESSAGE), NotificationType.WARNING));
            return;
        }
        if (vcsDiffProvider.isFromRevision(project, e) || Messages.showOkCancelDialog(project,
                "Upload all local changes?", "Confirmation", AllIcons.General.BalloonWarning) == Messages.OK) {
            TaskUtil.queueTask(project, "Generating diff", false,
                    new ThrowableFunction<ProgressIndicator, Object>() {
                        @Override
                        public Object throwableCall(ProgressIndicator params) throws Exception {
                            final String diffContent;
                            try {
                                diffContent = vcsDiffProvider.generateDiff(project, e);
                                ApplicationManager.getApplication().invokeLater(new Runnable() {
                                    @Override
                                    public void run() {
                                        if (isEmpty(diffContent)) {
                                            Messages.showErrorDialog(project, "Cannot generate diff", "Error");
                                        } else {
                                            showCreateReviewPanel(project, diffContent);
                                        }
                                    }
                                });
                            } catch (Exception ex) {
                                ExceptionHandler.handleException(ex);
                            }
                            return null;
                        }
                    }, null, null);

        }
    } catch (Exception ex) {
        ExceptionHandler.handleException(ex);
    }
}

From source file:defrac.intellij.sdk.DefracSdkType.java

License:Apache License

@Override
public void showCustomCreateUI(final SdkModel sdkModel, final JComponent parentComponent,
        final Consumer<Sdk> sdkCreatedCallback) {
    customImpl: {/*from ww w  .j  a  v a 2  s.c o m*/
        final Collection<String> homePaths = suggestHomePaths();

        if (homePaths.isEmpty()) {
            break customImpl;
        }

        final String home = homePaths.iterator().next();
        final File homePath = new File(home);

        if (!homePath.isDirectory()) {
            break customImpl;
        }

        if (!checkDependency(sdkModel)) {
            if (Messages.showOkCancelDialog(parentComponent, getUnsatisfiedDependencyMessage(),
                    "Cannot Create SDK", Messages.getWarningIcon()) != Messages.OK) {
                return;
            }

            if (fixDependency(sdkModel, sdkCreatedCallback) == null) {
                return;
            }
        }

        final String newSdkName = SdkConfigurationUtil.createUniqueSdkName(this, home,
                Arrays.asList(sdkModel.getSdks()));
        final ProjectJdkImpl newJdk = new ProjectJdkImpl(newSdkName, this);

        newJdk.setHomePath(home);
        sdkCreatedCallback.consume(newJdk);

        return;
    }

    super.showCustomCreateUI(sdkModel, parentComponent, sdkCreatedCallback);
}

From source file:net.groboclown.idea.p4ic.actions.P4WorkOfflineAction.java

License:Apache License

@Override
public void actionPerformed(@NotNull AnActionEvent e) {
    Project project = getProject(e);/*from ww w.ja va2  s. c  o  m*/
    if (project == null) {
        return;
    }
    final P4Vcs vcs = P4Vcs.getInstance(getProject(e));
    List<P4Server> onlineServers = new ArrayList<P4Server>();
    for (P4Server server : vcs.getP4Servers()) {
        if (server.isWorkingOnline()) {
            onlineServers.add(server);
        }
    }
    if (!onlineServers.isEmpty()) {
        if (Messages.showOkCancelDialog(e.getProject(),
                P4Bundle.message("dialog.go-offline.message", P4Bundle.applicationName()),
                P4Bundle.message("dialog.go-offline.title"), Messages.getQuestionIcon()) == Messages.CANCEL) {
            return;
        }
        for (P4Server server : onlineServers) {
            server.workOffline();
        }
    }
}

From source file:org.community.intellij.plugins.communitycase.checkin.CheckinEnvironment.java

License:Apache License

/**
 * Preform a merge commit// w  w  w  . ja va  2  s .c om
 *
 *
 * @param project     a project
 * @param root        a vcs root
 * @param added       added files
 * @param removed     removed files
 * @param modified    modified files
 * @param messageFile a message file for commit
 * @param exceptions  the list of exceptions to report    @return true if merge commit was successful
 * */
private static boolean mergeCommit(final Project project, final VirtualFile root, final Set<FilePath> added,
        final Set<FilePath> removed, final Set<FilePath> modified, final File messageFile,
        List<VcsException> exceptions) {
    /*    HashSet<FilePath> realAdded = new HashSet<FilePath>();
        HashSet<FilePath> realRemoved = new HashSet<FilePath>();
        // perform diff
        SimpleHandler diff = new SimpleHandler(project, root, Command.DIFF);
        diff.setRemote(true);
        diff.setSilent(true);
        diff.setStdoutSuppressed(true);
        diff.addParameters("--diff-filter=ADMRUX", "--name-status", "HEAD");
        diff.endOptions();
        String output;
        try {
          output = diff.run();
        }
        catch (VcsException ex) {
          exceptions.add(ex);
          return false;
        }
        String rootPath = root.getPath();
        for (StringTokenizer lines = new StringTokenizer(output, "\n", false); lines.hasMoreTokens();) {
          String line = lines.nextToken().trim();
          if (line.length() == 0) {
            continue;
          }
          String[] tk = line.split("[ \t]+");
          switch (tk[0].charAt(0)) {
            case 'M':
            case 'A':
              realAdded.add(VcsUtil.getFilePath(rootPath + "/" + tk[tk.length - 1]));
              break;
            case 'D':
              realRemoved.add(VcsUtil.getFilePathForDeletedFile(rootPath + "/" + tk[tk.length - 1], false));
              break;
            default:
              throw new IllegalStateException("Unexpected status: " + line);
          }
        }
        realAdded.removeAll(added);
        realRemoved.removeAll(removed);
    */
    //if (realAdded.size() != 0 || realRemoved.size() != 0) {
    TreeSet<String> files = new TreeSet<String>();
    /*
      for (FilePath f : realAdded) {
        files.add(f.getPresentableUrl());
      }
      for (FilePath f : realRemoved) {
        files.add(f.getPresentableUrl());
      }
      */
    for (FilePath f : added) {
        files.add(f.getPresentableUrl());
    }
    for (FilePath f : removed) {
        files.add(f.getPresentableUrl());
    }
    for (FilePath f : modified) {
        files.add(f.getPresentableUrl());
    }
    final StringBuilder fileList = new StringBuilder();
    for (String f : files) {
        //noinspection HardCodedStringLiteral
        fileList.append("<li>");
        fileList.append(StringUtil.escapeXml(f));
        fileList.append("</li>");
    }
    final int[] rc = new int[1];
    try {
        EventQueue.invokeAndWait(new Runnable() {
            public void run() {
                rc[0] = Messages.showOkCancelDialog(project,
                        Bundle.message("commit.partial.merge.message", fileList.toString()),
                        Bundle.getString("commit.partial.merge.title"), null);

            }
        });
    } catch (RuntimeException ex) {
        throw ex;
    } catch (Exception ex) {
        throw new RuntimeException("Unable to invoke a message box on AWT thread", ex);
    }
    if (rc[0] != 0) {
        return false;
    }
    // update non-indexed files
    /*if (!updateIndex(project, root, realAdded, realRemoved, exceptions)) {
      return false;
    }
    for (FilePath f : realAdded) {
      VcsDirtyScopeManager.getInstance(project).fileDirty(f);
    }
    for (FilePath f : realRemoved) {
      VcsDirtyScopeManager.getInstance(project).fileDirty(f);
    }*/
    //}
    // perform merge commit
    try {
        SimpleHandler handler = new SimpleHandler(project, root, Command.CHECKIN);
        handler.addParameters("-cfi", messageFile.getAbsolutePath());
        handler.endOptions();
        for (FilePath path : added)
            handler.addParameters(path.getName());
        for (FilePath path : modified)
            handler.addParameters(path.getName());
        for (FilePath path : removed)
            handler.addParameters(path.getName());
        handler.run();
    } catch (VcsException ex) {
        exceptions.add(ex);
        return false;
    }
    return true;
}

From source file:org.jetbrains.android.inspections.MoveFileQuickFix.java

License:Apache License

@Override
public void applyFix(@NotNull Project project, @NotNull ProblemDescriptor descriptor) {
    final XmlFile xmlFile = myFile.getElement();
    if (xmlFile == null) {
        return;/*from  ww  w.j a va 2s.  c om*/
    }

    // Following assertions should be satisfied by xmlFile being passed to the constructor
    final PsiDirectory directory = xmlFile.getContainingDirectory();
    assert directory != null;

    final PsiDirectory parent = directory.getParent();
    assert parent != null;

    PsiDirectory existingDirectory = parent.findSubdirectory(myFolderName);
    final PsiDirectory resultDirectory = existingDirectory == null ? parent.createSubdirectory(myFolderName)
            : existingDirectory;

    final boolean removeFirst;
    if (resultDirectory.findFile(xmlFile.getName()) != null) {
        final String message = String.format("File %s already exists in directory %s. Overwrite it?",
                xmlFile.getName(), resultDirectory.getName());
        removeFirst = Messages.showOkCancelDialog(project, message, "Move Resource File",
                Messages.getWarningIcon()) == Messages.OK;

        if (!removeFirst) {
            // User pressed "Cancel", do nothing
            return;
        }
    } else {
        removeFirst = false;
    }

    new WriteCommandAction.Simple(project, xmlFile) {
        @Override
        protected void run() throws Throwable {
            if (removeFirst) {
                final PsiFile file = resultDirectory.findFile(xmlFile.getName());
                if (file != null) {
                    file.delete();
                }
            }
            MoveFilesOrDirectoriesUtil.doMoveFile(xmlFile, resultDirectory);
        }
    }.execute();
}

From source file:org.jetbrains.idea.svn.checkin.SvnCheckinHandlerFactory.java

License:Apache License

@NotNull
@Override/*w  w w .j av  a 2  s.  c  o m*/
protected CheckinHandler createVcsHandler(final CheckinProjectPanel panel) {
    final Project project = panel.getProject();
    final Collection<VirtualFile> commitRoots = panel.getRoots();
    return new CheckinHandler() {
        private Collection<Change> myChanges = panel.getSelectedChanges();

        @Override
        public RefreshableOnComponent getBeforeCheckinConfigurationPanel() {
            return null;
        }

        @Override
        public ReturnResult beforeCheckin(@Nullable CommitExecutor executor,
                PairConsumer<Object, Object> additionalDataConsumer) {
            if (executor instanceof LocalCommitExecutor)
                return ReturnResult.COMMIT;
            final SvnVcs vcs = SvnVcs.getInstance(project);
            final Map<String, Integer> copiesInfo = splitIntoCopies(vcs, myChanges);
            final List<String> repoUrls = new ArrayList<String>();
            for (Map.Entry<String, Integer> entry : copiesInfo.entrySet()) {
                if (entry.getValue() == 3) {
                    repoUrls.add(entry.getKey());
                }
            }
            if (!repoUrls.isEmpty()) {
                final String join = StringUtil.join(repoUrls.toArray(new String[repoUrls.size()]), ",\n");
                final int isOk = Messages.showOkCancelDialog(
                        project, SvnBundle.message("checkin.different.formats.involved",
                                repoUrls.size() > 1 ? 1 : 0, join),
                        "Subversion: Commit Will Split", Messages.getWarningIcon());
                if (Messages.OK == isOk) {
                    return ReturnResult.COMMIT;
                }
                return ReturnResult.CANCEL;
            }
            return ReturnResult.COMMIT;
        }

        @Override
        public void includedChangesChanged() {
            myChanges = panel.getSelectedChanges();
        }

        @Override
        public void checkinSuccessful() {
            if (SvnConfiguration.getInstance(project).isAutoUpdateAfterCommit()) {
                final VirtualFile[] roots = ProjectLevelVcsManager.getInstance(project)
                        .getRootsUnderVcs(SvnVcs.getInstance(project));
                final List<FilePath> paths = new ArrayList<FilePath>();
                for (int i = 0; i < roots.length; i++) {
                    VirtualFile root = roots[i];
                    boolean take = false;
                    for (VirtualFile commitRoot : commitRoots) {
                        if (VfsUtil.isAncestor(root, commitRoot, false)) {
                            take = true;
                            break;
                        }
                    }
                    if (!take)
                        continue;
                    paths.add(new FilePathImpl(root));
                }
                if (paths.isEmpty())
                    return;
                ApplicationManager.getApplication().invokeLater(new Runnable() {
                    @Override
                    public void run() {
                        AutoSvnUpdater.run(
                                new AutoSvnUpdater(project, paths.toArray(new FilePath[paths.size()])),
                                ActionInfo.UPDATE.getActionName());
                    }
                }, ModalityState.NON_MODAL);
            }
        }
    };
}