6bb69cfac545766716805cd175364eb5af933ed6
[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.ui.GraphicsUtil;
42 import com.intellij.util.ui.JBUI;
43 import com.intellij.util.ui.UIUtil;
44 import org.jetbrains.annotations.NotNull;
45 import org.jetbrains.annotations.Nullable;
46
47 import javax.swing.*;
48 import javax.swing.event.HyperlinkEvent;
49 import javax.swing.event.HyperlinkListener;
50 import java.awt.*;
51 import java.awt.geom.Ellipse2D;
52
53 public class ExecutionUtil {
54   private static final Logger LOG = Logger.getInstance("com.intellij.execution.runners.ExecutionUtil");
55
56   private static final NotificationGroup ourNotificationGroup = NotificationGroup.logOnlyGroup("Execution");
57
58   private ExecutionUtil() {
59   }
60
61   public static void handleExecutionError(@NotNull Project project,
62                                           @NotNull String toolWindowId,
63                                           @NotNull RunProfile runProfile,
64                                           @NotNull ExecutionException e) {
65     handleExecutionError(project, toolWindowId, runProfile.getName(), e);
66   }
67
68   public static void handleExecutionError(@NotNull ExecutionEnvironment environment, @NotNull ExecutionException e) {
69     handleExecutionError(environment.getProject(), environment.getExecutor().getToolWindowId(), environment.getRunProfile().getName(), e);
70   }
71
72   public static void handleExecutionError(@NotNull final Project project,
73                                           @NotNull final String toolWindowId,
74                                           @NotNull String taskName,
75                                           @NotNull ExecutionException e) {
76     if (e instanceof RunCanceledByUserException) {
77       return;
78     }
79
80     LOG.debug(e);
81
82     String description = e.getMessage();
83     if (StringUtil.isEmptyOrSpaces(description)) {
84       LOG.warn("Execution error without description", e);
85       description = "Unknown error";
86     }
87
88     HyperlinkListener listener = null;
89     if ((description.contains("87") || description.contains("111") || description.contains("206")) &&
90         e instanceof ProcessNotCreatedException &&
91         !PropertiesComponent.getInstance(project).isTrueValue("dynamic.classpath")) {
92       final String commandLineString = ((ProcessNotCreatedException)e).getCommandLine().getCommandLineString();
93       if (commandLineString.length() > 1024 * 32) {
94         description = "Command line is too long. In order to reduce its length classpath file can be used.<br>" +
95                       "Would you like to enable classpath file mode for all run configurations of your project?<br>" +
96                       "<a href=\"\">Enable</a>";
97
98         listener = new HyperlinkListener() {
99           @Override
100           public void hyperlinkUpdate(HyperlinkEvent event) {
101             PropertiesComponent.getInstance(project).setValue("dynamic.classpath", "true");
102           }
103         };
104       }
105     }
106     final String title = ExecutionBundle.message("error.running.configuration.message", taskName);
107     final String fullMessage = title + ":<br>" + description;
108
109     if (ApplicationManager.getApplication().isUnitTestMode()) {
110       LOG.error(fullMessage, e);
111     }
112
113     if (listener == null && e instanceof HyperlinkListener) {
114       listener = (HyperlinkListener)e;
115     }
116
117     final HyperlinkListener finalListener = listener;
118     final String finalDescription = description;
119     UIUtil.invokeLaterIfNeeded(() -> {
120       if (project.isDisposed()) {
121         return;
122       }
123
124       ToolWindowManager toolWindowManager = ToolWindowManager.getInstance(project);
125       if (toolWindowManager.canShowNotification(toolWindowId)) {
126         //noinspection SSBasedInspection
127         toolWindowManager.notifyByBalloon(toolWindowId, MessageType.ERROR, fullMessage, null, finalListener);
128       }
129       else {
130         Messages.showErrorDialog(project, UIUtil.toHtml(fullMessage), "");
131       }
132       NotificationListener notificationListener = finalListener == null ? null : new NotificationListener() {
133         @Override
134         public void hyperlinkUpdate(@NotNull Notification notification, @NotNull HyperlinkEvent event) {
135           finalListener.hyperlinkUpdate(event);
136         }
137       };
138       ourNotificationGroup.createNotification(title, finalDescription, NotificationType.ERROR, notificationListener).notify(project);
139     });
140   }
141
142   public static void restartIfActive(@NotNull RunContentDescriptor descriptor) {
143     ProcessHandler processHandler = descriptor.getProcessHandler();
144     if (processHandler != null
145         && processHandler.isStartNotified()
146         && !processHandler.isProcessTerminating()
147         && !processHandler.isProcessTerminated()) {
148       restart(descriptor);
149     }
150   }
151
152   public static void restart(@NotNull RunContentDescriptor descriptor) {
153     restart(descriptor.getComponent());
154   }
155
156   public static void restart(@NotNull Content content) {
157     restart(content.getComponent());
158   }
159
160   private static void restart(@Nullable JComponent component) {
161     if (component != null) {
162       ExecutionEnvironment environment = LangDataKeys.EXECUTION_ENVIRONMENT.getData(DataManager.getInstance().getDataContext(component));
163       if (environment != null) {
164         restart(environment);
165       }
166     }
167   }
168
169   public static void restart(@NotNull ExecutionEnvironment environment) {
170     if (!ExecutorRegistry.getInstance().isStarting(environment)) {
171       ExecutionManager.getInstance(environment.getProject()).restartRunProfile(environment);
172     }
173   }
174
175   public static void runConfiguration(@NotNull RunnerAndConfigurationSettings configuration, @NotNull Executor executor) {
176     ExecutionEnvironmentBuilder builder = createEnvironment(executor, configuration);
177     if (builder != null) {
178       ExecutionManager.getInstance(configuration.getConfiguration().getProject()).restartRunProfile(builder
179                                                                                                       .activeTarget()
180                                                                                                       .build());
181     }
182   }
183
184   @Nullable
185   public static ExecutionEnvironmentBuilder createEnvironment(@NotNull Executor executor, @NotNull RunnerAndConfigurationSettings settings) {
186     try {
187       return ExecutionEnvironmentBuilder.create(executor, settings);
188     }
189     catch (ExecutionException e) {
190       handleExecutionError(settings.getConfiguration().getProject(), executor.getToolWindowId(), settings.getConfiguration().getName(), e);
191       return null;
192     }
193   }
194
195   public static Icon getLiveIndicator(@Nullable final Icon base) {
196     return new LayeredIcon(base, new Icon() {
197       @SuppressWarnings("UseJBColor")
198       @Override
199       public void paintIcon(Component c, Graphics g, int x, int y) {
200         int iSize = JBUI.scale(4);
201         Graphics2D g2d = (Graphics2D)g.create();
202         try {
203           GraphicsUtil.setupAAPainting(g2d);
204           g2d.setColor(Color.GREEN);
205           Ellipse2D.Double shape =
206             new Ellipse2D.Double(x + getIconWidth() - iSize, y + getIconHeight() - iSize, iSize, iSize);
207           g2d.fill(shape);
208           g2d.setColor(ColorUtil.withAlpha(Color.BLACK, .40));
209           g2d.draw(shape);
210         }
211         finally {
212           g2d.dispose();
213         }
214       }
215
216       @Override
217       public int getIconWidth() {
218         return base != null ? base.getIconWidth() : 13;
219       }
220
221       @Override
222       public int getIconHeight() {
223         return base != null ? base.getIconHeight() : 13;
224       }
225     });
226   }
227 }