notifications: Only propagate ACTIVATE events to HyperlinkListener
[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.NotificationGroup;
27 import com.intellij.notification.NotificationListener;
28 import com.intellij.notification.NotificationType;
29 import com.intellij.openapi.actionSystem.LangDataKeys;
30 import com.intellij.openapi.application.ApplicationManager;
31 import com.intellij.openapi.diagnostic.Logger;
32 import com.intellij.openapi.project.Project;
33 import com.intellij.openapi.ui.MessageType;
34 import com.intellij.openapi.ui.Messages;
35 import com.intellij.openapi.util.text.StringUtil;
36 import com.intellij.openapi.wm.ToolWindowManager;
37 import com.intellij.ui.ColorUtil;
38 import com.intellij.ui.LayeredIcon;
39 import com.intellij.ui.content.Content;
40 import com.intellij.util.ExceptionUtil;
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) {
114       listener = ExceptionUtil.findCause(e, HyperlinkListener.class);
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 : (notification, event) -> {
133         if (event.getEventType() == HyperlinkEvent.EventType.ACTIVATED) {
134           finalListener.hyperlinkUpdate(event);
135         }
136       };
137       ourNotificationGroup.createNotification(title, finalDescription, NotificationType.ERROR, notificationListener).notify(project);
138     });
139   }
140
141   public static void restartIfActive(@NotNull RunContentDescriptor descriptor) {
142     ProcessHandler processHandler = descriptor.getProcessHandler();
143     if (processHandler != null
144         && processHandler.isStartNotified()
145         && !processHandler.isProcessTerminating()
146         && !processHandler.isProcessTerminated()) {
147       restart(descriptor);
148     }
149   }
150
151   public static void restart(@NotNull RunContentDescriptor descriptor) {
152     restart(descriptor.getComponent());
153   }
154
155   public static void restart(@NotNull Content content) {
156     restart(content.getComponent());
157   }
158
159   private static void restart(@Nullable JComponent component) {
160     if (component != null) {
161       ExecutionEnvironment environment = LangDataKeys.EXECUTION_ENVIRONMENT.getData(DataManager.getInstance().getDataContext(component));
162       if (environment != null) {
163         restart(environment);
164       }
165     }
166   }
167
168   public static void restart(@NotNull ExecutionEnvironment environment) {
169     if (!ExecutorRegistry.getInstance().isStarting(environment)) {
170       ExecutionManager.getInstance(environment.getProject()).restartRunProfile(environment);
171     }
172   }
173
174   public static void runConfiguration(@NotNull RunnerAndConfigurationSettings configuration, @NotNull Executor executor) {
175     ExecutionEnvironmentBuilder builder = createEnvironment(executor, configuration);
176     if (builder != null) {
177       ExecutionManager.getInstance(configuration.getConfiguration().getProject()).restartRunProfile(builder
178                                                                                                       .activeTarget()
179                                                                                                       .build());
180     }
181   }
182
183   @Nullable
184   public static ExecutionEnvironmentBuilder createEnvironment(@NotNull Executor executor, @NotNull RunnerAndConfigurationSettings settings) {
185     try {
186       return ExecutionEnvironmentBuilder.create(executor, settings);
187     }
188     catch (ExecutionException e) {
189       handleExecutionError(settings.getConfiguration().getProject(), executor.getToolWindowId(), settings.getConfiguration().getName(), e);
190       return null;
191     }
192   }
193
194   public static Icon getLiveIndicator(@Nullable final Icon base) {
195     return new LayeredIcon(base, new Icon() {
196       @SuppressWarnings("UseJBColor")
197       @Override
198       public void paintIcon(Component c, Graphics g, int x, int y) {
199         int iSize = JBUI.scale(4);
200         Graphics2D g2d = (Graphics2D)g.create();
201         try {
202           GraphicsUtil.setupAAPainting(g2d);
203           g2d.setColor(Color.GREEN);
204           Ellipse2D.Double shape =
205             new Ellipse2D.Double(x + getIconWidth() - iSize, y + getIconHeight() - iSize, iSize, iSize);
206           g2d.fill(shape);
207           g2d.setColor(ColorUtil.withAlpha(Color.BLACK, .40));
208           g2d.draw(shape);
209         }
210         finally {
211           g2d.dispose();
212         }
213       }
214
215       @Override
216       public int getIconWidth() {
217         return base != null ? base.getIconWidth() : 13;
218       }
219
220       @Override
221       public int getIconHeight() {
222         return base != null ? base.getIconHeight() : 13;
223       }
224     });
225   }
226 }