private ValidationResult getValidationResult() {
    if (!myValidationResultValid) {
      myLastValidationResult = null;
      try {
        RunnerAndConfigurationSettings snapshot = getSnapshot();
        if (snapshot != null) {
          snapshot.setName(getNameText());
          snapshot.checkSettings();
          for (ProgramRunner runner : RunnerRegistry.getInstance().getRegisteredRunners()) {
            for (Executor executor : ExecutorRegistry.getInstance().getRegisteredExecutors()) {
              if (runner.canRun(executor.getId(), snapshot.getConfiguration())) {
                checkConfiguration(runner, snapshot);
                break;
              }
            }
          }
        }
      } catch (RuntimeConfigurationException exception) {
        myLastValidationResult =
            exception != null
                ? new ValidationResult(
                    exception.getLocalizedMessage(), exception.getTitle(), exception.getQuickFix())
                : null;
      } catch (ConfigurationException e) {
        myLastValidationResult =
            new ValidationResult(
                e.getLocalizedMessage(),
                ExecutionBundle.message("invalid.data.dialog.title"),
                null);
      }

      myValidationResultValid = true;
    }
    return myLastValidationResult;
  }
 @Override
 protected void hyperlinkActivated(HyperlinkEvent e) {
   final Module moduleByName =
       ModuleManager.getInstance(myProject).findModuleByName(e.getDescription());
   if (moduleByName != null) {
     myConfiguration.getConfigurationModule().setModule(moduleByName);
     try {
       final Executor executor =
           myConsoleProperties.isDebug()
               ? DefaultDebugExecutor.getDebugExecutorInstance()
               : DefaultRunExecutor.getRunExecutorInstance();
       final ProgramRunner runner =
           RunnerRegistry.getInstance().getRunner(executor.getId(), myConfiguration);
       assert runner != null;
       runner.execute(
           executor,
           new ExecutionEnvironment(
               myConfiguration,
               myProject,
               getRunnerSettings(),
               getConfigurationSettings(),
               null));
       final Balloon balloon = myToolWindowManager.getToolWindowBalloon(myTestRunDebugId);
       if (balloon != null) {
         balloon.hide();
       }
     } catch (ExecutionException e1) {
       LOG.error(e1);
     }
   }
 }
 private ContentManager getContentManagerForRunner(final Executor executor) {
   final ContentManager contentManager =
       myToolwindowIdToContentManagerMap.get(executor.getToolWindowId());
   if (contentManager == null) {
     LOG.error("Runner " + executor.getId() + " is not registered");
   }
   return contentManager;
 }
  private void registerToolwindow(@NotNull final Executor executor) {
    final String toolWindowId = executor.getToolWindowId();
    final ToolWindowManager toolWindowManager = ToolWindowManager.getInstance(myProject);
    if (toolWindowManager == null) return; // headless environment
    if (toolWindowManager.getToolWindow(toolWindowId) != null) {
      return;
    }

    final ToolWindow toolWindow =
        toolWindowManager.registerToolWindow(
            toolWindowId, true, ToolWindowAnchor.BOTTOM, this, true);

    final ContentManager contentManager = toolWindow.getContentManager();
    class MyDataProvider implements DataProvider {
      private int myInsideGetData = 0;

      public Object getData(String dataId) {
        myInsideGetData++;
        try {
          if (PlatformDataKeys.HELP_ID.is(dataId)) {
            return executor.getHelpId();
          } else {
            return myInsideGetData == 1
                ? DataManager.getInstance()
                    .getDataContext(contentManager.getComponent())
                    .getData(dataId)
                : null;
          }
        } finally {
          myInsideGetData--;
        }
      }
    }
    contentManager.addDataProvider(new MyDataProvider());

    toolWindow.setIcon(executor.getToolWindowIcon());
    new ContentManagerWatcher(toolWindow, contentManager);
    contentManager.addContentManagerListener(
        new ContentManagerAdapter() {
          public void selectionChanged(final ContentManagerEvent event) {
            final Content content = event.getContent();
            final RunContentDescriptor descriptor =
                content != null ? getRunContentDescriptorByContent(content) : null;
            getSyncPublisher().contentSelected(descriptor, executor);
          }
        });
    myToolwindowIdToContentManagerMap.put(toolWindowId, contentManager);
    Disposer.register(
        contentManager,
        new Disposable() {
          public void dispose() {
            unregisterToolwindow(toolWindowId);
          }
        });
    myToolwindowIdZbuffer.addLast(toolWindowId);
  }
 public void restart() {
   final Project project =
       PlatformDataKeys.PROJECT.getData(
           DataManager.getInstance().getDataContext(myDescriptor.getComponent()));
   if (ExecutorRegistry.getInstance()
       .isStarting(project, myExecutor.getId(), myRunner.getRunnerId())) {
     return;
   }
   try {
     final ExecutionEnvironment old = myEnvironment;
     myRunner.execute(
         myExecutor,
         new ExecutionEnvironment(
             old.getRunProfile(),
             old.getExecutionTarget(),
             project,
             old.getRunnerSettings(),
             old.getConfigurationSettings(),
             myDescriptor,
             old.getRunnerAndConfigurationSettings()));
   } catch (RunCanceledByUserException ignore) {
   } catch (ExecutionException e1) {
     Messages.showErrorDialog(
         project, e1.getMessage(), ExecutionBundle.message("restart.error.message.title"));
   }
 }
 boolean isEnabled() {
   ProcessHandler processHandler = myDescriptor.getProcessHandler();
   boolean isTerminating = processHandler != null && processHandler.isProcessTerminating();
   boolean isStarting =
       ExecutorRegistry.getInstance()
           .isStarting(myEnvironment.getProject(), myExecutor.getId(), myRunner.getRunnerId());
   return !isStarting && !isTerminating;
 }
Esempio n. 7
0
 private void runTriggers(Executor executor, RunnerAndConfigurationSettings configuration) {
   final ConfigurationType configurationType = configuration.getType();
   if (configurationType != null) {
     UsageTrigger.trigger(
         "execute."
             + ConvertUsagesUtil.ensureProperKey(configurationType.getId())
             + "."
             + executor.getId());
   }
 }
  @Override
  public void update(final AnActionEvent event) {
    final Presentation presentation = event.getPresentation();
    String name = myEnvironment.getRunProfile().getName();
    ProcessHandler processHandler = myDescriptor.getProcessHandler();
    final boolean isRunning = processHandler != null && !processHandler.isProcessTerminated();

    presentation.setText(ExecutionBundle.message("rerun.configuration.action.name", name));
    presentation.setIcon(isRunning ? AllIcons.Actions.Restart : myExecutor.getIcon());
    presentation.setEnabled(isEnabled());
  }
  private static void patchProjectAreaExtensions(@NotNull final Project project) {
    Executor debugExecutor = DefaultDebugExecutor.getDebugExecutorInstance();
    unregisterAction(debugExecutor.getId(), ExecutorRegistryImpl.RUNNERS_GROUP);
    unregisterAction(debugExecutor.getContextActionId(), ExecutorRegistryImpl.RUN_CONTEXT_GROUP);

    ExtensionsArea projectArea = Extensions.getArea(project);

    for (SelectInTarget target : Extensions.getExtensions(SelectInTarget.EP_NAME, project)) {
      if (ToolWindowId.FAVORITES_VIEW.equals(target.getToolWindowId())
          || ToolWindowId.STRUCTURE_VIEW.equals(target.getToolWindowId())) {
        projectArea.getExtensionPoint(SelectInTarget.EP_NAME).unregisterExtension(target);
      }
    }

    for (AbstractProjectViewPane pane :
        Extensions.getExtensions(AbstractProjectViewPane.EP_NAME, project)) {
      if (pane.getId().equals(ScopeViewPane.ID)) {
        Disposer.dispose(pane);
        projectArea.getExtensionPoint(AbstractProjectViewPane.EP_NAME).unregisterExtension(pane);
      }
    }
  }
 @Override
 public void actionPerformed(AnActionEvent e) {
   final Project project = e.getProject();
   LOG.assertTrue(project != null);
   final VirtualFile file = getFile(project);
   if (file != null) {
     try {
       final ImportRunProfile profile = new ImportRunProfile(file, project);
       SMTRunnerConsoleProperties properties = profile.getProperties();
       if (properties == null) {
         properties = myProperties;
         LOG.info(
             "Failed to detect test framework in "
                 + file.getPath()
                 + "; use "
                 + (properties != null
                     ? properties.getTestFrameworkName() + " from toolbar"
                     : "no properties"));
       }
       final Executor executor =
           properties != null
               ? properties.getExecutor()
               : ExecutorRegistry.getInstance().getExecutorById(DefaultRunExecutor.EXECUTOR_ID);
       ExecutionEnvironmentBuilder builder =
           ExecutionEnvironmentBuilder.create(project, executor, profile);
       final RunConfiguration initialConfiguration = profile.getInitialConfiguration();
       final ProgramRunner runner =
           initialConfiguration != null
               ? RunnerRegistry.getInstance().getRunner(executor.getId(), initialConfiguration)
               : null;
       if (runner != null) {
         builder = builder.runner(runner);
       }
       builder.buildAndExecute();
     } catch (ExecutionException e1) {
       Messages.showErrorDialog(project, e1.getMessage(), "Import Failed");
     }
   }
 }
 @Nullable
 public static ExecutionEnvironmentBuilder createEnvironment(
     @NotNull Executor executor, @NotNull RunnerAndConfigurationSettings settings) {
   try {
     return ExecutionEnvironmentBuilder.create(executor, settings);
   } catch (ExecutionException e) {
     handleExecutionError(
         settings.getConfiguration().getProject(),
         executor.getToolWindowId(),
         settings.getConfiguration().getName(),
         e);
     return null;
   }
 }
  protected void showConsole(Executor defaultExecutor, RunContentDescriptor myDescriptor) {
    // Show in run toolwindow
    ExecutionManager.getInstance(myProject)
        .getContentManager()
        .showRunContent(defaultExecutor, myDescriptor);

    // Request focus
    final ToolWindow window =
        ToolWindowManager.getInstance(myProject).getToolWindow(defaultExecutor.getId());
    window.activate(
        new Runnable() {
          public void run() {
            IdeFocusManager.getInstance(myProject)
                .requestFocus(getLanguageConsole().getCurrentEditor().getContentComponent(), true);
          }
        });
  }
Esempio n. 13
0
  private boolean checkRunConfiguration(
      Executor executor, Project project, RunnerAndConfigurationSettings configuration) {
    ExecutionTarget target = ExecutionTargetManager.getActiveTarget(project);

    if (!ExecutionTargetManager.canRun(configuration, target)) {
      ExecutionUtil.handleExecutionError(
          project,
          executor.getToolWindowId(),
          configuration.getConfiguration(),
          new ExecutionException(
              StringUtil.escapeXml(
                  "Cannot run '"
                      + configuration.getName()
                      + "' on '"
                      + target.getDisplayName()
                      + "'")));
      return false;
    }

    if (!RunManagerImpl.canRunConfiguration(configuration, executor)
        || configuration.isEditBeforeRun()) {
      if (!RunDialog.editConfiguration(project, configuration, "Edit configuration", executor)) {
        return false;
      }

      while (!RunManagerImpl.canRunConfiguration(configuration, executor)) {
        if (0
            == Messages.showYesNoDialog(
                project,
                "Configuration is still incorrect. Do you want to edit it again?",
                "Change Configuration Settings",
                "Edit",
                "Continue Anyway",
                Messages.getErrorIcon())) {
          if (!RunDialog.editConfiguration(
              project, configuration, "Edit configuration", executor)) {
            break;
          }
        } else {
          break;
        }
      }
    }
    return true;
  }
  private void appendForkInfo(Executor executor) throws ExecutionException {
    final String forkMode = myConfiguration.getForkMode();
    if (Comparing.strEqual(forkMode, "none")) {
      return;
    }

    if (getRunnerSettings().getData() != null) {
      final String actionName = executor.getActionName();
      throw new CantRunException(
          actionName
              + " is disabled in fork mode.<br/>Please change fork mode to &lt;none&gt; to "
              + actionName.toLowerCase()
              + ".");
    }

    final JavaParameters javaParameters = getJavaParameters();
    final Sdk jdk = javaParameters.getJdk();
    if (jdk == null) {
      throw new ExecutionException(
          ExecutionBundle.message("run.configuration.error.no.jdk.specified"));
    }

    try {
      final File tempFile = FileUtil.createTempFile("command.line", "", true);
      final PrintWriter writer = new PrintWriter(tempFile, "UTF-8");
      try {
        writer.println(((JavaSdkType) jdk.getSdkType()).getVMExecutablePath(jdk));
        for (String vmParameter : javaParameters.getVMParametersList().getList()) {
          writer.println(vmParameter);
        }
        writer.println("-classpath");
        writer.println(javaParameters.getClassPath().getPathsString());
      } finally {
        writer.close();
      }

      myJavaParameters
          .getProgramParametersList()
          .add("@@@" + forkMode + ',' + tempFile.getAbsolutePath());
    } catch (Exception e) {
      LOG.error(e);
    }
  }
  @NotNull
  private static ExecutionEnvironmentBuilder createEnvironmentBuilder(
      @NotNull Project project,
      @NotNull Executor executor,
      @Nullable RunnerAndConfigurationSettings configuration) {
    ExecutionEnvironmentBuilder builder = new ExecutionEnvironmentBuilder(project, executor);

    ProgramRunner runner =
        RunnerRegistry.getInstance()
            .getRunner(
                executor.getId(), configuration != null ? configuration.getConfiguration() : null);
    if (runner == null && configuration != null) {
      LOG.error("Cannot find runner for " + configuration.getName());
    } else if (runner != null) {
      assert configuration != null;
      builder.runnerAndSettings(runner, configuration);
    }
    return builder;
  }
  @Override
  public void startRunProfile(
      @NotNull final RunProfileStarter starter,
      @NotNull final RunProfileState state,
      @NotNull final ExecutionEnvironment environment) {
    final Project project = environment.getProject();
    RunContentDescriptor reuseContent = getContentManager().getReuseContent(environment);
    if (reuseContent != null) {
      reuseContent.setExecutionId(environment.getExecutionId());
      environment.setContentToReuse(reuseContent);
    }

    final Executor executor = environment.getExecutor();
    project
        .getMessageBus()
        .syncPublisher(EXECUTION_TOPIC)
        .processStartScheduled(executor.getId(), environment);

    Runnable startRunnable;
    startRunnable =
        () -> {
          if (project.isDisposed()) {
            return;
          }

          RunProfile profile = environment.getRunProfile();
          boolean started = false;
          try {
            project
                .getMessageBus()
                .syncPublisher(EXECUTION_TOPIC)
                .processStarting(executor.getId(), environment);

            final RunContentDescriptor descriptor = starter.execute(state, environment);
            if (descriptor != null) {
              final Trinity<RunContentDescriptor, RunnerAndConfigurationSettings, Executor>
                  trinity =
                      Trinity.create(
                          descriptor, environment.getRunnerAndConfigurationSettings(), executor);
              myRunningConfigurations.add(trinity);
              Disposer.register(descriptor, () -> myRunningConfigurations.remove(trinity));
              getContentManager()
                  .showRunContent(executor, descriptor, environment.getContentToReuse());
              final ProcessHandler processHandler = descriptor.getProcessHandler();
              if (processHandler != null) {
                if (!processHandler.isStartNotified()) {
                  processHandler.startNotify();
                }
                project
                    .getMessageBus()
                    .syncPublisher(EXECUTION_TOPIC)
                    .processStarted(executor.getId(), environment, processHandler);
                started = true;

                ProcessExecutionListener listener =
                    new ProcessExecutionListener(
                        project, executor.getId(), environment, processHandler, descriptor);
                processHandler.addProcessListener(listener);

                // Since we cannot guarantee that the listener is added before process handled is
                // start notified,
                // we have to make sure the process termination events are delivered to the clients.
                // Here we check the current process state and manually deliver events, while
                // the ProcessExecutionListener guarantees each such event is only delivered once
                // either by this code, or by the ProcessHandler.

                boolean terminating = processHandler.isProcessTerminating();
                boolean terminated = processHandler.isProcessTerminated();
                if (terminating || terminated) {
                  listener.processWillTerminate(
                      new ProcessEvent(processHandler), false /*doesn't matter*/);

                  if (terminated) {
                    //noinspection ConstantConditions
                    int exitCode = processHandler.getExitCode();
                    listener.processTerminated(new ProcessEvent(processHandler, exitCode));
                  }
                }
              }
              environment.setContentToReuse(descriptor);
            }
          } catch (ProcessCanceledException e) {
            LOG.info(e);
          } catch (ExecutionException e) {
            ExecutionUtil.handleExecutionError(project, executor.getToolWindowId(), profile, e);
            LOG.info(e);
          } finally {
            if (!started) {
              project
                  .getMessageBus()
                  .syncPublisher(EXECUTION_TOPIC)
                  .processNotStarted(executor.getId(), environment);
            }
          }
        };

    if (ApplicationManager.getApplication().isUnitTestMode() && !myForceCompilationInTests) {
      startRunnable.run();
    } else {
      compileAndRun(
          () -> TransactionGuard.submitTransaction(project, startRunnable),
          environment,
          state,
          () -> {
            if (!project.isDisposed()) {
              project
                  .getMessageBus()
                  .syncPublisher(EXECUTION_TOPIC)
                  .processNotStarted(executor.getId(), environment);
            }
          });
    }
  }
  @Override
  public boolean executeTask(
      DataContext context,
      RunConfiguration configuration,
      ExecutionEnvironment env,
      ExternalSystemBeforeRunTask beforeRunTask) {

    final ExternalSystemTaskExecutionSettings executionSettings =
        beforeRunTask.getTaskExecutionSettings();

    final List<ExternalTaskPojo> tasks = ContainerUtilRt.newArrayList();
    for (String taskName : executionSettings.getTaskNames()) {
      tasks.add(new ExternalTaskPojo(taskName, executionSettings.getExternalProjectPath(), null));
    }
    if (tasks.isEmpty()) return true;

    final Pair<ProgramRunner, ExecutionEnvironment> pair =
        ExternalSystemUtil.createRunner(
            executionSettings, DefaultRunExecutor.EXECUTOR_ID, myProject, mySystemId);

    if (pair == null) return false;

    final ProgramRunner runner = pair.first;
    final ExecutionEnvironment environment = pair.second;
    environment.setExecutionId(env.getExecutionId());

    final Semaphore targetDone = new Semaphore();
    final Ref<Boolean> result = new Ref<Boolean>(false);
    final Disposable disposable = Disposer.newDisposable();

    final Executor executor = DefaultRunExecutor.getRunExecutorInstance();
    final String executorId = executor.getId();

    myProject
        .getMessageBus()
        .connect(disposable)
        .subscribe(
            ExecutionManager.EXECUTION_TOPIC,
            new ExecutionAdapter() {
              public void processStartScheduled(
                  final String executorIdLocal, final ExecutionEnvironment environmentLocal) {
                if (executorId.equals(executorIdLocal) && environment.equals(environmentLocal)) {
                  targetDone.down();
                }
              }

              public void processNotStarted(
                  final String executorIdLocal,
                  @NotNull final ExecutionEnvironment environmentLocal) {
                if (executorId.equals(executorIdLocal) && environment.equals(environmentLocal)) {
                  targetDone.up();
                }
              }

              public void processStarted(
                  final String executorIdLocal,
                  @NotNull final ExecutionEnvironment environmentLocal,
                  @NotNull final ProcessHandler handler) {
                if (executorId.equals(executorIdLocal) && environment.equals(environmentLocal)) {
                  handler.addProcessListener(
                      new ProcessAdapter() {
                        public void processTerminated(ProcessEvent event) {
                          result.set(event.getExitCode() == 0);
                          targetDone.up();
                          environmentLocal.getContentToReuse();
                        }
                      });
                }
              }
            });

    try {
      ApplicationManager.getApplication()
          .invokeAndWait(
              new Runnable() {
                @Override
                public void run() {
                  try {
                    runner.execute(environment);
                  } catch (ExecutionException e) {
                    targetDone.up();
                    LOG.error(e);
                  }
                }
              },
              ModalityState.NON_MODAL);
    } catch (Exception e) {
      LOG.error(e);
      Disposer.dispose(disposable);
      return false;
    }

    targetDone.waitFor();
    Disposer.dispose(disposable);

    return result.get();
  }
  public void showRunContent(
      @NotNull final Executor executor, final RunContentDescriptor descriptor) {
    if (ApplicationManager.getApplication().isUnitTestMode()) return;

    final ContentManager contentManager = getContentManagerForRunner(executor);
    RunContentDescriptor oldDescriptor =
        chooseReuseContentForDescriptor(contentManager, descriptor);

    final Content content;

    if (oldDescriptor != null) {
      content = oldDescriptor.getAttachedContent();
      getSyncPublisher().contentRemoved(oldDescriptor, executor);
      oldDescriptor.dispose(); // is of the same category, can be reused
    } else {
      content = createNewContent(contentManager, descriptor, executor);
      final Icon icon = descriptor.getIcon();
      content.setIcon(icon == null ? executor.getToolWindowIcon() : icon);
    }

    content.setComponent(descriptor.getComponent());
    content.putUserData(DESCRIPTOR_KEY, descriptor);
    final ProcessHandler processHandler = descriptor.getProcessHandler();
    if (processHandler != null) {
      final ProcessAdapter processAdapter =
          new ProcessAdapter() {
            public void startNotified(final ProcessEvent event) {
              LaterInvocator.invokeLater(
                  new Runnable() {
                    public void run() {
                      final Icon icon = descriptor.getIcon();
                      content.setIcon(icon == null ? executor.getToolWindowIcon() : icon);
                    }
                  });
            }

            public void processTerminated(final ProcessEvent event) {
              LaterInvocator.invokeLater(
                  new Runnable() {
                    public void run() {
                      final Icon icon = descriptor.getIcon();
                      content.setIcon(
                          icon == null
                              ? executor.getDisabledIcon()
                              : IconLoader.getTransparentIcon(icon));
                    }
                  });
            }
          };
      processHandler.addProcessListener(processAdapter);
      final Disposable disposer = content.getDisposer();
      if (disposer != null) {
        Disposer.register(
            disposer,
            new Disposable() {
              public void dispose() {
                processHandler.removeProcessListener(processAdapter);
              }
            });
      }
    }
    content.setDisplayName(descriptor.getDisplayName());
    descriptor.setAttachedContent(content);
    content.getManager().setSelectedContent(content);

    ApplicationManager.getApplication()
        .invokeLater(
            new Runnable() {
              public void run() {
                ToolWindow window =
                    ToolWindowManager.getInstance(myProject)
                        .getToolWindow(executor.getToolWindowId());
                // let's activate tool window, but don't move focus
                //
                // window.show() isn't valid here, because it will not
                // mark the window as "last activated" windows and thus
                // some action like navigation up/down in stactrace wont
                // work correctly
                window.activate(null, false, false);
              }
            });
  }
Esempio n. 19
0
  private void runConfigurations(
      final Executor executor, final List<RunConfiguration> runConfigurations, final int index) {
    if (index >= runConfigurations.size()) {
      stopRunningMultirunConfiguration.doneStaringConfigurations();
      return;
    }
    if (!stopRunningMultirunConfiguration.canContinueStartingConfigurations()) {
      stopRunningMultirunConfiguration.doneStaringConfigurations();
      // don't start more configurations if user stopped the plugin work.
      return;
    }

    final RunConfiguration runConfiguration = runConfigurations.get(index);
    final Project project = runConfiguration.getProject();
    final RunnerAndConfigurationSettings configuration =
        new RunnerAndConfigurationSettingsImpl(
            RunManagerImpl.getInstanceImpl(project), runConfiguration, false);

    boolean started = false;
    try {
      ProgramRunner runner =
          RunnerRegistry.getInstance().getRunner(executor.getId(), runConfiguration);
      if (runner == null) return;
      if (!checkRunConfiguration(executor, project, configuration)) return;

      runTriggers(executor, configuration);
      RunContentDescriptor runContentDescriptor =
          getRunContentDescriptor(runConfiguration, project);
      ExecutionEnvironment executionEnvironment =
          new ExecutionEnvironment(
              runner,
              DefaultExecutionTarget.INSTANCE,
              configuration,
              runContentDescriptor,
              project);

      runner.execute(
          executor,
          executionEnvironment,
          new ProgramRunner.Callback() {
            @SuppressWarnings("ConstantConditions")
            @Override
            public void processStarted(final RunContentDescriptor descriptor) {
              if (descriptor == null) {
                if (startOneByOne) {
                  // start next configuration..
                  runConfigurations(executor, runConfigurations, index + 1);
                }
                return;
              }

              final ProcessHandler processHandler = descriptor.getProcessHandler();
              if (processHandler != null) {
                processHandler.addProcessListener(
                    new ProcessAdapter() {
                      @SuppressWarnings("ConstantConditions")
                      @Override
                      public void startNotified(ProcessEvent processEvent) {
                        Content content = descriptor.getAttachedContent();
                        if (content != null) {
                          content.setIcon(descriptor.getIcon());
                          if (!stopRunningMultirunConfiguration
                              .canContinueStartingConfigurations()) {
                            // Multirun was stopped - destroy processes that are still starting up
                            processHandler.destroyProcess();

                            if (!content.isPinned() && !startOneByOne) {
                              // checks if not pinned, to avoid destroying already existed tab
                              // checks if start one by one - no need to close the console tab, as
                              // it's won't be shown
                              // as other checks disallow starting it

                              // content.getManager() can be null, if content is removed already as
                              // part of destroy above
                              if (content.getManager() != null) {
                                content.getManager().removeContent(content, false);
                              }
                            }
                          } else {
                            // mark all current console tab as pinned
                            content.setPinned(true);

                            // mark running process tab with *
                            content.setDisplayName(descriptor.getDisplayName() + "*");
                          }
                        }
                      }

                      @Override
                      public void processTerminated(final ProcessEvent processEvent) {
                        onTermination(processEvent, true);
                      }

                      @Override
                      public void processWillTerminate(
                          ProcessEvent processEvent, boolean willBeDestroyed) {
                        onTermination(processEvent, false);
                      }

                      private void onTermination(
                          final ProcessEvent processEvent, final boolean terminated) {
                        if (descriptor.getAttachedContent() == null) {
                          return;
                        }

                        LaterInvocator.invokeLater(
                            new Runnable() {
                              @Override
                              public void run() {
                                final Content content = descriptor.getAttachedContent();
                                if (content == null) return;

                                // exit code is 0 if the process completed successfully
                                final boolean completedSuccessfully =
                                    (terminated && processEvent.getExitCode() == 0);

                                if (hideSuccessProcess && completedSuccessfully) {
                                  // close the tab for the success process and exit - nothing else
                                  // could be done
                                  if (content.getManager() != null) {
                                    content.getManager().removeContent(content, false);
                                    return;
                                  }
                                }

                                if (!separateTabs && completedSuccessfully) {
                                  // un-pin the console tab if re-use is allowed and process
                                  // completed successfully,
                                  // so the tab could be re-used for other processes
                                  content.setPinned(false);
                                }

                                // remove the * used to identify running process
                                content.setDisplayName(descriptor.getDisplayName());

                                // add the alert icon in case if process existed with non-0 status
                                if (markFailedProcess && processEvent.getExitCode() != 0) {
                                  LaterInvocator.invokeLater(
                                      new Runnable() {
                                        @Override
                                        public void run() {
                                          content.setIcon(
                                              LayeredIcon.create(
                                                  content.getIcon(), AllIcons.Nodes.TabAlert));
                                        }
                                      });
                                }
                              }
                            });
                      }
                    });
              }
              stopRunningMultirunConfiguration.addProcess(project, processHandler);

              if (startOneByOne) {
                // start next configuration..
                runConfigurations(executor, runConfigurations, index + 1);
              }
            }
          });
      started = true;
    } catch (ExecutionException e) {
      ExecutionUtil.handleExecutionError(
          project, executor.getToolWindowId(), configuration.getConfiguration(), e);
    } finally {
      // start the next one
      if (!startOneByOne) {
        runConfigurations(executor, runConfigurations, index + 1);
      } else if (!started) {
        // failed to start current, means the chain is broken
        runConfigurations(executor, runConfigurations, index + 1);
      }
    }
  }
  void execute(@NotNull AnActionEvent e, @NotNull ExecutionEnvironment environment) {
    MyRunProfile profile = getRunProfile(environment);
    if (profile == null) {
      return;
    }

    final ExecutionEnvironmentBuilder environmentBuilder =
        new ExecutionEnvironmentBuilder(environment).runProfile(profile);

    final InputEvent event = e.getInputEvent();
    if (!(event instanceof MouseEvent) || !event.isShiftDown()) {
      performAction(environmentBuilder);
      return;
    }

    final LinkedHashMap<Executor, ProgramRunner> availableRunners = new LinkedHashMap<>();
    for (Executor ex :
        new Executor[] {
          DefaultRunExecutor.getRunExecutorInstance(),
          DefaultDebugExecutor.getDebugExecutorInstance()
        }) {
      final ProgramRunner runner = RunnerRegistry.getInstance().getRunner(ex.getId(), profile);
      if (runner != null) {
        availableRunners.put(ex, runner);
      }
    }

    if (availableRunners.isEmpty()) {
      LOG.error(environment.getExecutor().getActionName() + " is not available now");
    } else if (availableRunners.size() == 1) {
      //noinspection ConstantConditions
      performAction(environmentBuilder.runner(availableRunners.get(environment.getExecutor())));
    } else {
      final JBList list = new JBList(availableRunners.keySet());
      list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
      list.setSelectedValue(environment.getExecutor(), true);
      list.setCellRenderer(
          new DefaultListCellRenderer() {
            @NotNull
            @Override
            public Component getListCellRendererComponent(
                @NotNull JList list,
                Object value,
                int index,
                boolean isSelected,
                boolean cellHasFocus) {
              final Component component =
                  super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);
              if (value instanceof Executor) {
                setText(UIUtil.removeMnemonic(((Executor) value).getStartActionText()));
                setIcon(((Executor) value).getIcon());
              }
              return component;
            }
          });
      //noinspection ConstantConditions
      JBPopupFactory.getInstance()
          .createListPopupBuilder(list)
          .setTitle("Restart Failed Tests")
          .setMovable(false)
          .setResizable(false)
          .setRequestFocus(true)
          .setItemChoosenCallback(
              () -> {
                final Object value = list.getSelectedValue();
                if (value instanceof Executor) {
                  //noinspection ConstantConditions
                  performAction(
                      environmentBuilder
                          .runner(availableRunners.get(value))
                          .executor((Executor) value));
                }
              })
          .createPopup()
          .showUnderneathOf(event.getComponent());
    }
  }
Esempio n. 21
0
  @Override
  public boolean executeTask(
      final DataContext dataContext,
      RunConfiguration configuration,
      final ExecutionEnvironment env,
      RunConfigurableBeforeRunTask task) {
    RunnerAndConfigurationSettings settings = task.getSettings();
    if (settings == null) {
      return false;
    }
    final Executor executor = DefaultRunExecutor.getRunExecutorInstance();
    final String executorId = executor.getId();
    ExecutionEnvironmentBuilder builder =
        ExecutionEnvironmentBuilder.createOrNull(executor, settings);
    if (builder == null) {
      return false;
    }
    final ExecutionEnvironment environment = builder.build();
    environment.setExecutionId(env.getExecutionId());
    if (!ExecutionTargetManager.canRun(settings, env.getExecutionTarget())) {
      return false;
    }

    if (!environment.getRunner().canRun(executorId, environment.getRunProfile())) {
      return false;
    } else {
      final Semaphore targetDone = new Semaphore();
      final Ref<Boolean> result = new Ref<Boolean>(false);
      final Disposable disposable = Disposer.newDisposable();

      myProject
          .getMessageBus()
          .connect(disposable)
          .subscribe(
              ExecutionManager.EXECUTION_TOPIC,
              new ExecutionAdapter() {
                @Override
                public void processStartScheduled(
                    final String executorIdLocal, final ExecutionEnvironment environmentLocal) {
                  if (executorId.equals(executorIdLocal) && environment.equals(environmentLocal)) {
                    targetDone.down();
                  }
                }

                @Override
                public void processNotStarted(
                    final String executorIdLocal,
                    @NotNull final ExecutionEnvironment environmentLocal) {
                  if (executorId.equals(executorIdLocal) && environment.equals(environmentLocal)) {
                    targetDone.up();
                  }
                }

                @Override
                public void processStarted(
                    final String executorIdLocal,
                    @NotNull final ExecutionEnvironment environmentLocal,
                    @NotNull final ProcessHandler handler) {
                  if (executorId.equals(executorIdLocal) && environment.equals(environmentLocal)) {
                    handler.addProcessListener(
                        new ProcessAdapter() {
                          @Override
                          public void processTerminated(ProcessEvent event) {
                            result.set(event.getExitCode() == 0);
                            targetDone.up();
                          }
                        });
                  }
                }
              });

      try {
        ApplicationManager.getApplication()
            .invokeAndWait(
                new Runnable() {
                  @Override
                  public void run() {
                    try {
                      environment.getRunner().execute(environment);
                    } catch (ExecutionException e) {
                      targetDone.up();
                      LOG.error(e);
                    }
                  }
                },
                ModalityState.NON_MODAL);
      } catch (Exception e) {
        LOG.error(e);
        Disposer.dispose(disposable);
        return false;
      }

      targetDone.waitFor();
      Disposer.dispose(disposable);

      return result.get();
    }
  }