Search in sources :

Example 6 with Task

use of com.intellij.openapi.progress.Task in project intellij-community by JetBrains.

the class DependenciesHandlerBase method analyze.

public void analyze() {
    final List<DependenciesBuilder> builders = new ArrayList<>();
    final Task task;
    if (canStartInBackground()) {
        task = new Task.Backgroundable(myProject, getProgressTitle(), true, new PerformAnalysisInBackgroundOption(myProject)) {

            @Override
            public void run(@NotNull final ProgressIndicator indicator) {
                perform(builders);
            }

            @Override
            public void onSuccess() {
                DependenciesHandlerBase.this.onSuccess(builders);
            }
        };
    } else {
        task = new Task.Modal(myProject, getProgressTitle(), true) {

            @Override
            public void run(@NotNull ProgressIndicator indicator) {
                perform(builders);
            }

            @Override
            public void onSuccess() {
                DependenciesHandlerBase.this.onSuccess(builders);
            }
        };
    }
    ProgressManager.getInstance().run(task);
}
Also used : DependenciesBuilder(com.intellij.packageDependencies.DependenciesBuilder) Task(com.intellij.openapi.progress.Task) ProgressIndicator(com.intellij.openapi.progress.ProgressIndicator) ArrayList(java.util.ArrayList) PerformAnalysisInBackgroundOption(com.intellij.analysis.PerformAnalysisInBackgroundOption)

Example 7 with Task

use of com.intellij.openapi.progress.Task in project intellij-community by JetBrains.

the class FindJarFix method findJarsForFqn.

private void findJarsForFqn(final String fqn, final Editor editor) {
    final Map<String, String> libs = new HashMap<>();
    final Runnable runnable = () -> {
        try {
            final DOMParser parser = new DOMParser();
            parser.parse(CLASS_ROOT_URL + fqn.replace('.', '/') + CLASS_PAGE_EXT);
            final Document doc = parser.getDocument();
            if (doc != null) {
                final NodeList links = doc.getElementsByTagName(LINK_TAG_NAME);
                for (int i = 0; i < links.getLength(); i++) {
                    final Node link = links.item(i);
                    final String libName = link.getTextContent();
                    final NamedNodeMap attributes = link.getAttributes();
                    if (attributes != null) {
                        final Node href = attributes.getNamedItem(LINK_ATTR_NAME);
                        if (href != null) {
                            final String pathToJar = href.getTextContent();
                            if (pathToJar != null && (pathToJar.startsWith("/jar/") || pathToJar.startsWith("/class/../"))) {
                                libs.put(libName, SERVICE_URL + pathToJar);
                            }
                        }
                    }
                }
            }
        } catch (IOException ignore) {
        //
        } catch (Exception e) {
            //
            LOG.warn(e);
        }
    };
    final Task.Modal task = new Task.Modal(editor.getProject(), "Looking for libraries", true) {

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

        @Override
        public void onSuccess() {
            super.onSuccess();
            if (libs.isEmpty()) {
                HintManager.getInstance().showInformationHint(editor, "No libraries found for '" + fqn + "'");
            } else {
                final ArrayList<String> variants = new ArrayList<>(libs.keySet());
                Collections.sort(variants, (o1, o2) -> o1.compareTo(o2));
                final JBList libNames = new JBList(variants);
                libNames.installCellRenderer(o -> new JLabel(o.toString(), PlatformIcons.JAR_ICON, SwingConstants.LEFT));
                if (libs.size() == 1) {
                    final String jarName = libs.keySet().iterator().next();
                    final String url = libs.get(jarName);
                    initiateDownload(url, jarName);
                } else {
                    JBPopupFactory.getInstance().createListPopupBuilder(libNames).setTitle("Select a JAR file").setItemChoosenCallback(() -> {
                        final Object value = libNames.getSelectedValue();
                        if (value instanceof String) {
                            final String jarName = (String) value;
                            final String url = libs.get(jarName);
                            if (url != null) {
                                initiateDownload(url, jarName);
                            }
                        }
                    }).createPopup().showInBestPositionFor(editor);
                }
            }
        }
    };
    ProgressManager.getInstance().run(task);
}
Also used : Task(com.intellij.openapi.progress.Task) NamedNodeMap(org.w3c.dom.NamedNodeMap) NodeList(org.w3c.dom.NodeList) Node(org.w3c.dom.Node) IOException(java.io.IOException) Document(org.w3c.dom.Document) NotNull(org.jetbrains.annotations.NotNull) IncorrectOperationException(com.intellij.util.IncorrectOperationException) IOException(java.io.IOException) SAXException(org.xml.sax.SAXException) ProgressIndicator(com.intellij.openapi.progress.ProgressIndicator) JBList(com.intellij.ui.components.JBList) DOMParser(org.cyberneko.html.parsers.DOMParser)

Example 8 with Task

use of com.intellij.openapi.progress.Task in project intellij-community by JetBrains.

the class InternetAttachSourceProvider method getActions.

@NotNull
@Override
public Collection<AttachSourcesAction> getActions(List<LibraryOrderEntry> orderEntries, @Nullable PsiFile psiFile) {
    final VirtualFile jar = getJarByPsiFile(psiFile);
    if (jar == null)
        return Collections.emptyList();
    final String jarName = jar.getNameWithoutExtension();
    int index = jarName.lastIndexOf('-');
    if (index == -1)
        return Collections.emptyList();
    final String version = jarName.substring(index + 1);
    final String artifactId = jarName.substring(0, index);
    if (!ARTIFACT_IDENTIFIER.matcher(version).matches() || !ARTIFACT_IDENTIFIER.matcher(artifactId).matches()) {
        return Collections.emptyList();
    }
    final Set<Library> libraries = new HashSet<>();
    for (LibraryOrderEntry orderEntry : orderEntries) {
        ContainerUtil.addIfNotNull(libraries, orderEntry.getLibrary());
    }
    if (libraries.isEmpty())
        return Collections.emptyList();
    final String sourceFileName = jarName + "-sources.jar";
    for (Library library : libraries) {
        for (VirtualFile file : library.getFiles(OrderRootType.SOURCES)) {
            if (file.getPath().contains(sourceFileName)) {
                if (isRootInExistingFile(file)) {
                    // Sources already attached, but source-jar doesn't contain current class.
                    return Collections.emptyList();
                }
            }
        }
    }
    final File libSourceDir = getLibrarySourceDir();
    final File sourceFile = new File(libSourceDir, sourceFileName);
    if (sourceFile.exists()) {
        return Collections.singleton(new LightAttachSourcesAction() {

            @Override
            public String getName() {
                return "Attach downloaded source";
            }

            @Override
            public String getBusyText() {
                return getName();
            }

            @Override
            public ActionCallback perform(List<LibraryOrderEntry> orderEntriesContainingFile) {
                attachSourceJar(sourceFile, libraries);
                return ActionCallback.DONE;
            }
        });
    }
    return Collections.singleton(new LightAttachSourcesAction() {

        @Override
        public String getName() {
            return "Download...";
        }

        @Override
        public String getBusyText() {
            return "Searching...";
        }

        @Override
        public ActionCallback perform(List<LibraryOrderEntry> orderEntriesContainingFile) {
            final Task task = new Task.Modal(psiFile.getProject(), "Searching source...", true) {

                @Override
                public void run(@NotNull final ProgressIndicator indicator) {
                    String artifactUrl = null;
                    SourceSearcher[] searchers = { new MavenCentralSourceSearcher(), new SonatypeSourceSearcher() };
                    for (SourceSearcher searcher : searchers) {
                        try {
                            artifactUrl = searcher.findSourceJar(indicator, artifactId, version, jar);
                        } catch (SourceSearchException e) {
                            LOG.warn(e);
                            showMessage("Downloading failed", e.getMessage(), NotificationType.ERROR);
                            continue;
                        }
                        if (artifactUrl != null)
                            break;
                    }
                    if (artifactUrl == null) {
                        showMessage("Sources not found", "Sources for '" + jarName + ".jar' not found", NotificationType.WARNING);
                        return;
                    }
                    if (!(libSourceDir.isDirectory() || libSourceDir.mkdirs())) {
                        showMessage("Downloading failed", "Failed to create directory to store sources: " + libSourceDir, NotificationType.ERROR);
                        return;
                    }
                    try {
                        File tmpDownload = FileUtil.createTempFile(libSourceDir, "download.", ".tmp", false, false);
                        HttpRequests.request(artifactUrl).saveToFile(tmpDownload, indicator);
                        if (!sourceFile.exists() && !tmpDownload.renameTo(sourceFile)) {
                            LOG.warn("Failed to rename file " + tmpDownload + " to " + sourceFileName);
                        }
                    } catch (IOException e) {
                        LOG.warn(e);
                        showMessage("Downloading failed", "Connection problem. See log for more details.", NotificationType.ERROR);
                    }
                }

                @Override
                public void onSuccess() {
                    attachSourceJar(sourceFile, libraries);
                }

                private void showMessage(String title, String message, NotificationType notificationType) {
                    new Notification("Source searcher", title, message, notificationType).notify(getProject());
                }
            };
            task.queue();
            return ActionCallback.DONE;
        }
    });
}
Also used : VirtualFile(com.intellij.openapi.vfs.VirtualFile) Task(com.intellij.openapi.progress.Task) ActionCallback(com.intellij.openapi.util.ActionCallback) LibraryOrderEntry(com.intellij.openapi.roots.LibraryOrderEntry) IOException(java.io.IOException) Notification(com.intellij.notification.Notification) ProgressIndicator(com.intellij.openapi.progress.ProgressIndicator) NotificationType(com.intellij.notification.NotificationType) Library(com.intellij.openapi.roots.libraries.Library) VirtualFile(com.intellij.openapi.vfs.VirtualFile) PsiFile(com.intellij.psi.PsiFile) File(java.io.File) NotNull(org.jetbrains.annotations.NotNull)

Example 9 with Task

use of com.intellij.openapi.progress.Task in project intellij-community by JetBrains.

the class MacMessagesTest method actionPerformed.

@Override
public void actionPerformed(final AnActionEvent anActionEvent) {
    JDialog controlDialog = new JDialog();
    controlDialog.setTitle("Messages testing control panel");
    controlDialog.setModalExclusionType(Dialog.ModalExclusionType.APPLICATION_EXCLUDE);
    controlDialog.setModal(false);
    controlDialog.setFocusableWindowState(false);
    controlDialog.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
    Container cp = controlDialog.getContentPane();
    cp.setLayout(new FlowLayout());
    JButton showDialogWrapperButton = new JButton("Show a dialog wrapper");
    showDialogWrapperButton.setFocusable(false);
    FocusManagerImpl fmi = FocusManagerImpl.getInstance();
    final Project p = fmi.getLastFocusedFrame().getProject();
    showDialogWrapperButton.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent event) {
            DialogWrapper dw = new SimpleDialogWrapper(p);
            dw.setTitle(dw.getWindow().getName());
            dw.show();
        }
    });
    JButton showMessageButton = new JButton("Show a message");
    showDialogWrapperButton.setFocusable(false);
    showMessageButton.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent event) {
            showTestMessage(p);
        }
    });
    JButton showProgressIndicatorButton = new JButton("Show progress indicator");
    showProgressIndicatorButton.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {
            final Task task = new Task.Modal(null, "Test task", true) {

                public void run(@NotNull final ProgressIndicator indicator) {
                    ApplicationManager.getApplication().invokeAndWait(() -> {
                        FocusManagerImpl fmi1 = FocusManagerImpl.getInstance();
                        final Project p1 = fmi1.getLastFocusedFrame().getProject();
                        showTestMessage(p1);
                    }, ModalityState.any());
                }

                @Override
                public void onCancel() {
                }
            };
            ProgressManager.getInstance().run(task);
        }
    });
    cp.add(showDialogWrapperButton);
    cp.add(showMessageButton);
    cp.add(showProgressIndicatorButton);
    controlDialog.pack();
    controlDialog.setVisible(true);
}
Also used : FocusManagerImpl(com.intellij.openapi.wm.impl.FocusManagerImpl) Task(com.intellij.openapi.progress.Task) ActionEvent(java.awt.event.ActionEvent) AnActionEvent(com.intellij.openapi.actionSystem.AnActionEvent) DialogWrapper(com.intellij.openapi.ui.DialogWrapper) Project(com.intellij.openapi.project.Project) ActionListener(java.awt.event.ActionListener) ProgressIndicator(com.intellij.openapi.progress.ProgressIndicator)

Example 10 with Task

use of com.intellij.openapi.progress.Task in project intellij-community by JetBrains.

the class CallbackData method createInteractive.

@NotNull
private static CallbackData createInteractive(@NotNull Project project, @NotNull InvokeAfterUpdateMode mode, @NotNull Runnable afterUpdate, String title, @Nullable ModalityState state) {
    Task task = mode.isSynchronous() ? new Waiter(project, afterUpdate, title, mode.isCancellable()) : new FictiveBackgroundable(project, afterUpdate, title, mode.isCancellable(), state);
    Runnable callback = () -> {
        logUpdateFinished(project, mode);
        setDone(task);
    };
    return new CallbackData(callback, () -> ProgressManager.getInstance().run(task));
}
Also used : Task(com.intellij.openapi.progress.Task) EmptyRunnable(com.intellij.openapi.util.EmptyRunnable) NotNull(org.jetbrains.annotations.NotNull)

Aggregations

Task (com.intellij.openapi.progress.Task)33 ProgressIndicator (com.intellij.openapi.progress.ProgressIndicator)28 NotNull (org.jetbrains.annotations.NotNull)20 Project (com.intellij.openapi.project.Project)10 VirtualFile (com.intellij.openapi.vfs.VirtualFile)8 File (java.io.File)6 IOException (java.io.IOException)5 Editor (com.intellij.openapi.editor.Editor)3 ProcessCanceledException (com.intellij.openapi.progress.ProcessCanceledException)3 Ref (com.intellij.openapi.util.Ref)3 Semaphore (com.intellij.util.concurrency.Semaphore)3 ArrayList (java.util.ArrayList)3 Nullable (org.jetbrains.annotations.Nullable)3 Disposable (com.intellij.openapi.Disposable)2 ProgressExecutionMode (com.intellij.openapi.externalSystem.service.execution.ProgressExecutionMode)2 BackgroundableProcessIndicator (com.intellij.openapi.progress.impl.BackgroundableProcessIndicator)2 ActionEvent (java.awt.event.ActionEvent)2 ActionListener (java.awt.event.ActionListener)2 Installer (com.android.repository.api.Installer)1 InstallerFactory (com.android.repository.api.InstallerFactory)1