Skip to content

Commit 2609a37

Browse files
authored
feat: Util for opening a file in the IDE running the application (#15605)
1 parent d12939d commit 2609a37

5 files changed

Lines changed: 910 additions & 2 deletions

File tree

‎flow-server/src/main/java/com/vaadin/flow/component/internal/ComponentTracker.java‎

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -51,7 +51,8 @@ public class ComponentTracker {
5151
/**
5252
* Represents a location in the source code.
5353
*/
54-
public record Location(String className, String filename, int lineNumber) implements Serializable {
54+
public record Location(String className, String filename, String methodName, int lineNumber)
55+
implements Serializable {
5556
}
5657

5758
/**
@@ -197,8 +198,9 @@ private static Location toLocation(StackTraceElement stackTraceElement) {
197198

198199
String className = stackTraceElement.getClassName();
199200
String fileName = stackTraceElement.getFileName();
201+
String methodName = stackTraceElement.getMethodName();
200202
int lineNumber = stackTraceElement.getLineNumber();
201-
return new Location(className, fileName, lineNumber);
203+
return new Location(className, fileName, methodName, lineNumber);
202204
}
203205

204206
}

‎flow-test-generic/src/main/java/com/vaadin/flow/testutil/ClassesSerializableTest.java‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -79,6 +79,8 @@ protected Stream<String> getExcludedPatterns() {
7979
"com\\.vaadin\\.base\\.devserver\\.DevModeHandlerManagerImpl",
8080
"com\\.vaadin\\.base\\.devserver\\.DevServerWatchDog",
8181
"com\\.vaadin\\.base\\.devserver\\.DevServerWatchDog\\$WatchDogServer",
82+
"com\\.vaadin\\.base\\.devserver\\.IdeIntegration",
83+
"com\\.vaadin\\.base\\.devserver\\.OpenInCurrentIde",
8284
"com\\.vaadin\\.base\\.devserver\\.util\\.BrowserLauncher",
8385
"com\\.vaadin\\.base\\.devserver\\.util\\.net\\.PortProber",
8486
"com\\.vaadin\\.base\\.devserver\\.util\\.net\\.FixedIANAPortRange",
Lines changed: 113 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,113 @@
1+
/*
2+
* Copyright 2000-2022 Vaadin Ltd.
3+
*
4+
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
5+
* use this file except in compliance with the License. You may obtain a copy of
6+
* 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, WITHOUT
12+
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13+
* License for the specific language governing permissions and limitations under
14+
* the License.
15+
*/
16+
package com.vaadin.base.devserver;
17+
18+
import java.io.File;
19+
20+
import org.slf4j.Logger;
21+
import org.slf4j.LoggerFactory;
22+
23+
import com.vaadin.flow.component.Component;
24+
import com.vaadin.flow.component.internal.ComponentTracker;
25+
import com.vaadin.flow.component.internal.ComponentTracker.Location;
26+
import com.vaadin.flow.internal.UsageStatistics;
27+
import com.vaadin.flow.server.startup.ApplicationConfiguration;
28+
29+
/**
30+
* Integration with IDEs for development mode.
31+
*/
32+
public final class IdeIntegration {
33+
34+
private ApplicationConfiguration configuration;
35+
36+
/**
37+
* Creates a new integration with the given configuration.
38+
*/
39+
public IdeIntegration(ApplicationConfiguration configuration) {
40+
this.configuration = configuration;
41+
if (configuration.isProductionMode()) {
42+
getLogger().error(getClass().getSimpleName()
43+
+ " should never be created in production mode");
44+
}
45+
46+
}
47+
48+
/**
49+
* Opens, in the current IDE, the location (file + line number) where the
50+
* given component was created.
51+
*
52+
* @param component
53+
* the component to show
54+
*/
55+
public void showComponentCreateInIde(Component component) {
56+
UsageStatistics.markAsUsed("flow/showComponentCreateInIde", null);
57+
internalShowInIde(component, ComponentTracker.findCreate(component));
58+
}
59+
60+
/**
61+
* Opens, in the current IDE, the location (file + line number) where the
62+
* given component was attached.
63+
*
64+
* @param component
65+
* the component to show
66+
*/
67+
public void showComponentAttachInIde(Component component) {
68+
UsageStatistics.markAsUsed("flow/showComponentAttachInIde", null);
69+
internalShowInIde(component, ComponentTracker.findAttach(component));
70+
}
71+
72+
private void internalShowInIde(Component component, Location location) {
73+
if (location == null) {
74+
getLogger().error("Unable to find the location where the component "
75+
+ component.getClass().getName() + " was created");
76+
return;
77+
}
78+
79+
String cls = location.className();
80+
String filename = location.filename();
81+
82+
if (cls.endsWith(filename.replace(".java", ""))) {
83+
File src = configuration.getJavaSourceFolder();
84+
File javaFile = new File(src, cls.replace(".", "/") + ".java");
85+
String absoluteFilename = javaFile.getAbsolutePath();
86+
if (!javaFile.exists()) {
87+
getLogger().error("Unable to find file in " + absoluteFilename);
88+
return;
89+
}
90+
91+
if (!OpenInCurrentIde.openFile(javaFile, location.lineNumber())) {
92+
// Failed to open in IDE so print the file and line info.
93+
// Either an IDE makes it clickable or you can copy the file
94+
// info
95+
System.out.println(toStackTraceElement(location));
96+
}
97+
} else {
98+
System.out.println(toStackTraceElement(location));
99+
}
100+
}
101+
102+
private StackTraceElement toStackTraceElement(Location location) {
103+
return new StackTraceElement("", "", "", location.className(),
104+
location.methodName(), location.filename(),
105+
location.lineNumber());
106+
107+
}
108+
109+
private static Logger getLogger() {
110+
return LoggerFactory.getLogger(IdeIntegration.class);
111+
}
112+
113+
}
Lines changed: 238 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,238 @@
1+
/*
2+
* Copyright 2000-2022 Vaadin Ltd.
3+
*
4+
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
5+
* use this file except in compliance with the License. You may obtain a copy of
6+
* 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, WITHOUT
12+
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13+
* License for the specific language governing permissions and limitations under
14+
* the License.
15+
*/
16+
package com.vaadin.base.devserver;
17+
18+
import java.io.File;
19+
import java.lang.ProcessHandle.Info;
20+
import java.util.ArrayList;
21+
import java.util.Arrays;
22+
import java.util.List;
23+
import java.util.Locale;
24+
import java.util.Optional;
25+
import java.util.function.Consumer;
26+
import java.util.stream.Collectors;
27+
import java.util.stream.Stream;
28+
29+
import org.slf4j.Logger;
30+
import org.slf4j.LoggerFactory;
31+
32+
import com.vaadin.open.OSUtils;
33+
import com.vaadin.open.Open;
34+
35+
/**
36+
* Util for opening a file in the currently used IDE.
37+
* <p>
38+
* Supports detecting VS Code, Eclipse and IntelliJ.
39+
*/
40+
public final class OpenInCurrentIde {
41+
42+
private OpenInCurrentIde() {
43+
// Utils only
44+
}
45+
46+
/**
47+
* Opens the given file at the given line number in the IDE used to launch
48+
* the current Java application.
49+
* <p>
50+
* If you are running the Java application from the command line or from an
51+
* unsupported IDE, then this method does nothing.
52+
*
53+
* @param file
54+
* the file to open
55+
* @param lineNumber
56+
* the line number to highlight
57+
* @return true if the file was opened, false otherwise
58+
*/
59+
public static boolean openFile(File file, int lineNumber) {
60+
String absolutePath = file.getAbsolutePath();
61+
62+
Optional<Info> maybeIdeCommand = findIdeCommandInfo();
63+
if (!maybeIdeCommand.isPresent()) {
64+
getLogger().debug("Unable to detect IDE from process tree");
65+
printProcessTree(msg -> getLogger().debug(msg));
66+
return false;
67+
}
68+
69+
Info processInfo = maybeIdeCommand.get();
70+
71+
if (isVSCode(processInfo)) {
72+
return Open.open("vscode://file" + absolutePath + ":" + lineNumber);
73+
} else if (isIdea(processInfo)) {
74+
if (OSUtils.isMac()) {
75+
// On Mac, the idea:// protocol works...
76+
return Open.open("idea://open?file=" + absolutePath + "&line="
77+
+ lineNumber);
78+
} else {
79+
try {
80+
run(getBinary(processInfo), "--line", lineNumber + "",
81+
absolutePath);
82+
} catch (Exception e) {
83+
getLogger().error("Unable to launch IntelliJ IDEA", e);
84+
}
85+
}
86+
} else if (isEclipse(processInfo)) {
87+
if (OSUtils.isMac()) {
88+
try {
89+
run("open", "-a", getBinary(processInfo), absolutePath);
90+
} catch (Exception e) {
91+
getLogger().error("Unable to launch Eclipse", e);
92+
}
93+
} else {
94+
try {
95+
run(getBinary(processInfo),
96+
absolutePath + ":" + lineNumber);
97+
} catch (Exception e) {
98+
getLogger().error("Unable to launch Eclipse", e);
99+
}
100+
}
101+
return true;
102+
}
103+
104+
return false;
105+
106+
}
107+
108+
static String getBinary(Info info) {
109+
String cmd = info.command().get();
110+
if (isIdea(info)) {
111+
return getIdeaBinary(info);
112+
} else if (isEclipse(info)) {
113+
return cmd.replaceFirst("/Contents/MacOS/eclipse$", "");
114+
}
115+
return cmd;
116+
}
117+
118+
private static Logger getLogger() {
119+
return LoggerFactory.getLogger(OpenInCurrentIde.class);
120+
}
121+
122+
public static void main(String[] args) {
123+
// This is so it will be easier to debug problems in the future
124+
printProcessTree(System.out::println);
125+
}
126+
127+
private static void printProcessTree(Consumer<String> printer) {
128+
for (Info info : getProcessTree()) {
129+
printer.accept("Process tree:");
130+
info.command()
131+
.ifPresent(value -> printer.accept("Command: " + value));
132+
info.commandLine().ifPresent(
133+
value -> printer.accept("Command line: " + value));
134+
info.arguments().ifPresent(values -> {
135+
for (int i = 0; i < values.length; i++) {
136+
printer.accept("Arguments[" + i + "]: " + values[i]);
137+
}
138+
});
139+
printer.accept("");
140+
}
141+
142+
}
143+
144+
private static void run(String command, String... arguments)
145+
throws Exception {
146+
List<String> cmd = new ArrayList<>();
147+
cmd.add(command);
148+
cmd.addAll(Arrays.asList(arguments));
149+
ProcessBuilder pb = new ProcessBuilder().command(cmd);
150+
pb.start().waitFor();
151+
}
152+
153+
private static List<Info> getProcessTree() {
154+
return getParentProcesses().stream().map(p -> p.info())
155+
.collect(Collectors.toList());
156+
}
157+
158+
private static Optional<Info> findIdeCommandInfo() {
159+
return findIdeCommand(getProcessTree());
160+
}
161+
162+
static Optional<Info> findIdeCommand(List<Info> processes) {
163+
for (Info info : processes) {
164+
if (isIdea(info) || isVSCode(info) || isEclipse(info)) {
165+
return Optional.of(info);
166+
}
167+
}
168+
return Optional.empty();
169+
}
170+
171+
private static String getCommandAndArguments(Info info) {
172+
return info.commandLine().get();
173+
}
174+
175+
private static List<ProcessHandle> getParentProcesses() {
176+
List<ProcessHandle> proceses = new ArrayList<>();
177+
ProcessHandle p = ProcessHandle.current();
178+
while (p != null) {
179+
proceses.add(p);
180+
p = p.parent().orElse(null);
181+
}
182+
return proceses;
183+
}
184+
185+
static boolean isEclipse(Info info) {
186+
String lowerCase = info.command().get().toLowerCase(Locale.ENGLISH);
187+
// Eclipse has a lot of other products like Temurin and Adoptium so we
188+
// cannot
189+
// check with "contains"
190+
return lowerCase.endsWith("eclipse")
191+
|| lowerCase.endsWith("eclipse.exe");
192+
193+
}
194+
195+
static boolean isIdea(Info info) {
196+
return getIdeaBinary(info) != null;
197+
}
198+
199+
private static String getIdeaBinary(Info info) {
200+
String commandAndArguments = getCommandAndArguments(info);
201+
if (commandAndArguments.contains("idea_rt.jar")) {
202+
String replaced = commandAndArguments
203+
.replaceFirst(".*[:;]([^:;]*)(idea_rt.jar).*", "$1$2");
204+
if (!replaced.equals(commandAndArguments)) {
205+
File binFolder = new File(
206+
new File(replaced).getParentFile().getParentFile(),
207+
"bin");
208+
Optional<File> bin = Stream.of("idea", "idea.sh", "idea.bat")
209+
.map(binName -> new File(binFolder, binName))
210+
.filter(binaryFile -> binaryFile.exists()).findFirst();
211+
if (bin.isPresent()) {
212+
return bin.get().getAbsolutePath();
213+
}
214+
}
215+
}
216+
if (info.command().get().contains("idea")) {
217+
return info.command().get();
218+
}
219+
return null;
220+
}
221+
222+
static boolean isVSCode(Info info) {
223+
String termProgram = System.getenv("TERM_PROGRAM");
224+
if ("vscode".equalsIgnoreCase(termProgram)) {
225+
return true;
226+
}
227+
228+
String cmd = getCommandAndArguments(info).toLowerCase(Locale.ENGLISH);
229+
if (cmd.contains("vscode") || cmd.contains("vs code")
230+
|| cmd.contains("code helper")
231+
|| cmd.contains("visual studio code")) {
232+
return true;
233+
}
234+
235+
return false;
236+
}
237+
238+
}

0 commit comments

Comments
 (0)