Search in sources :

Example 1 with ProgressWindow

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

the class ApplicationImpl method runProcessWithProgressSynchronously.

@Override
public boolean runProcessWithProgressSynchronously(@NotNull final Runnable process, @NotNull final String progressTitle, final boolean canBeCanceled, @Nullable final Project project, final JComponent parentComponent, final String cancelText) {
    assertIsDispatchThread();
    boolean writeAccessAllowed = isWriteAccessAllowed();
    if (// Disallow running process in separate thread from under write action.
    writeAccessAllowed || // The thread will deadlock trying to get read action otherwise.
    isHeadlessEnvironment() && !isUnitTestMode()) {
        if (writeAccessAllowed) {
            LOG.debug("Starting process with progress from within write action makes no sense");
        }
        try {
            ProgressManager.getInstance().runProcess(process, new EmptyProgressIndicator());
        } catch (ProcessCanceledException e) {
            // ok to ignore.
            return false;
        }
        return true;
    }
    final ProgressWindow progress = new ProgressWindow(canBeCanceled, false, project, parentComponent, cancelText);
    // in case of abrupt application exit when 'ProgressManager.getInstance().runProcess(process, progress)' below
    // does not have a chance to run, and as a result the progress won't be disposed
    Disposer.register(this, progress);
    progress.setTitle(progressTitle);
    final AtomicBoolean threadStarted = new AtomicBoolean();
    //noinspection SSBasedInspection
    SwingUtilities.invokeLater(() -> {
        executeOnPooledThread(() -> {
            try {
                ProgressManager.getInstance().runProcess(process, progress);
            } catch (ProcessCanceledException e) {
                progress.cancel();
            // ok to ignore.
            } catch (RuntimeException e) {
                progress.cancel();
                throw e;
            }
        });
        threadStarted.set(true);
    });
    progress.startBlocking();
    LOG.assertTrue(threadStarted.get());
    LOG.assertTrue(!progress.isRunning());
    return !progress.isCanceled();
}
Also used : AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) ProgressWindow(com.intellij.openapi.progress.util.ProgressWindow)

Example 2 with ProgressWindow

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

the class ApplicationImpl method runProcessWithProgressSynchronouslyInReadAction.

@Override
public boolean runProcessWithProgressSynchronouslyInReadAction(@Nullable final Project project, @NotNull final String progressTitle, final boolean canBeCanceled, final String cancelText, final JComponent parentComponent, @NotNull final Runnable process) {
    assertIsDispatchThread();
    boolean writeAccessAllowed = isWriteAccessAllowed();
    if (// Disallow running process in separate thread from under write action.
    writeAccessAllowed) // The thread will deadlock trying to get read action otherwise.
    {
        throw new IncorrectOperationException("Starting process with progress from within write action makes no sense");
    }
    final ProgressWindow progress = new ProgressWindow(canBeCanceled, false, project, parentComponent, cancelText);
    // in case of abrupt application exit when 'ProgressManager.getInstance().runProcess(process, progress)' below
    // does not have a chance to run, and as a result the progress won't be disposed
    Disposer.register(this, progress);
    progress.setTitle(progressTitle);
    final Semaphore readActionAcquired = new Semaphore();
    readActionAcquired.down();
    final Semaphore modalityEntered = new Semaphore();
    modalityEntered.down();
    executeOnPooledThread(() -> {
        try {
            ApplicationManager.getApplication().runReadAction(() -> {
                readActionAcquired.up();
                modalityEntered.waitFor();
                ProgressManager.getInstance().runProcess(process, progress);
            });
        } catch (ProcessCanceledException e) {
            progress.cancel();
        // ok to ignore.
        } catch (RuntimeException e) {
            progress.cancel();
            throw e;
        }
    });
    readActionAcquired.waitFor();
    progress.startBlocking(modalityEntered::up);
    LOG.assertTrue(!progress.isRunning());
    return !progress.isCanceled();
}
Also used : ProgressWindow(com.intellij.openapi.progress.util.ProgressWindow) Semaphore(com.intellij.util.concurrency.Semaphore)

Example 3 with ProgressWindow

use of com.intellij.openapi.progress.util.ProgressWindow in project android by JetBrains.

the class InstallComponentsPath method createComponentTree.

private ComponentTreeNode createComponentTree(@NotNull FirstRunWizardMode reason, @NotNull ScopedStateStore stateStore, boolean createAvd) {
    List<ComponentTreeNode> components = Lists.newArrayList();
    components.add(new AndroidSdk(stateStore, myInstallUpdates));
    DynamicWizard wizard = getWizard();
    ProgressWindow progressWindow = new ProgressWindow(false, false, null);
    if (wizard != null) {
        Disposer.register(wizard.getDisposable(), progressWindow);
    }
    com.android.repository.api.ProgressIndicator progress = new RepoProgressIndicatorAdapter(progressWindow);
    RepoManager sdkManager = myLocalHandler.getSdkManager(new StudioLoggerProgressIndicator(getClass()));
    sdkManager.loadSynchronously(RepoManager.DEFAULT_EXPIRATION_PERIOD_MS, progress, new StudioDownloader(progressWindow), StudioSettingsController.getInstance());
    Map<String, RemotePackage> remotePackages = sdkManager.getPackages().getRemotePackages();
    ComponentTreeNode platforms = Platform.createSubtree(stateStore, remotePackages, myInstallUpdates);
    if (platforms != null) {
        components.add(platforms);
    }
    if (Haxm.canRun() && reason == FirstRunWizardMode.NEW_INSTALL) {
        Haxm.HaxmInstallationIntention haxmInstallationIntention = myInstallUpdates ? Haxm.HaxmInstallationIntention.INSTALL_WITH_UPDATES : Haxm.HaxmInstallationIntention.INSTALL_WITHOUT_UPDATES;
        components.add(new Haxm(haxmInstallationIntention, stateStore, FirstRunWizard.KEY_CUSTOM_INSTALL));
    }
    if (createAvd) {
        components.add(new AndroidVirtualDevice(stateStore, remotePackages, myInstallUpdates, myFileOp));
    }
    return new ComponentCategory("Root", "Root node that is not supposed to appear in the UI", components);
}
Also used : StudioDownloader(com.android.tools.idea.sdk.StudioDownloader) DynamicWizard(com.android.tools.idea.wizard.dynamic.DynamicWizard) StudioLoggerProgressIndicator(com.android.tools.idea.sdk.progress.StudioLoggerProgressIndicator) RepoManager(com.android.repository.api.RepoManager) RepoProgressIndicatorAdapter(com.android.tools.idea.sdk.progress.RepoProgressIndicatorAdapter) ProgressWindow(com.intellij.openapi.progress.util.ProgressWindow) RemotePackage(com.android.repository.api.RemotePackage)

Example 4 with ProgressWindow

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

the class GotoActionAction method createPopup.

@Nullable
private static ChooseByNamePopup createPopup(@Nullable Project project, @NotNull final GotoActionModel model, String initialText, int initialIndex, final Component component, final AnActionEvent e) {
    ChooseByNamePopup oldPopup = project == null ? null : project.getUserData(ChooseByNamePopup.CHOOSE_BY_NAME_POPUP_IN_PROJECT_KEY);
    if (oldPopup != null) {
        oldPopup.close(false);
    }
    final Disposable disposable = Disposer.newDisposable();
    final ChooseByNamePopup popup = new ChooseByNamePopup(project, model, new GotoActionItemProvider(model), oldPopup, initialText, false, initialIndex) {

        private boolean myPaintInternalInfo;

        @Override
        protected void initUI(Callback callback, ModalityState modalityState, boolean allowMultipleSelection) {
            super.initUI(callback, modalityState, allowMultipleSelection);
            myList.addListSelectionListener(new ListSelectionListener() {

                @Override
                public void valueChanged(ListSelectionEvent e) {
                    Object value = myList.getSelectedValue();
                    String text = getText(value);
                    if (text != null && myDropdownPopup != null) {
                        myDropdownPopup.setAdText(text, SwingConstants.LEFT);
                    }
                    String description = getValueDescription(value);
                    ActionMenu.showDescriptionInStatusBar(true, myList, description);
                }

                @Nullable
                private String getText(@Nullable Object o) {
                    if (o instanceof GotoActionModel.MatchedValue) {
                        GotoActionModel.MatchedValue mv = (GotoActionModel.MatchedValue) o;
                        if (myPaintInternalInfo) {
                            if (mv.value instanceof GotoActionModel.ActionWrapper) {
                                AnAction action = ((GotoActionModel.ActionWrapper) mv.value).getAction();
                                String actionId = ActionManager.getInstance().getId(action);
                                return StringUtil.notNullize(actionId, "class: " + action.getClass().getName());
                            }
                        }
                        if (mv.value instanceof BooleanOptionDescription || mv.value instanceof GotoActionModel.ActionWrapper && ((GotoActionModel.ActionWrapper) mv.value).getAction() instanceof ToggleAction) {
                            return "Press " + KeymapUtil.getKeystrokeText(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0)) + " to toggle option";
                        }
                    }
                    return getAdText();
                }
            });
            myList.addMouseMotionListener(new MouseMotionAdapter() {

                @Override
                public void mouseMoved(MouseEvent e) {
                    int index = myList.locationToIndex(e.getPoint());
                    if (index == -1)
                        return;
                    Object value = myList.getModel().getElementAt(index);
                    String description = getValueDescription(value);
                    ActionMenu.showDescriptionInStatusBar(true, myList, description);
                }
            });
            if (Registry.is("show.configurables.ids.in.settings")) {
                new HeldDownKeyListener() {

                    @Override
                    protected void heldKeyTriggered(JComponent component, boolean pressed) {
                        myPaintInternalInfo = pressed;
                        // an easy way to repaint the AdText
                        ListSelectionEvent event = new ListSelectionEvent(this, -1, -1, false);
                        for (ListSelectionListener listener : myList.getListSelectionListeners()) {
                            listener.valueChanged(event);
                        }
                    }
                }.installOn(myTextField);
            }
        }

        @Nullable
        private String getValueDescription(@Nullable Object value) {
            if (value instanceof GotoActionModel.MatchedValue) {
                GotoActionModel.MatchedValue mv = (GotoActionModel.MatchedValue) value;
                if (mv.value instanceof GotoActionModel.ActionWrapper) {
                    AnAction action = ((GotoActionModel.ActionWrapper) mv.value).getAction();
                    return action.getTemplatePresentation().getDescription();
                }
            }
            return null;
        }

        @NotNull
        @Override
        protected Set<Object> filter(@NotNull Set<Object> elements) {
            return super.filter(model.sortItems(elements));
        }

        @Override
        protected boolean closeForbidden(boolean ok) {
            if (!ok)
                return false;
            Object element = getChosenElement();
            return element instanceof GotoActionModel.MatchedValue && processOptionInplace(((GotoActionModel.MatchedValue) element).value, this, component, e) || super.closeForbidden(true);
        }

        @Override
        public void setDisposed(boolean disposedFlag) {
            super.setDisposed(disposedFlag);
            Disposer.dispose(disposable);
            ActionMenu.showDescriptionInStatusBar(true, myList, null);
            for (ListSelectionListener listener : myList.getListSelectionListeners()) {
                myList.removeListSelectionListener(listener);
            }
            UIUtil.dispose(myList);
        }
    };
    ApplicationManager.getApplication().getMessageBus().connect(disposable).subscribe(ProgressWindow.TOPIC, new ProgressWindow.Listener() {

        @Override
        public void progressWindowCreated(ProgressWindow pw) {
            Disposer.register(pw, new Disposable() {

                @Override
                public void dispose() {
                    if (!popup.checkDisposed()) {
                        popup.repaintList();
                    }
                }
            });
        }
    });
    if (project != null) {
        project.putUserData(ChooseByNamePopup.CHOOSE_BY_NAME_POPUP_IN_PROJECT_KEY, popup);
    }
    popup.addMouseClickListener(new MouseAdapter() {

        @Override
        public void mouseClicked(@NotNull MouseEvent me) {
            Object element = popup.getSelectionByPoint(me.getPoint());
            if (element instanceof GotoActionModel.MatchedValue) {
                if (processOptionInplace(((GotoActionModel.MatchedValue) element).value, popup, component, e)) {
                    me.consume();
                }
            }
        }
    });
    CustomShortcutSet shortcutSet = new CustomShortcutSet(KeymapManager.getInstance().getActiveKeymap().getShortcuts(IdeActions.ACTION_SHOW_INTENTION_ACTIONS));
    new DumbAwareAction() {

        @Override
        public void actionPerformed(AnActionEvent e) {
            Object o = popup.getChosenElement();
            if (o instanceof GotoActionModel.MatchedValue) {
                Comparable value = ((GotoActionModel.MatchedValue) o).value;
                if (value instanceof GotoActionModel.ActionWrapper) {
                    GotoActionModel.ActionWrapper aw = (GotoActionModel.ActionWrapper) value;
                    boolean available = aw.isAvailable();
                    if (available) {
                        AnAction action = aw.getAction();
                        String id = ActionManager.getInstance().getId(action);
                        KeymapManagerImpl km = ((KeymapManagerImpl) KeymapManager.getInstance());
                        Keymap k = km.getActiveKeymap();
                        if (!k.canModify())
                            return;
                        KeymapPanel.addKeyboardShortcut(id, ActionShortcutRestrictions.getInstance().getForActionId(id), k, component);
                        popup.repaintListImmediate();
                    }
                }
            }
        }
    }.registerCustomShortcutSet(shortcutSet, popup.getTextField(), disposable);
    return popup;
}
Also used : Set(java.util.Set) ListSelectionEvent(javax.swing.event.ListSelectionEvent) NotNull(org.jetbrains.annotations.NotNull) DumbAwareAction(com.intellij.openapi.project.DumbAwareAction) GotoActionItemProvider(com.intellij.ide.util.gotoByName.GotoActionItemProvider) ChooseByNamePopup(com.intellij.ide.util.gotoByName.ChooseByNamePopup) Disposable(com.intellij.openapi.Disposable) GotoActionModel(com.intellij.ide.util.gotoByName.GotoActionModel) HeldDownKeyListener(com.intellij.ui.HeldDownKeyListener) ListSelectionListener(javax.swing.event.ListSelectionListener) ProgressWindow(com.intellij.openapi.progress.util.ProgressWindow) BooleanOptionDescription(com.intellij.ide.ui.search.BooleanOptionDescription) ModalityState(com.intellij.openapi.application.ModalityState) Nullable(org.jetbrains.annotations.Nullable) KeymapManagerImpl(com.intellij.openapi.keymap.impl.KeymapManagerImpl) Keymap(com.intellij.openapi.keymap.Keymap) Nullable(org.jetbrains.annotations.Nullable)

Example 5 with ProgressWindow

use of com.intellij.openapi.progress.util.ProgressWindow in project android by JetBrains.

the class AvdManagerConnection method startAvd.

/**
   * Launch the given AVD in the emulator.
   * @return a future with the device that was launched
   */
@NotNull
public ListenableFuture<IDevice> startAvd(@Nullable final Project project, @NotNull final AvdInfo info) {
    if (!initIfNecessary()) {
        return Futures.immediateFailedFuture(new RuntimeException("No Android SDK Found"));
    }
    AccelerationErrorCode error = checkAcceleration();
    ListenableFuture<IDevice> errorResult = handleAccelerationError(project, info, error);
    if (errorResult != null) {
        return errorResult;
    }
    final File emulatorBinary = getEmulatorBinary();
    if (!emulatorBinary.isFile()) {
        IJ_LOG.error("No emulator binary found!");
        return Futures.immediateFailedFuture(new RuntimeException("No emulator binary found"));
    }
    final String avdName = info.getName();
    // perform the same action here. If it is not stale, then we should show this error and if possible, bring that window to the front.
    if (myAvdManager.isAvdRunning(info, SDK_LOG)) {
        String baseFolder;
        try {
            baseFolder = myAvdManager.getBaseAvdFolder().getAbsolutePath();
        } catch (AndroidLocation.AndroidLocationException e) {
            baseFolder = "$HOME";
        }
        String message = String.format("AVD %1$s is already running.\n" + "If that is not the case, delete the files at\n" + "   %2$s/%1$s.avd/*.lock\n" + "and try again.", avdName, baseFolder);
        Messages.showErrorDialog(project, message, "AVD Manager");
        return Futures.immediateFailedFuture(new RuntimeException(message));
    }
    GeneralCommandLine commandLine = new GeneralCommandLine();
    commandLine.setExePath(emulatorBinary.getPath());
    addParameters(info, commandLine);
    EmulatorRunner runner = new EmulatorRunner(commandLine, info);
    EmulatorRunner.ProcessOutputCollector collector = new EmulatorRunner.ProcessOutputCollector();
    runner.addProcessListener(collector);
    final ProcessHandler processHandler;
    try {
        processHandler = runner.start();
    } catch (ExecutionException e) {
        IJ_LOG.error("Error launching emulator", e);
        return Futures.immediateFailedFuture(new RuntimeException(String.format("Error launching emulator %1$s ", avdName), e));
    }
    // If we're using qemu2, it has its own progress bar, so put ours in the background. Otherwise show it.
    final ProgressWindow p = hasQEMU2Installed() ? new BackgroundableProcessIndicator(project, "Launching Emulator", PerformInBackgroundOption.ALWAYS_BACKGROUND, "", "", false) : new ProgressWindow(false, true, project);
    p.setIndeterminate(false);
    p.setDelayInMillis(0);
    // It takes >= 8 seconds to start the Emulator. Display a small progress indicator otherwise it seems like
    // the action wasn't invoked and users tend to click multiple times on it, ending up with several instances of the emulator
    ApplicationManager.getApplication().executeOnPooledThread(() -> {
        try {
            p.start();
            p.setText("Starting AVD...");
            for (double d = 0; d < 1; d += 1.0 / 80) {
                p.setFraction(d);
                //noinspection BusyWait
                Thread.sleep(100);
                if (processHandler.isProcessTerminated()) {
                    break;
                }
            }
        } catch (InterruptedException ignore) {
        } finally {
            p.stop();
            p.processFinish();
        }
        processHandler.removeProcessListener(collector);
        String message = limitErrorMessage(collector.getText());
        if (message.toLowerCase(Locale.ROOT).contains("error") || processHandler.isProcessTerminated() && !message.trim().isEmpty()) {
            ApplicationManager.getApplication().invokeLater(() -> Messages.showErrorDialog(project, "Cannot launch AVD in emulator.\nOutput:\n" + message, avdName));
        }
    });
    return EmulatorConnectionListener.getDeviceForEmulator(project, info.getName(), processHandler, 5, TimeUnit.MINUTES);
}
Also used : IDevice(com.android.ddmlib.IDevice) ProgressWindow(com.intellij.openapi.progress.util.ProgressWindow) GeneralCommandLine(com.intellij.execution.configurations.GeneralCommandLine) BackgroundableProcessIndicator(com.intellij.openapi.progress.impl.BackgroundableProcessIndicator) CapturingAnsiEscapesAwareProcessHandler(com.intellij.execution.process.CapturingAnsiEscapesAwareProcessHandler) ProcessHandler(com.intellij.execution.process.ProcessHandler) ExecutionException(com.intellij.execution.ExecutionException) File(java.io.File) AndroidLocation(com.android.prefs.AndroidLocation) NotNull(org.jetbrains.annotations.NotNull)

Aggregations

ProgressWindow (com.intellij.openapi.progress.util.ProgressWindow)8 ModalityState (com.intellij.openapi.application.ModalityState)2 BackgroundableProcessIndicator (com.intellij.openapi.progress.impl.BackgroundableProcessIndicator)2 File (java.io.File)2 NotNull (org.jetbrains.annotations.NotNull)2 IDevice (com.android.ddmlib.IDevice)1 AndroidLocation (com.android.prefs.AndroidLocation)1 RemotePackage (com.android.repository.api.RemotePackage)1 RepoManager (com.android.repository.api.RepoManager)1 StudioDownloader (com.android.tools.idea.sdk.StudioDownloader)1 RepoProgressIndicatorAdapter (com.android.tools.idea.sdk.progress.RepoProgressIndicatorAdapter)1 StudioLoggerProgressIndicator (com.android.tools.idea.sdk.progress.StudioLoggerProgressIndicator)1 DynamicWizard (com.android.tools.idea.wizard.dynamic.DynamicWizard)1 ExecutionException (com.intellij.execution.ExecutionException)1 GeneralCommandLine (com.intellij.execution.configurations.GeneralCommandLine)1 CapturingAnsiEscapesAwareProcessHandler (com.intellij.execution.process.CapturingAnsiEscapesAwareProcessHandler)1 ProcessHandler (com.intellij.execution.process.ProcessHandler)1 BooleanOptionDescription (com.intellij.ide.ui.search.BooleanOptionDescription)1 ChooseByNamePopup (com.intellij.ide.util.gotoByName.ChooseByNamePopup)1 GotoActionItemProvider (com.intellij.ide.util.gotoByName.GotoActionItemProvider)1