f31feeb120491434b98e7934a18ca6dfaa953f69
[idea/community.git] / platform / lang-api / src / com / intellij / execution / runners / ExecutionUtil.java
1 /*
2  * Copyright 2000-2016 JetBrains s.r.o.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 package com.intellij.execution.runners;
18
19 import com.intellij.execution.*;
20 import com.intellij.execution.configurations.RunProfile;
21 import com.intellij.execution.process.ProcessHandler;
22 import com.intellij.execution.process.ProcessNotCreatedException;
23 import com.intellij.execution.ui.RunContentDescriptor;
24 import com.intellij.ide.DataManager;
25 import com.intellij.ide.util.PropertiesComponent;
26 import com.intellij.notification.Notification;
27 import com.intellij.notification.NotificationGroup;
28 import com.intellij.notification.NotificationListener;
29 import com.intellij.notification.NotificationType;
30 import com.intellij.openapi.actionSystem.LangDataKeys;
31 import com.intellij.openapi.application.ApplicationManager;
32 import com.intellij.openapi.diagnostic.Logger;
33 import com.intellij.openapi.project.Project;
34 import com.intellij.openapi.ui.MessageType;
35 import com.intellij.openapi.ui.Messages;
36 import com.intellij.openapi.util.text.StringUtil;
37 import com.intellij.openapi.wm.ToolWindowManager;
38 import com.intellij.ui.ColorUtil;
39 import com.intellij.ui.LayeredIcon;
40 import com.intellij.ui.content.Content;
41 import com.intellij.util.ExceptionUtil;
42 import com.intellij.util.ui.GraphicsUtil;
43 import com.intellij.util.ui.JBUI;
44 import com.intellij.util.ui.UIUtil;
45 import org.jetbrains.annotations.NotNull;
46 import org.jetbrains.annotations.Nullable;
47
48 import javax.swing.*;
49 import javax.swing.event.HyperlinkEvent;
50 import javax.swing.event.HyperlinkListener;
51 import java.awt.*;
52 import java.awt.geom.Ellipse2D;
53
54 public class ExecutionUtil {
55   private static final Logger LOG = Logger.getInstance("com.intellij.execution.runners.ExecutionUtil");
56
57   private static final NotificationGroup ourNotificationGroup = NotificationGroup.logOnlyGroup("Execution");
58
59   private ExecutionUtil() {
60   }
61
62   public static void handleExecutionError(@NotNull Project project,
63                                           @NotNull String toolWindowId,
64                                           @NotNull RunProfile runProfile,
65                                           @NotNull ExecutionException e) {
66     handleExecutionError(project, toolWindowId, runProfile.getName(), e);
67   }
68
69   public static void handleExecutionError(@NotNull ExecutionEnvironment environment, @NotNull ExecutionException e) {
70     handleExecutionError(environment.getProject(), environment.getExecutor().getToolWindowId(), environment.getRunProfile().getName(), e);
71   }
72
73   public static void handleExecutionError(@NotNull final Project project,
74                                           @NotNull final String toolWindowId,
75                                           @NotNull String taskName,
76                                           @NotNull ExecutionException e) {
77     if (e instanceof RunCanceledByUserException) {
78       return;
79     }
80
81     LOG.debug(e);
82
83     String description = e.getMessage();
84     if (StringUtil.isEmptyOrSpaces(description)) {
85       LOG.warn("Execution error without description", e);
86       description = "Unknown error";
87     }
88
89     HyperlinkListener listener = null;
90     if ((description.contains("87") || description.contains("111") || description.contains("206")) &&
91         e instanceof ProcessNotCreatedException &&
92         !PropertiesComponent.getInstance(project).isTrueValue("dynamic.classpath")) {
93       final String commandLineString = ((ProcessNotCreatedException)e).getCommandLine().getCommandLineString();
94       if (commandLineString.length() > 1024 * 32) {
95         description = "Command line is too long. In order to reduce its length classpath file can be used.<br>" +
96                       "Would you like to enable classpath file mode for all run configurations of your project?<br>" +
97                       "<a href=\"\">Enable</a>";
98
99         listener = new HyperlinkListener() {
100           @Override
101           public void hyperlinkUpdate(HyperlinkEvent event) {
102             PropertiesComponent.getInstance(project).setValue("dynamic.classpath", "true");
103           }
104         };
105       }
106     }
107     final String title = ExecutionBundle.message("error.running.configuration.message", taskName);
108     final String fullMessage = title + ":<br>" + description;
109
110     if (ApplicationManager.getApplication().isUnitTestMode()) {
111       LOG.error(fullMessage, e);
112     }
113
114     if (listener == null) {
115       listener = ExceptionUtil.findCause(e, HyperlinkListener.class);
116     }
117
118     final HyperlinkListener finalListener = listener;
119     final String finalDescription = description;
120     UIUtil.invokeLaterIfNeeded(() -> {
121       if (project.isDisposed()) {
122         return;
123       }
124
125       ToolWindowManager toolWindowManager = ToolWindowManager.getInstance(project);
126       if (toolWindowManager.canShowNotification(toolWindowId)) {
127         //noinspection SSBasedInspection
128         toolWindowManager.notifyByBalloon(toolWindowId, MessageType.ERROR, fullMessage, null, finalListener);
129       }
130       else {
131         Messages.showErrorDialog(project, UIUtil.toHtml(fullMessage), "");
132       }
133       NotificationListener notificationListener = finalListener == null ? null : new NotificationListener() {
134         @Override
135         public void hyperlinkUpdate(@NotNull Notification notification, @NotNull HyperlinkEvent event) {
136           finalListener.hyperlinkUpdate(event);
137         }
138       };
139       ourNotificationGroup.createNotification(title, finalDescription, NotificationType.ERROR, notificationListener).notify(project);
140     });
141   }
142
143   public static void restartIfActive(@NotNull RunContentDescriptor descriptor) {
144     ProcessHandler processHandler = descriptor.getProcessHandler();
145     if (processHandler != null
146         && processHandler.isStartNotified()
147         && !processHandler.isProcessTerminating()
148         && !processHandler.isProcessTerminated()) {
149       restart(descriptor);
150     }
151   }
152
153   public static void restart(@NotNull RunContentDescriptor descriptor) {
154     restart(descriptor.getComponent());
155   }
156
157   public static void restart(@NotNull Content content) {
158     restart(content.getComponent());
159   }
160
161   private static void restart(@Nullable JComponent component) {
162     if (component != null) {
163       ExecutionEnvironment environment = LangDataKeys.EXECUTION_ENVIRONMENT.getData(DataManager.getInstance().getDataContext(component));
164       if (environment != null) {
165         restart(environment);
166       }
167     }
168   }
169
170   public static void restart(@NotNull ExecutionEnvironment environment) {
171     if (!ExecutorRegistry.getInstance().isStarting(environment)) {
172       ExecutionManager.getInstance(environment.getProject()).restartRunProfile(environment);
173     }
174   }
175
176   public static void runConfiguration(@NotNull RunnerAndConfigurationSettings configuration, @NotNull Executor executor) {
177     ExecutionEnvironmentBuilder builder = createEnvironment(executor, configuration);
178     if (builder != null) {
179       ExecutionManager.getInstance(configuration.getConfiguration().getProject()).restartRunProfile(builder
180                                                                                                       .activeTarget()
181                                                                                                       .build());
182     }
183   }
184
185   @Nullable
186   public static ExecutionEnvironmentBuilder createEnvironment(@NotNull Executor executor, @NotNull RunnerAndConfigurationSettings settings) {
187     try {
188       return ExecutionEnvironmentBuilder.create(executor, settings);
189     }
190     catch (ExecutionException e) {
191       handleExecutionError(settings.getConfiguration().getProject(), executor.getToolWindowId(), settings.getConfiguration().getName(), e);
192       return null;
193     }
194   }
195
196   public static Icon getLiveIndicator(@Nullable final Icon base) {
197     return new LayeredIcon(base, new Icon() {
198       @SuppressWarnings("UseJBColor")
199       @Override
200       public void paintIcon(Component c, Graphics g, int x, int y) {
201         int iSize = JBUI.scale(4);
202         Graphics2D g2d = (Graphics2D)g.create();
203         try {
204           GraphicsUtil.setupAAPainting(g2d);
205           g2d.setColor(Color.GREEN);
206           Ellipse2D.Double shape =
207             new Ellipse2D.Double(x + getIconWidth() - iSize, y + getIconHeight() - iSize, iSize, iSize);
208           g2d.fill(shape);
209           g2d.setColor(ColorUtil.withAlpha(Color.BLACK, .40));
210           g2d.draw(shape);
211         }
212         finally {
213           g2d.dispose();
214         }
215       }
216
217       @Override
218       public int getIconWidth() {
219         return base != null ? base.getIconWidth() : 13;
220       }
221
222       @Override
223       public int getIconHeight() {
224         return base != null ? base.getIconHeight() : 13;
225       }
226     });
227   }
228 }