Example usage for com.intellij.openapi.ui DialogWrapper OK_EXIT_CODE

List of usage examples for com.intellij.openapi.ui DialogWrapper OK_EXIT_CODE

Introduction

In this page you can find the example usage for com.intellij.openapi.ui DialogWrapper OK_EXIT_CODE.

Prototype

int OK_EXIT_CODE

To view the source code for com.intellij.openapi.ui DialogWrapper OK_EXIT_CODE.

Click Source Link

Document

The default exit code for "OK" action.

Usage

From source file:com.intellij.debugger.actions.ForceEarlyReturnAction.java

License:Apache License

private static void forceEarlyReturn(final Value value, final ThreadReferenceProxyImpl thread,
        final DebugProcessImpl debugProcess, @Nullable final DialogWrapper dialog) {
    debugProcess.getManagerThread().schedule(new DebuggerCommandImpl() {
        @Override/*from   www.j a v a 2 s . com*/
        protected void action() throws Exception {
            try {
                thread.forceEarlyReturn(value);
            } catch (Exception e) {
                showError(debugProcess.getProject(),
                        DebuggerBundle.message("error.early.return", e.getLocalizedMessage()));
                return;
            }
            //noinspection SSBasedInspection
            SwingUtilities.invokeLater(() -> {
                if (dialog != null) {
                    dialog.close(DialogWrapper.OK_EXIT_CODE);
                }
                debugProcess.getSession().stepInto(true, null);
            });
        }
    });
}

From source file:com.intellij.debugger.settings.ArrayRendererConfigurable.java

License:Apache License

private void applyTo(ArrayRenderer renderer, boolean showBigRangeWarning) {
    int newStartIndex = getInt(myStartIndex);
    int newEndIndex = getInt(myEndIndex);
    int newLimit = getInt(myEntriesLimit);

    if (newStartIndex >= 0 && newEndIndex >= 0) {
        if (newStartIndex >= newEndIndex) {
            int currentStartIndex = renderer.START_INDEX;
            int currentEndIndex = renderer.END_INDEX;
            newEndIndex = newStartIndex + (currentEndIndex - currentStartIndex);
        }//from   w  w  w .  j  a  va2  s . com

        if (newLimit <= 0) {
            newLimit = 1;
        }

        if (showBigRangeWarning && (newEndIndex - newStartIndex > 10000)) {
            final int answer = Messages.showOkCancelDialog(myPanel.getRootPane(),
                    DebuggerBundle.message("warning.range.too.big",
                            ApplicationNamesInfo.getInstance().getProductName()),
                    DebuggerBundle.message("title.range.too.big"), Messages.getWarningIcon());
            if (answer != DialogWrapper.OK_EXIT_CODE) {
                return;
            }
        }
    }

    renderer.START_INDEX = newStartIndex;
    renderer.END_INDEX = newEndIndex;
    renderer.ENTRIES_LIMIT = newLimit;
}

From source file:com.intellij.debugger.ui.HotSwapUIImpl.java

License:Apache License

private void hotSwapSessions(final List<DebuggerSession> sessions,
        @Nullable final Map<String, List<String>> generatedPaths) {
    final boolean shouldAskBeforeHotswap = myAskBeforeHotswap;
    myAskBeforeHotswap = true;/*  w ww  . jav a 2  s  .c  o m*/

    // need this because search with PSI is perormed during hotswap
    PsiDocumentManager.getInstance(myProject).commitAllDocuments();

    final DebuggerSettings settings = DebuggerSettings.getInstance();
    final String runHotswap = settings.RUN_HOTSWAP_AFTER_COMPILE;
    final boolean shouldDisplayHangWarning = shouldDisplayHangWarning(settings, sessions);

    if (shouldAskBeforeHotswap && DebuggerSettings.RUN_HOTSWAP_NEVER.equals(runHotswap)) {
        return;
    }

    final boolean shouldPerformScan = true;

    final HotSwapProgressImpl findClassesProgress;
    if (shouldPerformScan) {
        findClassesProgress = new HotSwapProgressImpl(myProject);
    } else {
        boolean createProgress = false;
        for (DebuggerSession session : sessions) {
            if (session.isModifiedClassesScanRequired()) {
                createProgress = true;
                break;
            }
        }
        findClassesProgress = createProgress ? new HotSwapProgressImpl(myProject) : null;
    }

    ApplicationManager.getApplication().executeOnPooledThread(new Runnable() {
        public void run() {
            final Map<DebuggerSession, Map<String, HotSwapFile>> modifiedClasses;
            if (shouldPerformScan) {
                modifiedClasses = scanForModifiedClassesWithProgress(sessions, findClassesProgress, true);
            } else {
                final List<DebuggerSession> toScan = new ArrayList<DebuggerSession>();
                final List<DebuggerSession> toUseGenerated = new ArrayList<DebuggerSession>();
                for (DebuggerSession session : sessions) {
                    (session.isModifiedClassesScanRequired() ? toScan : toUseGenerated).add(session);
                    session.setModifiedClassesScanRequired(false);
                }
                modifiedClasses = new HashMap<DebuggerSession, Map<String, HotSwapFile>>();
                if (!toUseGenerated.isEmpty()) {
                    modifiedClasses.putAll(HotSwapManager.findModifiedClasses(toUseGenerated, generatedPaths));
                }
                if (!toScan.isEmpty()) {
                    modifiedClasses
                            .putAll(scanForModifiedClassesWithProgress(toScan, findClassesProgress, true));
                }
            }

            final Application application = ApplicationManager.getApplication();
            if (modifiedClasses.isEmpty()) {
                final String message = DebuggerBundle.message("status.hotswap.uptodate");
                HotSwapProgressImpl.NOTIFICATION_GROUP.createNotification(message, NotificationType.INFORMATION)
                        .notify(myProject);
                return;
            }

            application.invokeLater(new Runnable() {
                public void run() {
                    if (shouldAskBeforeHotswap && !DebuggerSettings.RUN_HOTSWAP_ALWAYS.equals(runHotswap)) {
                        final RunHotswapDialog dialog = new RunHotswapDialog(myProject, sessions,
                                shouldDisplayHangWarning);
                        dialog.show();
                        if (!dialog.isOK()) {
                            for (DebuggerSession session : modifiedClasses.keySet()) {
                                session.setModifiedClassesScanRequired(true);
                            }
                            return;
                        }
                        final Set<DebuggerSession> toReload = new HashSet<DebuggerSession>(
                                dialog.getSessionsToReload());
                        for (DebuggerSession session : modifiedClasses.keySet()) {
                            if (!toReload.contains(session)) {
                                session.setModifiedClassesScanRequired(true);
                            }
                        }
                        modifiedClasses.keySet().retainAll(toReload);
                    } else {
                        if (shouldDisplayHangWarning) {
                            final int answer = Messages.showCheckboxMessageDialog(
                                    DebuggerBundle.message("hotswap.dialog.hang.warning"),
                                    DebuggerBundle.message("hotswap.dialog.title"),
                                    new String[] { "Perform &Reload Classes", "&Skip Reload Classes" },
                                    CommonBundle.message("dialog.options.do.not.show"), false, 1, 1,
                                    Messages.getWarningIcon(), new PairFunction<Integer, JCheckBox, Integer>() {
                                        @Override
                                        public Integer fun(Integer exitCode, JCheckBox cb) {
                                            settings.HOTSWAP_HANG_WARNING_ENABLED = !cb.isSelected();
                                            return exitCode == DialogWrapper.OK_EXIT_CODE ? exitCode
                                                    : DialogWrapper.CANCEL_EXIT_CODE;
                                        }
                                    });
                            if (answer == DialogWrapper.CANCEL_EXIT_CODE) {
                                for (DebuggerSession session : modifiedClasses.keySet()) {
                                    session.setModifiedClassesScanRequired(true);
                                }
                                return;
                            }
                        }
                    }

                    if (!modifiedClasses.isEmpty()) {
                        final HotSwapProgressImpl progress = new HotSwapProgressImpl(myProject);
                        application.executeOnPooledThread(new Runnable() {
                            public void run() {
                                reloadModifiedClasses(modifiedClasses, progress);
                            }
                        });
                    }
                }
            }, ModalityState.NON_MODAL);
        }
    });
}

From source file:com.intellij.execution.junit.JUnit4Framework.java

License:Apache License

@Override
@Nullable//from  w ww.ja v  a2  s .co m
protected PsiMethod findOrCreateSetUpMethod(PsiClass clazz) throws IncorrectOperationException {
    PsiMethod method = findSetUpMethod(clazz);
    if (method != null)
        return method;

    PsiManager manager = clazz.getManager();
    PsiElementFactory factory = JavaPsiFacade.getInstance(manager.getProject()).getElementFactory();

    method = createSetUpPatternMethod(factory);
    PsiMethod existingMethod = clazz.findMethodBySignature(method, false);
    if (existingMethod != null) {
        int exit = ApplicationManager.getApplication().isUnitTestMode() ? DialogWrapper.OK_EXIT_CODE
                : Messages.showOkCancelDialog(
                        "Method setUp already exist but is not annotated as @Before. Annotate?",
                        CommonBundle.getWarningTitle(), Messages.getWarningIcon());
        if (exit == DialogWrapper.OK_EXIT_CODE) {
            new AddAnnotationFix(JUnitUtil.BEFORE_ANNOTATION_NAME, existingMethod)
                    .invoke(existingMethod.getProject(), null, existingMethod.getContainingFile());
            return existingMethod;
        }
    }
    final PsiMethod testMethod = JUnitUtil.findFirstTestMethod(clazz);
    if (testMethod != null) {
        method = (PsiMethod) clazz.addBefore(method, testMethod);
    } else {
        method = (PsiMethod) clazz.add(method);
    }
    JavaCodeStyleManager.getInstance(manager.getProject()).shortenClassReferences(method);

    return method;
}

From source file:com.intellij.execution.testframework.export.ExportTestResultsAction.java

License:Apache License

@Override
public void actionPerformed(AnActionEvent e) {
    final Project project = CommonDataKeys.PROJECT.getData(e.getDataContext());
    LOG.assertTrue(project != null);//ww  w  .java 2 s  .  com
    final ExportTestResultsConfiguration config = ExportTestResultsConfiguration.getInstance(project);

    final String name = ExecutionBundle.message("export.test.results.filename",
            PathUtil.suggestFileName(myRunConfiguration.getName()));
    String filename = name + "." + config.getExportFormat().getDefaultExtension();
    boolean showDialog = true;
    while (showDialog) {
        final ExportTestResultsDialog d = new ExportTestResultsDialog(project, config, filename);
        d.show();
        if (!d.isOK()) {
            return;
        }
        filename = d.getFileName();
        showDialog = getOutputFile(config, project, filename).exists() && Messages.showOkCancelDialog(project,
                ExecutionBundle.message("export.test.results.file.exists.message", filename),
                ExecutionBundle.message("export.test.results.file.exists.title"),
                Messages.getQuestionIcon()) != DialogWrapper.OK_EXIT_CODE;
    }

    final String filename_ = filename;
    ProgressManager.getInstance().run(new Task.Backgroundable(project,
            ExecutionBundle.message("export.test.results.task.name"), false, new PerformInBackgroundOption() {
                @Override
                public boolean shouldStartInBackground() {
                    return true;
                }

                @Override
                public void processSentToBackground() {
                }
            }) {
        @Override
        public void run(@NotNull ProgressIndicator indicator) {
            indicator.setIndeterminate(true);

            final File outputFile = getOutputFile(config, project, filename_);
            final String outputText;
            try {
                outputText = getOutputText(config);
                if (outputText == null) {
                    return;
                }
            } catch (IOException ex) {
                LOG.warn(ex);
                showBalloon(project, MessageType.ERROR,
                        ExecutionBundle.message("export.test.results.failed", ex.getMessage()), null);
                return;
            } catch (TransformerException ex) {
                LOG.warn(ex);
                showBalloon(project, MessageType.ERROR,
                        ExecutionBundle.message("export.test.results.failed", ex.getMessage()), null);
                return;
            } catch (SAXException ex) {
                LOG.warn(ex);
                showBalloon(project, MessageType.ERROR,
                        ExecutionBundle.message("export.test.results.failed", ex.getMessage()), null);
                return;
            } catch (RuntimeException ex) {
                ExportTestResultsConfiguration c = new ExportTestResultsConfiguration();
                c.setExportFormat(ExportTestResultsConfiguration.ExportFormat.Xml);
                c.setOpenResults(false);
                try {
                    String xml = getOutputText(c);
                    LOG.error(LogMessageEx.createEvent("Failed to export test results",
                            ExceptionUtil.getThrowableText(ex), null, null, new Attachment("dump.xml", xml)));
                } catch (Throwable ignored) {
                    LOG.error("Failed to export test results", ex);
                }
                return;
            }

            final Ref<VirtualFile> result = new Ref<VirtualFile>();
            final Ref<String> error = new Ref<String>();
            ApplicationManager.getApplication().invokeAndWait(new Runnable() {
                @Override
                public void run() {
                    result.set(
                            ApplicationManager.getApplication().runWriteAction(new Computable<VirtualFile>() {
                                @Override
                                public VirtualFile compute() {
                                    outputFile.getParentFile().mkdirs();
                                    final VirtualFile parent = LocalFileSystem.getInstance()
                                            .refreshAndFindFileByIoFile(outputFile.getParentFile());
                                    if (parent == null || !parent.isValid()) {
                                        error.set(ExecutionBundle.message("failed.to.create.output.file",
                                                outputFile.getPath()));
                                        return null;
                                    }

                                    try {
                                        VirtualFile result = parent.createChildData(this, outputFile.getName());
                                        VfsUtil.saveText(result, outputText);
                                        return result;
                                    } catch (IOException e) {
                                        LOG.warn(e);
                                        error.set(e.getMessage());
                                        return null;
                                    }
                                }
                            }));
                }
            }, ModalityState.defaultModalityState());

            if (!result.isNull()) {
                if (config.isOpenResults()) {
                    openEditorOrBrowser(result.get(), project,
                            config.getExportFormat() == ExportTestResultsConfiguration.ExportFormat.Xml);
                } else {
                    HyperlinkListener listener = new HyperlinkListener() {
                        @Override
                        public void hyperlinkUpdate(HyperlinkEvent e) {
                            if (e.getEventType() == HyperlinkEvent.EventType.ACTIVATED) {
                                openEditorOrBrowser(result.get(), project, config
                                        .getExportFormat() == ExportTestResultsConfiguration.ExportFormat.Xml);
                            }
                        }
                    };
                    showBalloon(project, MessageType.INFO,
                            ExecutionBundle.message("export.test.results.succeeded", outputFile.getName()),
                            listener);
                }
            } else {
                showBalloon(project, MessageType.ERROR,
                        ExecutionBundle.message("export.test.results.failed", error.get()), null);
            }
        }
    });
}

From source file:com.intellij.find.findUsages.FindUsagesManager.java

License:Apache License

public void findUsages(@NotNull PsiElement psiElement, final PsiFile scopeFile, final FileEditor editor,
        boolean showDialog, @Nullable("null means default (stored in options)") SearchScope searchScope) {
    FindUsagesHandler handler = getFindUsagesHandler(psiElement, false);
    if (handler == null)
        return;//  www  .j  a va2s .co m

    boolean singleFile = scopeFile != null;
    AbstractFindUsagesDialog dialog = handler.getFindUsagesDialog(singleFile, shouldOpenInNewTab(),
            mustOpenInNewTab());
    if (showDialog) {
        if (!dialog.showAndGet()) {
            return;
        }
    } else {
        dialog.close(DialogWrapper.OK_EXIT_CODE);
    }

    setOpenInNewTab(dialog.isShowInSeparateWindow());

    FindUsagesOptions findUsagesOptions = dialog.calcFindUsagesOptions();
    if (searchScope != null) {
        findUsagesOptions.searchScope = searchScope;
    }

    clearFindingNextUsageInFile();

    startFindUsages(findUsagesOptions, handler, scopeFile, editor);
}

From source file:com.intellij.history.integration.ui.views.HistoryDialog.java

License:Apache License

private boolean showAsDialog(CreatePatchConfigurationPanel p) {
    final DialogBuilder b = new DialogBuilder(myProject);
    JComponent createPatchPanel = p.getPanel();
    b.setPreferredFocusComponent(IdeFocusTraversalPolicy.getPreferredFocusedComponent(createPatchPanel));
    b.setTitle(message("create.patch.dialog.title"));
    b.setCenterPanel(createPatchPanel);//from   w ww .j a  v  a 2 s  . com
    p.installOkEnabledListener(new Consumer<Boolean>() {
        public void consume(final Boolean aBoolean) {
            b.setOkActionEnabled(aBoolean);
        }
    });
    return b.show() == DialogWrapper.OK_EXIT_CODE;
}

From source file:com.intellij.ide.actions.StartUseVcsAction.java

License:Apache License

@Override
@RequiredDispatchThread//w  w w.  ja  v  a 2  s  .  co  m
public void actionPerformed(final AnActionEvent e) {
    final VcsDataWrapper data = new VcsDataWrapper(e);
    final boolean enabled = data.enabled();
    if (!enabled) {
        return;
    }

    final StartUseVcsDialog dialog = new StartUseVcsDialog(data);
    dialog.show();
    if (dialog.getExitCode() == DialogWrapper.OK_EXIT_CODE) {
        final String vcsName = dialog.getVcs();
        if (vcsName.length() > 0) {
            final ProjectLevelVcsManager manager = data.getManager();
            AbstractVcs vcs = manager.findVcsByName(vcsName);
            assert vcs != null : "No vcs found for name " + vcsName;
            vcs.enableIntegration();
        }
    }
}

From source file:com.intellij.ide.browsers.BrowserLauncherAppless.java

License:Apache License

@Nullable
private static String extractFiles(String url) {
    try {/*from ww w .j ava2  s.co m*/
        int sharpPos = url.indexOf('#');
        String anchor = "";
        if (sharpPos != -1) {
            anchor = url.substring(sharpPos);
            url = url.substring(0, sharpPos);
        }

        Pair<String, String> pair = URLUtil.splitJarUrl(url);
        if (pair == null)
            return null;

        File jarFile = new File(FileUtil.toSystemDependentName(pair.first));
        if (!jarFile.canRead())
            return null;

        String jarUrl = StandardFileSystems.FILE_PROTOCOL_PREFIX
                + FileUtil.toSystemIndependentName(jarFile.getPath());
        String jarLocationHash = jarFile.getName() + "." + Integer.toHexString(jarUrl.hashCode());
        final File outputDir = new File(getExtractedFilesDir(), jarLocationHash);

        final String currentTimestamp = String.valueOf(new File(jarFile.getPath()).lastModified());
        final File timestampFile = new File(outputDir, ".idea.timestamp");

        String previousTimestamp = null;
        if (timestampFile.exists()) {
            previousTimestamp = FileUtilRt.loadFile(timestampFile);
        }

        if (!currentTimestamp.equals(previousTimestamp)) {
            final Ref<Boolean> extract = new Ref<Boolean>();
            Runnable r = new Runnable() {
                @Override
                public void run() {
                    final ConfirmExtractDialog dialog = new ConfirmExtractDialog();
                    if (dialog.isToBeShown()) {
                        dialog.show();
                        extract.set(dialog.isOK());
                    } else {
                        dialog.close(DialogWrapper.OK_EXIT_CODE);
                        extract.set(true);
                    }
                }
            };

            try {
                GuiUtils.runOrInvokeAndWait(r);
            } catch (InvocationTargetException ignored) {
                extract.set(false);
            } catch (InterruptedException ignored) {
                extract.set(false);
            }

            if (!extract.get()) {
                return null;
            }

            boolean closeZip = true;
            final ZipFile zipFile = new ZipFile(jarFile);
            try {
                ZipEntry entry = zipFile.getEntry(pair.second);
                if (entry == null) {
                    return null;
                }
                InputStream is = zipFile.getInputStream(entry);
                ZipUtil.extractEntry(entry, is, outputDir);
                closeZip = false;
            } finally {
                if (closeZip) {
                    zipFile.close();
                }
            }

            ApplicationManager.getApplication().invokeLater(new Runnable() {
                @Override
                public void run() {
                    new Task.Backgroundable(null, "Extracting files...", true) {
                        @Override
                        public void run(@NotNull final ProgressIndicator indicator) {
                            final int size = zipFile.size();
                            final int[] counter = new int[] { 0 };

                            class MyFilter implements FilenameFilter {
                                private final Set<File> myImportantDirs = ContainerUtil.newHashSet(outputDir,
                                        new File(outputDir, "resources"));
                                private final boolean myImportantOnly;

                                private MyFilter(boolean importantOnly) {
                                    myImportantOnly = importantOnly;
                                }

                                @Override
                                public boolean accept(@NotNull File dir, @NotNull String name) {
                                    indicator.checkCanceled();
                                    boolean result = myImportantOnly == myImportantDirs.contains(dir);
                                    if (result) {
                                        indicator.setFraction(((double) counter[0]) / size);
                                        counter[0]++;
                                    }
                                    return result;
                                }
                            }

                            try {
                                try {
                                    ZipUtil.extract(zipFile, outputDir, new MyFilter(true));
                                    ZipUtil.extract(zipFile, outputDir, new MyFilter(false));
                                    FileUtil.writeToFile(timestampFile, currentTimestamp);
                                } finally {
                                    zipFile.close();
                                }
                            } catch (IOException ignore) {
                            }
                        }
                    }.queue();
                }
            });
        }

        return VfsUtilCore.pathToUrl(
                FileUtil.toSystemIndependentName(new File(outputDir, pair.second).getPath())) + anchor;
    } catch (IOException e) {
        LOG.warn(e);
        Messages.showErrorDialog("Cannot extract files: " + e.getMessage(), "Error");
        return null;
    }
}

From source file:com.intellij.ide.fileTemplates.impl.AllFileTemplatesConfigurable.java

License:Apache License

private void onReset() {
    FileTemplate selected = myCurrentTab.getSelectedTemplate();
    if (selected instanceof BundledFileTemplate) {
        if (Messages.showOkCancelDialog(IdeBundle.message("prompt.reset.to.original.template"),
                IdeBundle.message("title.reset.template"),
                Messages.getQuestionIcon()) != DialogWrapper.OK_EXIT_CODE) {
            return;
        }// w w w.  j  av a2  s  .c o m
        ((BundledFileTemplate) selected).revertToDefaults();
        myEditor.reset();
        myModified = true;
    }
}