summaryrefslogtreecommitdiff
path: root/platform/lang-impl/src/com/intellij/execution/impl/ExecutionManagerImpl.java
blob: 9d675ecdc65e607b0570053b1bf0f44dec885ae0 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
/*
 * Copyright 2000-2012 JetBrains s.r.o.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.intellij.execution.impl;

import com.intellij.CommonBundle;
import com.intellij.execution.*;
import com.intellij.execution.configurations.ConfigurationPerRunnerSettings;
import com.intellij.execution.configurations.RunConfiguration;
import com.intellij.execution.configurations.RunProfile;
import com.intellij.execution.configurations.RunProfileState;
import com.intellij.execution.process.ProcessAdapter;
import com.intellij.execution.process.ProcessEvent;
import com.intellij.execution.process.ProcessHandler;
import com.intellij.execution.runners.ExecutionEnvironment;
import com.intellij.execution.runners.ExecutionUtil;
import com.intellij.execution.ui.RunContentDescriptor;
import com.intellij.execution.ui.RunContentManager;
import com.intellij.execution.ui.RunContentManagerImpl;
import com.intellij.openapi.Disposable;
import com.intellij.openapi.actionSystem.DataContext;
import com.intellij.openapi.actionSystem.impl.SimpleDataContext;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.components.ProjectComponent;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.project.DumbService;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.DialogWrapper;
import com.intellij.openapi.ui.Messages;
import com.intellij.openapi.util.Disposer;
import com.intellij.openapi.util.Trinity;
import com.intellij.openapi.vfs.VirtualFileManager;
import com.intellij.ui.docking.DockManager;
import com.intellij.util.Alarm;
import com.intellij.util.containers.ContainerUtil;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import javax.swing.*;
import java.util.ArrayList;
import java.util.List;

/**
 * @author dyoma
 */
public class ExecutionManagerImpl extends ExecutionManager implements ProjectComponent {
  private static final Logger LOG = Logger.getInstance("com.intellij.execution.impl.ExecutionManagerImpl");

  private final Project myProject;

  private RunContentManagerImpl myContentManager;
  private final Alarm awaitingTerminationAlarm = new Alarm(Alarm.ThreadToUse.SWING_THREAD);
  private final List<Trinity<RunContentDescriptor, RunnerAndConfigurationSettings, Executor>> myRunningConfigurations =
    ContainerUtil.createLockFreeCopyOnWriteList();

  /**
   * reflection
   */
  ExecutionManagerImpl(final Project project) {
    myProject = project;
  }

  @Override
  public void projectOpened() {
    ((RunContentManagerImpl)getContentManager()).init();
  }

  @Override
  public void projectClosed() {
  }

  @Override
  public void initComponent() {
  }

  @Override
  public void disposeComponent() {
    for (Trinity<RunContentDescriptor, RunnerAndConfigurationSettings, Executor> trinity : myRunningConfigurations) {
      Disposer.dispose(trinity.first);
    }
    myRunningConfigurations.clear();
  }

  @Override
  public RunContentManager getContentManager() {
    if (myContentManager == null) {
      myContentManager = new RunContentManagerImpl(myProject, DockManager.getInstance(myProject));
      Disposer.register(myProject, myContentManager);
    }
    return myContentManager;
  }

  @Override
  public ProcessHandler[] getRunningProcesses() {
    final List<ProcessHandler> handlers = new ArrayList<ProcessHandler>();
    for (RunContentDescriptor descriptor : getContentManager().getAllDescriptors()) {
      final ProcessHandler processHandler = descriptor.getProcessHandler();
      if (processHandler != null) {
        handlers.add(processHandler);
      }
    }
    return handlers.toArray(new ProcessHandler[handlers.size()]);
  }

  @Override
  public void compileAndRun(@NotNull final Runnable startRunnable,
                            @NotNull final ExecutionEnvironment env,
                            @Nullable final RunProfileState state,
                            @Nullable final Runnable onCancelRunnable) {
    long id = env.getExecutionId();
    if (id == 0) {
      id = env.assignNewExecutionId();
    }
    RunProfile profile = env.getRunProfile();

    if (profile instanceof RunConfiguration) {
      final RunConfiguration runConfiguration = (RunConfiguration)profile;
      final RunManagerImpl runManager = RunManagerImpl.getInstanceImpl(myProject);

      final List<BeforeRunTask> activeTasks = new ArrayList<BeforeRunTask>();
      activeTasks.addAll(runManager.getBeforeRunTasks(runConfiguration));

      ConfigurationPerRunnerSettings configurationSettings = state != null ? state.getConfigurationSettings() : null;
      final DataContext projectContext = SimpleDataContext.getProjectContext(myProject);
      final DataContext dataContext = configurationSettings != null ? SimpleDataContext
        .getSimpleContext(BeforeRunTaskProvider.RUNNER_ID, configurationSettings.getRunnerId(), projectContext) : projectContext;

      if (!activeTasks.isEmpty()) {
        final long finalId = id;
        ApplicationManager.getApplication().executeOnPooledThread(new Runnable() {
          /** @noinspection SSBasedInspection*/
          @Override
          public void run() {
            for (BeforeRunTask task : activeTasks) {
              BeforeRunTaskProvider<BeforeRunTask> provider = BeforeRunTaskProvider.getProvider(myProject, task.getProviderId());
              if (provider == null) {
                LOG.warn("Cannot find BeforeRunTaskProvider for id='" + task.getProviderId() + "'");
                continue;
              }
              ExecutionEnvironment taskEnvironment = new ExecutionEnvironment(env.getRunProfile(),
                                                                              env.getExecutionTarget(),
                                                                              env.getProject(),
                                                                              env.getRunnerSettings(),
                                                                              env.getConfigurationSettings(),
                                                                              null,
                                                                              env.getRunnerAndConfigurationSettings());
              taskEnvironment.setExecutionId(finalId);
              if (!provider.executeTask(dataContext, runConfiguration, taskEnvironment, task)) {
                if (onCancelRunnable != null) {
                  SwingUtilities.invokeLater(onCancelRunnable);
                }
                return;
              }
            }
            // important! Do not use DumbService.smartInvokelater here because it depends on modality state
            // and execution of startRunnable could be skipped if modality state check fails
            SwingUtilities.invokeLater(new Runnable() {
              @Override
              public void run() {
                if (!myProject.isDisposed()) {
                  DumbService.getInstance(myProject).runWhenSmart(startRunnable);
                }
              }
            });
          }
        });
      }
      else {
        startRunnable.run();
      }
    }
    else {
      startRunnable.run();
    }
  }

  @Override
  public void startRunProfile(@NotNull final RunProfileStarter starter, @NotNull final RunProfileState state,
                              @NotNull final Project project, @NotNull final Executor executor, @NotNull final ExecutionEnvironment env) {
    final RunContentDescriptor reuseContent =
      ExecutionManager.getInstance(project).getContentManager().getReuseContent(executor, env);
    if (reuseContent != null) {
      reuseContent.setExecutionId(env.getExecutionId());
    }
    final RunProfile profile = env.getRunProfile();

    project.getMessageBus().syncPublisher(EXECUTION_TOPIC).processStartScheduled(executor.getId(), env);

    Runnable startRunnable = new Runnable() {
      @Override
      public void run() {
        if (project.isDisposed()) return;
        boolean started = false;
        try {
          project.getMessageBus().syncPublisher(EXECUTION_TOPIC).processStarting(executor.getId(), env);

          final RunContentDescriptor descriptor = starter.execute(project, executor, state, reuseContent, env);

          if (descriptor != null) {
            final Trinity<RunContentDescriptor, RunnerAndConfigurationSettings, Executor> trinity =
              Trinity.create(descriptor, env.getRunnerAndConfigurationSettings(), executor);
            myRunningConfigurations.add(trinity);
            Disposer.register(descriptor, new Disposable() {
              @Override
              public void dispose() {
                myRunningConfigurations.remove(trinity);
              }
            });
            ExecutionManager.getInstance(project).getContentManager().showRunContent(executor, descriptor, reuseContent);
            final ProcessHandler processHandler = descriptor.getProcessHandler();
            if (processHandler != null) {
              processHandler.startNotify();
              project.getMessageBus().syncPublisher(EXECUTION_TOPIC).processStarted(executor.getId(), env, processHandler);
              started = true;
              processHandler.addProcessListener(new ProcessExecutionListener(project, profile, processHandler));
            }
          }
        }
        catch (ExecutionException e) {
          ExecutionUtil.handleExecutionError(project, executor.getToolWindowId(), profile, e);
          LOG.info(e);
        }
        finally {
          if (!started) {
            project.getMessageBus().syncPublisher(EXECUTION_TOPIC).processNotStarted(executor.getId(), env);
          }
        }
      }
    };

    if (ApplicationManager.getApplication().isUnitTestMode()) {
      startRunnable.run();
    }
    else {
      compileAndRun(startRunnable, env, state, new Runnable() {
        @Override
        public void run() {
          if (!project.isDisposed()) {
            project.getMessageBus().syncPublisher(EXECUTION_TOPIC).processNotStarted(executor.getId(), env);
          }
        }
      });
    }
  }

  @Override
  public void restartRunProfile(@NotNull final Project project,
                                @NotNull final Executor executor,
                                @NotNull final ExecutionTarget target,
                                @Nullable final RunnerAndConfigurationSettings configuration,
                                @Nullable final ProcessHandler processHandler) {
    if (processHandler != null) {
      for (RunContentDescriptor descriptor : getContentManager().getAllDescriptors()) {
        final ProcessHandler handler = descriptor.getProcessHandler();
        if (handler == processHandler) {
          restartRunProfile(project, executor, target, configuration, descriptor);
          return;
        }
      }
    }
    restartRunProfile(project, executor, target, configuration, (RunContentDescriptor)null);
  }

  @Override
  public void restartRunProfile(@NotNull final Project project,
                                @NotNull final Executor executor,
                                @NotNull final ExecutionTarget target,
                                @Nullable final RunnerAndConfigurationSettings configuration,
                                @Nullable final RunContentDescriptor currentDescriptor) {
    if (configuration != null && ProgramRunnerUtil.getRunner(executor.getId(), configuration) == null) {
      LOG.error("Cannot find runner for " + configuration.getName());
      return;
    }
    if (configuration == null && (currentDescriptor == null || currentDescriptor.getRestarter() == null)) {
      LOG.error("Nothing to restart");
      return;
    }
    final List<RunContentDescriptor> descriptorsToStop = new ArrayList<RunContentDescriptor>();
    if (configuration != null && configuration.isSingleton()) {
      descriptorsToStop.addAll(getRunningDescriptors(configuration));
    }
    else if (currentDescriptor != null) {
      descriptorsToStop.add(currentDescriptor);
    }

    if (!descriptorsToStop.isEmpty()) {
      if (configuration != null && (descriptorsToStop.size() > 1 || currentDescriptor == null || descriptorsToStop.get(0) != currentDescriptor) &&
          !userApprovesStop(project, configuration.getName(), descriptorsToStop.size())) {
        return;
      }
      for (RunContentDescriptor descriptor : descriptorsToStop) {
        stop(descriptor);
      }
    }
    else {
      start(project, configuration, executor, target, currentDescriptor);
      return;
    }

    Runnable runnable = new Runnable() {
      @Override
      public void run() {
        for (RunContentDescriptor descriptor : descriptorsToStop) {
          ProcessHandler processHandler = descriptor.getProcessHandler();
          if (processHandler != null && !processHandler.isProcessTerminated()) {
            awaitingTerminationAlarm.addRequest(this, 100);
            return;
          }
        }
        start(project, configuration, executor, target, currentDescriptor);
      }
    };
    awaitingTerminationAlarm.addRequest(runnable, 100);
  }

  private static void start(@NotNull Project project,
                            @Nullable RunnerAndConfigurationSettings configuration,
                            @NotNull Executor executor,
                            @NotNull ExecutionTarget target,
                            @Nullable RunContentDescriptor descriptor) {
    Runnable restarter = descriptor != null ? descriptor.getRestarter() : null;
    if (configuration != null) {
      ProgramRunnerUtil.executeConfiguration(project, configuration, executor, target, descriptor, true);
    }
    else if (restarter != null) {
      restarter.run();
    }
  }

  private static boolean userApprovesStop(Project project, String configName, int instancesCount) {
    RunManagerImpl runManager = RunManagerImpl.getInstanceImpl(project);
    final RunManagerConfig config = runManager.getConfig();
    if (!config.isRestartRequiresConfirmation()) return true;

    DialogWrapper.DoNotAskOption option = new DialogWrapper.DoNotAskOption() {
      @Override
      public boolean isToBeShown() {
        return config.isRestartRequiresConfirmation();
      }

      @Override
      public void setToBeShown(boolean value, int exitCode) {
        config.setRestartRequiresConfirmation(value);
      }

      @Override
      public boolean canBeHidden() {
        return true;
      }

      @Override
      public boolean shouldSaveOptionsOnCancel() {
        return false;
      }

      @Override
      public String getDoNotShowMessage() {
        return CommonBundle.message("dialog.options.do.not.show");
      }
    };
    return Messages.showOkCancelDialog(
      project,
      ExecutionBundle.message("rerun.singleton.confirmation.message", configName, instancesCount),
      ExecutionBundle.message("process.is.running.dialog.title", configName),
      ExecutionBundle.message("rerun.confirmation.button.text"),
      CommonBundle.message("button.cancel"),
      Messages.getQuestionIcon(), option) == Messages.OK;
  }

  private List<RunContentDescriptor> getRunningDescriptors(RunnerAndConfigurationSettings configuration) {
    List<RunContentDescriptor> result = new ArrayList<RunContentDescriptor>();
    for (Trinity<RunContentDescriptor, RunnerAndConfigurationSettings, Executor> trinity : myRunningConfigurations) {
      if (trinity.getSecond() == configuration) {
        ProcessHandler processHandler = trinity.getFirst().getProcessHandler();
        if (processHandler != null && !processHandler.isProcessTerminating() && !processHandler.isProcessTerminated()) {
          result.add(trinity.getFirst());
        }
      }
    }
    return result;
  }


  private static void stop(RunContentDescriptor runContentDescriptor) {
    ProcessHandler processHandler = runContentDescriptor != null ? runContentDescriptor.getProcessHandler() : null;
    if (processHandler == null) {
      return;
    }
    if (processHandler instanceof KillableProcess && processHandler.isProcessTerminating()) {
      ((KillableProcess)processHandler).killProcess();
      return;
    }

    if (processHandler.detachIsDefault()) {
      processHandler.detachProcess();
    }
    else {
      processHandler.destroyProcess();
    }
  }

  @Override
  @NotNull
  public String getComponentName() {
    return "ExecutionManager";
  }

  private static class ProcessExecutionListener extends ProcessAdapter {
    private final Project myProject;
    private final RunProfile myProfile;
    private final ProcessHandler myProcessHandler;

    public ProcessExecutionListener(Project project, RunProfile profile, ProcessHandler processHandler) {
      myProject = project;
      myProfile = profile;
      myProcessHandler = processHandler;
    }

    @Override
    public void processTerminated(ProcessEvent event) {
      if (myProject.isDisposed()) return;

      myProject.getMessageBus().syncPublisher(EXECUTION_TOPIC).processTerminated(myProfile, myProcessHandler);
      VirtualFileManager.getInstance().asyncRefresh(null);
    }

    @Override
    public void processWillTerminate(ProcessEvent event, boolean willBeDestroyed) {
      if (myProject.isDisposed()) return;

      myProject.getMessageBus().syncPublisher(EXECUTION_TOPIC).processTerminating(myProfile, myProcessHandler);
    }
  }
}