diff --git a/java-compiler-impl/src/main/java/com/intellij/java/compiler/impl/javaCompiler/JavaCompilerConfiguration.java b/java-compiler-impl/src/main/java/com/intellij/java/compiler/impl/javaCompiler/JavaCompilerConfiguration.java index bcef528162..351b91b957 100644 --- a/java-compiler-impl/src/main/java/com/intellij/java/compiler/impl/javaCompiler/JavaCompilerConfiguration.java +++ b/java-compiler-impl/src/main/java/com/intellij/java/compiler/impl/javaCompiler/JavaCompilerConfiguration.java @@ -17,6 +17,7 @@ import consulo.module.Module; import consulo.module.ModuleManager; import consulo.project.Project; +import consulo.util.lang.Couple; import consulo.util.lang.Pair; import consulo.util.lang.StringUtil; import jakarta.inject.Inject; @@ -61,7 +62,7 @@ public static JavaCompilerConfiguration getInstance(@Nonnull Project project) { private BackendCompiler myBackendCompilerCache; private final ProcessorConfigProfile myDefaultProcessorsProfile = new ProcessorConfigProfileImpl("Default"); - private final List myModuleProcessorProfiles = new ArrayList(); + private final List myModuleProcessorProfiles = new ArrayList<>(); // the map is calculated by module processor profiles list for faster access to module settings private Map myProcessorsProfilesMap = null; @@ -72,7 +73,7 @@ public static JavaCompilerConfiguration getInstance(@Nonnull Project project) { @Deprecated @DeprecationInfo("We used JavaModuleExtension for store info about bytecode version") - private final Map myModuleBytecodeTarget = new HashMap(); + private final Map myModuleBytecodeTarget = new HashMap<>(); @Inject public JavaCompilerConfiguration(@Nonnull Project project) { @@ -124,11 +125,11 @@ public BackendCompiler findCompiler(@Nonnull String className) { public Element getState() { Element parentNode = new Element("state"); - final Element annotationProcessingSettings = addChild(parentNode, ANNOTATION_PROCESSING); - final Element defaultProfileElem = addChild(annotationProcessingSettings, "profile").setAttribute("default", "true"); + Element annotationProcessingSettings = addChild(parentNode, ANNOTATION_PROCESSING); + Element defaultProfileElem = addChild(annotationProcessingSettings, "profile").setAttribute("default", "true"); AnnotationProcessorProfileSerializer.writeExternal(myDefaultProcessorsProfile, defaultProfileElem); for (ProcessorConfigProfile profile : myModuleProcessorProfiles) { - final Element profileElem = addChild(annotationProcessingSettings, "profile").setAttribute("default", "false"); + Element profileElem = addChild(annotationProcessingSettings, "profile").setAttribute("default", "false"); AnnotationProcessorProfileSerializer.writeExternal(profile, profileElem); } @@ -141,17 +142,17 @@ public Element getState() { } if (!StringUtil.isEmpty(myBytecodeTargetLevel) || !myModuleBytecodeTarget.isEmpty()) { - final Element bytecodeTarget = addChild(parentNode, BYTECODE_TARGET_LEVEL); + Element bytecodeTarget = addChild(parentNode, BYTECODE_TARGET_LEVEL); if (!StringUtil.isEmpty(myBytecodeTargetLevel)) { bytecodeTarget.setAttribute(TARGET_ATTRIBUTE, myBytecodeTargetLevel); } if (!myModuleBytecodeTarget.isEmpty()) { - final List moduleNames = new ArrayList(myModuleBytecodeTarget.keySet()); + List moduleNames = new ArrayList<>(myModuleBytecodeTarget.keySet()); Collections.sort(moduleNames, String.CASE_INSENSITIVE_ORDER); for (String name : moduleNames) { - final Element moduleElement = addChild(bytecodeTarget, MODULE); + Element moduleElement = addChild(bytecodeTarget, MODULE); moduleElement.setAttribute(NAME, name); - final String value = myModuleBytecodeTarget.get(name); + String value = myModuleBytecodeTarget.get(name); moduleElement.setAttribute(TARGET_ATTRIBUTE, value != null ? value : ""); } } @@ -159,8 +160,8 @@ public Element getState() { return parentNode; } - private static Element addChild(Element parent, final String childName) { - final Element child = new Element(childName); + private static Element addChild(Element parent, String childName) { + Element child = new Element(childName); parent.addContent(child); return child; } @@ -170,18 +171,18 @@ public void loadState(Element parentNode) { myBackendCompilerCache = findCompiler(parentNode.getAttributeValue("compiler")); myAddNotNullAssertions = Boolean.parseBoolean(parentNode.getAttributeValue(ADD_NOTNULL_ASSERTIONS, String.valueOf(Boolean.FALSE))); - final Element annotationProcessingSettings = parentNode.getChild(ANNOTATION_PROCESSING); + Element annotationProcessingSettings = parentNode.getChild(ANNOTATION_PROCESSING); if (annotationProcessingSettings != null) { - final List profiles = annotationProcessingSettings.getChildren("profile"); + List profiles = annotationProcessingSettings.getChildren("profile"); if (!profiles.isEmpty()) { for (Object elem : profiles) { - final Element profileElement = (Element)elem; - final boolean isDefault = "true".equals(profileElement.getAttributeValue("default")); + Element profileElement = (Element)elem; + boolean isDefault = "true".equals(profileElement.getAttributeValue("default")); if (isDefault) { AnnotationProcessorProfileSerializer.readExternal(myDefaultProcessorsProfile, profileElement); } else { - final ProcessorConfigProfile profile = new ProcessorConfigProfileImpl(""); + ProcessorConfigProfile profile = new ProcessorConfigProfileImpl(""); AnnotationProcessorProfileSerializer.readExternal(profile, profileElement); myModuleProcessorProfiles.add(profile); } @@ -215,16 +216,16 @@ public void loadState(Element parentNode) { private void loadProfilesFromOldFormat(Element processing) { // collect data - final boolean isEnabled = Boolean.parseBoolean(processing.getAttributeValue(ENABLED, "false")); - final boolean isUseClasspath = Boolean.parseBoolean(processing.getAttributeValue("useClasspath", "true")); - final StringBuilder processorPath = new StringBuilder(); - final Set optionPairs = new HashSet(); - final Set processors = new HashSet(); - final List> modulesToProcess = new ArrayList>(); + boolean isEnabled = Boolean.parseBoolean(processing.getAttributeValue(ENABLED, "false")); + boolean isUseClasspath = Boolean.parseBoolean(processing.getAttributeValue("useClasspath", "true")); + StringBuilder processorPath = new StringBuilder(); + Set optionPairs = new HashSet<>(); + Set processors = new HashSet<>(); + List> modulesToProcess = new ArrayList<>(); for (Object child : processing.getChildren("processorPath")) { - final Element pathElement = (Element)child; - final String path = pathElement.getAttributeValue("value", (String)null); + Element pathElement = (Element)child; + String path = pathElement.getAttributeValue("value", (String)null); if (path != null) { if (processorPath.length() > 0) { processorPath.append(File.pathSeparator); @@ -234,26 +235,26 @@ private void loadProfilesFromOldFormat(Element processing) { } for (Object child : processing.getChildren("processor")) { - final Element processorElement = (Element)child; - final String proc = processorElement.getAttributeValue(NAME, (String)null); + Element processorElement = (Element)child; + String proc = processorElement.getAttributeValue(NAME, (String)null); if (proc != null) { processors.add(proc); } - final StringTokenizer tokenizer = new StringTokenizer(processorElement.getAttributeValue("options", ""), " ", false); + StringTokenizer tokenizer = new StringTokenizer(processorElement.getAttributeValue("options", ""), " ", false); while (tokenizer.hasMoreTokens()) { - final String pair = tokenizer.nextToken(); + String pair = tokenizer.nextToken(); optionPairs.add(pair); } } for (Object child : processing.getChildren("processModule")) { - final Element moduleElement = (Element)child; - final String name = moduleElement.getAttributeValue(NAME, (String)null); + Element moduleElement = (Element)child; + String name = moduleElement.getAttributeValue(NAME, (String)null); if (name == null) { continue; } - final String dir = moduleElement.getAttributeValue("generatedDirName", (String)null); - modulesToProcess.add(Pair.create(name, dir)); + String dir = moduleElement.getAttributeValue("generatedDirName", (String)null); + modulesToProcess.add(Couple.of(name, dir)); } myDefaultProcessorsProfile.setEnabled(false); @@ -263,7 +264,7 @@ private void loadProfilesFromOldFormat(Element processing) { } if (!optionPairs.isEmpty()) { for (String pair : optionPairs) { - final int index = pair.indexOf("="); + int index = pair.indexOf("="); if (index > 0) { myDefaultProcessorsProfile.setOption(pair.substring(0, index), pair.substring(index + 1)); } @@ -273,12 +274,12 @@ private void loadProfilesFromOldFormat(Element processing) { myDefaultProcessorsProfile.addProcessor(processor); } - final Map> dirNameToModulesMap = new HashMap>(); + Map> dirNameToModulesMap = new HashMap<>(); for (Pair moduleDirPair : modulesToProcess) { - final String dir = moduleDirPair.getSecond(); + String dir = moduleDirPair.getSecond(); Set set = dirNameToModulesMap.get(dir); if (set == null) { - set = new HashSet(); + set = new HashSet<>(); dirNameToModulesMap.put(dir, set); } set.add(moduleDirPair.getFirst()); @@ -286,8 +287,8 @@ private void loadProfilesFromOldFormat(Element processing) { int profileIndex = 0; for (Map.Entry> entry : dirNameToModulesMap.entrySet()) { - final String dirName = entry.getKey(); - final ProcessorConfigProfile profile = new ProcessorConfigProfileImpl(myDefaultProcessorsProfile); + String dirName = entry.getKey(); + ProcessorConfigProfile profile = new ProcessorConfigProfileImpl(myDefaultProcessorsProfile); profile.setName("Profile" + (++profileIndex)); profile.setEnabled(isEnabled); profile.setGeneratedSourcesDirectoryName(dirName, false); @@ -299,18 +300,19 @@ private void loadProfilesFromOldFormat(Element processing) { } @Nonnull + @RequiredReadAction public ProcessorConfigProfile getAnnotationProcessingConfiguration(Module module) { Map map = myProcessorsProfilesMap; if (map == null) { - map = new HashMap(); - final Map namesMap = new HashMap(); + map = new HashMap<>(); + Map namesMap = new HashMap<>(); for (Module m : ModuleManager.getInstance(module.getProject()).getModules()) { namesMap.put(m.getName(), m); } if (!namesMap.isEmpty()) { for (ProcessorConfigProfile profile : myModuleProcessorProfiles) { for (String name : profile.getModuleNames()) { - final Module mod = namesMap.get(name); + Module mod = namesMap.get(name); if (mod != null) { map.put(mod, profile); } @@ -319,7 +321,7 @@ public ProcessorConfigProfile getAnnotationProcessingConfiguration(Module module } myProcessorsProfilesMap = map; } - final ProcessorConfigProfile profile = map.get(module); + ProcessorConfigProfile profile = map.get(module); return profile != null ? profile : myDefaultProcessorsProfile; } diff --git a/java-coverage-impl/src/main/java/com/intellij/java/coverage/JavaCoverageEngine.java b/java-coverage-impl/src/main/java/com/intellij/java/coverage/JavaCoverageEngine.java index b143a90c10..eafd06172a 100644 --- a/java-coverage-impl/src/main/java/com/intellij/java/coverage/JavaCoverageEngine.java +++ b/java-coverage-impl/src/main/java/com/intellij/java/coverage/JavaCoverageEngine.java @@ -14,11 +14,9 @@ import consulo.annotation.access.RequiredReadAction; import consulo.annotation.component.ExtensionImpl; import consulo.application.Application; -import consulo.application.util.function.Computable; import consulo.codeEditor.Editor; import consulo.compiler.CompilerManager; import consulo.compiler.ModuleCompilerPathsManager; -import consulo.component.extension.Extensions; import consulo.content.ContentFolderTypeProvider; import consulo.execution.configuration.RunConfigurationBase; import consulo.execution.coverage.*; @@ -51,6 +49,7 @@ import java.io.IOException; import java.nio.file.Files; import java.util.*; +import java.util.function.Supplier; /** * @author Roman.Chernyatchik @@ -60,7 +59,7 @@ public class JavaCoverageEngine extends CoverageEngine { private static final Logger LOG = Logger.getInstance(JavaCoverageEngine.class); @Override - public boolean isApplicableTo(@Nullable final RunConfigurationBase conf) { + public boolean isApplicableTo(@Nullable RunConfigurationBase conf) { if (conf instanceof CommonJavaRunConfigurationParameters) { return true; } @@ -79,16 +78,16 @@ public boolean canHavePerTestCoverage(@Nullable RunConfigurationBase conf) { @Nonnull @Override - public CoverageEnabledConfiguration createCoverageEnabledConfiguration(@Nullable final RunConfigurationBase conf) { + public CoverageEnabledConfiguration createCoverageEnabledConfiguration(@Nullable RunConfigurationBase conf) { return new JavaCoverageEnabledConfiguration(conf, this); } @Nullable @Override public CoverageSuite createCoverageSuite( - @Nonnull final CoverageRunner covRunner, - @Nonnull final String name, - @Nonnull final CoverageFileProvider coverageDataFileProvider, + @Nonnull CoverageRunner covRunner, + @Nonnull String name, + @Nonnull CoverageFileProvider coverageDataFileProvider, String[] filters, long lastCoverageTimeStamp, String suiteToMerge, @@ -111,10 +110,10 @@ public CoverageSuite createCoverageSuite( @Override public CoverageSuite createCoverageSuite( - @Nonnull final CoverageRunner covRunner, - @Nonnull final String name, - @Nonnull final CoverageFileProvider coverageDataFileProvider, - @Nonnull final CoverageEnabledConfiguration config + @Nonnull CoverageRunner covRunner, + @Nonnull String name, + @Nonnull CoverageFileProvider coverageDataFileProvider, + @Nonnull CoverageEnabledConfiguration config ) { if (config instanceof JavaCoverageEnabledConfiguration javaConfig) { return createSuite( @@ -150,42 +149,39 @@ public CoverageAnnotator getCoverageAnnotator(Project project) { * @param psiFile * @return */ - public boolean coverageEditorHighlightingApplicableTo(@Nonnull final PsiFile psiFile) { + @Override + public boolean coverageEditorHighlightingApplicableTo(@Nonnull PsiFile psiFile) { if (!(psiFile instanceof PsiClassOwner)) { return false; } // let's show coverage only for module files - final Module module = psiFile.getApplication().runReadAction(new Computable() { - @Nullable - public Module compute() { - return ModuleUtilCore.findModuleForPsiElement(psiFile); - } - }); + Module module = psiFile.getApplication().runReadAction((Supplier)() -> ModuleUtilCore.findModuleForPsiElement(psiFile)); return module != null; } - public boolean acceptedByFilters(@Nonnull final PsiFile psiFile, @Nonnull final CoverageSuitesBundle suite) { - final VirtualFile virtualFile = psiFile.getVirtualFile(); + @Override + public boolean acceptedByFilters(@Nonnull PsiFile psiFile, @Nonnull CoverageSuitesBundle suite) { + VirtualFile virtualFile = psiFile.getVirtualFile(); if (virtualFile == null) { return false; } - final Project project = psiFile.getProject(); - final ProjectFileIndex fileIndex = ProjectRootManager.getInstance(project).getFileIndex(); + Project project = psiFile.getProject(); + ProjectFileIndex fileIndex = ProjectRootManager.getInstance(project).getFileIndex(); if (!suite.isTrackTestFolders() && fileIndex.isInTestSourceContent(virtualFile)) { return false; } for (CoverageSuite coverageSuite : suite.getSuites()) { - final JavaCoverageSuite javaSuite = (JavaCoverageSuite)coverageSuite; + JavaCoverageSuite javaSuite = (JavaCoverageSuite)coverageSuite; - final List packages = javaSuite.getCurrentSuitePackages(project); + List packages = javaSuite.getCurrentSuitePackages(project); if (isUnderFilteredPackages((PsiClassOwner)psiFile, packages)) { return true; } else { - final List classes = javaSuite.getCurrentSuiteClasses(project); + List classes = javaSuite.getCurrentSuiteClasses(project); for (PsiClass aClass : classes) { - final PsiFile containingFile = aClass.getContainingFile(); + PsiFile containingFile = aClass.getContainingFile(); if (psiFile.equals(containingFile)) { return true; } @@ -197,31 +193,31 @@ public boolean acceptedByFilters(@Nonnull final PsiFile psiFile, @Nonnull final @Override public boolean recompileProjectAndRerunAction( - @Nonnull final Module module, @Nonnull final CoverageSuitesBundle suite, - @Nonnull final Runnable chooseSuiteAction + @Nonnull Module module, + @Nonnull CoverageSuitesBundle suite, + @Nonnull Runnable chooseSuiteAction ) { - final VirtualFile outputpath = - ModuleCompilerPathsManager.getInstance(module).getCompilerOutput(ProductionContentFolderTypeProvider.getInstance - ()); - final VirtualFile testOutputpath = + VirtualFile outputpath = + ModuleCompilerPathsManager.getInstance(module).getCompilerOutput(ProductionContentFolderTypeProvider.getInstance()); + VirtualFile testOutputpath = ModuleCompilerPathsManager.getInstance(module).getCompilerOutput(TestContentFolderTypeProvider.getInstance()); if ((outputpath == null && isModuleOutputNeeded(module, ProductionContentFolderTypeProvider.getInstance())) || (suite.isTrackTestFolders() && testOutputpath == null && isModuleOutputNeeded(module, TestContentFolderTypeProvider.getInstance()))) { - final Project project = module.getProject(); + Project project = module.getProject(); if (suite.isModuleChecked(module)) { return false; } suite.checkModule(module); - final Runnable runnable = () -> { + Runnable runnable = () -> { if (Messages.showOkCancelDialog( "Project class files are out of date. Would you like to recompile?" + " The refusal to do it will result in incomplete coverage information", "Project is out of date", UIUtil.getWarningIcon() ) == Messages.OK) { - final CompilerManager compilerManager = CompilerManager.getInstance(project); + CompilerManager compilerManager = CompilerManager.getInstance(project); compilerManager.make( compilerManager.createProjectCompileScope(), (aborted, errors, warnings, compileContext) -> { @@ -247,12 +243,12 @@ else if (!project.isDisposed()) { return false; } - private static boolean isModuleOutputNeeded(Module module, final ContentFolderTypeProvider rootType) { + private static boolean isModuleOutputNeeded(Module module, ContentFolderTypeProvider rootType) { return ModuleRootManager.getInstance(module).getContentFolderFiles(it -> it.equals(rootType)).length != 0; } - public static boolean isUnderFilteredPackages(final PsiClassOwner javaFile, final List packages) { - final String hisPackageName = Application.get().runReadAction((Computable)javaFile::getPackageName); + public static boolean isUnderFilteredPackages(PsiClassOwner javaFile, List packages) { + String hisPackageName = javaFile.getApplication().runReadAction((Supplier)javaFile::getPackageName); PsiPackage hisPackage = JavaPsiFacade.getInstance(javaFile.getProject()).findPackage(hisPackageName); if (hisPackage == null) { return false; @@ -266,10 +262,11 @@ public static boolean isUnderFilteredPackages(final PsiClassOwner javaFile, fina } @Nullable - public List collectSrcLinesForUntouchedFile(@Nonnull final File classFile, @Nonnull final CoverageSuitesBundle suite) { - final List uncoveredLines = new ArrayList<>(); + @Override + public List collectSrcLinesForUntouchedFile(@Nonnull File classFile, @Nonnull CoverageSuitesBundle suite) { + List uncoveredLines = new ArrayList<>(); - final byte[] content; + byte[] content; try { content = Files.readAllBytes(classFile.toPath()); } @@ -286,13 +283,15 @@ public List collectSrcLinesForUntouchedFile(@Nonnull final File classFi return uncoveredLines; } + @Override public boolean includeUntouchedFileInCoverage( - @Nonnull final String qualifiedName, - @Nonnull final File outputFile, - @Nonnull final PsiFile sourceFile, @Nonnull CoverageSuitesBundle suite + @Nonnull String qualifiedName, + @Nonnull File outputFile, + @Nonnull PsiFile sourceFile, + @Nonnull CoverageSuitesBundle suite ) { for (CoverageSuite coverageSuite : suite.getSuites()) { - final JavaCoverageSuite javaSuite = (JavaCoverageSuite)coverageSuite; + JavaCoverageSuite javaSuite = (JavaCoverageSuite)coverageSuite; if (javaSuite.isClassFiltered(qualifiedName) || javaSuite.isPackageFiltered(getPackageName(sourceFile))) { return true; } @@ -301,29 +300,25 @@ public boolean includeUntouchedFileInCoverage( } - public String getQualifiedName(@Nonnull final File outputFile, @Nonnull final PsiFile sourceFile) { - final String packageFQName = getPackageName(sourceFile); + @Override + public String getQualifiedName(@Nonnull File outputFile, @Nonnull PsiFile sourceFile) { + String packageFQName = getPackageName(sourceFile); return StringUtil.getQualifiedName(packageFQName, FileUtil.getNameWithoutExtension(outputFile)); } @Nonnull @Override - public Set getQualifiedNames(@Nonnull final PsiFile sourceFile) { + public Set getQualifiedNames(@Nonnull PsiFile sourceFile) { Application application = sourceFile.getApplication(); - final PsiClass[] classes = application.runReadAction((Computable)((PsiClassOwner)sourceFile)::getClasses); - final Set qNames = new HashSet<>(); - for (final JavaCoverageEngineExtension nameExtension : Extensions.getExtensions(JavaCoverageEngineExtension.EP_NAME)) { - if (application.runReadAction((Computable)() -> nameExtension.suggestQualifiedName(sourceFile, classes, qNames))) { + PsiClass[] classes = application.runReadAction((Supplier)((PsiClassOwner)sourceFile)::getClasses); + Set qNames = new HashSet<>(); + for (JavaCoverageEngineExtension nameExtension : JavaCoverageEngineExtension.EP_NAME.getExtensions()) { + if (application.runReadAction((Supplier)() -> nameExtension.suggestQualifiedName(sourceFile, classes, qNames))) { return qNames; } } - for (final PsiClass aClass : classes) { - final String qName = application.runReadAction(new Computable() { - @Nullable - public String compute() { - return aClass.getQualifiedName(); - } - }); + for (PsiClass aClass : classes) { + String qName = application.runReadAction((Supplier)aClass::getQualifiedName); if (qName == null) { continue; } @@ -333,54 +328,57 @@ public String compute() { } @Nonnull + @Override public Set getCorrespondingOutputFiles( - @Nonnull final PsiFile srcFile, - @Nullable final Module module, - @Nonnull final CoverageSuitesBundle suite + @Nonnull PsiFile srcFile, + @Nullable Module module, + @Nonnull CoverageSuitesBundle suite ) { if (module == null) { return Collections.emptySet(); } - final Set classFiles = new HashSet<>(); - final ModuleCompilerPathsManager pathsManager = ModuleCompilerPathsManager.getInstance(module); - final VirtualFile outputpath = pathsManager.getCompilerOutput(ProductionContentFolderTypeProvider.getInstance()); - final VirtualFile testOutputpath = pathsManager.getCompilerOutput(TestContentFolderTypeProvider.getInstance()); + Set classFiles = new HashSet<>(); + ModuleCompilerPathsManager pathsManager = ModuleCompilerPathsManager.getInstance(module); + VirtualFile outputpath = pathsManager.getCompilerOutput(ProductionContentFolderTypeProvider.getInstance()); + VirtualFile testOutputpath = pathsManager.getCompilerOutput(TestContentFolderTypeProvider.getInstance()); - for (JavaCoverageEngineExtension extension : Extensions.getExtensions(JavaCoverageEngineExtension.EP_NAME)) { + for (JavaCoverageEngineExtension extension : JavaCoverageEngineExtension.EP_NAME.getExtensions()) { if (extension.collectOutputFiles(srcFile, outputpath, testOutputpath, suite, classFiles)) { return classFiles; } } - final String packageFQName = getPackageName(srcFile); - final String packageVmName = packageFQName.replace('.', '/'); + String packageFQName = getPackageName(srcFile); + String packageVmName = packageFQName.replace('.', '/'); - final List children = new ArrayList<>(); - final File vDir = - outputpath == null - ? null : packageVmName.length() > 0 - ? new File(outputpath.getPath() + File.separator + packageVmName) : VirtualFileUtil.virtualToIoFile(outputpath); + List children = new ArrayList<>(); + File vDir = outputpath == null + ? null + : packageVmName.length() > 0 + ? new File(outputpath.getPath() + File.separator + packageVmName) + : VirtualFileUtil.virtualToIoFile(outputpath); if (vDir != null && vDir.exists()) { Collections.addAll(children, vDir.listFiles()); } if (suite.isTrackTestFolders()) { - final File testDir = - testOutputpath == null - ? null : packageVmName.length() > 0 - ? new File(testOutputpath.getPath() + File.separator + packageVmName) : VirtualFileUtil.virtualToIoFile(testOutputpath); + File testDir = testOutputpath == null + ? null + : packageVmName.length() > 0 + ? new File(testOutputpath.getPath() + File.separator + packageVmName) + : VirtualFileUtil.virtualToIoFile(testOutputpath); if (testDir != null && testDir.exists()) { Collections.addAll(children, testDir.listFiles()); } } Application application = srcFile.getApplication(); - final PsiClass[] classes = application.runReadAction((Computable)((PsiClassOwner)srcFile)::getClasses); - for (final PsiClass psiClass : classes) { - final String className = application.runReadAction((Computable)psiClass::getName); + PsiClass[] classes = application.runReadAction((Supplier)((PsiClassOwner)srcFile)::getClasses); + for (PsiClass psiClass : classes) { + String className = application.runReadAction((Supplier)psiClass::getName); for (File child : children) { if (FileUtil.extensionEquals(child.getName(), JavaClassFileType.INSTANCE.getDefaultExtension())) { - final String childName = FileUtil.getNameWithoutExtension(child); + String childName = FileUtil.getNameWithoutExtension(child); if (childName.equals(className) || //class or inner childName.startsWith(className) && childName.charAt(className.length()) == '$') { classFiles.add(child); @@ -391,6 +389,7 @@ public Set getCorrespondingOutputFiles( return classFiles; } + @Override @RequiredReadAction public String generateBriefReport( @Nonnull Editor editor, @@ -400,7 +399,7 @@ public String generateBriefReport( int endOffset, @Nullable LineData lineData ) { - final StringBuilder buf = new StringBuilder(); + StringBuilder buf = new StringBuilder(); buf.append("Hits: "); if (lineData == null) { buf.append(0); @@ -408,9 +407,9 @@ public String generateBriefReport( } buf.append(lineData.getHits()).append("\n"); - final List expressions = new ArrayList<>(); + List expressions = new ArrayList<>(); - final Project project = editor.getProject(); + Project project = editor.getProject(); for (int offset = startOffset; offset < endOffset; offset++) { PsiElement parent = PsiTreeUtil.getParentOfType(psiFile.findElementAt(offset), PsiStatement.class); PsiElement condition = null; @@ -437,11 +436,11 @@ else if (parent instanceof PsiAssertStatement assertStatement) { } if (condition != null && PsiTreeUtil.isAncestor(condition, psiFile.findElementAt(offset), false)) { try { - final ControlFlow controlFlow = ControlFlowFactory.getInstance(project) + ControlFlow controlFlow = ControlFlowFactory.getInstance(project) .getControlFlow(parent, AllVariablesControlFlowPolicy.getInstance()); for (Instruction instruction : controlFlow.getInstructions()) { if (instruction instanceof ConditionalBranchingInstruction branchingInstruction) { - final PsiExpression expression = branchingInstruction.expression; + PsiExpression expression = branchingInstruction.expression; if (!expressions.contains(expression)) { expressions.add(expression); } @@ -454,16 +453,16 @@ else if (parent instanceof PsiAssertStatement assertStatement) { } } - final String indent = " "; + String indent = " "; try { int idx = 0; int hits = 0; if (lineData.getJumps() != null) { for (Object o : lineData.getJumps()) { - final JumpData jumpData = (JumpData)o; + JumpData jumpData = (JumpData)o; if (jumpData.getTrueHits() + jumpData.getFalseHits() > 0) { - final PsiExpression expression = expressions.get(idx++); - final PsiElement parentExpression = expression.getParent(); + PsiExpression expression = expressions.get(idx++); + PsiElement parentExpression = expression.getParent(); boolean reverse = parentExpression instanceof PsiPolyadicExpression polyExpr && polyExpr.getOperationTokenType() == JavaTokenType.OROR || parentExpression instanceof PsiDoWhileStatement @@ -486,17 +485,17 @@ else if (parent instanceof PsiAssertStatement assertStatement) { if (lineData.getSwitches() != null) { for (Object o : lineData.getSwitches()) { - final SwitchData switchData = (SwitchData)o; - final PsiExpression conditionExpression = expressions.get(idx++); + SwitchData switchData = (SwitchData)o; + PsiExpression conditionExpression = expressions.get(idx++); buf.append(indent).append(conditionExpression.getText()).append("\n"); int i = 0; for (int key : switchData.getKeys()) { - final int switchHits = switchData.getHits()[i++]; + int switchHits = switchData.getHits()[i++]; buf.append(indent).append(indent).append("case ").append(key).append(": ").append(switchHits).append("\n"); hits += switchHits; } int defaultHits = switchData.getDefaultHits(); - final boolean hasDefaultLabel = hasDefaultLabel(conditionExpression); + boolean hasDefaultLabel = hasDefaultLabel(conditionExpression); if (hasDefaultLabel || defaultHits > 0) { if (!hasDefaultLabel) { defaultHits -= hits; @@ -521,18 +520,17 @@ else if (parent instanceof PsiAssertStatement assertStatement) { } @Nullable - public String getTestMethodName( - @Nonnull final PsiElement element, - @Nonnull final AbstractTestProxy testProxy - ) { + @Override + public String getTestMethodName(@Nonnull PsiElement element, @Nonnull AbstractTestProxy testProxy) { return testProxy.toString(); } @Nonnull + @Override public List findTestsByNames(@Nonnull String[] testNames, @Nonnull Project project) { - final List elements = new ArrayList<>(); - final JavaPsiFacade facade = JavaPsiFacade.getInstance(project); - final GlobalSearchScope projectScope = GlobalSearchScope.projectScope(project); + List elements = new ArrayList<>(); + JavaPsiFacade facade = JavaPsiFacade.getInstance(project); + GlobalSearchScope projectScope = GlobalSearchScope.projectScope(project); for (String testName : testNames) { PsiClass psiClass = facade.findClass(StringUtil.getPackageName(testName, '_').replaceAll("\\_", "\\."), projectScope); @@ -544,7 +542,10 @@ public List findTestsByNames(@Nonnull String[] testNames, @Nonnull P String className = testName; while (lastIdx > 0) { className = className.substring(0, lastIdx - 1); - psiClass = facade.findClass(StringUtil.getPackageName(className, '_').replaceAll("\\_", "\\."), projectScope); + psiClass = facade.findClass( + StringUtil.getPackageName(className, '_').replaceAll("\\_", "\\."), + projectScope + ); lastIdx = className.lastIndexOf("_"); if (psiClass != null) { collectTestsByName(elements, testName, psiClass, lastIdx); @@ -557,18 +558,19 @@ public List findTestsByNames(@Nonnull String[] testNames, @Nonnull P } private static void collectTestsByName(List elements, String testName, PsiClass psiClass, int lastIdx) { - final PsiMethod[] testsByName = psiClass.findMethodsByName(testName.substring(lastIdx + 1), true); + PsiMethod[] testsByName = psiClass.findMethodsByName(testName.substring(lastIdx + 1), true); if (testsByName.length == 1) { elements.add(testsByName[0]); } } - private static boolean hasDefaultLabel(final PsiElement conditionExpression) { + @RequiredReadAction + private static boolean hasDefaultLabel(PsiElement conditionExpression) { boolean hasDefault = false; - final PsiSwitchStatement switchStatement = PsiTreeUtil.getParentOfType(conditionExpression, PsiSwitchStatement.class); - final PsiCodeBlock body = ((PsiSwitchStatementImpl)conditionExpression.getParent()).getBody(); + PsiSwitchStatement switchStatement = PsiTreeUtil.getParentOfType(conditionExpression, PsiSwitchStatement.class); + PsiCodeBlock body = ((PsiSwitchStatementImpl)conditionExpression.getParent()).getBody(); if (body != null) { - final PsiElement bodyElement = body.getFirstBodyElement(); + PsiElement bodyElement = body.getFirstBodyElement(); if (bodyElement != null) { PsiSwitchLabelStatement label = PsiTreeUtil.getNextSiblingOfType(bodyElement, PsiSwitchLabelStatement.class); while (label != null) { @@ -608,8 +610,8 @@ protected JavaCoverageSuite createSuite( } @Nonnull - protected static String getPackageName(final PsiFile sourceFile) { - return sourceFile.getApplication().runReadAction((Computable)((PsiClassOwner)sourceFile)::getPackageName); + protected static String getPackageName(PsiFile sourceFile) { + return sourceFile.getApplication().runReadAction((Supplier)((PsiClassOwner)sourceFile)::getPackageName); } @Override diff --git a/java-coverage-impl/src/main/java/com/intellij/java/coverage/JavaCoverageEngineExtension.java b/java-coverage-impl/src/main/java/com/intellij/java/coverage/JavaCoverageEngineExtension.java index 3344a8b78b..60b36fd133 100644 --- a/java-coverage-impl/src/main/java/com/intellij/java/coverage/JavaCoverageEngineExtension.java +++ b/java-coverage-impl/src/main/java/com/intellij/java/coverage/JavaCoverageEngineExtension.java @@ -15,8 +15,8 @@ import java.util.Set; /** - * User: anna - * Date: 2/14/11 + * @author anna + * @since 2011-02-14 */ @ExtensionAPI(ComponentScope.APPLICATION) public abstract class JavaCoverageEngineExtension { @@ -30,11 +30,11 @@ public boolean suggestQualifiedName(@Nonnull PsiFile sourceFile, PsiClass[] clas } public boolean collectOutputFiles( - @Nonnull final PsiFile srcFile, - @Nullable final VirtualFile output, - @Nullable final VirtualFile testoutput, - @Nonnull final CoverageSuitesBundle suite, - @Nonnull final Set classFiles + @Nonnull PsiFile srcFile, + @Nullable VirtualFile output, + @Nullable VirtualFile testoutput, + @Nonnull CoverageSuitesBundle suite, + @Nonnull Set classFiles ) { return false; } diff --git a/java-debugger-api/src/main/java/com/intellij/java/debugger/DebuggerBundle.java b/java-debugger-api/src/main/java/com/intellij/java/debugger/DebuggerBundle.java index a6c1a7d653..2b38b55dc6 100644 --- a/java-debugger-api/src/main/java/com/intellij/java/debugger/DebuggerBundle.java +++ b/java-debugger-api/src/main/java/com/intellij/java/debugger/DebuggerBundle.java @@ -15,6 +15,7 @@ */ package com.intellij.java.debugger; +import com.intellij.java.debugger.engine.DebuggerUtils; import com.intellij.java.debugger.localize.JavaDebuggerLocalize; import consulo.annotation.DeprecationInfo; import consulo.annotation.internal.MigratedExtensionsTo; @@ -27,14 +28,16 @@ @MigratedExtensionsTo(JavaDebuggerLocalize.class) public class DebuggerBundle extends AbstractBundle { + @Deprecated public static String getAddressDisplayName(final RemoteConnection connection) { - return connection.isUseSockets() ? connection.getHostName() + ":" + connection.getAddress() : connection.getAddress(); + return DebuggerUtils.getAddressDisplayName(connection); } + @Deprecated public static String getTransportName(final RemoteConnection connection) { - return connection.isUseSockets() ? message("transport.name.socket") : message("transport.name.shared.memory"); + return DebuggerUtils.getTransportName(connection).get(); } private static final DebuggerBundle ourInstance = new DebuggerBundle(); diff --git a/java-debugger-api/src/main/java/com/intellij/java/debugger/engine/DebuggerUtils.java b/java-debugger-api/src/main/java/com/intellij/java/debugger/engine/DebuggerUtils.java index 7197fec4ed..9156797e2f 100644 --- a/java-debugger-api/src/main/java/com/intellij/java/debugger/engine/DebuggerUtils.java +++ b/java-debugger-api/src/main/java/com/intellij/java/debugger/engine/DebuggerUtils.java @@ -15,20 +15,21 @@ */ package com.intellij.java.debugger.engine; -import com.intellij.java.debugger.DebuggerBundle; import com.intellij.java.debugger.DebuggerContext; import com.intellij.java.debugger.engine.evaluation.EvaluateException; import com.intellij.java.debugger.engine.evaluation.EvaluateExceptionUtil; import com.intellij.java.debugger.engine.evaluation.EvaluationContext; import com.intellij.java.debugger.engine.evaluation.TextWithImports; +import com.intellij.java.debugger.localize.JavaDebuggerLocalize; +import com.intellij.java.execution.configurations.RemoteConnection; import com.intellij.java.language.LanguageLevel; import com.intellij.java.language.psi.*; import com.intellij.java.language.psi.util.ClassUtil; import com.intellij.java.language.psi.util.InheritanceUtil; +import consulo.annotation.access.RequiredReadAction; import consulo.annotation.component.ComponentScope; import consulo.annotation.component.ServiceAPI; import consulo.application.Application; -import consulo.application.ApplicationManager; import consulo.application.dumb.IndexNotReadyException; import consulo.dataContext.DataContext; import consulo.ide.ServiceManager; @@ -42,33 +43,31 @@ import consulo.language.psi.PsiManager; import consulo.language.psi.scope.GlobalSearchScope; import consulo.language.util.IncorrectOperationException; +import consulo.localize.LocalizeValue; import consulo.logging.Logger; import consulo.process.ExecutionException; import consulo.project.Project; import consulo.util.dataholder.Key; import consulo.util.lang.StringUtil; -import consulo.util.lang.ref.Ref; -import org.jdom.Element; -import org.jetbrains.annotations.NonNls; - +import consulo.util.lang.ref.SimpleReference; import jakarta.annotation.Nonnull; import jakarta.annotation.Nullable; +import org.jdom.Element; import java.util.*; @ServiceAPI(ComponentScope.APPLICATION) public abstract class DebuggerUtils { private static final Logger LOG = Logger.getInstance(DebuggerUtils.class); - private static final Key TO_STRING_METHOD_KEY = new Key("CachedToStringMethod"); + private static final Key TO_STRING_METHOD_KEY = Key.create("CachedToStringMethod"); public static final Set ourPrimitiveTypeNames = - new HashSet(Arrays.asList("byte", "short", "int", "long", "float", "double", "boolean", "char")); + new HashSet<>(Arrays.asList("byte", "short", "int", "long", "float", "double", "boolean", "char")); public static void cleanupAfterProcessFinish(DebugProcess debugProcess) { debugProcess.putUserData(TO_STRING_METHOD_KEY, null); } - @NonNls - public static String getValueAsString(final EvaluationContext evaluationContext, Value value) throws EvaluateException { + public static String getValueAsString(EvaluationContext evaluationContext, Value value) throws EvaluateException { try { if (value == null) { return "null"; @@ -94,10 +93,10 @@ public static String getValueAsString(final EvaluationContext evaluationContext, } if (value instanceof ObjectReference) { if (value instanceof ArrayReference) { - final StringBuilder builder = new StringBuilder(); + StringBuilder builder = new StringBuilder(); builder.append("["); for (Iterator iterator = ((ArrayReference)value).getValues().iterator(); iterator.hasNext(); ) { - final Value element = iterator.next(); + Value element = iterator.next(); builder.append(getValueAsString(evaluationContext, element)); if (iterator.hasNext()) { builder.append(","); @@ -107,8 +106,8 @@ public static String getValueAsString(final EvaluationContext evaluationContext, return builder.toString(); } - final ObjectReference objRef = (ObjectReference)value; - final DebugProcess debugProcess = evaluationContext.getDebugProcess(); + ObjectReference objRef = (ObjectReference)value; + DebugProcess debugProcess = evaluationContext.getDebugProcess(); Method toStringMethod = debugProcess.getUserData(TO_STRING_METHOD_KEY); if (toStringMethod == null) { try { @@ -117,28 +116,26 @@ public static String getValueAsString(final EvaluationContext evaluationContext, debugProcess.putUserData(TO_STRING_METHOD_KEY, toStringMethod); } catch (Exception ignored) { - throw EvaluateExceptionUtil.createEvaluateException(DebuggerBundle.message( - "evaluation.error.cannot.evaluate.tostring", - objRef.referenceType().name() - )); + throw EvaluateExceptionUtil.createEvaluateException( + JavaDebuggerLocalize.evaluationErrorCannotEvaluateTostring(objRef.referenceType().name()) + ); } } if (toStringMethod == null) { - throw EvaluateExceptionUtil.createEvaluateException(DebuggerBundle.message( - "evaluation.error.cannot.evaluate.tostring", - objRef.referenceType().name() - )); + throw EvaluateExceptionUtil.createEvaluateException( + JavaDebuggerLocalize.evaluationErrorCannotEvaluateTostring(objRef.referenceType().name()) + ); } // while result must be of com.sun.jdi.StringReference type, it turns out that sometimes (jvm bugs?) // it is a plain com.sun.tools.jdi.ObjectReferenceImpl - final Value result = + Value result = debugProcess.invokeInstanceMethod(evaluationContext, objRef, toStringMethod, Collections.emptyList(), 0); if (result == null) { return "null"; } return result instanceof StringReference ? ((StringReference)result).value() : result.toString(); } - throw EvaluateExceptionUtil.createEvaluateException(DebuggerBundle.message("evaluation.error.unsupported.expression.type")); + throw EvaluateExceptionUtil.createEvaluateException(JavaDebuggerLocalize.evaluationErrorUnsupportedExpressionType()); } catch (ObjectCollectedException ignored) { throw EvaluateExceptionUtil.OBJECT_WAS_COLLECTED; @@ -161,10 +158,10 @@ public static String convertToPresentationString(String str) { } @Nullable - public static Method findMethod(@Nonnull ReferenceType refType, @NonNls String methodName, @NonNls String methodSignature) { + public static Method findMethod(@Nonnull ReferenceType refType, String methodName, String methodSignature) { if (refType instanceof ArrayType) { // for array types methodByName() in JDI always returns empty list - final Method method = + Method method = findMethod(refType.virtualMachine().classesByName(JavaClassNames.JAVA_LANG_OBJECT).get(0), methodName, methodSignature); if (method != null) { return method; @@ -177,7 +174,7 @@ public static Method findMethod(@Nonnull ReferenceType refType, @NonNls String m method = ((ClassType)refType).concreteMethodByName(methodName, methodSignature); } if (method == null) { - final List methods = refType.methodsByName(methodName, methodSignature); + List methods = refType.methodsByName(methodName, methodSignature); if (methods.size() > 0) { method = methods.get(0); } @@ -208,9 +205,9 @@ public static boolean isInteger(Value value) { value instanceof IntegerValue); } - public static String translateStringValue(final String str) { + public static String translateStringValue(String str) { int length = str.length(); - final StringBuilder buffer = new StringBuilder(); + StringBuilder buffer = new StringBuilder(); StringUtil.escapeStringCharacters(length, str, buffer); if (str.length() > length) { buffer.append("..."); @@ -311,15 +308,14 @@ private static Type getSuperTypeInt(@Nonnull Type subType, @Nonnull String super } Type result; - if (subType instanceof ClassType) { + if (subType instanceof ClassType classType) { try { - ClassType clsType = (ClassType)subType; - result = getSuperType(clsType.superclass(), superType); + result = getSuperType(classType.superclass(), superType); if (result != null) { return result; } - for (InterfaceType iface : clsType.allInterfaces()) { + for (InterfaceType iface : classType.allInterfaces()) { if (typeEquals(iface, superType)) { return iface; } @@ -331,9 +327,9 @@ private static Type getSuperTypeInt(@Nonnull Type subType, @Nonnull String super return null; } - if (subType instanceof InterfaceType) { + if (subType instanceof InterfaceType interfaceType) { try { - for (InterfaceType iface : ((InterfaceType)subType).superinterfaces()) { + for (InterfaceType iface : interfaceType.superinterfaces()) { result = getSuperType(iface, superType); if (result != null) { return result; @@ -344,11 +340,11 @@ private static Type getSuperTypeInt(@Nonnull Type subType, @Nonnull String super LOG.info(e); } } - else if (subType instanceof ArrayType) { + else if (subType instanceof ArrayType arrayType) { if (superType.endsWith("[]")) { try { String superTypeItem = superType.substring(0, superType.length() - 2); - Type subTypeItem = ((ArrayType)subType).componentType(); + Type subTypeItem = arrayType.componentType(); return instanceOf(subTypeItem, superTypeItem) ? subType : null; } catch (ClassNotLoadedException e) { @@ -378,8 +374,9 @@ public static boolean instanceOf(@Nullable Type subType, @Nonnull String superTy } @Nullable - public static PsiClass findClass(@Nonnull final String className, @Nonnull Project project, final GlobalSearchScope scope) { - ApplicationManager.getApplication().assertReadAccessAllowed(); + @RequiredReadAction + public static PsiClass findClass(@Nonnull String className, @Nonnull Project project, GlobalSearchScope scope) { + Application.get().assertReadAccessAllowed(); try { if (getArrayClass(className) != null) { return JavaPsiFacade.getInstance(project).getElementFactory().getArrayClass(LanguageLevel.HIGHEST); @@ -405,10 +402,11 @@ public static PsiClass findClass(@Nonnull final String className, @Nonnull Proje } @Nullable + @RequiredReadAction public static PsiType getType(@Nonnull String className, @Nonnull Project project) { - ApplicationManager.getApplication().assertReadAccessAllowed(); + Application.get().assertReadAccessAllowed(); - final PsiManager psiManager = PsiManager.getInstance(project); + PsiManager psiManager = PsiManager.getInstance(project); try { if (getArrayClass(className) != null) { return JavaPsiFacade.getInstance(psiManager.getProject()).getElementFactory().createTypeFromText(className, null); @@ -416,7 +414,7 @@ public static PsiType getType(@Nonnull String className, @Nonnull Project projec if (project.isDefault()) { return null; } - final PsiClass aClass = JavaPsiFacade.getInstance(psiManager.getProject()) + PsiClass aClass = JavaPsiFacade.getInstance(psiManager.getProject()) .findClass(className.replace('$', '.'), GlobalSearchScope.allScope(project)); if (aClass != null) { return JavaPsiFacade.getInstance(psiManager.getProject()).getElementFactory().createType(aClass); @@ -428,18 +426,16 @@ public static PsiType getType(@Nonnull String className, @Nonnull Project projec return null; } + @RequiredReadAction public static void checkSyntax(PsiCodeFragment codeFragment) throws EvaluateException { PsiElement[] children = codeFragment.getChildren(); if (children.length == 0) { - throw EvaluateExceptionUtil.createEvaluateException(DebuggerBundle.message("evaluation.error.empty.code.fragment")); + throw EvaluateExceptionUtil.createEvaluateException(JavaDebuggerLocalize.evaluationErrorEmptyCodeFragment()); } for (PsiElement child : children) { if (child instanceof PsiErrorElement) { - throw EvaluateExceptionUtil.createEvaluateException(DebuggerBundle.message( - "evaluation.error.invalid.expression", - child.getText() - )); + throw EvaluateExceptionUtil.createEvaluateException(JavaDebuggerLocalize.evaluationErrorInvalidExpression(child.getText())); } } } @@ -448,39 +444,38 @@ public static boolean hasSideEffects(PsiElement element) { return hasSideEffectsOrReferencesMissingVars(element, null); } - public static boolean hasSideEffectsOrReferencesMissingVars(PsiElement element, @Nullable final Set visibleLocalVariables) { - final Ref rv = new Ref(Boolean.FALSE); + public static boolean hasSideEffectsOrReferencesMissingVars(PsiElement element, @Nullable Set visibleLocalVariables) { + SimpleReference rv = new SimpleReference<>(Boolean.FALSE); element.accept(new JavaRecursiveElementWalkingVisitor() { @Override - public void visitPostfixExpression(final PsiPostfixExpression expression) { + public void visitPostfixExpression(@Nonnull PsiPostfixExpression expression) { rv.set(Boolean.TRUE); } @Override - public void visitReferenceExpression(final PsiReferenceExpression expression) { - final PsiElement psiElement = expression.resolve(); - if (psiElement instanceof PsiLocalVariable) { - if (visibleLocalVariables != null) { - if (!visibleLocalVariables.contains(((PsiLocalVariable)psiElement).getName())) { - rv.set(Boolean.TRUE); - } + @RequiredReadAction + public void visitReferenceExpression(PsiReferenceExpression expression) { + PsiElement psiElement = expression.resolve(); + if (psiElement instanceof PsiLocalVariable localVar) { + if (visibleLocalVariables != null && !visibleLocalVariables.contains(localVar.getName())) { + rv.set(Boolean.TRUE); } } else if (psiElement instanceof PsiMethod) { rv.set(Boolean.TRUE); - //final PsiMethod method = (PsiMethod)psiElement; + //PsiMethod method = (PsiMethod)psiElement; //if (!isSimpleGetter(method)) { - // rv.set(Boolean.TRUE); + // rv.set(Boolean.TRUE); //} } - if (!rv.get().booleanValue()) { + if (!rv.get()) { super.visitReferenceExpression(expression); } } @Override - public void visitPrefixExpression(final PsiPrefixExpression expression) { - final IElementType op = expression.getOperationTokenType(); + public void visitPrefixExpression(@Nonnull PsiPrefixExpression expression) { + IElementType op = expression.getOperationTokenType(); if (JavaTokenType.PLUSPLUS.equals(op) || JavaTokenType.MINUSMINUS.equals(op)) { rv.set(Boolean.TRUE); } @@ -490,40 +485,49 @@ public void visitPrefixExpression(final PsiPrefixExpression expression) { } @Override - public void visitAssignmentExpression(final PsiAssignmentExpression expression) { + public void visitAssignmentExpression(@Nonnull PsiAssignmentExpression expression) { rv.set(Boolean.TRUE); } @Override - public void visitCallExpression(final PsiCallExpression callExpression) { + public void visitCallExpression(@Nonnull PsiCallExpression callExpression) { rv.set(Boolean.TRUE); - //final PsiMethod method = callExpression.resolveMethod(); + //PsiMethod method = callExpression.resolveMethod(); //if (method == null || !isSimpleGetter(method)) { - // rv.set(Boolean.TRUE); + // rv.set(Boolean.TRUE); //} //else { - // super.visitCallExpression(callExpression); + // super.visitCallExpression(callExpression); //} } }); - return rv.get().booleanValue(); + return rv.get(); + } + + public static String getAddressDisplayName(RemoteConnection connection) + { + return connection.isUseSockets() ? connection.getHostName() + ":" + connection.getAddress() : connection.getAddress(); + } + + @Nonnull + public static LocalizeValue getTransportName(RemoteConnection connection) + { + return connection.isUseSockets() + ? JavaDebuggerLocalize.transportNameSocket() + : JavaDebuggerLocalize.transportNameSharedMemory(); } @Nonnull public abstract TransportService.ListenKey findAvailableDebugAddress(int type) throws ExecutionException; public static boolean isSynthetic(TypeComponent typeComponent) { + //noinspection SimplifiableIfStatement if (typeComponent == null) { return false; } - for (SyntheticTypeComponentProvider syntheticTypeComponentProvider - : Application.get().getExtensionList(SyntheticTypeComponentProvider.class)) { - if (syntheticTypeComponentProvider.isSynthetic(typeComponent)) { - return true; - } - } - return false; + return Application.get().getExtensionPoint(SyntheticTypeComponentProvider.class) + .anyMatchSafe(provider -> provider.isSynthetic(typeComponent)); } public static boolean isInsideSimpleGetter(@Nonnull PsiElement contextElement) { @@ -535,7 +539,7 @@ public static boolean isInsideSimpleGetter(@Nonnull PsiElement contextElement) { return false; } - public static boolean isPrimitiveType(final String typeName) { + public static boolean isPrimitiveType(String typeName) { return ourPrimitiveTypeNames.contains(typeName); } @@ -566,13 +570,13 @@ public abstract PsiExpression substituteThis( public abstract TextWithImports readTextWithImports(Element element); - public abstract void writeTextWithImports(Element root, @NonNls String name, TextWithImports value); + public abstract void writeTextWithImports(Element root, String name, TextWithImports value); - public abstract TextWithImports readTextWithImports(Element root, @NonNls String name); + public abstract TextWithImports readTextWithImports(Element root, String name); - public abstract TextWithImports createExpressionWithImports(@NonNls String expression); + public abstract TextWithImports createExpressionWithImports(String expression); - public abstract PsiElement getContextElement(final StackFrameContext context); + public abstract PsiElement getContextElement(StackFrameContext context); public abstract PsiClass chooseClassDialog(String title, Project project); } diff --git a/java-debugger-api/src/main/java/com/intellij/java/debugger/engine/evaluation/EvaluateException.java b/java-debugger-api/src/main/java/com/intellij/java/debugger/engine/evaluation/EvaluateException.java index 0009737a45..448a95ee31 100644 --- a/java-debugger-api/src/main/java/com/intellij/java/debugger/engine/evaluation/EvaluateException.java +++ b/java-debugger-api/src/main/java/com/intellij/java/debugger/engine/evaluation/EvaluateException.java @@ -21,49 +21,49 @@ import jakarta.annotation.Nullable; public class EvaluateException extends Exception { - private static final Logger LOG = Logger.getInstance(EvaluateException.class); - private ObjectReference myTargetException; + private static final Logger LOG = Logger.getInstance(EvaluateException.class); + private ObjectReference myTargetException; - public EvaluateException(final String message) { - super(message); - if (LOG.isDebugEnabled()) { - LOG.debug(message); + public EvaluateException(String message) { + super(message); + if (LOG.isDebugEnabled()) { + LOG.debug(message); + } } - } - public EvaluateException(String msg, Throwable th) { - super(msg, th); - if (th instanceof EvaluateException) { - myTargetException = ((EvaluateException)th).getExceptionFromTargetVM(); + public EvaluateException(String msg, Throwable th) { + super(msg, th); + if (th instanceof EvaluateException evaluateException) { + myTargetException = evaluateException.getExceptionFromTargetVM(); + } + else if (th instanceof InvocationException invocationException) { + myTargetException = invocationException.exception(); + } + if (LOG.isDebugEnabled()) { + LOG.debug(msg); + } } - else if(th instanceof InvocationException){ - InvocationException invocationException = (InvocationException) th; - myTargetException = invocationException.exception(); - } - if (LOG.isDebugEnabled()) { - LOG.debug(msg); - } - } - - @Nullable - public ObjectReference getExceptionFromTargetVM() { - return myTargetException; - } - public void setTargetException(final ObjectReference targetException) { - myTargetException = targetException; - } + @Nullable + public ObjectReference getExceptionFromTargetVM() { + return myTargetException; + } - public String getMessage() { - final String errorMessage = super.getMessage(); - if (errorMessage != null) { - return errorMessage; + public void setTargetException(ObjectReference targetException) { + myTargetException = targetException; } - final Throwable cause = getCause(); - final String causeMessage = cause != null? cause.getMessage() : null; - if (causeMessage != null) { - return causeMessage; + + @Override + public String getMessage() { + String errorMessage = super.getMessage(); + if (errorMessage != null) { + return errorMessage; + } + Throwable cause = getCause(); + String causeMessage = cause != null ? cause.getMessage() : null; + if (causeMessage != null) { + return causeMessage; + } + return "unknown error"; } - return "unknown error"; - } } \ No newline at end of file diff --git a/java-debugger-api/src/main/java/com/intellij/java/debugger/engine/evaluation/EvaluateExceptionUtil.java b/java-debugger-api/src/main/java/com/intellij/java/debugger/engine/evaluation/EvaluateExceptionUtil.java index ebaef48aa3..56ebfeb359 100644 --- a/java-debugger-api/src/main/java/com/intellij/java/debugger/engine/evaluation/EvaluateExceptionUtil.java +++ b/java-debugger-api/src/main/java/com/intellij/java/debugger/engine/evaluation/EvaluateExceptionUtil.java @@ -16,72 +16,94 @@ package com.intellij.java.debugger.engine.evaluation; import com.intellij.java.debugger.DebuggerBundle; +import com.intellij.java.debugger.localize.JavaDebuggerLocalize; +import consulo.annotation.DeprecationInfo; import consulo.internal.com.sun.jdi.*; +import consulo.localize.LocalizeValue; +import jakarta.annotation.Nonnull; /** * @author lex */ public class EvaluateExceptionUtil { - public static final EvaluateException INCONSISTEND_DEBUG_INFO = createEvaluateException(DebuggerBundle.message("evaluation.error.inconsistent.debug.info")); - public static final EvaluateException BOOLEAN_EXPECTED = createEvaluateException(DebuggerBundle.message("evaluation.error.boolean.value.expected.in.condition")); - public static final EvaluateException PROCESS_EXITED = createEvaluateException(DebuggerBundle.message("evaluation.error.process.exited")); - public static final EvaluateException NULL_STACK_FRAME = createEvaluateException(DebuggerBundle.message("evaluation.error.stack.frame.unavailable")); - public static final EvaluateException NESTED_EVALUATION_ERROR = createEvaluateException(DebuggerBundle.message("evaluation.error.nested.evaluation")); - public static final EvaluateException INVALID_DEBUG_INFO = createEvaluateException(DebuggerBundle.message("evaluation.error.sources.out.of.sync")); - public static final EvaluateException CANNOT_FIND_SOURCE_CLASS = createEvaluateException(DebuggerBundle.message("evaluation.error.cannot.find.stackframe.source")); - public static final EvaluateException OBJECT_WAS_COLLECTED = createEvaluateException(DebuggerBundle.message("evaluation.error.object.collected")); - public static final EvaluateException ARRAY_WAS_COLLECTED = createEvaluateException(DebuggerBundle.message("evaluation.error.array.collected")); - public static final EvaluateException THREAD_WAS_RESUMED = createEvaluateException(DebuggerBundle.message("evaluation.error.thread.resumed")); - public static final EvaluateException DEBUG_INFO_UNAVAILABLE = createEvaluateException(DebuggerBundle.message("evaluation.error.debug.info.unavailable")); + public static final EvaluateException INCONSISTEND_DEBUG_INFO = + createEvaluateException(DebuggerBundle.message("evaluation.error.inconsistent.debug.info")); + public static final EvaluateException BOOLEAN_EXPECTED = + createEvaluateException(DebuggerBundle.message("evaluation.error.boolean.value.expected.in.condition")); + public static final EvaluateException PROCESS_EXITED = + createEvaluateException(DebuggerBundle.message("evaluation.error.process.exited")); + public static final EvaluateException NULL_STACK_FRAME = + createEvaluateException(DebuggerBundle.message("evaluation.error.stack.frame.unavailable")); + public static final EvaluateException NESTED_EVALUATION_ERROR = + createEvaluateException(DebuggerBundle.message("evaluation.error.nested.evaluation")); + public static final EvaluateException INVALID_DEBUG_INFO = + createEvaluateException(DebuggerBundle.message("evaluation.error.sources.out.of.sync")); + public static final EvaluateException CANNOT_FIND_SOURCE_CLASS = + createEvaluateException(DebuggerBundle.message("evaluation.error.cannot.find.stackframe.source")); + public static final EvaluateException OBJECT_WAS_COLLECTED = + createEvaluateException(DebuggerBundle.message("evaluation.error.object.collected")); + public static final EvaluateException ARRAY_WAS_COLLECTED = + createEvaluateException(DebuggerBundle.message("evaluation.error.array.collected")); + public static final EvaluateException THREAD_WAS_RESUMED = + createEvaluateException(DebuggerBundle.message("evaluation.error.thread.resumed")); + public static final EvaluateException DEBUG_INFO_UNAVAILABLE = + createEvaluateException(DebuggerBundle.message("evaluation.error.debug.info.unavailable")); - private EvaluateExceptionUtil() { - } - - public static EvaluateException createEvaluateException(Throwable th) { - return createEvaluateException(null, th); - } - - public static EvaluateException createEvaluateException(String msg, Throwable th) { - final String message = msg != null? msg + ": " + reason(th) : reason(th); - return new EvaluateException(message, th instanceof EvaluateException ? th.getCause() : th); - } - - public static EvaluateException createEvaluateException(String reason) { - return new EvaluateException(reason, null); - } - - private static String reason(Throwable th) { - if(th instanceof InvalidTypeException) { - final String originalReason = th.getMessage(); - return DebuggerBundle.message("evaluation.error.type.mismatch") + (originalReason != null? " " + originalReason : ""); - } - else if(th instanceof AbsentInformationException) { - return DebuggerBundle.message("evaluation.error.debug.info.unavailable"); - } - else if(th instanceof ClassNotLoadedException) { - return DebuggerBundle.message("evaluation.error.class.not.loaded", ((ClassNotLoadedException)th).className()); - } - else if(th instanceof ClassNotPreparedException) { - return th.getMessage(); + private EvaluateExceptionUtil() { } - else if(th instanceof IncompatibleThreadStateException) { - return DebuggerBundle.message("evaluation.error.thread.not.at.breakpoint"); - } - else if(th instanceof InconsistentDebugInfoException) { - return DebuggerBundle.message("evaluation.error.inconsistent.debug.info"); + + public static EvaluateException createEvaluateException(Throwable th) { + return createEvaluateException(null, th); } - else if(th instanceof ObjectCollectedException) { - return DebuggerBundle.message("evaluation.error.object.collected"); + + public static EvaluateException createEvaluateException(String msg, Throwable th) { + String message = msg != null ? msg + ": " + reason(th) : reason(th).get(); + return new EvaluateException(message, th instanceof EvaluateException ? th.getCause() : th); } - else if(th instanceof InvocationException){ - InvocationException invocationException = (InvocationException) th; - return DebuggerBundle.message("evaluation.error.method.exception", invocationException.exception().referenceType().name()); + + public static EvaluateException createEvaluateException(@Nonnull LocalizeValue reason) { + return new EvaluateException(reason.get(), null); } - else if(th instanceof EvaluateException) { - return th.getMessage(); + + @Deprecated + @DeprecationInfo("Use variant with LocalizeValue") + public static EvaluateException createEvaluateException(String reason) { + return new EvaluateException(reason, null); } - else { - return th.getClass().getName() + " : " + (th.getMessage() != null ? th.getMessage() : ""); + + @Nonnull + private static LocalizeValue reason(Throwable th) { + if (th instanceof InvalidTypeException) { + String originalReason = th.getMessage(); + return LocalizeValue.join(JavaDebuggerLocalize.evaluationErrorTypeMismatch(), LocalizeValue.ofNullable(originalReason)); + } + else if (th instanceof AbsentInformationException) { + return JavaDebuggerLocalize.evaluationErrorDebugInfoUnavailable(); + } + else if (th instanceof ClassNotLoadedException cnle) { + return JavaDebuggerLocalize.evaluationErrorClassNotLoaded(cnle.className()); + } + else if (th instanceof ClassNotPreparedException) { + return LocalizeValue.ofNullable(th.getLocalizedMessage()); + } + else if (th instanceof IncompatibleThreadStateException) { + return JavaDebuggerLocalize.evaluationErrorThreadNotAtBreakpoint(); + } + else if (th instanceof InconsistentDebugInfoException) { + return JavaDebuggerLocalize.evaluationErrorInconsistentDebugInfo(); + } + else if (th instanceof ObjectCollectedException) { + return JavaDebuggerLocalize.evaluationErrorObjectCollected(); + } + else if (th instanceof InvocationException ie) { + return JavaDebuggerLocalize.evaluationErrorMethodException(ie.exception().referenceType().name()); + } + else if (th instanceof EvaluateException) { + return LocalizeValue.of(th.getMessage()); + } + else { + String message = th.getLocalizedMessage(); + return LocalizeValue.of(th.getClass().getName() + " : " + (message != null ? message : "")); + } } - } } diff --git a/java-debugger-impl/src/main/java/com/intellij/java/debugger/impl/DebuggerContextUtil.java b/java-debugger-impl/src/main/java/com/intellij/java/debugger/impl/DebuggerContextUtil.java index bc87521c54..21b11d46a3 100644 --- a/java-debugger-impl/src/main/java/com/intellij/java/debugger/impl/DebuggerContextUtil.java +++ b/java-debugger-impl/src/main/java/com/intellij/java/debugger/impl/DebuggerContextUtil.java @@ -31,6 +31,7 @@ import consulo.language.psi.PsiFile; import consulo.language.psi.util.PsiTreeUtil; import consulo.ui.UIAccess; +import consulo.ui.annotation.RequiredUIAccess; import consulo.util.lang.Couple; import jakarta.annotation.Nonnull; @@ -39,69 +40,90 @@ import java.util.List; public class DebuggerContextUtil { - public static void setStackFrame(DebuggerStateManager manager, final StackFrameProxyImpl stackFrame) { - UIAccess.assertIsUIThread(); + @RequiredUIAccess + public static void setStackFrame(DebuggerStateManager manager, StackFrameProxyImpl stackFrame) { + UIAccess.assertIsUIThread(); - final DebuggerContextImpl context = manager.getContext(); + DebuggerContextImpl context = manager.getContext(); - final DebuggerSession session = context.getDebuggerSession(); - SuspendContextImpl threadSuspendContext = SuspendManagerUtil.getSuspendContextForThread(context.getSuspendContext(), stackFrame.threadProxy()); - final DebuggerContextImpl newContext = DebuggerContextImpl.createDebuggerContext(session, threadSuspendContext, stackFrame.threadProxy(), stackFrame); + DebuggerSession session = context.getDebuggerSession(); + SuspendContextImpl threadSuspendContext = + SuspendManagerUtil.getSuspendContextForThread(context.getSuspendContext(), stackFrame.threadProxy()); + DebuggerContextImpl newContext = + DebuggerContextImpl.createDebuggerContext(session, threadSuspendContext, stackFrame.threadProxy(), stackFrame); - manager.setState(newContext, session != null ? session.getState() : DebuggerSession.State.DISPOSED, DebuggerSession.Event.REFRESH, null); - } + manager.setState( + newContext, + session != null ? session.getState() : DebuggerSession.State.DISPOSED, + DebuggerSession.Event.REFRESH + ); + } - public static void setThread(DebuggerStateManager contextManager, ThreadDescriptorImpl item) { - UIAccess.assertIsUIThread(); + @RequiredUIAccess + public static void setThread(DebuggerStateManager contextManager, ThreadDescriptorImpl item) { + UIAccess.assertIsUIThread(); - final DebuggerSession session = contextManager.getContext().getDebuggerSession(); - final DebuggerContextImpl newContext = DebuggerContextImpl.createDebuggerContext(session, item.getSuspendContext(), item.getThreadReference(), null); + DebuggerSession session = contextManager.getContext().getDebuggerSession(); + DebuggerContextImpl newContext = + DebuggerContextImpl.createDebuggerContext(session, item.getSuspendContext(), item.getThreadReference(), null); - contextManager.setState(newContext, session != null ? session.getState() : DebuggerSession.State.DISPOSED, DebuggerSession.Event.CONTEXT, null); - } + contextManager.setState( + newContext, + session != null ? session.getState() : DebuggerSession.State.DISPOSED, + DebuggerSession.Event.CONTEXT + ); + } - @Nonnull - public static DebuggerContextImpl createDebuggerContext(@Nonnull DebuggerSession session, SuspendContextImpl suspendContext) { - return DebuggerContextImpl.createDebuggerContext(session, suspendContext, suspendContext != null ? suspendContext.getThread() : null, null); - } + @Nonnull + public static DebuggerContextImpl createDebuggerContext(@Nonnull DebuggerSession session, SuspendContextImpl suspendContext) { + return DebuggerContextImpl.createDebuggerContext( + session, + suspendContext, + suspendContext != null ? suspendContext.getThread() : null, + null + ); + } - public static SourcePosition findNearest(@Nonnull DebuggerContextImpl context, @Nonnull PsiElement psi, @Nonnull PsiFile file) { - final DebuggerSession session = context.getDebuggerSession(); - if (session != null) { - try { - final XDebugSession debugSession = session.getXDebugSession(); - if (debugSession != null) { - final XSourcePosition position = debugSession.getCurrentPosition(); - Editor editor = FileEditorManager.getInstance(file.getProject()).getSelectedTextEditor(true); + public static SourcePosition findNearest(@Nonnull DebuggerContextImpl context, @Nonnull PsiElement psi, @Nonnull PsiFile file) { + DebuggerSession session = context.getDebuggerSession(); + if (session != null) { + try { + XDebugSession debugSession = session.getXDebugSession(); + if (debugSession != null) { + XSourcePosition position = debugSession.getCurrentPosition(); + Editor editor = FileEditorManager.getInstance(file.getProject()).getSelectedTextEditor(true); - //final Editor editor = fileEditor instanceof TextEditorImpl ? ((TextEditorImpl)fileEditor).getEditor() : null; - if (editor != null && position != null && file.getVirtualFile().equals(position.getFile())) { - PsiMethod method = PsiTreeUtil.getParentOfType(PositionUtil.getContextElement(context), PsiMethod.class, false); - final Couple> usages = IdentifierHighlighterPass.getHighlightUsages(psi, method != null ? method : file, false); - final List ranges = new ArrayList(); - ranges.addAll(usages.first); - ranges.addAll(usages.second); - final int breakPointLine = position.getLine(); - int bestLine = -1; - int bestOffset = -1; - for (TextRange range : ranges) { - final int line = editor.offsetToLogicalPosition(range.getStartOffset()).line; - if (line > bestLine && line < breakPointLine) { - bestLine = line; - bestOffset = range.getStartOffset(); - } else if (line == breakPointLine) { - bestOffset = range.getStartOffset(); - break; - } + //Editor editor = fileEditor instanceof TextEditorImpl ? ((TextEditorImpl)fileEditor).getEditor() : null; + if (editor != null && position != null && file.getVirtualFile().equals(position.getFile())) { + PsiMethod method = PsiTreeUtil.getParentOfType(PositionUtil.getContextElement(context), PsiMethod.class, false); + Couple> usages = + IdentifierHighlighterPass.getHighlightUsages(psi, method != null ? method : file, false); + List ranges = new ArrayList<>(); + ranges.addAll(usages.first); + ranges.addAll(usages.second); + int breakPointLine = position.getLine(); + int bestLine = -1; + int bestOffset = -1; + for (TextRange range : ranges) { + int line = editor.offsetToLogicalPosition(range.getStartOffset()).line; + if (line > bestLine && line < breakPointLine) { + bestLine = line; + bestOffset = range.getStartOffset(); + } + else if (line == breakPointLine) { + bestOffset = range.getStartOffset(); + break; + } + } + if (bestOffset > -1) { + return SourcePosition.createFromOffset(file, bestOffset); + } + } + } } - if (bestOffset > -1) { - return SourcePosition.createFromOffset(file, bestOffset); + catch (Exception ignore) { } - } } - } catch (Exception ignore) { - } + return null; } - return null; - } } diff --git a/java-debugger-impl/src/main/java/com/intellij/java/debugger/impl/DebuggerInvocationUtil.java b/java-debugger-impl/src/main/java/com/intellij/java/debugger/impl/DebuggerInvocationUtil.java index 6ab007b934..4b618c3693 100644 --- a/java-debugger-impl/src/main/java/com/intellij/java/debugger/impl/DebuggerInvocationUtil.java +++ b/java-debugger-impl/src/main/java/com/intellij/java/debugger/impl/DebuggerInvocationUtil.java @@ -20,12 +20,13 @@ import consulo.language.psi.PsiDocumentManager; import consulo.project.Project; import consulo.ui.ModalityState; +import consulo.ui.annotation.RequiredUIAccess; import jakarta.annotation.Nonnull; import javax.swing.*; public class DebuggerInvocationUtil { - public static void swingInvokeLater(final Project project, @Nonnull final Runnable runnable) { + public static void swingInvokeLater(final Project project, @Nonnull @RequiredUIAccess Runnable runnable) { SwingUtilities.invokeLater(() -> { if (project != null && !project.isDisposed()) { runnable.run(); diff --git a/java-debugger-impl/src/main/java/com/intellij/java/debugger/impl/DebuggerManagerImpl.java b/java-debugger-impl/src/main/java/com/intellij/java/debugger/impl/DebuggerManagerImpl.java index e94498edf5..0bb1544228 100644 --- a/java-debugger-impl/src/main/java/com/intellij/java/debugger/impl/DebuggerManagerImpl.java +++ b/java-debugger-impl/src/main/java/com/intellij/java/debugger/impl/DebuggerManagerImpl.java @@ -15,7 +15,6 @@ */ package com.intellij.java.debugger.impl; -import com.intellij.java.debugger.DebuggerBundle; import com.intellij.java.debugger.DebuggerManager; import com.intellij.java.debugger.NameMapper; import com.intellij.java.debugger.PositionManager; @@ -31,6 +30,7 @@ import com.intellij.java.debugger.impl.ui.GetJPDADialog; import com.intellij.java.debugger.impl.ui.breakpoints.BreakpointManager; import com.intellij.java.debugger.impl.ui.tree.render.BatchEvaluator; +import com.intellij.java.debugger.localize.JavaDebuggerLocalize; import com.intellij.java.execution.configurations.RemoteConnection; import com.intellij.java.language.impl.projectRoots.ex.JavaSdkUtil; import com.intellij.java.language.projectRoots.JavaSdkVersion; @@ -38,7 +38,6 @@ import consulo.annotation.component.ServiceImpl; import consulo.application.Application; import consulo.application.progress.ProgressManager; -import consulo.colorScheme.event.EditorColorsListener; import consulo.component.persist.State; import consulo.component.persist.Storage; import consulo.component.persist.StoragePathMacros; @@ -85,10 +84,10 @@ public class DebuggerManagerImpl extends DebuggerManagerEx { private final MyDebuggerStateManager myDebuggerStateManager = new MyDebuggerStateManager(); private final DebuggerContextListener mySessionListener = (newContext, event) -> { - final DebuggerSession session = newContext.getDebuggerSession(); + DebuggerSession session = newContext.getDebuggerSession(); if (event == DebuggerSession.Event.PAUSE && myDebuggerStateManager.myDebuggerSession != session) { // if paused in non-active session; switch current session - myDebuggerStateManager.setState(newContext, session != null ? session.getState() : DebuggerSession.State.DISPOSED, event, null); + myDebuggerStateManager.setState(newContext, session != null ? session.getState() : DebuggerSession.State.DISPOSED, event); return; } @@ -107,8 +106,7 @@ else if (event == DebuggerSession.Event.DISPOSE) { myDebuggerStateManager.setState( DebuggerContextImpl.EMPTY_CONTEXT, DebuggerSession.State.DISPOSED, - DebuggerSession.Event.DISPOSE, - null + DebuggerSession.Event.DISPOSE ); } } @@ -117,19 +115,19 @@ else if (event == DebuggerSession.Event.DISPOSE) { private static final String DEBUG_KEY_NAME = "idea.xdebug.key"; @Override - public void addClassNameMapper(final NameMapper mapper) { + public void addClassNameMapper(NameMapper mapper) { myNameMappers.add(mapper); } @Override - public void removeClassNameMapper(final NameMapper mapper) { + public void removeClassNameMapper(NameMapper mapper) { myNameMappers.remove(mapper); } @Override - public String getVMClassQualifiedName(@Nonnull final PsiClass aClass) { + public String getVMClassQualifiedName(@Nonnull PsiClass aClass) { for (NameMapper nameMapper : myNameMappers) { - final String qName = nameMapper.getQualifiedName(aClass); + String qName = nameMapper.getQualifiedName(aClass); if (qName != null) { return qName; } @@ -160,7 +158,7 @@ public DebuggerSession getSession(DebugProcess process) { @Override public Collection getSessions() { synchronized (mySessions) { - final Collection values = mySessions.values(); + Collection values = mySessions.values(); return values.isEmpty() ? Collections.emptyList() : new ArrayList<>(values); } } @@ -191,11 +189,10 @@ public DebuggerSession attachVirtualMachine(@Nonnull DebugEnvironment environmen session.getContextManager().getContext().getSuspendContext() ), session.getState(), - DebuggerSession.Event.CONTEXT, - null + DebuggerSession.Event.CONTEXT ); - final ProcessHandler processHandler = executionResult.getProcessHandler(); + ProcessHandler processHandler = executionResult.getProcessHandler(); synchronized (mySessions) { mySessions.put(processHandler, session); @@ -211,7 +208,7 @@ public DebuggerSession attachVirtualMachine(@Nonnull DebugEnvironment environmen @Override public void processWillTerminate(ProcessEvent event, boolean willBeDestroyed) { ProcessHandler processHandler = event.getProcessHandler(); - final DebugProcessImpl debugProcess = getDebugProcess(processHandler); + DebugProcessImpl debugProcess = getDebugProcess(processHandler); if (debugProcess != null) { // if current thread is a "debugger manager thread", stop will execute synchronously // it is KillableProcessHandler responsibility to terminate VM @@ -260,7 +257,7 @@ public void processWillTerminate(ProcessEvent event, boolean willBeDestroyed) { } @Override - public DebugProcessImpl getDebugProcess(final ProcessHandler processHandler) { + public DebugProcessImpl getDebugProcess(ProcessHandler processHandler) { synchronized (mySessions) { DebuggerSession session = mySessions.get(processHandler); return session != null ? session.getProcess() : null; @@ -269,14 +266,14 @@ public DebugProcessImpl getDebugProcess(final ProcessHandler processHandler) { @SuppressWarnings("UnusedDeclaration") @Nullable - public DebuggerSession getDebugSession(final ProcessHandler processHandler) { + public DebuggerSession getDebugSession(ProcessHandler processHandler) { synchronized (mySessions) { return mySessions.get(processHandler); } } @Override - public void addDebugProcessListener(final ProcessHandler processHandler, final DebugProcessListener listener) { + public void addDebugProcessListener(ProcessHandler processHandler, DebugProcessListener listener) { DebugProcessImpl debugProcess = getDebugProcess(processHandler); if (debugProcess != null) { debugProcess.addDebugProcessListener(listener); @@ -296,7 +293,7 @@ public void startNotified(ProcessEvent event) { } @Override - public void removeDebugProcessListener(final ProcessHandler processHandler, final DebugProcessListener listener) { + public void removeDebugProcessListener(ProcessHandler processHandler, DebugProcessListener listener) { DebugProcessImpl debugProcess = getDebugProcess(processHandler); if (debugProcess != null) { debugProcess.removeDebugProcessListener(listener); @@ -339,38 +336,41 @@ public DebuggerStateManager getContextManager() { } @Override - public void registerPositionManagerFactory(final Function factory) { + public void registerPositionManagerFactory(Function factory) { myCustomPositionManagerFactories.add(factory); } @Override - public void unregisterPositionManagerFactory(final Function factory) { + public void unregisterPositionManagerFactory(Function factory) { myCustomPositionManagerFactories.remove(factory); } /* Remoting */ + @RequiredUIAccess private static void checkTargetJPDAInstalled(OwnJavaParameters parameters) throws ExecutionException { - final Sdk jdk = parameters.getJdk(); + Sdk jdk = parameters.getJdk(); if (jdk == null) { - throw new ExecutionException(DebuggerBundle.message("error.jdk.not.specified")); + throw new ExecutionException(JavaDebuggerLocalize.errorJdkNotSpecified().get()); } - final JavaSdkVersion version = JavaSdkTypeUtil.getVersion(jdk); + JavaSdkVersion version = JavaSdkTypeUtil.getVersion(jdk); String versionString = jdk.getVersionString(); if (version == JavaSdkVersion.JDK_1_0 || version == JavaSdkVersion.JDK_1_1) { - throw new ExecutionException(DebuggerBundle.message("error.unsupported.jdk.version", versionString)); + throw new ExecutionException(JavaDebuggerLocalize.errorUnsupportedJdkVersion(versionString).get()); } if (Platform.current().os().isWindows() && version == JavaSdkVersion.JDK_1_2) { - final VirtualFile homeDirectory = jdk.getHomeDirectory(); + VirtualFile homeDirectory = jdk.getHomeDirectory(); if (homeDirectory == null || !homeDirectory.isValid()) { - throw new ExecutionException(DebuggerBundle.message("error.invalid.jdk.home", versionString)); + throw new ExecutionException(JavaDebuggerLocalize.errorInvalidJdkHome(versionString).get()); } //noinspection HardCodedStringLiteral - File dllFile = - new File(homeDirectory.getPath().replace('/', File.separatorChar) + File.separator + "bin" + File.separator + "jdwp.dll"); + File dllFile = new File( + homeDirectory.getPath().replace('/', File.separatorChar) + + File.separator + "bin" + File.separator + "jdwp.dll" + ); if (!dllFile.exists()) { GetJPDADialog dialog = new GetJPDADialog(); dialog.show(); - throw new ExecutionException(DebuggerBundle.message("error.debug.libraries.missing")); + throw new ExecutionException(JavaDebuggerLocalize.errorDebugLibrariesMissing().get()); } } } @@ -383,19 +383,20 @@ private static boolean shouldForceClassicVM(Sdk jdk) { return false; } + @RequiredUIAccess @SuppressWarnings({"HardCodedStringLiteral"}) public static RemoteConnection createDebugParameters( - final OwnJavaParameters parameters, - final boolean debuggerInServerMode, + OwnJavaParameters parameters, + boolean debuggerInServerMode, int transport, - final String debugPort, + String debugPort, boolean checkValidity ) throws ExecutionException { if (checkValidity) { checkTargetJPDAInstalled(parameters); } - final boolean useSockets = transport == DebuggerSettings.SOCKET_TRANSPORT; + boolean useSockets = transport == DebuggerSettings.SOCKET_TRANSPORT; String address = ""; if (StringUtil.isEmptyOrSpaces(debugPort)) { @@ -412,8 +413,8 @@ public static RemoteConnection createDebugParameters( address = debugPort; } - final TransportServiceWrapper transportService = TransportServiceWrapper.createTransportService(transport); - final String debugAddress = debuggerInServerMode && useSockets ? "127.0.0.1:" + address : address; + TransportServiceWrapper transportService = TransportServiceWrapper.createTransportService(transport); + String debugAddress = debuggerInServerMode && useSockets ? "127.0.0.1:" + address : address; String debuggeeRunProperties = "transport=" + transportService.transportId() + ",address=" + debugAddress; if (debuggerInServerMode) { debuggeeRunProperties += ",suspend=y,server=n"; @@ -425,16 +426,16 @@ public static RemoteConnection createDebugParameters( if (StringUtil.containsWhitespaces(debuggeeRunProperties)) { debuggeeRunProperties = "\"" + debuggeeRunProperties + "\""; } - final String _debuggeeRunProperties = debuggeeRunProperties; + String _debuggeeRunProperties = debuggeeRunProperties; Application.get().runReadAction(() -> { JavaSdkUtil.addRtJar(parameters.getClassPath()); - final Sdk jdk = parameters.getJdk(); - final boolean forceClassicVM = shouldForceClassicVM(jdk); - final boolean forceNoJIT = shouldForceNoJIT(jdk); - final String debugKey = Platform.current().jvm().getRuntimeProperty(DEBUG_KEY_NAME, "-Xdebug"); - final boolean needDebugKey = shouldAddXdebugKey(jdk) || !"-Xdebug".equals(debugKey) /*the key is non-standard*/; + Sdk jdk = parameters.getJdk(); + boolean forceClassicVM = shouldForceClassicVM(jdk); + boolean forceNoJIT = shouldForceNoJIT(jdk); + String debugKey = Platform.current().jvm().getRuntimeProperty(DEBUG_KEY_NAME, "-Xdebug"); + boolean needDebugKey = shouldAddXdebugKey(jdk) || !"-Xdebug".equals(debugKey) /*the key is non-standard*/; if (forceClassicVM || forceNoJIT || needDebugKey || !isJVMTIAvailable(jdk)) { parameters.getVMParametersList().replaceOrPrepend("-Xrunjdwp:", "-Xrunjdwp:" + _debuggeeRunProperties); @@ -487,8 +488,9 @@ private static boolean isJVMTIAvailable(Sdk jdk) { return true; } + @RequiredUIAccess public static RemoteConnection createDebugParameters( - final OwnJavaParameters parameters, + OwnJavaParameters parameters, GenericDebuggerRunnerSettings settings, boolean checkValidity ) throws ExecutionException { @@ -507,7 +509,7 @@ public DebuggerContextImpl getContext() { @Override @RequiredUIAccess public void setState( - @Nonnull final DebuggerContextImpl context, + @Nonnull DebuggerContextImpl context, DebuggerSession.State state, DebuggerSession.Event event, String description diff --git a/java-debugger-impl/src/main/java/com/intellij/java/debugger/impl/DebuggerSession.java b/java-debugger-impl/src/main/java/com/intellij/java/debugger/impl/DebuggerSession.java index a5c92c315e..215e8b5b7b 100644 --- a/java-debugger-impl/src/main/java/com/intellij/java/debugger/impl/DebuggerSession.java +++ b/java-debugger-impl/src/main/java/com/intellij/java/debugger/impl/DebuggerSession.java @@ -15,9 +15,9 @@ */ package com.intellij.java.debugger.impl; -import com.intellij.java.debugger.DebuggerBundle; import com.intellij.java.debugger.SourcePosition; import com.intellij.java.debugger.engine.DebugProcess; +import com.intellij.java.debugger.engine.DebuggerUtils; import com.intellij.java.debugger.engine.StackFrameContext; import com.intellij.java.debugger.engine.evaluation.EvaluateException; import com.intellij.java.debugger.engine.jdi.StackFrameProxy; @@ -30,6 +30,7 @@ import com.intellij.java.debugger.impl.ui.breakpoints.Breakpoint; import com.intellij.java.debugger.impl.ui.breakpoints.BreakpointWithHighlighter; import com.intellij.java.debugger.impl.ui.breakpoints.LineBreakpoint; +import com.intellij.java.debugger.localize.JavaDebuggerLocalize; import com.intellij.java.execution.configurations.RemoteConnection; import com.intellij.java.execution.configurations.RemoteState; import com.intellij.java.language.psi.PsiElementFinder; @@ -51,6 +52,7 @@ import consulo.language.psi.PsiCompiledElement; import consulo.language.psi.PsiFile; import consulo.language.psi.scope.GlobalSearchScope; +import consulo.localize.LocalizeValue; import consulo.logging.Logger; import consulo.platform.base.localize.ActionLocalize; import consulo.process.ExecutionException; @@ -181,12 +183,11 @@ public DebuggerContextImpl getContext() { */ @Override @RequiredUIAccess - public void setState(@Nonnull final DebuggerContextImpl context, final State state, final Event event, final String description) { + public void setState(@Nonnull DebuggerContextImpl context, State state, Event event, String description) { Application.get().assertIsDispatchThread(); - final DebuggerSession session = context.getDebuggerSession(); + DebuggerSession session = context.getDebuggerSession(); LOG.assertTrue(session == DebuggerSession.this || session == null); - final Runnable setStateRunnable = () -> - { + Runnable setStateRunnable = () -> { LOG.assertTrue(myDebuggerContext.isInitialised()); myDebuggerContext = context; if (LOG.isDebugEnabled()) { @@ -219,9 +220,10 @@ public void contextAction() throws Exception { } } + @RequiredUIAccess static DebuggerSession create( String sessionName, - @Nonnull final DebugProcessImpl debugProcess, + @Nonnull DebugProcessImpl debugProcess, DebugEnvironment environment ) throws ExecutionException { DebuggerSession session = new DebuggerSession(sessionName, debugProcess, environment); @@ -235,7 +237,7 @@ static DebuggerSession create( return session; } - private DebuggerSession(String sessionName, @Nonnull final DebugProcessImpl debugProcess, DebugEnvironment environment) { + private DebuggerSession(String sessionName, @Nonnull DebugProcessImpl debugProcess, DebugEnvironment environment) { mySessionName = sessionName; myDebugProcess = debugProcess; SESSION_EMPTY_CONTEXT = DebuggerContextImpl.createDebuggerContext(this, null, null, null); @@ -288,29 +290,29 @@ public String getStateDescription() { switch (myState.myState) { case STOPPED: - return DebuggerBundle.message("status.debug.stopped"); + return JavaDebuggerLocalize.statusDebugStopped().get(); case RUNNING: - return DebuggerBundle.message("status.app.running"); + return JavaDebuggerLocalize.statusAppRunning().get(); case WAITING_ATTACH: RemoteConnection connection = getProcess().getConnection(); - final String addressDisplayName = DebuggerBundle.getAddressDisplayName(connection); - final String transportName = DebuggerBundle.getTransportName(connection); + String addressDisplayName = DebuggerUtils.getAddressDisplayName(connection); + LocalizeValue transportName = DebuggerUtils.getTransportName(connection); return connection.isServerMode() - ? DebuggerBundle.message("status.listening", addressDisplayName, transportName) - : DebuggerBundle.message("status.connecting", addressDisplayName, transportName); + ? JavaDebuggerLocalize.statusListening(addressDisplayName, transportName).get() + : JavaDebuggerLocalize.statusConnecting(addressDisplayName, transportName).get(); case PAUSED: - return DebuggerBundle.message("status.paused"); + return JavaDebuggerLocalize.statusPaused().get(); case WAIT_EVALUATION: - return DebuggerBundle.message("status.waiting.evaluation.result"); + return JavaDebuggerLocalize.statusWaitingEvaluationResult().get(); case DISPOSED: - return DebuggerBundle.message("status.debug.stopped"); + return JavaDebuggerLocalize.statusDebugStopped().get(); } return null; } /* Stepping */ - private void resumeAction(final DebugProcessImpl.ResumeCommand command, Event event) { - getContextManager().setState(SESSION_EMPTY_CONTEXT, State.WAIT_EVALUATION, event, null); + private void resumeAction(DebugProcessImpl.ResumeCommand command, Event event) { + getContextManager().setState(SESSION_EMPTY_CONTEXT, State.WAIT_EVALUATION, event); myDebugProcess.getManagerThread().schedule(command); } @@ -359,8 +361,8 @@ public void stepOver(boolean ignoreBreakpoints) { } @RequiredUIAccess - public void stepInto(final boolean ignoreFilters, final @Nullable MethodFilter smartStepFilter, int stepSize) { - final SuspendContextImpl suspendContext = getSuspendContext(); + public void stepInto(boolean ignoreFilters, @Nullable MethodFilter smartStepFilter, int stepSize) { + SuspendContextImpl suspendContext = getSuspendContext(); DebugProcessImpl.ResumeCommand cmd = null; for (JvmSteppingCommandProvider handler : JvmSteppingCommandProvider.EP_NAME.getExtensions()) { cmd = handler.getStepIntoCommand(suspendContext, ignoreFilters, smartStepFilter, stepSize); @@ -376,12 +378,12 @@ public void stepInto(final boolean ignoreFilters, final @Nullable MethodFilter s } @RequiredUIAccess - public void stepInto(final boolean ignoreFilters, final @Nullable MethodFilter smartStepFilter) { + public void stepInto(boolean ignoreFilters, @Nullable MethodFilter smartStepFilter) { stepInto(ignoreFilters, smartStepFilter, StepRequest.STEP_LINE); } @RequiredUIAccess - public void runToCursor(@Nonnull XSourcePosition position, final boolean ignoreBreakpoints) { + public void runToCursor(@Nonnull XSourcePosition position, boolean ignoreBreakpoints) { try { DebugProcessImpl.ResumeCommand runToCursorCommand = myDebugProcess.createRunToCursorCommand(getSuspendContext(), position, ignoreBreakpoints); @@ -395,7 +397,7 @@ public void runToCursor(@Nonnull XSourcePosition position, final boolean ignoreB @RequiredUIAccess public void resume() { - final SuspendContextImpl suspendContext = getSuspendContext(); + SuspendContextImpl suspendContext = getSuspendContext(); if (suspendContext != null) { clearSteppingThrough(); resumeAction(myDebugProcess.createResumeCommand(suspendContext), Event.RESUME); @@ -424,26 +426,28 @@ public void pause() { @RequiredUIAccess public void showExecutionPoint() { getContextManager() - .setState(DebuggerContextUtil.createDebuggerContext(this, getSuspendContext()), State.PAUSED, Event.REFRESH, null); + .setState(DebuggerContextUtil.createDebuggerContext(this, getSuspendContext()), State.PAUSED, Event.REFRESH); } @RequiredUIAccess - public void refresh(final boolean refreshWithStack) { - final State state = getState(); + public void refresh(boolean refreshWithStack) { + State state = getState(); DebuggerContextImpl context = myContextManager.getContext(); DebuggerContextImpl newContext = DebuggerContextImpl.createDebuggerContext(this, context.getSuspendContext(), context.getThreadProxy(), context.getFrameProxy()); - myContextManager.setState(newContext, state, refreshWithStack ? Event.REFRESH_WITH_STACK : Event.REFRESH, null); + myContextManager.setState(newContext, state, refreshWithStack ? Event.REFRESH_WITH_STACK : Event.REFRESH); } public void dispose() { getProcess().dispose(); Disposer.dispose(myUpdateAlarm); - DebuggerInvocationUtil.swingInvokeLater(getProject(), () -> - { - myContextManager.setState(SESSION_EMPTY_CONTEXT, State.DISPOSED, Event.DISPOSE, null); - myContextManager.dispose(); - }); + DebuggerInvocationUtil.swingInvokeLater( + getProject(), + () -> { + myContextManager.setState(SESSION_EMPTY_CONTEXT, State.DISPOSED, Event.DISPOSE); + myContextManager.dispose(); + } + ); } // ManagerCommands @@ -480,16 +484,17 @@ private SuspendContextImpl getSuspendContext() { } @Nullable + @RequiredUIAccess private ExecutionResult attach(DebugEnvironment environment) throws ExecutionException { RemoteConnection remoteConnection = environment.getRemoteConnection(); - final String addressDisplayName = DebuggerBundle.getAddressDisplayName(remoteConnection); - final String transportName = DebuggerBundle.getTransportName(remoteConnection); - final ExecutionResult executionResult = myDebugProcess.attachVirtualMachine(environment, this); + String addressDisplayName = DebuggerUtils.getAddressDisplayName(remoteConnection); + LocalizeValue transportName = DebuggerUtils.getTransportName(remoteConnection); + ExecutionResult executionResult = myDebugProcess.attachVirtualMachine(environment, this); getContextManager().setState( SESSION_EMPTY_CONTEXT, State.WAITING_ATTACH, Event.START_WAIT_ATTACH, - DebuggerBundle.message("status.waiting.attach", addressDisplayName, transportName) + JavaDebuggerLocalize.statusWaitingAttach(addressDisplayName, transportName) ); return executionResult; } @@ -497,27 +502,34 @@ private ExecutionResult attach(DebugEnvironment environment) throws ExecutionExc private class MyDebugProcessListener extends DebugProcessAdapterImpl { private final DebugProcessImpl myDebugProcess; - public MyDebugProcessListener(final DebugProcessImpl debugProcess) { + public MyDebugProcessListener(DebugProcessImpl debugProcess) { myDebugProcess = debugProcess; } //executed in manager thread @Override public void connectorIsReady() { - DebuggerInvocationUtil.invokeLater(getProject(), () -> - { - RemoteConnection connection = myDebugProcess.getConnection(); - final String addressDisplayName = DebuggerBundle.getAddressDisplayName(connection); - final String transportName = DebuggerBundle.getTransportName(connection); - final String connectionStatusMessage = connection.isServerMode() - ? DebuggerBundle.message("status.listening", addressDisplayName, transportName) - : DebuggerBundle.message("status.connecting", addressDisplayName, transportName); - getContextManager().setState(SESSION_EMPTY_CONTEXT, State.WAITING_ATTACH, Event.START_WAIT_ATTACH, connectionStatusMessage); - }); + DebuggerInvocationUtil.invokeLater( + getProject(), + () -> { + RemoteConnection connection = myDebugProcess.getConnection(); + String addressDisplayName = DebuggerUtils.getAddressDisplayName(connection); + LocalizeValue transportName = DebuggerUtils.getTransportName(connection); + LocalizeValue connectionStatusMessage = connection.isServerMode() + ? JavaDebuggerLocalize.statusListening(addressDisplayName, transportName) + : JavaDebuggerLocalize.statusConnecting(addressDisplayName, transportName); + getContextManager().setState( + SESSION_EMPTY_CONTEXT, + State.WAITING_ATTACH, + Event.START_WAIT_ATTACH, + connectionStatusMessage + ); + } + ); } @Override - public void paused(final SuspendContextImpl suspendContext) { + public void paused(SuspendContextImpl suspendContext) { LOG.debug("paused"); ThreadReferenceProxyImpl currentThread = suspendContext.getThread(); @@ -533,8 +545,8 @@ public void paused(final SuspendContextImpl suspendContext) { DebuggerUtilsEx.getEventDescriptors(suspendContext); if (!descriptors.isEmpty()) { XDebuggerUIConstants.NOTIFICATION_GROUP.createNotification( - DebuggerBundle.message("status.breakpoint.reached.in.thread", thread.name()), - DebuggerBundle.message("status.breakpoint.reached.in.thread.switch"), + JavaDebuggerLocalize.statusBreakpointReachedInThread(thread.name()).get(), + JavaDebuggerLocalize.statusBreakpointReachedInThreadSwitch().get(), NotificationType.INFORMATION, (notification, event) -> { if (event.getEventType() == HyperlinkEvent.EventType.ACTIVATED) { @@ -542,11 +554,13 @@ public void paused(final SuspendContextImpl suspendContext) { getProcess().getManagerThread().schedule(new SuspendContextCommandImpl(suspendContext) { @Override public void contextAction() throws Exception { - final DebuggerContextImpl debuggerContext = + DebuggerContextImpl debuggerContext = DebuggerContextUtil.createDebuggerContext(DebuggerSession.this, suspendContext); - DebuggerInvocationUtil.invokeLater(getProject(), () -> getContextManager() - .setState(debuggerContext, State.PAUSED, Event.PAUSE, null)); + DebuggerInvocationUtil.invokeLater( + getProject(), + () -> getContextManager().setState(debuggerContext, State.PAUSED, Event.PAUSE) + ); } }); } @@ -565,7 +579,7 @@ public void contextAction() throws Exception { setSteppingThrough(currentThread); } - final StackFrameContext positionContext; + StackFrameContext positionContext; if (currentThread == null) { //Pause pressed @@ -577,9 +591,9 @@ public void contextAction() throws Exception { } if (currentThread == null) { - final Collection allThreads = getProcess().getVirtualMachineProxy().allThreads(); + Collection allThreads = getProcess().getVirtualMachineProxy().allThreads(); // heuristics: try to pre-select EventDispatchThread - for (final ThreadReferenceProxyImpl thread : allThreads) { + for (ThreadReferenceProxyImpl thread : allThreads) { if (ThreadState.isEDT(thread.name())) { currentThread = thread; break; @@ -587,7 +601,7 @@ public void contextAction() throws Exception { } if (currentThread == null) { // heuristics: display the first thread with RUNNABLE status - for (final ThreadReferenceProxyImpl thread : allThreads) { + for (ThreadReferenceProxyImpl thread : allThreads) { currentThread = thread; if (currentThread.status() == ThreadReference.THREAD_STATUS_RUNNING) { break; @@ -622,7 +636,7 @@ public void contextAction() throws Exception { if (currentThread != null) { try { - final int frameCount = currentThread.frameCount(); + int frameCount = currentThread.frameCount(); if (frameCount == 0 || (frameCount <= myIgnoreFiltersFrameCountThreshold)) { resetIgnoreStepFiltersFlag(); } @@ -636,24 +650,24 @@ public void contextAction() throws Exception { SourcePosition position = ContextUtil.getSourcePosition(positionContext); if (position != null) { - final List> eventDescriptors = + List> eventDescriptors = DebuggerUtilsEx.getEventDescriptors(suspendContext); - final RequestManagerImpl requestsManager = suspendContext.getDebugProcess().getRequestsManager(); - final PsiFile foundFile = position.getFile(); - final boolean sourceMissing = foundFile instanceof PsiCompiledElement; + RequestManagerImpl requestsManager = suspendContext.getDebugProcess().getRequestsManager(); + PsiFile foundFile = position.getFile(); + boolean sourceMissing = foundFile instanceof PsiCompiledElement; for (Pair eventDescriptor : eventDescriptors) { Breakpoint breakpoint = eventDescriptor.getFirst(); if (breakpoint instanceof LineBreakpoint) { - final SourcePosition breakpointPosition = ((BreakpointWithHighlighter)breakpoint).getSourcePosition(); + SourcePosition breakpointPosition = ((BreakpointWithHighlighter)breakpoint).getSourcePosition(); if (breakpointPosition == null || (!sourceMissing && breakpointPosition.getLine() != position.getLine())) { requestsManager.deleteRequest(breakpoint); - requestsManager.setInvalid(breakpoint, DebuggerBundle.message("error.invalid.breakpoint.source.changed")); + requestsManager.setInvalid(breakpoint, JavaDebuggerLocalize.errorInvalidBreakpointSourceChanged().get()); breakpoint.updateUI(); } else if (sourceMissing) { // adjust position to be position of the breakpoint in order to show the real originator of the event position = breakpointPosition; - final StackFrameProxy frameProxy = positionContext.getFrameProxy(); + StackFrameProxy frameProxy = positionContext.getFrameProxy(); String className; try { className = frameProxy != null ? frameProxy.location().declaringType().name() : ""; @@ -663,7 +677,7 @@ else if (sourceMissing) { } requestsManager.setInvalid( breakpoint, - DebuggerBundle.message("error.invalid.breakpoint.source.not.found", className) + JavaDebuggerLocalize.errorInvalidBreakpointSourceNotFound(className).get() ); breakpoint.updateUI(); } @@ -671,7 +685,7 @@ else if (sourceMissing) { } } - final DebuggerContextImpl debuggerContext = + DebuggerContextImpl debuggerContext = DebuggerContextImpl.createDebuggerContext(DebuggerSession.this, suspendContext, currentThread, null); if (suspendContext.getThread() == currentThread) { debuggerContext.setPositionCache(position); @@ -683,17 +697,17 @@ else if (sourceMissing) { ); } - private boolean shouldSetAsActiveContext(final SuspendContextImpl suspendContext) { - final ThreadReferenceProxyImpl newThread = suspendContext.getThread(); + private boolean shouldSetAsActiveContext(SuspendContextImpl suspendContext) { + ThreadReferenceProxyImpl newThread = suspendContext.getThread(); if (newThread == null || suspendContext.getSuspendPolicy() == EventRequest.SUSPEND_ALL || isSteppingThrough(newThread)) { return true; } - final SuspendContextImpl currentSuspendContext = getContextManager().getContext().getSuspendContext(); + SuspendContextImpl currentSuspendContext = getContextManager().getContext().getSuspendContext(); if (currentSuspendContext == null) { return mySteppingThroughThread.get() == null; } if (enableBreakpointsDuringEvaluation()) { - final ThreadReferenceProxyImpl currentThread = currentSuspendContext.getThread(); + ThreadReferenceProxyImpl currentThread = currentSuspendContext.getThread(); return currentThread == null || Comparing.equal(currentThread.getThreadReference(), newThread.getThreadReference()); } return false; @@ -709,13 +723,13 @@ public void resumed(SuspendContextImpl suspendContext) { suspendContext.getThread())) { steppingThread = suspendContext.getThread(); } - final DebuggerContextImpl debuggerContext = context != null + DebuggerContextImpl debuggerContext = context != null ? DebuggerContextImpl.createDebuggerContext( - DebuggerSession.this, - context, - steppingThread != null ? steppingThread : context.getThread(), - null - ) + DebuggerSession.this, + context, + steppingThread != null ? steppingThread : context.getThread(), + null + ) : null; DebuggerInvocationUtil.invokeLater( @@ -725,18 +739,18 @@ public void resumed(SuspendContextImpl suspendContext) { getContextManager().setState(debuggerContext, State.PAUSED, Event.CONTEXT, getDescription(debuggerContext)); } else { - getContextManager().setState(SESSION_EMPTY_CONTEXT, State.RUNNING, Event.CONTEXT, null); + getContextManager().setState(SESSION_EMPTY_CONTEXT, State.RUNNING, Event.CONTEXT); } } ); } @Override - public void processAttached(final DebugProcessImpl process) { - final RemoteConnection connection = getProcess().getConnection(); - final String addressDisplayName = DebuggerBundle.getAddressDisplayName(connection); - final String transportName = DebuggerBundle.getTransportName(connection); - final String message = DebuggerBundle.message("status.connected", addressDisplayName, transportName); + public void processAttached(DebugProcessImpl process) { + RemoteConnection connection = getProcess().getConnection(); + String addressDisplayName = DebuggerUtils.getAddressDisplayName(connection); + LocalizeValue transportName = DebuggerUtils.getTransportName(connection); + LocalizeValue message = JavaDebuggerLocalize.statusConnected(addressDisplayName, transportName); process.printToConsole(message + "\n"); DebuggerInvocationUtil.invokeLater( @@ -746,17 +760,16 @@ public void processAttached(final DebugProcessImpl process) { } @Override - public void attachException(final RunProfileState state, final ExecutionException exception, final RemoteConnection remoteConnection) { + public void attachException(RunProfileState state, ExecutionException exception, RemoteConnection remoteConnection) { DebuggerInvocationUtil.invokeLater( getProject(), () -> { String message = ""; if (state instanceof RemoteState) { - message = DebuggerBundle.message( - "status.connect.failed", - DebuggerBundle.getAddressDisplayName(remoteConnection), - DebuggerBundle.getTransportName(remoteConnection) - ); + message = JavaDebuggerLocalize.statusConnectFailed( + DebuggerUtils.getAddressDisplayName(remoteConnection), + DebuggerUtils.getTransportName(remoteConnection) + ).get(); } message += exception.getMessage(); getContextManager().setState(SESSION_EMPTY_CONTEXT, State.STOPPED, Event.DETACHED, message); @@ -765,31 +778,33 @@ public void attachException(final RunProfileState state, final ExecutionExceptio } @Override - public void processDetached(final DebugProcessImpl debugProcess, boolean closedByUser) { + public void processDetached(DebugProcessImpl debugProcess, boolean closedByUser) { if (!closedByUser) { ProcessHandler processHandler = debugProcess.getProcessHandler(); if (processHandler != null) { - final RemoteConnection connection = getProcess().getConnection(); - final String addressDisplayName = DebuggerBundle.getAddressDisplayName(connection); - final String transportName = DebuggerBundle.getTransportName(connection); + RemoteConnection connection = getProcess().getConnection(); + String addressDisplayName = DebuggerUtils.getAddressDisplayName(connection); + LocalizeValue transportName = DebuggerUtils.getTransportName(connection); processHandler.notifyTextAvailable( - DebuggerBundle.message("status.disconnected", addressDisplayName, transportName) + "\n", + JavaDebuggerLocalize.statusDisconnected(addressDisplayName, transportName) + "\n", ProcessOutputTypes.SYSTEM ); } } - DebuggerInvocationUtil.invokeLater(getProject(), () -> - { - final RemoteConnection connection = getProcess().getConnection(); - final String addressDisplayName = DebuggerBundle.getAddressDisplayName(connection); - final String transportName = DebuggerBundle.getTransportName(connection); - getContextManager().setState( - SESSION_EMPTY_CONTEXT, - State.STOPPED, - Event.DETACHED, - DebuggerBundle.message("status.disconnected", addressDisplayName, transportName) - ); - }); + DebuggerInvocationUtil.invokeLater( + getProject(), + () -> { + RemoteConnection connection = getProcess().getConnection(); + String addressDisplayName = DebuggerUtils.getAddressDisplayName(connection); + LocalizeValue transportName = DebuggerUtils.getTransportName(connection); + getContextManager().setState( + SESSION_EMPTY_CONTEXT, + State.STOPPED, + Event.DETACHED, + JavaDebuggerLocalize.statusDisconnected(addressDisplayName, transportName).get() + ); + } + ); clearSteppingThrough(); } @@ -814,11 +829,14 @@ public void threadStopped(DebugProcess proc, ThreadReference thread) { private void notifyThreadsRefresh() { if (!myUpdateAlarm.isDisposed()) { myUpdateAlarm.cancelAllRequests(); - myUpdateAlarm.addRequest(() -> - { - final DebuggerStateManager contextManager = getContextManager(); - contextManager.fireStateChanged(contextManager.getContext(), Event.THREADS_REFRESH); - }, 100, Application.get().getNoneModalityState()); + myUpdateAlarm.addRequest( + () -> { + DebuggerStateManager contextManager = getContextManager(); + contextManager.fireStateChanged(contextManager.getContext(), Event.THREADS_REFRESH); + }, + 100, + Application.get().getNoneModalityState() + ); } } } @@ -826,7 +844,7 @@ private void notifyThreadsRefresh() { private static String getDescription(DebuggerContextImpl debuggerContext) { SuspendContextImpl suspendContext = debuggerContext.getSuspendContext(); if (suspendContext != null && debuggerContext.getThreadProxy() != suspendContext.getThread()) { - return DebuggerBundle.message("status.paused.in.another.thread"); + return JavaDebuggerLocalize.statusPausedInAnotherThread().get(); } return null; } @@ -838,7 +856,7 @@ public void evaluationStarted(SuspendContextImpl context) { } @Override - public void evaluationFinished(final SuspendContextImpl context) { + public void evaluationFinished(SuspendContextImpl context) { myIsEvaluating = false; //seems to be not required after move to xdebugger //DebuggerInvocationUtil.invokeLater( diff --git a/java-debugger-impl/src/main/java/com/intellij/java/debugger/impl/DebuggerStateManager.java b/java-debugger-impl/src/main/java/com/intellij/java/debugger/impl/DebuggerStateManager.java index a968526faf..9284c4b491 100644 --- a/java-debugger-impl/src/main/java/com/intellij/java/debugger/impl/DebuggerStateManager.java +++ b/java-debugger-impl/src/main/java/com/intellij/java/debugger/impl/DebuggerStateManager.java @@ -15,37 +15,58 @@ */ package com.intellij.java.debugger.impl; +import consulo.annotation.DeprecationInfo; +import consulo.localize.LocalizeValue; import consulo.proxy.EventDispatcher; import jakarta.annotation.Nonnull; -public abstract class DebuggerStateManager -{ - private final EventDispatcher myEventDispatcher = EventDispatcher.create(DebuggerContextListener.class); +public abstract class DebuggerStateManager { + private final EventDispatcher myEventDispatcher = EventDispatcher.create(DebuggerContextListener.class); - @Nonnull - public abstract DebuggerContextImpl getContext(); + @Nonnull + public abstract DebuggerContextImpl getContext(); - public abstract void setState(@Nonnull DebuggerContextImpl context, DebuggerSession.State state, DebuggerSession.Event event, String description); + public void setState( + @Nonnull DebuggerContextImpl context, + DebuggerSession.State state, + DebuggerSession.Event event, + @Nonnull LocalizeValue description + ) { + setState(context, state, event, description.get()); + } - //we allow add listeners inside DebuggerContextListener.changeEvent - public void addListener(DebuggerContextListener listener) - { - myEventDispatcher.addListener(listener); - } + public void setState( + @Nonnull DebuggerContextImpl context, + DebuggerSession.State state, + DebuggerSession.Event event + ) { + setState(context, state, event, (String)null); + } - //we allow remove listeners inside DebuggerContextListener.changeEvent - public void removeListener(DebuggerContextListener listener) - { - myEventDispatcher.removeListener(listener); - } + @Deprecated + @DeprecationInfo("Use variant with LocalizeValue") + public abstract void setState( + @Nonnull DebuggerContextImpl context, + DebuggerSession.State state, + DebuggerSession.Event event, + String description + ); - protected void fireStateChanged(@Nonnull DebuggerContextImpl newContext, DebuggerSession.Event event) - { - myEventDispatcher.getMulticaster().changeEvent(newContext, event); - } + //we allow add listeners inside DebuggerContextListener.changeEvent + public void addListener(DebuggerContextListener listener) { + myEventDispatcher.addListener(listener); + } - void dispose() - { - myEventDispatcher.getListeners().clear(); - } + //we allow remove listeners inside DebuggerContextListener.changeEvent + public void removeListener(DebuggerContextListener listener) { + myEventDispatcher.removeListener(listener); + } + + protected void fireStateChanged(@Nonnull DebuggerContextImpl newContext, DebuggerSession.Event event) { + myEventDispatcher.getMulticaster().changeEvent(newContext, event); + } + + void dispose() { + myEventDispatcher.getListeners().clear(); + } } diff --git a/java-debugger-impl/src/main/java/com/intellij/java/debugger/impl/engine/DebugProcessEvents.java b/java-debugger-impl/src/main/java/com/intellij/java/debugger/impl/engine/DebugProcessEvents.java index e3428e763c..a99ee4c53a 100644 --- a/java-debugger-impl/src/main/java/com/intellij/java/debugger/impl/engine/DebugProcessEvents.java +++ b/java-debugger-impl/src/main/java/com/intellij/java/debugger/impl/engine/DebugProcessEvents.java @@ -15,9 +15,9 @@ */ package com.intellij.java.debugger.impl.engine; -import com.intellij.java.debugger.DebuggerBundle; import com.intellij.java.debugger.DebuggerManager; import com.intellij.java.debugger.PositionManagerFactory; +import com.intellij.java.debugger.engine.DebuggerUtils; import com.intellij.java.debugger.impl.DebuggerInvocationUtil; import com.intellij.java.debugger.impl.DebuggerManagerEx; import com.intellij.java.debugger.impl.DebuggerManagerImpl; @@ -31,9 +31,9 @@ import com.intellij.java.debugger.impl.settings.DebuggerSettings; import com.intellij.java.debugger.impl.ui.breakpoints.Breakpoint; import com.intellij.java.debugger.impl.ui.breakpoints.StackCapturingLineBreakpoint; +import com.intellij.java.debugger.localize.JavaDebuggerLocalize; import com.intellij.java.debugger.requests.Requestor; import com.intellij.java.execution.configurations.RemoteConnection; -import consulo.application.Application; import consulo.component.ProcessCanceledException; import consulo.execution.debug.XDebugSession; import consulo.execution.debug.breakpoint.XBreakpoint; @@ -47,12 +47,15 @@ import consulo.internal.com.sun.jdi.request.EventRequestManager; import consulo.internal.com.sun.jdi.request.ThreadDeathRequest; import consulo.internal.com.sun.jdi.request.ThreadStartRequest; +import consulo.localize.LocalizeValue; import consulo.logging.Logger; import consulo.project.Project; import consulo.project.ui.notification.NotificationType; +import consulo.ui.UIAccess; +import consulo.ui.annotation.RequiredUIAccess; import consulo.ui.ex.awt.Messages; import consulo.ui.ex.awt.UIUtil; -import consulo.util.lang.Pair; +import jakarta.annotation.Nonnull; import jakarta.annotation.Nullable; import java.util.Objects; @@ -71,51 +74,46 @@ public DebugProcessEvents(Project project) { } @Override - protected void commitVM(final VirtualMachine vm) { + @RequiredUIAccess + protected void commitVM(VirtualMachine vm) { super.commitVM(vm); if (vm != null) { vmAttached(); myEventThread = new DebuggerEventThread(); - Application.get().executeOnPooledThread(myEventThread); + UIAccess.assertIsUIThread(); } } private static void showStatusText(DebugProcessEvents debugProcess, Event event) { Requestor requestor = debugProcess.getRequestsManager().findRequestor(event.request()); - Breakpoint breakpoint = null; - if (requestor instanceof Breakpoint requestorBreakpoint) { - breakpoint = requestorBreakpoint; - } - String text = debugProcess.getEventText(Pair.create(breakpoint, event)); + Breakpoint breakpoint = requestor instanceof Breakpoint requestorBreakpoint ? requestorBreakpoint : null; + LocalizeValue text = debugProcess.getEventText(breakpoint, event); debugProcess.showStatusText(text); } - public String getEventText(Pair descriptor) { - String text = ""; - final Event event = descriptor.getSecond(); - final Breakpoint breakpoint = descriptor.getFirst(); - if (event instanceof LocatableEvent locatableEvent) { - try { - text = breakpoint != null ? breakpoint.getEventMessage(locatableEvent) - : DebuggerBundle.message("status.generic.breakpoint.reached"); + @Nonnull + public LocalizeValue getEventText(Breakpoint breakpoint, Event event) { + return switch (event) { + case LocatableEvent locatableEvent -> { + try { + yield breakpoint != null + ? LocalizeValue.ofNullable(breakpoint.getEventMessage(locatableEvent)) + : JavaDebuggerLocalize.statusGenericBreakpointReached(); + } + catch (InternalException e) { + yield JavaDebuggerLocalize.statusGenericBreakpointReached(); + } } - catch (InternalException e) { - text = DebuggerBundle.message("status.generic.breakpoint.reached"); + case VMStartEvent startEvent -> JavaDebuggerLocalize.statusProcessStarted(); + case VMDeathEvent deathEvent -> JavaDebuggerLocalize.statusProcessTerminated(); + case VMDisconnectEvent disconnectEvent -> { + RemoteConnection connection = getConnection(); + String addressDisplayName = DebuggerUtils.getAddressDisplayName(connection); + LocalizeValue transportName = DebuggerUtils.getTransportName(connection); + yield JavaDebuggerLocalize.statusDisconnected(addressDisplayName, transportName); } - } - else if (event instanceof VMStartEvent) { - text = DebuggerBundle.message("status.process.started"); - } - else if (event instanceof VMDeathEvent) { - text = DebuggerBundle.message("status.process.terminated"); - } - else if (event instanceof VMDisconnectEvent) { - final RemoteConnection connection = getConnection(); - final String addressDisplayName = DebuggerBundle.getAddressDisplayName(connection); - final String transportName = DebuggerBundle.getTransportName(connection); - text = DebuggerBundle.message("status.disconnected", addressDisplayName, transportName); - } - return text; + default -> LocalizeValue.empty(); + }; } private class DebuggerEventThread implements Runnable { @@ -144,7 +142,7 @@ public void run() { EventQueue eventQueue = myVmProxy.eventQueue(); while (!isStopped()) { try { - final EventSet eventSet = eventQueue.remove(); + EventSet eventSet = eventQueue.remove(); getManagerThread().invokeAndWait(new DebuggerCommandImpl() { @Override @@ -205,8 +203,10 @@ else if (event instanceof ThreadDeathEvent threadDeathEvent) { if (isResumeOnlyCurrentThread() && locatableEvent != null) { for (SuspendContextImpl context : getSuspendManager().getEventContexts()) { - ThreadReferenceProxyImpl threadProxy = getVirtualMachineProxy().getThreadReferenceProxy(locatableEvent.thread()); - if (context.getSuspendPolicy() == EventRequest.SUSPEND_ALL && context.isExplicitlyResumed(threadProxy)) { + ThreadReferenceProxyImpl threadProxy = + getVirtualMachineProxy().getThreadReferenceProxy(locatableEvent.thread()); + if (context.getSuspendPolicy() == EventRequest.SUSPEND_ALL && context.isExplicitlyResumed( + threadProxy)) { context.myResumedThreads.remove(threadProxy); suspendContext = context; suspendContext.myVotesToVote = eventSet.size(); @@ -300,7 +300,7 @@ private static void preprocessEvent(SuspendContextImpl suspendContext, ThreadRef } } - private void processVMStartEvent(final SuspendContextImpl suspendContext, VMStartEvent event) { + private void processVMStartEvent(SuspendContextImpl suspendContext, VMStartEvent event) { preprocessEvent(suspendContext, event.thread()); LOG.debug("enter: processVMStartEvent()"); @@ -314,44 +314,46 @@ private void vmAttached() { DebuggerManagerThreadImpl.assertIsManagerThread(); LOG.assertTrue(!isAttached()); if (myState.compareAndSet(State.INITIAL, State.ATTACHED)) { - final VirtualMachineProxyImpl machineProxy = getVirtualMachineProxy(); - final EventRequestManager requestManager = machineProxy.eventRequestManager(); + VirtualMachineProxyImpl machineProxy = getVirtualMachineProxy(); + EventRequestManager requestManager = machineProxy.eventRequestManager(); if (machineProxy.canGetMethodReturnValues()) { myReturnValueWatcher = new MethodReturnValueWatcher(requestManager); } - final ThreadStartRequest threadStartRequest = requestManager.createThreadStartRequest(); + ThreadStartRequest threadStartRequest = requestManager.createThreadStartRequest(); threadStartRequest.setSuspendPolicy(EventRequest.SUSPEND_NONE); threadStartRequest.enable(); - final ThreadDeathRequest threadDeathRequest = requestManager.createThreadDeathRequest(); + ThreadDeathRequest threadDeathRequest = requestManager.createThreadDeathRequest(); threadDeathRequest.setSuspendPolicy(EventRequest.SUSPEND_NONE); threadDeathRequest.enable(); // fill position managers - ((DebuggerManagerImpl) DebuggerManager.getInstance(getProject())).getCustomPositionManagerFactories() + ((DebuggerManagerImpl)DebuggerManager.getInstance(getProject())).getCustomPositionManagerFactories() .map(factory -> factory.apply(this)) .filter(Objects::nonNull) .forEach(this::appendPositionManager); - PositionManagerFactory.EP_NAME.getExtensionList(getProject()).stream().map(factory -> factory.createPositionManager - (this)).filter(Objects::nonNull).forEach - (this::appendPositionManager); + PositionManagerFactory.EP_NAME.getExtensionList(getProject()) + .stream() + .map(factory -> factory.createPositionManager(this)) + .filter(Objects::nonNull) + .forEach(this::appendPositionManager); myDebugProcessDispatcher.getMulticaster().processAttached(this); createStackCapturingBreakpoints(); // breakpoints should be initialized after all processAttached listeners work - Application.get().runReadAction(() -> { + getProject().getApplication().runReadAction(() -> { XDebugSession session = getSession().getXDebugSession(); if (session != null) { session.initBreakpoints(); } }); - final String addressDisplayName = DebuggerBundle.getAddressDisplayName(getConnection()); - final String transportName = DebuggerBundle.getTransportName(getConnection()); - showStatusText(DebuggerBundle.message("status.connected", addressDisplayName, transportName)); + String addressDisplayName = DebuggerUtils.getAddressDisplayName(getConnection()); + LocalizeValue transportName = DebuggerUtils.getTransportName(getConnection()); + showStatusText(JavaDebuggerLocalize.statusConnected(addressDisplayName, transportName)); LOG.debug("leave: processVMStartEvent()"); XDebugSession session = getSession().getXDebugSession(); @@ -404,26 +406,26 @@ private void processClassPrepareEvent(SuspendContextImpl suspendContext, ClassPr } private void processStepEvent(SuspendContextImpl suspendContext, StepEvent event) { - final ThreadReference thread = event.thread(); + ThreadReference thread = event.thread(); //LOG.assertTrue(thread.isSuspended()); preprocessEvent(suspendContext, thread); //noinspection HardCodedStringLiteral - RequestHint hint = (RequestHint) event.request().getProperty("hint"); + RequestHint hint = (RequestHint)event.request().getProperty("hint"); deleteStepRequests(event.thread()); boolean shouldResume = false; - final Project project = getProject(); + Project project = getProject(); if (hint != null) { - final int nextStepDepth = hint.getNextStepDepth(suspendContext); + int nextStepDepth = hint.getNextStepDepth(suspendContext); if (nextStepDepth == RequestHint.RESUME) { getSession().clearSteppingThrough(); shouldResume = true; } else if (nextStepDepth != RequestHint.STOP) { - final ThreadReferenceProxyImpl threadProxy = suspendContext.getThread(); + ThreadReferenceProxyImpl threadProxy = suspendContext.getThread(); doStep(suspendContext, threadProxy, hint.getSize(), nextStepDepth, hint); shouldResume = true; } @@ -437,15 +439,15 @@ else if (nextStepDepth != RequestHint.STOP) { getSuspendManager().voteResume(suspendContext); } else { - showStatusText(""); + showStatusText(LocalizeValue.empty()); if (myReturnValueWatcher != null) { myReturnValueWatcher.disable(); } getSuspendManager().voteSuspend(suspendContext); if (hint != null) { - final MethodFilter methodFilter = hint.getMethodFilter(); + MethodFilter methodFilter = hint.getMethodFilter(); if (methodFilter instanceof NamedMethodFilter namedMethodFilter && !hint.wasStepTargetMethodMatched()) { - final String message = "Method " + namedMethodFilter.getMethodName() + "() has not been called"; + String message = "Method " + namedMethodFilter.getMethodName() + "() has not been called"; XDebuggerUIConstants.NOTIFICATION_GROUP.createNotification(message, NotificationType.INFORMATION).notify(project); } if (hint.wasStepTargetMethodMatched() && hint.isResetIgnoreFilters()) { @@ -455,7 +457,7 @@ else if (nextStepDepth != RequestHint.STOP) { } } - private void processLocatableEvent(final SuspendContextImpl suspendContext, final LocatableEvent event) { + private void processLocatableEvent(SuspendContextImpl suspendContext, LocatableEvent event) { ThreadReference thread = event.thread(); //LOG.assertTrue(thread.isSuspended()); preprocessEvent(suspendContext, thread); @@ -465,7 +467,7 @@ private void processLocatableEvent(final SuspendContextImpl suspendContext, fina getManagerThread().schedule(new SuspendContextCommandImpl(suspendContext) { @Override public void contextAction() throws Exception { - final SuspendManager suspendManager = getSuspendManager(); + SuspendManager suspendManager = getSuspendManager(); SuspendContextImpl evaluatingContext = SuspendManagerUtil.getEvaluatingContext(suspendManager, suspendContext.getThread()); if (evaluatingContext != null && !DebuggerSession.enableBreakpointsDuringEvaluation()) { @@ -475,33 +477,39 @@ public void contextAction() throws Exception { return; } - final LocatableEventRequestor requestor = (LocatableEventRequestor) getRequestsManager().findRequestor(event.request()); + LocatableEventRequestor requestor = (LocatableEventRequestor)getRequestsManager().findRequestor(event.request()); boolean resumePreferred = requestor != null && DebuggerSettings.SUSPEND_NONE.equals(requestor.getSuspendPolicy()); boolean requestHit; try { requestHit = (requestor != null) && requestor.processLocatableEvent(this, event); } - catch (final LocatableEventRequestor.EventProcessingException ex) { + catch (LocatableEventRequestor.EventProcessingException ex) { if (LOG.isDebugEnabled()) { LOG.debug(ex.getMessage()); } - final boolean[] considerRequestHit = new boolean[]{true}; - DebuggerInvocationUtil.invokeAndWait(getProject(), () -> - { - final String displayName = - requestor instanceof Breakpoint breakpoint ? breakpoint.getDisplayName() : requestor.getClass().getSimpleName(); - final String message = DebuggerBundle.message("error.evaluating.breakpoint.condition.or.action", displayName, ex.getMessage()); - considerRequestHit[0] = - Messages.showYesNoDialog(getProject(), message, ex.getTitle(), UIUtil.getQuestionIcon()) == Messages.YES; - }, Application.get().getNoneModalityState()); + boolean[] considerRequestHit = new boolean[]{true}; + DebuggerInvocationUtil.invokeAndWait( + getProject(), + () -> { + String displayName = requestor instanceof Breakpoint breakpoint + ? breakpoint.getDisplayName() + : requestor.getClass().getSimpleName(); + LocalizeValue message = + JavaDebuggerLocalize.errorEvaluatingBreakpointConditionOrAction(displayName, ex.getMessage()); + //noinspection RequiredXAction + considerRequestHit[0] = + Messages.showYesNoDialog(getProject(), message.get(), ex.getTitle(), UIUtil.getQuestionIcon()) == Messages.YES; + }, + getProject().getApplication().getNoneModalityState() + ); requestHit = considerRequestHit[0]; resumePreferred = !requestHit; } if (requestHit && requestor instanceof Breakpoint requestorBreakpoint) { // if requestor is a breakpoint and this breakpoint was hit, no matter its suspend policy - Application.get().runReadAction(() -> { + getProject().getApplication().runReadAction(() -> { XDebugSession session = getSession().getXDebugSession(); if (session != null) { XBreakpoint breakpoint = requestorBreakpoint.getXBreakpoint(); @@ -535,14 +543,14 @@ public void contextAction() throws Exception { private void notifySkippedBreakpoints(LocatableEvent event) { XDebuggerUIConstants.NOTIFICATION_GROUP.createNotification( - DebuggerBundle.message("message.breakpoint.skipped", event.location()), + JavaDebuggerLocalize.messageBreakpointSkipped(event.location()).get(), NotificationType.INFORMATION ).notify(getProject()); } @Nullable private static LocatableEvent getLocatableEvent(EventSet eventSet) { - return (LocatableEvent) eventSet.stream().filter(event -> event instanceof LocatableEvent).findFirst().orElse(null); + return (LocatableEvent)eventSet.stream().filter(event -> event instanceof LocatableEvent).findFirst().orElse(null); } private void processDefaultEvent(SuspendContextImpl suspendContext) { diff --git a/java-debugger-impl/src/main/java/com/intellij/java/debugger/impl/engine/DebugProcessImpl.java b/java-debugger-impl/src/main/java/com/intellij/java/debugger/impl/engine/DebugProcessImpl.java index 061dd4e5dc..27bfcc0114 100644 --- a/java-debugger-impl/src/main/java/com/intellij/java/debugger/impl/engine/DebugProcessImpl.java +++ b/java-debugger-impl/src/main/java/com/intellij/java/debugger/impl/engine/DebugProcessImpl.java @@ -15,7 +15,6 @@ */ package com.intellij.java.debugger.impl.engine; -import com.intellij.java.debugger.DebuggerBundle; import com.intellij.java.debugger.PositionManager; import com.intellij.java.debugger.engine.DebugProcess; import com.intellij.java.debugger.engine.DebugProcessListener; @@ -49,12 +48,12 @@ import com.intellij.java.debugger.impl.ui.tree.render.ClassRenderer; import com.intellij.java.debugger.impl.ui.tree.render.NodeRenderer; import com.intellij.java.debugger.impl.ui.tree.render.PrimitiveRenderer; +import com.intellij.java.debugger.localize.JavaDebuggerLocalize; import com.intellij.java.debugger.ui.classFilter.ClassFilter; import com.intellij.java.debugger.ui.classFilter.DebuggerClassFilterProvider; import com.intellij.java.execution.configurations.RemoteConnection; import com.intellij.java.language.projectRoots.JavaSdkType; import consulo.annotation.access.RequiredReadAction; -import consulo.application.util.Patches; import consulo.application.util.Semaphore; import consulo.content.bundle.Sdk; import consulo.disposer.Disposable; @@ -76,6 +75,7 @@ import consulo.language.psi.PsiFile; import consulo.language.psi.PsiManager; import consulo.language.psi.scope.GlobalSearchScope; +import consulo.localize.LocalizeValue; import consulo.logging.Logger; import consulo.platform.Platform; import consulo.platform.base.localize.ActionLocalize; @@ -103,7 +103,6 @@ import jakarta.annotation.Nonnull; import jakarta.annotation.Nullable; import org.intellij.lang.annotations.MagicConstant; -import org.jetbrains.annotations.NonNls; import java.io.IOException; import java.net.UnknownHostException; @@ -116,13 +115,9 @@ public abstract class DebugProcessImpl extends UserDataHolderBase implements DebugProcess { private static final Logger LOG = Logger.getInstance(DebugProcessImpl.class); - @NonNls private static final String SOCKET_ATTACHING_CONNECTOR_NAME = "consulo.internal.com.sun.jdi.SocketAttach"; - @NonNls private static final String SHMEM_ATTACHING_CONNECTOR_NAME = "consulo.internal.com.sun.jdi.SharedMemoryAttach"; - @NonNls private static final String SOCKET_LISTENING_CONNECTOR_NAME = "consulo.internal.com.sun.jdi.SocketListen"; - @NonNls private static final String SHMEM_LISTENING_CONNECTOR_NAME = "consulo.internal.com.sun.jdi.SharedMemoryListen"; private final Project myProject; @@ -205,9 +200,8 @@ protected void action() throws Exception { finally { DebuggerInvocationUtil.swingInvokeLater( myProject, - () -> - { - final DebuggerSession session = mySession; + () -> { + DebuggerSession session = mySession; if (session != null && session.isAttached()) { DebuggerAction.refreshViews(mySession.getXDebugSession()); } @@ -220,11 +214,11 @@ protected void action() throws Exception { @Nullable public Pair getLastExecutedMethod() { - final MethodReturnValueWatcher watcher = myReturnValueWatcher; + MethodReturnValueWatcher watcher = myReturnValueWatcher; if (watcher == null) { return null; } - final Method method = watcher.getLastExecutedMethod(); + Method method = watcher.getLastExecutedMethod(); if (method == null) { return null; } @@ -232,14 +226,14 @@ public Pair getLastExecutedMethod() { } public void setWatchMethodReturnValuesEnabled(boolean enabled) { - final MethodReturnValueWatcher watcher = myReturnValueWatcher; + MethodReturnValueWatcher watcher = myReturnValueWatcher; if (watcher != null) { watcher.setFeatureEnabled(enabled); } } public boolean isWatchMethodReturnValuesEnabled() { - final MethodReturnValueWatcher watcher = myReturnValueWatcher; + MethodReturnValueWatcher watcher = myReturnValueWatcher; return watcher != null && watcher.isFeatureEnabled(); } @@ -284,25 +278,26 @@ public static NodeRenderer getDefaultRenderer(Value value) { @Nonnull public static NodeRenderer getDefaultRenderer(Type type) { - final NodeRendererSettings settings = NodeRendererSettings.getInstance(); + NodeRendererSettings settings = NodeRendererSettings.getInstance(); - final PrimitiveRenderer primitiveRenderer = settings.getPrimitiveRenderer(); + PrimitiveRenderer primitiveRenderer = settings.getPrimitiveRenderer(); if (primitiveRenderer.isApplicable(type)) { return primitiveRenderer; } - final ArrayRenderer arrayRenderer = settings.getArrayRenderer(); + ArrayRenderer arrayRenderer = settings.getArrayRenderer(); if (arrayRenderer.isApplicable(type)) { return arrayRenderer; } - final ClassRenderer classRenderer = settings.getClassRenderer(); + ClassRenderer classRenderer = settings.getClassRenderer(); LOG.assertTrue(classRenderer.isApplicable(type), type.name()); return classRenderer; } private static final String ourTrace = Platform.current().jvm().getRuntimeProperty("idea.debugger.trace"); + @RequiredUIAccess @SuppressWarnings({"HardCodedStringLiteral"}) protected void commitVM(VirtualMachine vm) { if (!isInInitialState()) { @@ -375,7 +370,7 @@ private void stopConnecting() { } @Override - public void printToConsole(final String text) { + public void printToConsole(String text) { myExecutionResult.getProcessHandler().notifyTextAvailable(text, ProcessOutputTypes.SYSTEM); } @@ -391,18 +386,12 @@ public ProcessHandler getProcessHandler() { * @param depth * @param hint may be null */ - protected void doStep( - final SuspendContextImpl suspendContext, - final ThreadReferenceProxyImpl stepThread, - int size, - int depth, - RequestHint hint - ) { + protected void doStep(SuspendContextImpl suspendContext, ThreadReferenceProxyImpl stepThread, int size, int depth, RequestHint hint) { if (stepThread == null) { return; } try { - final ThreadReference stepThreadReference = stepThread.getThreadReference(); + ThreadReference stepThreadReference = stepThread.getThreadReference(); if (LOG.isDebugEnabled()) { LOG.debug("DO_STEP: creating step request for " + stepThreadReference); } @@ -456,12 +445,12 @@ private static List getActiveFilters() { return classFilters.stream().filter(ClassFilter::isEnabled).collect(Collectors.toList()); } - void deleteStepRequests(@Nullable final ThreadReference stepThread) { + void deleteStepRequests(@Nullable ThreadReference stepThread) { EventRequestManager requestManager = getVirtualMachineProxy().eventRequestManager(); List stepRequests = requestManager.stepRequests(); if (!stepRequests.isEmpty()) { - final List toDelete = new ArrayList<>(stepRequests.size()); - for (final StepRequest request : stepRequests) { + List toDelete = new ArrayList<>(stepRequests.size()); + for (StepRequest request : stepRequests) { ThreadReference threadReference = request.thread(); // [jeka] on attempt to delete a request assigned to a thread with unknown status, a JDWP error occurs try { @@ -502,35 +491,34 @@ static String getCurrentClassName(ThreadReferenceProxyImpl thread) { private VirtualMachine createVirtualMachineInt() throws ExecutionException { try { if (myArguments != null) { - throw new IOException(DebuggerBundle.message("error.debugger.already.listening")); + throw new IOException(JavaDebuggerLocalize.errorDebuggerAlreadyListening().get()); } - final String address = myConnection.getAddress(); + String address = myConnection.getAddress(); if (myConnection.isServerMode()) { ListeningConnector connector = (ListeningConnector)findConnector(myConnection.isUseSockets() ? SOCKET_LISTENING_CONNECTOR_NAME : SHMEM_LISTENING_CONNECTOR_NAME); if (connector == null) { - throw new CantRunException(DebuggerBundle.message( - "error.debug.connector.not.found", - DebuggerBundle.getTransportName(myConnection) - )); + throw new CantRunException( + JavaDebuggerLocalize.errorDebugConnectorNotFound(DebuggerUtils.getTransportName(myConnection)).get() + ); } myArguments = connector.defaultArguments(); if (myArguments == null) { - throw new CantRunException(DebuggerBundle.message("error.no.debug.listen.port")); + throw new CantRunException(JavaDebuggerLocalize.errorNoDebugListenPort().get()); } if (address == null) { - throw new CantRunException(DebuggerBundle.message("error.no.debug.listen.port")); + throw new CantRunException(JavaDebuggerLocalize.errorNoDebugListenPort().get()); } // zero port number means the caller leaves to debugger to decide at which port to listen //noinspection HardCodedStringLiteral - final Connector.Argument portArg = myConnection.isUseSockets() ? myArguments.get("port") : myArguments.get("name"); + Connector.Argument portArg = myConnection.isUseSockets() ? myArguments.get("port") : myArguments.get("name"); if (portArg != null) { portArg.setValue(address); } //noinspection HardCodedStringLiteral - final Connector.Argument timeoutArg = myArguments.get("timeout"); + Connector.Argument timeoutArg = myArguments.get("timeout"); if (timeoutArg != null) { timeoutArg.setValue("0"); // wait forever } @@ -561,39 +549,38 @@ private VirtualMachine createVirtualMachineInt() throws ExecutionException { (AttachingConnector)findConnector(myConnection.isUseSockets() ? SOCKET_ATTACHING_CONNECTOR_NAME : SHMEM_ATTACHING_CONNECTOR_NAME); if (connector == null) { - throw new CantRunException(DebuggerBundle.message( - "error.debug.connector.not.found", - DebuggerBundle.getTransportName(myConnection) - )); + throw new CantRunException( + JavaDebuggerLocalize.errorDebugConnectorNotFound(DebuggerUtils.getTransportName(myConnection)).get() + ); } myArguments = connector.defaultArguments(); if (myConnection.isUseSockets()) { //noinspection HardCodedStringLiteral - final Connector.Argument hostnameArg = myArguments.get("hostname"); + Connector.Argument hostnameArg = myArguments.get("hostname"); if (hostnameArg != null && myConnection.getHostName() != null) { hostnameArg.setValue(myConnection.getHostName()); } if (address == null) { - throw new CantRunException(DebuggerBundle.message("error.no.debug.attach.port")); + throw new CantRunException(JavaDebuggerLocalize.errorNoDebugAttachPort().get()); } //noinspection HardCodedStringLiteral - final Connector.Argument portArg = myArguments.get("port"); + Connector.Argument portArg = myArguments.get("port"); if (portArg != null) { portArg.setValue(address); } } else { if (address == null) { - throw new CantRunException(DebuggerBundle.message("error.no.shmem.address")); + throw new CantRunException(JavaDebuggerLocalize.errorNoShmemAddress().get()); } //noinspection HardCodedStringLiteral - final Connector.Argument nameArg = myArguments.get("name"); + Connector.Argument nameArg = myArguments.get("name"); if (nameArg != null) { nameArg.setValue(address); } } //noinspection HardCodedStringLiteral - final Connector.Argument timeoutArg = myArguments.get("timeout"); + Connector.Argument timeoutArg = myArguments.get("timeout"); if (timeoutArg != null) { timeoutArg.setValue("0"); // wait forever } @@ -608,7 +595,7 @@ private VirtualMachine createVirtualMachineInt() throws ExecutionException { } } catch (IOException e) { - throw new ExecutionException(processIOException(e, DebuggerBundle.getAddressDisplayName(myConnection)), e); + throw new ExecutionException(processIOException(e, DebuggerUtils.getAddressDisplayName(myConnection)), e); } catch (IllegalConnectorArgumentsException e) { throw new ExecutionException(processError(e), e); @@ -618,7 +605,12 @@ private VirtualMachine createVirtualMachineInt() throws ExecutionException { } } - public void showStatusText(final String text) { + public void showStatusText(@Nonnull LocalizeValue text) { + showStatusText(text.get()); + } + + @Deprecated + public void showStatusText(String text) { if (!myStatusUpdateAlarm.isDisposed()) { myStatusUpdateAlarm.cancelAllRequests(); myStatusUpdateAlarm.addRequest(() -> StatusBarUtil.setStatusBarInfo(myProject, text), 50); @@ -631,17 +623,15 @@ static Connector findConnector(String connectorName) throws ExecutionException { virtualMachineManager = Bootstrap.virtualMachineManager(); } catch (Error e) { - final String error = e.getClass().getName() + " : " + e.getLocalizedMessage(); - throw new ExecutionException(DebuggerBundle.message("debugger.jdi.bootstrap.error", error)); + String error = e.getClass().getName() + " : " + e.getLocalizedMessage(); + throw new ExecutionException(JavaDebuggerLocalize.debuggerJdiBootstrapError(error).get()); } - List connectors; - if (SOCKET_ATTACHING_CONNECTOR_NAME.equals(connectorName) || SHMEM_ATTACHING_CONNECTOR_NAME.equals(connectorName)) { - connectors = virtualMachineManager.attachingConnectors(); - } - else if (SOCKET_LISTENING_CONNECTOR_NAME.equals(connectorName) || SHMEM_LISTENING_CONNECTOR_NAME.equals(connectorName)) { - connectors = virtualMachineManager.listeningConnectors(); - } - else { + List connectors = switch (connectorName) { + case SOCKET_ATTACHING_CONNECTOR_NAME, SHMEM_ATTACHING_CONNECTOR_NAME -> virtualMachineManager.attachingConnectors(); + case SOCKET_LISTENING_CONNECTOR_NAME, SHMEM_LISTENING_CONNECTOR_NAME -> virtualMachineManager.listeningConnectors(); + default -> null; + }; + if (connectors == null) { return null; } for (Object connector1 : connectors) { @@ -653,15 +643,16 @@ else if (SOCKET_LISTENING_CONNECTOR_NAME.equals(connectorName) || SHMEM_LISTENIN return null; } + @RequiredUIAccess private void checkVirtualMachineVersion(VirtualMachine vm) { - final String version = vm.version(); + String version = vm.version(); if ("1.4.0".equals(version)) { DebuggerInvocationUtil.swingInvokeLater( myProject, () -> Messages.showMessageDialog( myProject, - DebuggerBundle.message("warning.jdk140.unstable"), - DebuggerBundle.message("title.jdk140.unstable"), + JavaDebuggerLocalize.warningJdk140Unstable().get(), + JavaDebuggerLocalize.titleJdk140Unstable().get(), UIUtil.getWarningIcon() ) ); @@ -673,15 +664,13 @@ private void checkVirtualMachineVersion(VirtualMachine vm) { JavaSdkTypeUtil.getAllJavaSdks().stream() .filter(sdk -> versionMatch(sdk, version)) .findFirst() - .ifPresent(sdk -> - { + .ifPresent(sdk -> { XDebuggerUIConstants.NOTIFICATION_GROUP.createNotification( - DebuggerBundle.message( - "message.remote.jre.version.mismatch", + JavaDebuggerLocalize.messageRemoteJreVersionMismatch( version, runjre != null ? runjre.getVersionString() : "unknown", sdk.getName() - ), + ).get(), NotificationType.INFORMATION ).notify(myProject); getSession().setAlternativeJre(sdk); @@ -756,12 +745,12 @@ public Project getProject() { } public boolean canRedefineClasses() { - final VirtualMachineProxyImpl vm = myVirtualMachineProxy; + VirtualMachineProxyImpl vm = myVirtualMachineProxy; return vm != null && vm.canRedefineClasses(); } public boolean canWatchFieldModification() { - final VirtualMachineProxyImpl vm = myVirtualMachineProxy; + VirtualMachineProxyImpl vm = myVirtualMachineProxy; return vm != null && vm.canWatchFieldModification(); } @@ -793,7 +782,7 @@ public RequestManagerImpl getRequestsManager() { @Override public VirtualMachineProxyImpl getVirtualMachineProxy() { DebuggerManagerThreadImpl.assertIsManagerThread(); - final VirtualMachineProxyImpl vm = myVirtualMachineProxy; + VirtualMachineProxyImpl vm = myVirtualMachineProxy; if (vm == null) { if (isInInitialState()) { throw new IllegalStateException("Virtual machine is not initialized yet"); @@ -806,7 +795,7 @@ public VirtualMachineProxyImpl getVirtualMachineProxy() { } @Override - public void appendPositionManager(final PositionManager positionManager) { + public void appendPositionManager(PositionManager positionManager) { DebuggerManagerThreadImpl.assertIsManagerThread(); myPositionManager.appendPositionManager(positionManager); } @@ -819,7 +808,7 @@ public void setRunToCursorBreakpoint(@Nullable RunToCursorBreakpoint breakpoint) public void cancelRunToCursorBreakpoint() { DebuggerManagerThreadImpl.assertIsManagerThread(); - final RunToCursorBreakpoint runToCursorBreakpoint = myRunToCursorBreakpoint; + RunToCursorBreakpoint runToCursorBreakpoint = myRunToCursorBreakpoint; if (runToCursorBreakpoint != null) { setRunToCursorBreakpoint(null); getRequestsManager().deleteRequest(runToCursorBreakpoint); @@ -837,7 +826,7 @@ protected void closeProcess(boolean closedByUser) { getManagerThread().close(); } finally { - final VirtualMachineProxyImpl vm = myVirtualMachineProxy; + VirtualMachineProxyImpl vm = myVirtualMachineProxy; myVirtualMachineProxy = null; myPositionManager = CompoundPositionManager.EMPTY; myReturnValueWatcher = null; @@ -869,7 +858,7 @@ protected void closeProcess(boolean closedByUser) { } private static String formatMessage(String message) { - final int lineLength = 90; + int lineLength = 90; StringBuilder buf = new StringBuilder(message.length()); int index = 0; while (index < message.length()) { @@ -886,9 +875,9 @@ public static String processError(Exception e) { message = e1.getLocalizedMessage(); } else if (e instanceof IllegalConnectorArgumentsException e1) { - final List invalidArgumentNames = e1.argumentNames(); + List invalidArgumentNames = e1.argumentNames(); message = formatMessage( - DebuggerBundle.message("error.invalid.argument", invalidArgumentNames.size()) + ": " + e1.getLocalizedMessage() + JavaDebuggerLocalize.errorInvalidArgument(invalidArgumentNames.size()) + ": " + e1.getLocalizedMessage() ) + invalidArgumentNames; LOG.debug(e1); } @@ -896,7 +885,7 @@ else if (e instanceof CantRunException) { message = e.getLocalizedMessage(); } else if (e instanceof VMDisconnectedException) { - message = DebuggerBundle.message("error.vm.disconnected"); + message = JavaDebuggerLocalize.errorVmDisconnected().get(); } else if (e instanceof IOException e1) { message = processIOException(e1, null); @@ -905,7 +894,7 @@ else if (e instanceof ExecutionException) { message = e.getLocalizedMessage(); } else { - message = DebuggerBundle.message("error.exception.while.connecting", e.getClass().getName(), e.getLocalizedMessage()); + message = JavaDebuggerLocalize.errorExceptionWhileConnecting(e.getClass().getName(), e.getLocalizedMessage()).get(); LOG.debug(e); } return message; @@ -914,23 +903,24 @@ else if (e instanceof ExecutionException) { @Nonnull public static String processIOException(@Nonnull IOException e, @Nullable String address) { if (e instanceof UnknownHostException) { - return DebuggerBundle.message("error.unknown.host") + (address != null ? " (" + address + ")" : "") + ":\n" + e.getLocalizedMessage(); + return JavaDebuggerLocalize.errorUnknownHost() + + (address != null ? " (" + address + ")" : "") + ":\n" + e.getLocalizedMessage(); } String message; - final StringBuilder buf = new StringBuilder(); - buf.append(DebuggerBundle.message("error.cannot.open.debugger.port")); + StringBuilder sb = new StringBuilder(); + sb.append(JavaDebuggerLocalize.errorCannotOpenDebuggerPort()); if (address != null) { - buf.append(" (").append(address).append(")"); + sb.append(" (").append(address).append(")"); } - buf.append(": "); - buf.append(e.getClass().getName()).append(" "); - final String localizedMessage = e.getLocalizedMessage(); + sb.append(": "); + sb.append(e.getClass().getName()).append(" "); + String localizedMessage = e.getLocalizedMessage(); if (!StringUtil.isEmpty(localizedMessage)) { - buf.append('"').append(localizedMessage).append('"'); + sb.append('"').append(localizedMessage).append('"'); } LOG.debug(e); - message = buf.toString(); + message = sb.toString(); return message; } @@ -972,6 +962,7 @@ protected InvokeCommand(@Nonnull Method method, @Nonnull List a myArgs = new ArrayList<>(args); } + @Override public String toString() { return "INVOKE: " + super.toString(); } @@ -1022,7 +1013,7 @@ E startInternal(EvaluationContextImpl evaluationContext, boolean internalEvaluat } Set suspendingContexts = SuspendManagerUtil.getSuspendingContexts(getSuspendManager(), invokeThread); - final ThreadReference invokeThreadRef = invokeThread.getThreadReference(); + ThreadReference invokeThreadRef = invokeThread.getThreadReference(); myEvaluationDispatcher.getMulticaster().evaluationStarted(suspendContext); beforeMethodInvocation(suspendContext, myMethod, internalEvaluate); @@ -1030,7 +1021,7 @@ E startInternal(EvaluationContextImpl evaluationContext, boolean internalEvaluat Object resumeData = null; try { for (SuspendContextImpl suspendingContext : suspendingContexts) { - final ThreadReferenceProxyImpl suspendContextThread = suspendingContext.getThread(); + ThreadReferenceProxyImpl suspendContextThread = suspendingContext.getThread(); if (suspendContextThread != invokeThread) { if (LOG.isDebugEnabled()) { LOG.debug("Resuming " + invokeThread + " that is paused by " + suspendContextThread); @@ -1072,18 +1063,18 @@ E startInternal(EvaluationContextImpl evaluationContext, boolean internalEvaluat } } - private E invokeMethodAndFork(final SuspendContextImpl context) + private E invokeMethodAndFork(SuspendContextImpl context) throws InvocationException, ClassNotLoadedException, IncompatibleThreadStateException, InvalidTypeException { - final int invokePolicy = getInvokePolicy(context); - final Exception[] exception = new Exception[1]; - final Value[] result = new Value[1]; + int invokePolicy = getInvokePolicy(context); + Exception[] exception = new Exception[1]; + Value[] result = new Value[1]; getManagerThread().startLongProcessAndFork(() -> { ThreadReferenceProxyImpl thread = context.getThread(); try { try { if (LOG.isDebugEnabled()) { - final VirtualMachineProxyImpl virtualMachineProxy = getVirtualMachineProxy(); + VirtualMachineProxyImpl virtualMachineProxy = getVirtualMachineProxy(); virtualMachineProxy.logThreads(); LOG.debug("Invoke in " + thread.name()); assertThreadSuspended(thread, context); @@ -1175,10 +1166,10 @@ else if (exception[0] instanceof RuntimeException runtimeException) { return (E)result[0]; } - private void assertThreadSuspended(final ThreadReferenceProxyImpl thread, final SuspendContextImpl context) { + private void assertThreadSuspended(ThreadReferenceProxyImpl thread, SuspendContextImpl context) { LOG.assertTrue(context.isEvaluating()); try { - final boolean isSuspended = thread.isSuspended(); + boolean isSuspended = thread.isSuspended(); LOG.assertTrue(isSuspended, thread); } catch (ObjectCollectedException ignored) { @@ -1199,19 +1190,16 @@ public Value invokeMethod( @Override public Value invokeInstanceMethod( @Nonnull EvaluationContext evaluationContext, - @Nonnull final ObjectReference objRef, + @Nonnull ObjectReference objRef, @Nonnull Method method, @Nonnull List args, - final int invocationOptions + int invocationOptions ) throws EvaluateException { - final ThreadReference thread = getEvaluationThread(evaluationContext); + ThreadReference thread = getEvaluationThread(evaluationContext); return new InvokeCommand<>(method, args) { @Override - protected Value invokeMethod( - int invokePolicy, - Method method, - List args - ) throws InvocationException, ClassNotLoadedException, IncompatibleThreadStateException, InvalidTypeException { + protected Value invokeMethod(int invokePolicy, Method method, List args) + throws InvocationException, ClassNotLoadedException, IncompatibleThreadStateException, InvalidTypeException { if (LOG.isDebugEnabled()) { LOG.debug("Invoking " + objRef.type().name() + "." + method.name()); } @@ -1220,7 +1208,7 @@ protected Value invokeMethod( }.start((EvaluationContextImpl)evaluationContext, false); } - private static ThreadReference getEvaluationThread(final EvaluationContext evaluationContext) throws EvaluateException { + private static ThreadReference getEvaluationThread(EvaluationContext evaluationContext) throws EvaluateException { ThreadReferenceProxy evaluationThread = evaluationContext.getSuspendContext().getThread(); if (evaluationThread == null) { throw EvaluateExceptionUtil.NULL_STACK_FRAME; @@ -1240,12 +1228,12 @@ public Value invokeMethod( public Value invokeMethod( @Nonnull EvaluationContext evaluationContext, - @Nonnull final ClassType classType, + @Nonnull ClassType classType, @Nonnull Method method, @Nonnull List args, boolean internalEvaluate ) throws EvaluateException { - final ThreadReference thread = getEvaluationThread(evaluationContext); + ThreadReference thread = getEvaluationThread(evaluationContext); return new InvokeCommand<>(method, args) { @Override protected Value invokeMethod( @@ -1267,7 +1255,7 @@ public Value invokeMethod( Method method, List args ) throws EvaluateException { - final ThreadReference thread = getEvaluationThread(evaluationContext); + ThreadReference thread = getEvaluationThread(evaluationContext); return new InvokeCommand<>(method, args) { @Override protected Value invokeMethod( @@ -1285,7 +1273,7 @@ protected Value invokeMethod( @Override - public ArrayReference newInstance(final ArrayType arrayType, final int dimension) throws EvaluateException { + public ArrayReference newInstance(ArrayType arrayType, int dimension) throws EvaluateException { try { return arrayType.newInstance(dimension); } @@ -1296,12 +1284,12 @@ public ArrayReference newInstance(final ArrayType arrayType, final int dimension @Override public ObjectReference newInstance( - @Nonnull final EvaluationContext evaluationContext, - @Nonnull final ClassType classType, + @Nonnull EvaluationContext evaluationContext, + @Nonnull ClassType classType, @Nonnull Method method, @Nonnull List args ) throws EvaluateException { - final ThreadReference thread = getEvaluationThread(evaluationContext); + ThreadReference thread = getEvaluationThread(evaluationContext); InvokeCommand invokeCommand = new InvokeCommand<>(method, args) { @Override protected ObjectReference invokeMethod( @@ -1347,10 +1335,10 @@ private void beforeMethodInvocation(SuspendContextImpl suspendContext, Method me if (!internalEvaluate) { if (method != null) { - showStatusText(DebuggerBundle.message("progress.evaluating", DebuggerUtilsEx.methodName(method))); + showStatusText(JavaDebuggerLocalize.progressEvaluating(DebuggerUtilsEx.methodName(method))); } else { - showStatusText(DebuggerBundle.message("title.evaluating")); + showStatusText(JavaDebuggerLocalize.titleEvaluating()); } } } @@ -1360,7 +1348,7 @@ private void afterMethodInvocation(SuspendContextImpl suspendContext, boolean in LOG.debug("after invocation in thread " + suspendContext.getThread().name()); } if (!internalEvaluate) { - showStatusText(""); + showStatusText(LocalizeValue.empty()); } } @@ -1370,13 +1358,13 @@ public ReferenceType findClass(EvaluationContext evaluationContext, String class try { DebuggerManagerThreadImpl.assertIsManagerThread(); ReferenceType result = null; - for (final ReferenceType refType : getVirtualMachineProxy().classesByName(className)) { + for (ReferenceType refType : getVirtualMachineProxy().classesByName(className)) { if (refType.isPrepared() && isVisibleFromClassLoader(classLoader, refType)) { result = refType; break; } } - final EvaluationContextImpl evalContext = (EvaluationContextImpl)evaluationContext; + EvaluationContextImpl evalContext = (EvaluationContextImpl)evaluationContext; if (result == null && evalContext.isAutoLoadClasses()) { return loadClass(evalContext, className, classLoader); } @@ -1387,7 +1375,7 @@ public ReferenceType findClass(EvaluationContext evaluationContext, String class } } - private static boolean isVisibleFromClassLoader(final ClassLoaderReference fromLoader, final ReferenceType refType) { + private static boolean isVisibleFromClassLoader(ClassLoaderReference fromLoader, ReferenceType refType) { // IMPORTANT! Even if the refType is already loaded by some parent or bootstrap loader, it may not be visible from the given loader. // For example because there were no accesses yet from this loader to this class. So the loader is not in the list of "initialing" loaders // for this refType and the refType is not visible to the loader. @@ -1430,7 +1418,7 @@ public ReferenceType loadClass(EvaluationContextImpl evaluationContext, String q VirtualMachineProxyImpl virtualMachine = getVirtualMachineProxy(); ClassType classClassType = (ClassType)ContainerUtil.getFirstItem(virtualMachine.classesByName(JavaClassNames.JAVA_LANG_CLASS)); if (classClassType != null) { - final Method forNameMethod; + Method forNameMethod; List args = new ArrayList<>(); // do not use unmodifiable lists because the list is modified by JPDA args.add(virtualMachine.mirrorOf(qName)); if (classLoader != null) { @@ -1512,7 +1500,7 @@ public Priority getPriority() { @Override protected void action() throws Exception { if (isAttached()) { - final VirtualMachineProxyImpl virtualMachineProxy = getVirtualMachineProxy(); + VirtualMachineProxyImpl virtualMachineProxy = getVirtualMachineProxy(); if (myIsTerminateTargetVM) { virtualMachineProxy.exit(-1); } @@ -1547,12 +1535,12 @@ public StepOutCommand(SuspendContextImpl suspendContext, int stepSize) { @Override public void contextAction(@Nonnull SuspendContextImpl suspendContext) { - showStatusText(DebuggerBundle.message("status.step.out")); - final ThreadReferenceProxyImpl thread = getContextThread(); + showStatusText(JavaDebuggerLocalize.statusStepOut()); + ThreadReferenceProxyImpl thread = getContextThread(); RequestHint hint = new RequestHint(thread, suspendContext, StepRequest.STEP_OUT); hint.setIgnoreFilters(mySession.shouldIgnoreSteppingFilters()); applyThreadFilter(thread); - final MethodReturnValueWatcher rvWatcher = myReturnValueWatcher; + MethodReturnValueWatcher rvWatcher = myReturnValueWatcher; if (rvWatcher != null) { rvWatcher.enable(thread.getThreadReference()); } @@ -1571,7 +1559,7 @@ private class StepIntoCommand extends StepCommand { public StepIntoCommand( SuspendContextImpl suspendContext, boolean ignoreFilters, - @Nullable final MethodFilter methodFilter, + @Nullable MethodFilter methodFilter, int stepSize ) { super(suspendContext); @@ -1586,9 +1574,9 @@ public StepIntoCommand( @Override public void contextAction(@Nonnull SuspendContextImpl suspendContext) { - showStatusText(DebuggerBundle.message("status.step.into")); - final ThreadReferenceProxyImpl stepThread = getContextThread(); - final RequestHint hint = mySmartStepFilter != null + showStatusText(JavaDebuggerLocalize.statusStepInto()); + ThreadReferenceProxyImpl stepThread = getContextThread(); + RequestHint hint = mySmartStepFilter != null ? new RequestHint(stepThread, suspendContext, mySmartStepFilter) : new RequestHint(stepThread, suspendContext, StepRequest.STEP_INTO); hint.setResetIgnoreFilters(mySmartStepFilter != null && !mySession.shouldIgnoreSteppingFilters()); @@ -1603,7 +1591,11 @@ public void contextAction(@Nonnull SuspendContextImpl suspendContext) { hint.setIgnoreFilters(myForcedIgnoreFilters || mySession.shouldIgnoreSteppingFilters()); applyThreadFilter(stepThread); if (myBreakpoint != null) { - myBreakpoint.setSuspendPolicy(suspendContext.getSuspendPolicy() == EventRequest.SUSPEND_EVENT_THREAD ? DebuggerSettings.SUSPEND_THREAD : DebuggerSettings.SUSPEND_ALL); + myBreakpoint.setSuspendPolicy( + suspendContext.getSuspendPolicy() == EventRequest.SUSPEND_EVENT_THREAD + ? DebuggerSettings.SUSPEND_THREAD + : DebuggerSettings.SUSPEND_ALL + ); myBreakpoint.createRequest(suspendContext.getDebugProcess()); myBreakpoint.setRequestHint(hint); setRunToCursorBreakpoint(myBreakpoint); @@ -1628,8 +1620,8 @@ protected int getStepSize() { } @Nonnull - protected String getStatusText() { - return DebuggerBundle.message("status.step.over"); + protected LocalizeValue getStatusText() { + return JavaDebuggerLocalize.statusStepOver(); } @Nonnull @@ -1653,7 +1645,7 @@ public void contextAction(@Nonnull SuspendContextImpl suspendContext) { applyThreadFilter(stepThread); - final MethodReturnValueWatcher rvWatcher = myReturnValueWatcher; + MethodReturnValueWatcher rvWatcher = myReturnValueWatcher; if (rvWatcher != null) { rvWatcher.enable(stepThread.getThreadReference()); } @@ -1671,7 +1663,7 @@ private class RunToCursorCommand extends StepCommand { private final RunToCursorBreakpoint myRunToCursorBreakpoint; private final boolean myIgnoreBreakpoints; - private RunToCursorCommand(SuspendContextImpl suspendContext, @Nonnull XSourcePosition position, final boolean ignoreBreakpoints) { + private RunToCursorCommand(SuspendContextImpl suspendContext, @Nonnull XSourcePosition position, boolean ignoreBreakpoints) { super(suspendContext); myIgnoreBreakpoints = ignoreBreakpoints; myRunToCursorBreakpoint = @@ -1680,7 +1672,7 @@ private RunToCursorCommand(SuspendContextImpl suspendContext, @Nonnull XSourcePo @Override public void contextAction(@Nonnull SuspendContextImpl suspendContext) { - showStatusText(DebuggerBundle.message("status.run.to.cursor")); + showStatusText(JavaDebuggerLocalize.statusRunToCursor()); cancelRunToCursorBreakpoint(); if (myRunToCursorBreakpoint == null) { return; @@ -1689,11 +1681,13 @@ public void contextAction(@Nonnull SuspendContextImpl suspendContext) { DebuggerManagerEx.getInstanceEx(myProject).getBreakpointManager().disableBreakpoints(DebugProcessImpl.this); } applyThreadFilter(getContextThread()); - final SuspendContextImpl context = getSuspendContext(); + SuspendContextImpl context = getSuspendContext(); myRunToCursorBreakpoint.setSuspendPolicy( - context.getSuspendPolicy() == EventRequest.SUSPEND_EVENT_THREAD ? DebuggerSettings.SUSPEND_THREAD : DebuggerSettings.SUSPEND_ALL + context.getSuspendPolicy() == EventRequest.SUSPEND_EVENT_THREAD + ? DebuggerSettings.SUSPEND_THREAD + : DebuggerSettings.SUSPEND_ALL ); - final DebugProcessImpl debugProcess = context.getDebugProcess(); + DebugProcessImpl debugProcess = context.getDebugProcess(); myRunToCursorBreakpoint.createRequest(debugProcess); setRunToCursorBreakpoint(myRunToCursorBreakpoint); @@ -1701,24 +1695,24 @@ public void contextAction(@Nonnull SuspendContextImpl suspendContext) { super.contextAction(suspendContext); } else { - DebuggerInvocationUtil.swingInvokeLater(myProject, () -> - { - Messages.showErrorDialog( - DebuggerBundle.message( - "error.running.to.cursor.no.executable.code", - myRunToCursorBreakpoint.getSourcePosition().getFile().getName(), - myRunToCursorBreakpoint.getLineIndex() + 1 - ), - ActionLocalize.actionRuntocursorText().map(Presentation.NO_MNEMONIC).get() - ); - DebuggerSession session = debugProcess.getSession(); - session.getContextManager().setState( - DebuggerContextUtil.createDebuggerContext(session, context), - DebuggerSession.State.PAUSED, - DebuggerSession.Event.CONTEXT, - null - ); - }); + DebuggerInvocationUtil.swingInvokeLater( + myProject, + () -> { + Messages.showErrorDialog( + JavaDebuggerLocalize.errorRunningToCursorNoExecutableCode( + myRunToCursorBreakpoint.getSourcePosition().getFile().getName(), + myRunToCursorBreakpoint.getLineIndex() + 1 + ).get(), + ActionLocalize.actionRuntocursorText().map(Presentation.NO_MNEMONIC).get() + ); + DebuggerSession session = debugProcess.getSession(); + session.getContextManager().setState( + DebuggerContextUtil.createDebuggerContext(session, context), + DebuggerSession.State.PAUSED, + DebuggerSession.Event.CONTEXT + ); + } + ); } } } @@ -1749,7 +1743,7 @@ public abstract class ResumeCommand extends SuspendContextCommandImpl { public ResumeCommand(SuspendContextImpl suspendContext) { super(suspendContext); - final ThreadReferenceProxyImpl contextThread = getDebuggerContext().getThreadProxy(); + ThreadReferenceProxyImpl contextThread = getDebuggerContext().getThreadProxy(); myContextThread = contextThread != null ? contextThread : (suspendContext != null ? suspendContext.getThread() : null); } @@ -1760,7 +1754,7 @@ public Priority getPriority() { @Override public void contextAction(@Nonnull SuspendContextImpl suspendContext) { - showStatusText(DebuggerBundle.message("status.process.resumed")); + showStatusText(JavaDebuggerLocalize.statusProcessResumed()); resumeAction(); myDebugProcessDispatcher.getMulticaster().resumed(getSuspendContext()); } @@ -1780,7 +1774,7 @@ protected void applyThreadFilter(ThreadReferenceProxy thread) { // e.g. when breakpoint was considered invalid, in that case the filter will be applied _after_ // resuming and all breakpoints in other threads will be ignored. // As resume() implicitly cleares the filter, the filter must be always applied _before_ any resume() action happens - final BreakpointManager breakpointManager = DebuggerManagerEx.getInstanceEx(getProject()).getBreakpointManager(); + BreakpointManager breakpointManager = DebuggerManagerEx.getInstanceEx(getProject()).getBreakpointManager(); breakpointManager.applyThreadFilter(DebugProcessImpl.this, thread.getThreadReference()); } } @@ -1819,7 +1813,7 @@ public void contextAction() { return; } - final Set suspendingContexts = SuspendManagerUtil.getSuspendingContexts(getSuspendManager(), myThread); + Set suspendingContexts = SuspendManagerUtil.getSuspendingContexts(getSuspendManager(), myThread); for (SuspendContextImpl suspendContext : suspendingContexts) { if (suspendContext.getSuspendPolicy() == EventRequest.SUSPEND_EVENT_THREAD && suspendContext.getThread() == myThread) { getSession().getXDebugSession().sessionResumed(); @@ -1861,7 +1855,7 @@ public PopFrameCommand(DebuggerContextImpl context, StackFrameProxyImpl framePro @Override public void threadAction(@Nonnull SuspendContextImpl suspendContext) { - final ThreadReferenceProxyImpl thread = myStackFrame.threadProxy(); + ThreadReferenceProxyImpl thread = myStackFrame.threadProxy(); try { if (!getSuspendManager().isSuspended(thread)) { notifyCancelled(); @@ -1883,8 +1877,8 @@ public void threadAction(@Nonnull SuspendContextImpl suspendContext) { myProject, () -> Messages.showMessageDialog( myProject, - DebuggerBundle.message("error.pop.bottom.stackframe"), - ActionsBundle.actionText("Debugger.PopFrame"), + JavaDebuggerLocalize.errorPopBottomStackframe().get(), + ActionsBundle.message("action.Debugger.PopFrame.text"), UIUtil.getErrorIcon() ) ); @@ -1894,13 +1888,13 @@ public void threadAction(@Nonnull SuspendContextImpl suspendContext) { try { thread.popFrames(myStackFrame); } - catch (final EvaluateException e) { + catch (EvaluateException e) { DebuggerInvocationUtil.swingInvokeLater( myProject, () -> Messages.showMessageDialog( myProject, - DebuggerBundle.message("error.pop.stackframe", e.getLocalizedMessage()), - ActionsBundle.actionText(DebuggerActions.POP_FRAME), + JavaDebuggerLocalize.errorPopStackframe(e.getLocalizedMessage()).get(), + ActionsBundle.message("action." + DebuggerActions.POP_FRAME + ".text"), UIUtil.getErrorIcon() ) ); @@ -1919,7 +1913,7 @@ public GlobalSearchScope getSearchScope() { return mySession.getSearchScope(); } - public void reattach(final DebugEnvironment environment) throws ExecutionException { + public void reattach(DebugEnvironment environment) throws ExecutionException { getManagerThread().schedule(new DebuggerCommandImpl() { @Override protected void action() throws Exception { @@ -1933,21 +1927,23 @@ protected void commandCancelled() { } private void doReattach() { - DebuggerInvocationUtil.swingInvokeLater(myProject, () -> - { - getXdebugProcess().getSession().resetBreakpoints(); - myState.set(State.INITIAL); - myConnection = environment.getRemoteConnection(); - getManagerThread().restartIfNeeded(); - createVirtualMachine(environment); - }); + DebuggerInvocationUtil.swingInvokeLater( + myProject, + () -> { + getXdebugProcess().getSession().resetBreakpoints(); + myState.set(State.INITIAL); + myConnection = environment.getRemoteConnection(); + getManagerThread().restartIfNeeded(); + createVirtualMachine(environment); + } + ); } }); } @Nullable @RequiredUIAccess - public ExecutionResult attachVirtualMachine(final DebugEnvironment environment, final DebuggerSession session) + public ExecutionResult attachVirtualMachine(DebugEnvironment environment, DebuggerSession session) throws ExecutionException { mySession = session; myWaitFor.down(); @@ -1985,30 +1981,33 @@ public ExecutionResult attachVirtualMachine(final DebugEnvironment environment, return executionResult; } - /* - final Alarm debugPortTimeout = new Alarm(Alarm.ThreadToUse.SHARED_THREAD); + /* + Alarm debugPortTimeout = new Alarm(Alarm.ThreadToUse.SHARED_THREAD); - myExecutionResult.getProcessHandler().addProcessListener(new ProcessAdapter() { - public void processTerminated(ProcessEvent event) { - debugPortTimeout.cancelAllRequests(); - } + myExecutionResult.getProcessHandler().addProcessListener(new ProcessAdapter() { + public void processTerminated(ProcessEvent event) { + debugPortTimeout.cancelAllRequests(); + } - public void startNotified(ProcessEvent event) { - debugPortTimeout.addRequest(new Runnable() { - public void run() { - if (isInInitialState()) { - ApplicationManager.getApplication().schedule(new Runnable() { - public void run() { - String message = DebuggerBundle.message("status.connect.failed", DebuggerBundle.getAddressDisplayName(remoteConnection), DebuggerBundle.getTransportName(remoteConnection)); - Messages.showErrorDialog(myProject, message, DebuggerBundle.message("title.generic.debug.dialog")); - } - }); + public void startNotified(ProcessEvent event) { + debugPortTimeout.addRequest( + () -> { + if (isInInitialState()) { + ApplicationManager.getApplication().schedule(() -> { + String message = DebuggerBundle.message( + "status.connect.failed", + DebuggerBundle.getAddressDisplayName(remoteConnection), + DebuggerBundle.getTransportName(remoteConnection) + ); + Messages.showErrorDialog(myProject, message, DebuggerBundle.message("title.generic.debug.dialog")); + }); + } + }, + LOCAL_START_TIMEOUT + ); } - } - }, LOCAL_START_TIMEOUT); - } - }); - */ + }); + */ return executionResult; } @@ -2020,13 +2019,13 @@ private void fail() { } } - private void createVirtualMachine(final DebugEnvironment environment) { - final String sessionName = environment.getSessionName(); - final long pollTimeout = environment.getPollTimeout(); - final Semaphore semaphore = new Semaphore(); + private void createVirtualMachine(DebugEnvironment environment) { + String sessionName = environment.getSessionName(); + long pollTimeout = environment.getPollTimeout(); + Semaphore semaphore = new Semaphore(); semaphore.down(); - final AtomicBoolean connectorIsReady = new AtomicBoolean(false); + AtomicBoolean connectorIsReady = new AtomicBoolean(false); myDebugProcessDispatcher.addListener(new DebugProcessListener() { @Override public void connectorIsReady() { @@ -2045,13 +2044,13 @@ protected void action() { VirtualMachine vm = null; try { - final long time = System.currentTimeMillis(); + long time = System.currentTimeMillis(); do { try { vm = createVirtualMachineInt(); break; } - catch (final ExecutionException e) { + catch (ExecutionException e) { if (pollTimeout > 0 && !myConnection.isServerMode() && e.getCause() instanceof IOException) { synchronized (this) { try { @@ -2088,7 +2087,7 @@ protected void action() { } if (vm != null) { - final VirtualMachine vm1 = vm; + VirtualMachine vm1 = vm; afterProcessStarted(() -> getManagerThread().schedule(new DebuggerCommandImpl() { @Override protected void action() throws Exception { @@ -2117,7 +2116,7 @@ protected void commandCancelled() { semaphore.waitFor(); } - private void afterProcessStarted(final Runnable run) { + private void afterProcessStarted(Runnable run) { class MyProcessAdapter extends ProcessAdapter { private boolean alreadyRun = false; @@ -2144,7 +2143,7 @@ public void startNotified(ProcessEvent event) { } public boolean isPausePressed() { - final VirtualMachineProxyImpl vm = myVirtualMachineProxy; + VirtualMachineProxyImpl vm = myVirtualMachineProxy; return vm != null && vm.isPausePressed(); } @@ -2159,8 +2158,8 @@ public ResumeCommand createResumeCommand(SuspendContextImpl suspendContext) { } @Nonnull - public ResumeCommand createResumeCommand(SuspendContextImpl suspendContext, final PrioritizedTask.Priority priority) { - final BreakpointManager breakpointManager = DebuggerManagerEx.getInstanceEx(getProject()).getBreakpointManager(); + public ResumeCommand createResumeCommand(SuspendContextImpl suspendContext, PrioritizedTask.Priority priority) { + BreakpointManager breakpointManager = DebuggerManagerEx.getInstanceEx(getProject()).getBreakpointManager(); return new ResumeCommand(suspendContext) { @Override public void contextAction(@Nonnull SuspendContextImpl suspendContext) { @@ -2199,7 +2198,11 @@ public ResumeCommand createStepOutCommand(SuspendContextImpl suspendContext, int } @Nonnull - public ResumeCommand createStepIntoCommand(SuspendContextImpl suspendContext, boolean ignoreFilters, final MethodFilter smartStepFilter) { + public ResumeCommand createStepIntoCommand( + SuspendContextImpl suspendContext, + boolean ignoreFilters, + MethodFilter smartStepFilter + ) { return createStepIntoCommand(suspendContext, ignoreFilters, smartStepFilter, StepRequest.STEP_LINE); } @@ -2207,7 +2210,7 @@ public ResumeCommand createStepIntoCommand(SuspendContextImpl suspendContext, bo public ResumeCommand createStepIntoCommand( SuspendContextImpl suspendContext, boolean ignoreFilters, - final MethodFilter smartStepFilter, + MethodFilter smartStepFilter, int stepSize ) { return new StepIntoCommand(suspendContext, ignoreFilters, smartStepFilter, stepSize); @@ -2224,11 +2227,10 @@ public ResumeCommand createRunToCursorCommand( if (runToCursorCommand.myRunToCursorBreakpoint == null) { PsiFile psiFile = PsiManager.getInstance(myProject).findFile(position.getFile()); throw new EvaluateException( - DebuggerBundle.message( - "error.running.to.cursor.no.executable.code", + JavaDebuggerLocalize.errorRunningToCursorNoExecutableCode( psiFile != null ? psiFile.getName() : "", position.getLine() - ), + ).get(), null ); } @@ -2253,28 +2255,28 @@ public SuspendContextCommandImpl createPopFrameCommand(DebuggerContextImpl conte return new PopFrameCommand(context, stackFrame); } - //public void setBreakpointsMuted(final boolean muted) { - // XDebugSession session = mySession.getXDebugSession(); - // if (isAttached()) { - // getManagerThread().schedule(new DebuggerCommandImpl() { - // @Override - // protected void action() throws Exception { - // // set the flag before enabling/disabling cause it affects if breakpoints will create requests - // if (myBreakpointsMuted.getAndSet(muted) != muted) { - // final BreakpointManager breakpointManager = DebuggerManagerEx.getInstanceEx(myProject).getBreakpointManager(); - // if (muted) { - // breakpointManager.disableBreakpoints(DebugProcessImpl.this); - // } - // else { - // breakpointManager.enableBreakpoints(DebugProcessImpl.this); - // } - // } - // } - // }); - // } - // else { - // session.setBreakpointMuted(muted); - // } + //public void setBreakpointsMuted(boolean muted) { + // XDebugSession session = mySession.getXDebugSession(); + // if (isAttached()) { + // getManagerThread().schedule(new DebuggerCommandImpl() { + // @Override + // protected void action() throws Exception { + // // set the flag before enabling/disabling cause it affects if breakpoints will create requests + // if (myBreakpointsMuted.getAndSet(muted) != muted) { + // BreakpointManager breakpointManager = DebuggerManagerEx.getInstanceEx(myProject).getBreakpointManager(); + // if (muted) { + // breakpointManager.disableBreakpoints(DebugProcessImpl.this); + // } + // else { + // breakpointManager.enableBreakpoints(DebugProcessImpl.this); + // } + // } + // } + // }); + // } + // else { + // session.setBreakpointMuted(muted); + // } //} @Nonnull diff --git a/java-debugger-impl/src/main/java/com/intellij/java/debugger/impl/engine/JavaStackFrame.java b/java-debugger-impl/src/main/java/com/intellij/java/debugger/impl/engine/JavaStackFrame.java index 31d86b52a5..32a4747432 100644 --- a/java-debugger-impl/src/main/java/com/intellij/java/debugger/impl/engine/JavaStackFrame.java +++ b/java-debugger-impl/src/main/java/com/intellij/java/debugger/impl/engine/JavaStackFrame.java @@ -15,7 +15,6 @@ */ package com.intellij.java.debugger.impl.engine; -import com.intellij.java.debugger.DebuggerBundle; import com.intellij.java.debugger.SourcePosition; import com.intellij.java.debugger.engine.DebuggerUtils; import com.intellij.java.debugger.engine.evaluation.EvaluateException; @@ -37,8 +36,10 @@ import com.intellij.java.debugger.impl.ui.breakpoints.Breakpoint; import com.intellij.java.debugger.impl.ui.impl.watch.*; import com.intellij.java.debugger.impl.ui.tree.render.DescriptorLabelListener; +import com.intellij.java.debugger.localize.JavaDebuggerLocalize; import com.intellij.java.language.JavaLanguage; import com.intellij.java.language.psi.*; +import consulo.annotation.access.RequiredReadAction; import consulo.application.ReadAction; import consulo.application.dumb.IndexNotReadyException; import consulo.document.Document; @@ -64,10 +65,9 @@ import consulo.ui.image.Image; import consulo.util.collection.ContainerUtil; import consulo.util.lang.CharArrayUtil; -import consulo.util.lang.Comparing; import consulo.util.lang.Pair; import consulo.util.lang.StringUtil; -import consulo.util.lang.ref.Ref; +import consulo.util.lang.ref.SimpleReference; import consulo.virtualFileSystem.VirtualFile; import jakarta.annotation.Nonnull; import jakarta.annotation.Nullable; @@ -133,11 +133,8 @@ public void customizePresentation(@Nonnull ColoredTextContainer component) { DebuggerSession session = myDebugProcess.getSession(); if (session != null) { XDebugSession xSession = session.getXDebugSession(); - if (xSession != null) { - XStackFrame frame = xSession.getCurrentStackFrame(); - if (frame instanceof JavaStackFrame) { - selectedDescriptor = ((JavaStackFrame)frame).getDescriptor(); - } + if (xSession != null && xSession.getCurrentStackFrame() instanceof JavaStackFrame frame) { + selectedDescriptor = frame.getDescriptor(); } } FRAME_RENDERER.customizePresentation(myDescriptor, component, selectedDescriptor); @@ -147,7 +144,7 @@ public void customizePresentation(@Nonnull ColoredTextContainer component) { } @Override - public void computeChildren(@Nonnull final XCompositeNode node) { + public void computeChildren(@Nonnull XCompositeNode node) { if (node.isObsolete()) { return; } @@ -167,7 +164,8 @@ public void threadAction() { } if (myInsertCapturePoint != null) { node.setMessage( - "Async stacktrace from " + myInsertCapturePoint.myClassName + "." + myInsertCapturePoint.myMethodName + " could be available here, enable in", + "Async stacktrace from " + myInsertCapturePoint.myClassName + "." + + myInsertCapturePoint.myMethodName + " could be available here, enable in", XDebuggerUIConstants.INFORMATION_MESSAGE_ICON, SimpleTextAttributes.REGULAR_ATTRIBUTES, StackFrameItem.CAPTURE_SETTINGS_OPENER @@ -203,7 +201,7 @@ DebuggerContextImpl getFrameDebuggerContext(@Nullable DebuggerContextImpl contex // copied from DebuggerTree private void buildVariablesThreadAction(DebuggerContextImpl debuggerContext, XValueChildrenList children, XCompositeNode node) { try { - final EvaluationContextImpl evaluationContext = debuggerContext.createEvaluationContext(); + EvaluationContextImpl evaluationContext = debuggerContext.createEvaluationContext(); if (evaluationContext == null) { return; } @@ -212,9 +210,9 @@ private void buildVariablesThreadAction(DebuggerContextImpl debuggerContext, XVa //myChildren.add(myNodeManager.createNode(MessageDescriptor.EVALUATION_NOT_POSSIBLE, evaluationContext)); } - final Location location = myDescriptor.getLocation(); + Location location = myDescriptor.getLocation(); - final ObjectReference thisObjectReference = myDescriptor.getThisObject(); + ObjectReference thisObjectReference = myDescriptor.getThisObject(); if (thisObjectReference != null) { ValueDescriptorImpl thisDescriptor = myNodeManager.getThisDescriptor(null, thisObjectReference); children.add(JavaValue.create(thisDescriptor, evaluationContext, myNodeManager)); @@ -232,7 +230,7 @@ else if (location != null) { } // add last method return value if any - final Pair methodValuePair = debugProcess.getLastExecutedMethod(); + Pair methodValuePair = debugProcess.getLastExecutedMethod(); if (methodValuePair != null && myDescriptor.getUiIndex() == 0) { ValueDescriptorImpl returnValueDescriptor = myNodeManager.getMethodReturnValueDescriptor(myDescriptor, methodValuePair.getFirst(), methodValuePair.getSecond()); @@ -273,9 +271,10 @@ else if (location != null) { } catch (InternalException e) { if (e.errorCode() == 35) { - node.setErrorMessage(DebuggerBundle.message("error.corrupt.debug.info", e.getMessage())); - //myChildren.add( - // myNodeManager.createMessageNode(new MessageDescriptor(DebuggerBundle.message("error.corrupt.debug.info", e.getMessage())))); + node.setErrorMessage(JavaDebuggerLocalize.errorCorruptDebugInfo(e.getMessage()).get()); + //myChildren.add(myNodeManager.createMessageNode(new MessageDescriptor( + // JavaDebuggerLocalize.errorCorruptDebugInfo(e.getMessage()).get() + //))); } else { throw e; @@ -289,22 +288,22 @@ else if (location != null) { // copied from FrameVariablesTree private void buildVariables( DebuggerContextImpl debuggerContext, - final EvaluationContextImpl evaluationContext, + EvaluationContextImpl evaluationContext, @Nonnull DebugProcessImpl debugProcess, XValueChildrenList children, ObjectReference thisObjectReference, Location location ) throws EvaluateException { - final Set visibleLocals = new HashSet<>(); + Set visibleLocals = new HashSet<>(); if (NodeRendererSettings.getInstance().getClassRenderer().SHOW_VAL_FIELDS_AS_LOCAL_VARIABLES) { if (thisObjectReference != null && debugProcess.getVirtualMachineProxy().canGetSyntheticAttribute()) { - final ReferenceType thisRefType = thisObjectReference.referenceType(); - if (thisRefType instanceof ClassType && location != null && thisRefType.equals(location.declaringType()) && thisRefType.name() - .contains("$")) { // makes sense for nested classes only + ReferenceType thisRefType = thisObjectReference.referenceType(); + if (thisRefType instanceof ClassType && location != null && thisRefType.equals(location.declaringType()) + && thisRefType.name().contains("$")) { // makes sense for nested classes only for (Field field : thisRefType.fields()) { if (DebuggerUtils.isSynthetic(field) && StringUtil.startsWith(field.name(), FieldDescriptorImpl.OUTER_LOCAL_VAR_FIELD_PREFIX)) { - final FieldDescriptorImpl fieldDescriptor = + FieldDescriptorImpl fieldDescriptor = myNodeManager.getFieldDescriptor(myDescriptor, thisObjectReference, field); children.add(JavaValue.create(fieldDescriptor, evaluationContext, myNodeManager)); visibleLocals.add(fieldDescriptor.calcValueName()); @@ -325,8 +324,8 @@ private void buildVariables( superBuildVariables(evaluationContext, children); } else { - final SourcePosition sourcePosition = debuggerContext.getSourcePosition(); - final Map visibleVariables = + SourcePosition sourcePosition = debuggerContext.getSourcePosition(); + Map visibleVariables = ContainerUtil.map2Map(getVisibleVariables(), var -> Pair.create(var.name(), var)); Pair, Set> usedVars = EMPTY_USED_VARS; @@ -353,7 +352,7 @@ private void buildVariables( else { superBuildVariables(evaluationContext, children); } - final EvaluationContextImpl evalContextCopy = evaluationContext.createEvaluationContext(evaluationContext.getThisObject()); + EvaluationContextImpl evalContextCopy = evaluationContext.createEvaluationContext(evaluationContext.getThisObject()); evalContextCopy.setAutoLoadClasses(false); if (sourcePosition != null) { @@ -449,7 +448,7 @@ public String toString() { } } - protected void superBuildVariables(final EvaluationContextImpl evaluationContext, XValueChildrenList children) + protected void superBuildVariables(EvaluationContextImpl evaluationContext, XValueChildrenList children) throws EvaluateException { for (LocalVariableProxyImpl local : getVisibleVariables()) { children.add(JavaValue.create(myNodeManager.getLocalVariableDescriptor(null, local), evaluationContext, myNodeManager)); @@ -498,16 +497,17 @@ public Set getExpressions() { } @Override - public void visitElement(final PsiElement element) { + @RequiredReadAction + public void visitElement(PsiElement element) { if (myLineRange.intersects(element.getTextRange())) { super.visitElement(element); } } @Override - public void visitMethodCallExpression(final PsiMethodCallExpression expression) { + public void visitMethodCallExpression(@Nonnull PsiMethodCallExpression expression) { if (myCollectExpressions) { - final PsiMethod psiMethod = expression.resolveMethod(); + PsiMethod psiMethod = expression.resolveMethod(); if (psiMethod != null && !DebuggerUtils.hasSideEffectsOrReferencesMissingVars(expression, myVisibleLocals)) { myExpressions.add(new TextWithImportsImpl(expression)); } @@ -516,34 +516,33 @@ public void visitMethodCallExpression(final PsiMethodCallExpression expression) } @Override - public void visitReferenceExpression(final PsiReferenceExpression reference) { + @RequiredReadAction + public void visitReferenceExpression(PsiReferenceExpression reference) { if (myLineRange.intersects(reference.getTextRange())) { - final PsiElement psiElement = reference.resolve(); - if (psiElement instanceof PsiVariable) { - final PsiVariable var = (PsiVariable)psiElement; - if (var instanceof PsiField) { + if (reference.resolve() instanceof PsiVariable var) { + if (var instanceof PsiField field) { if (myCollectExpressions && !DebuggerUtils.hasSideEffectsOrReferencesMissingVars(reference, myVisibleLocals)) { - /* - if (var instanceof PsiEnumConstant && reference.getQualifier() == null) { - final PsiClass enumClass = ((PsiEnumConstant)var).getContainingClass(); - if (enumClass != null) { - final PsiExpression expression = JavaPsiFacade.getInstance(var.getProject()).getParserFacade().createExpressionFromText(enumClass.getName() + "." + var.getName(), var); - final PsiReference ref = expression.getReference(); - if (ref != null) { - ref.bindToElement(var); - myExpressions.add(new TextWithImportsImpl(expression)); - } - } - } - else { - myExpressions.add(new TextWithImportsImpl(reference)); - } - */ - final PsiModifierList modifierList = var.getModifierList(); - boolean isConstant = - (var instanceof PsiEnumConstant) || (modifierList != null && modifierList.hasModifierProperty(PsiModifier.STATIC) && modifierList - .hasModifierProperty - (PsiModifier.FINAL)); + /* + if (var instanceof PsiEnumConstant && reference.getQualifier() == null) { + PsiClass enumClass = ((PsiEnumConstant)var).getContainingClass(); + if (enumClass != null) { + PsiExpression expression = JavaPsiFacade.getInstance(var.getProject()).getParserFacade() + .createExpressionFromText(enumClass.getName() + "." + var.getName(), var); + PsiReference ref = expression.getReference(); + if (ref != null) { + ref.bindToElement(var); + myExpressions.add(new TextWithImportsImpl(expression)); + } + } + } + else { + myExpressions.add(new TextWithImportsImpl(reference)); + } + */ + PsiModifierList modifierList = field.getModifierList(); + boolean isConstant = (field instanceof PsiEnumConstant) + || (modifierList != null && modifierList.hasModifierProperty(PsiModifier.STATIC) + && modifierList.hasModifierProperty(PsiModifier.FINAL)); if (!isConstant) { myExpressions.add(new TextWithImportsImpl(reference)); } @@ -553,14 +552,12 @@ public void visitReferenceExpression(final PsiReferenceExpression reference) { if (myVisibleLocals.contains(var.getName())) { myVars.add(var.getName()); } - else { + else if (!Objects.equals( + PsiTreeUtil.getParentOfType(reference, PsiClass.class), + PsiTreeUtil.getParentOfType(var, PsiClass.class) + )) { // fix for variables used in inner classes - if (!Comparing.equal( - PsiTreeUtil.getParentOfType(reference, PsiClass.class), - PsiTreeUtil.getParentOfType(var, PsiClass.class) - )) { - myExpressions.add(new TextWithImportsImpl(reference)); - } + myExpressions.add(new TextWithImportsImpl(reference)); } } } @@ -569,7 +566,7 @@ public void visitReferenceExpression(final PsiReferenceExpression reference) { } @Override - public void visitArrayAccessExpression(final PsiArrayAccessExpression expression) { + public void visitArrayAccessExpression(@Nonnull PsiArrayAccessExpression expression) { if (myCollectExpressions && !DebuggerUtils.hasSideEffectsOrReferencesMissingVars(expression, myVisibleLocals)) { myExpressions.add(new TextWithImportsImpl(expression)); } @@ -577,25 +574,28 @@ public void visitArrayAccessExpression(final PsiArrayAccessExpression expression } @Override - public void visitParameter(final PsiParameter parameter) { + @RequiredReadAction + public void visitParameter(@Nonnull PsiParameter parameter) { processVariable(parameter); super.visitParameter(parameter); } @Override - public void visitLocalVariable(final PsiLocalVariable variable) { + @RequiredReadAction + public void visitLocalVariable(@Nonnull PsiLocalVariable variable) { processVariable(variable); super.visitLocalVariable(variable); } - private void processVariable(final PsiVariable variable) { + @RequiredReadAction + private void processVariable(PsiVariable variable) { if (myLineRange.intersects(variable.getTextRange()) && myVisibleLocals.contains(variable.getName())) { myVars.add(variable.getName()); } } @Override - public void visitClass(final PsiClass aClass) { + public void visitClass(@Nonnull PsiClass aClass) { // Do not step in to local and anonymous classes... } } @@ -604,10 +604,11 @@ protected List getVisibleVariables() throws EvaluateExce return getStackFrameProxy().visibleVariables(); } - private static boolean shouldSkipLine(final PsiFile file, Document doc, int line) { - final int start = doc.getLineStartOffset(line); - final int end = doc.getLineEndOffset(line); - final int _start = CharArrayUtil.shiftForward(doc.getCharsSequence(), start, " \n\t"); + @RequiredReadAction + private static boolean shouldSkipLine(PsiFile file, Document doc, int line) { + int start = doc.getLineStartOffset(line); + int end = doc.getLineEndOffset(line); + int _start = CharArrayUtil.shiftForward(doc.getCharsSequence(), start, " \n\t"); if (_start >= end) { return true; } @@ -619,19 +620,17 @@ private static boolean shouldSkipLine(final PsiFile file, Document doc, int line for (PsiElement _elem = elem; _elem.getTextOffset() >= _start; _elem = _elem.getParent()) { alreadyChecked = _elem.getTextRange(); - if (_elem instanceof PsiDeclarationStatement) { - final PsiElement[] declared = ((PsiDeclarationStatement)_elem).getDeclaredElements(); - for (PsiElement declaredElement : declared) { + if (_elem instanceof PsiDeclarationStatement declaration) { + for (PsiElement declaredElement : declaration.getDeclaredElements()) { if (declaredElement instanceof PsiVariable) { return false; } } } - if (_elem instanceof PsiJavaCodeReferenceElement) { + if (_elem instanceof PsiJavaCodeReferenceElement javaCodeRef) { try { - final PsiElement resolved = ((PsiJavaCodeReferenceElement)_elem).resolve(); - if (resolved instanceof PsiVariable) { + if (javaCodeRef.resolve() instanceof PsiVariable) { return false; } } @@ -644,40 +643,41 @@ private static boolean shouldSkipLine(final PsiFile file, Document doc, int line return true; } + @RequiredReadAction private static Pair, Set> findReferencedVars(Set visibleVars, @Nonnull SourcePosition position) { - final int line = position.getLine(); + int line = position.getLine(); if (line < 0) { return Pair.create(Collections.emptySet(), Collections.emptySet()); } - final PsiFile positionFile = position.getFile(); + PsiFile positionFile = position.getFile(); if (!positionFile.isValid() || !positionFile.getLanguage().isKindOf(JavaLanguage.INSTANCE)) { return Pair.create(visibleVars, Collections.emptySet()); } - final VirtualFile vFile = positionFile.getVirtualFile(); - final Document doc = vFile != null ? FileDocumentManager.getInstance().getDocument(vFile) : null; + VirtualFile vFile = positionFile.getVirtualFile(); + Document doc = vFile != null ? FileDocumentManager.getInstance().getDocument(vFile) : null; if (doc == null || doc.getLineCount() == 0 || line > (doc.getLineCount() - 1)) { return Pair.create(Collections.emptySet(), Collections.emptySet()); } - final TextRange limit = calculateLimitRange(positionFile, doc, line); + TextRange limit = calculateLimitRange(positionFile, doc, line); int startLine = Math.max(limit.getStartOffset(), line - 1); startLine = Math.min(startLine, limit.getEndOffset()); while (startLine > limit.getStartOffset() && shouldSkipLine(positionFile, doc, startLine)) { startLine--; } - final int startOffset = doc.getLineStartOffset(startLine); + int startOffset = doc.getLineStartOffset(startLine); int endLine = Math.min(line + 2, limit.getEndOffset()); while (endLine < limit.getEndOffset() && shouldSkipLine(positionFile, doc, endLine)) { endLine++; } - final int endOffset = doc.getLineEndOffset(endLine); + int endOffset = doc.getLineEndOffset(endLine); - final TextRange lineRange = new TextRange(startOffset, endOffset); + TextRange lineRange = new TextRange(startOffset, endOffset); if (!lineRange.isEmpty()) { - final int offset = CharArrayUtil.shiftForward(doc.getCharsSequence(), doc.getLineStartOffset(line), " \t"); + int offset = CharArrayUtil.shiftForward(doc.getCharsSequence(), doc.getLineStartOffset(line), " \t"); PsiElement element = positionFile.findElementAt(offset); if (element != null) { PsiMethod method = PsiTreeUtil.getNonStrictParentOfType(element, PsiMethod.class); @@ -690,7 +690,7 @@ private static Pair, Set> findReferencedVars(Set, Set> findReferencedVars(SetemptySet()); } - private static TextRange calculateLimitRange(final PsiFile file, final Document doc, final int line) { - final int offset = doc.getLineStartOffset(line); + @RequiredReadAction + private static TextRange calculateLimitRange(PsiFile file, Document doc, int line) { + int offset = doc.getLineStartOffset(line); if (offset > 0) { PsiMethod method = PsiTreeUtil.getParentOfType(file.findElementAt(offset), PsiMethod.class, false); if (method != null) { - final TextRange elemRange = method.getTextRange(); + TextRange elemRange = method.getTextRange(); return new TextRange(doc.getLineNumber(elemRange.getStartOffset()), doc.getLineNumber(elemRange.getEndOffset())); } } return new TextRange(0, doc.getLineCount() - 1); } - private static TextRange adjustRange(final PsiElement element, final TextRange originalRange) { - final Ref rangeRef = new Ref<>(originalRange); + private static TextRange adjustRange(PsiElement element, TextRange originalRange) { + SimpleReference rangeRef = SimpleReference.create(originalRange); element.accept(new JavaRecursiveElementVisitor() { @Override - public void visitExpressionStatement(final PsiExpressionStatement statement) { - final TextRange stRange = statement.getTextRange(); + @RequiredReadAction + public void visitExpressionStatement(@Nonnull PsiExpressionStatement statement) { + TextRange stRange = statement.getTextRange(); if (originalRange.intersects(stRange)) { - final TextRange currentRange = rangeRef.get(); - final int start = Math.min(currentRange.getStartOffset(), stRange.getStartOffset()); - final int end = Math.max(currentRange.getEndOffset(), stRange.getEndOffset()); + TextRange currentRange = rangeRef.get(); + int start = Math.min(currentRange.getStartOffset(), stRange.getStartOffset()); + int end = Math.max(currentRange.getEndOffset(), stRange.getEndOffset()); rangeRef.set(new TextRange(start, end)); } } diff --git a/java-debugger-impl/src/main/java/com/intellij/java/debugger/impl/engine/RequestHint.java b/java-debugger-impl/src/main/java/com/intellij/java/debugger/impl/engine/RequestHint.java index 884f16644d..867b10fa8d 100644 --- a/java-debugger-impl/src/main/java/com/intellij/java/debugger/impl/engine/RequestHint.java +++ b/java-debugger-impl/src/main/java/com/intellij/java/debugger/impl/engine/RequestHint.java @@ -73,37 +73,40 @@ public class RequestHint { private boolean myRestoreBreakpoints = false; public RequestHint( - final ThreadReferenceProxyImpl stepThread, - final SuspendContextImpl suspendContext, + ThreadReferenceProxyImpl stepThread, + SuspendContextImpl suspendContext, @Nonnull MethodFilter methodFilter ) { this(stepThread, suspendContext, StepRequest.STEP_LINE, StepRequest.STEP_INTO, methodFilter); } public RequestHint( - final ThreadReferenceProxyImpl stepThread, - final SuspendContextImpl suspendContext, + ThreadReferenceProxyImpl stepThread, + SuspendContextImpl suspendContext, @MagicConstant(intValues = { StepRequest.STEP_INTO, StepRequest.STEP_OVER, StepRequest.STEP_OUT - }) int depth + }) + int depth ) { this(stepThread, suspendContext, StepRequest.STEP_LINE, depth, null); } protected RequestHint( - final ThreadReferenceProxyImpl stepThread, - final SuspendContextImpl suspendContext, + ThreadReferenceProxyImpl stepThread, + SuspendContextImpl suspendContext, @MagicConstant(intValues = { StepRequest.STEP_MIN, StepRequest.STEP_LINE - }) int stepSize, + }) + int stepSize, @MagicConstant(intValues = { StepRequest.STEP_INTO, StepRequest.STEP_OVER, StepRequest.STEP_OUT - }) int depth, + }) + int depth, @Nullable MethodFilter methodFilter ) { mySize = stepSize; @@ -197,7 +200,7 @@ protected boolean isTheSameFrame(SuspendContextImpl context) { if (mySteppedOut) { return false; } - final ThreadReferenceProxyImpl contextThread = context.getThread(); + ThreadReferenceProxyImpl contextThread = context.getThread(); if (contextThread != null) { try { int currentDepth = contextThread.frameCount(); @@ -226,9 +229,9 @@ protected boolean isSteppedOut() { return mySteppedOut; } - public int getNextStepDepth(final SuspendContextImpl context) { + public int getNextStepDepth(SuspendContextImpl context) { try { - final StackFrameProxyImpl frameProxy = context.getFrameProxy(); + StackFrameProxyImpl frameProxy = context.getFrameProxy(); // smart step feature stop check if (myMethodFilter != null && frameProxy != null && !(myMethodFilter instanceof BreakpointStepMethodFilter) @@ -248,17 +251,17 @@ public int getNextStepDepth(final SuspendContextImpl context) { return null; }); if (resultDepth != null) { - return resultDepth.intValue(); + return resultDepth; } } } // Now check filters - final DebuggerSettings settings = DebuggerSettings.getInstance(); + DebuggerSettings settings = DebuggerSettings.getInstance(); if ((myMethodFilter != null || (settings.SKIP_SYNTHETIC_METHODS && !myIgnoreFilters)) && frameProxy != null) { - final Location location = frameProxy.location(); + Location location = frameProxy.location(); if (location != null) { if (DebuggerUtils.isSynthetic(location.method())) { return myDepth; @@ -268,11 +271,10 @@ public int getNextStepDepth(final SuspendContextImpl context) { if (!myIgnoreFilters) { if (settings.SKIP_GETTERS) { - boolean isGetter = ReadAction.compute(() -> - { + boolean isGetter = ReadAction.compute(() -> { PsiElement contextElement = ContextUtil.getContextElement(context); return contextElement != null && DebuggerUtils.isInsideSimpleGetter(contextElement); - }).booleanValue(); + }); if (isGetter) { return StepRequest.STEP_OUT; @@ -281,9 +283,9 @@ public int getNextStepDepth(final SuspendContextImpl context) { if (frameProxy != null) { if (settings.SKIP_CONSTRUCTORS) { - final Location location = frameProxy.location(); + Location location = frameProxy.location(); if (location != null) { - final Method method = location.method(); + Method method = location.method(); if (method != null && method.isConstructor()) { return StepRequest.STEP_OUT; } @@ -291,7 +293,7 @@ public int getNextStepDepth(final SuspendContextImpl context) { } if (settings.SKIP_CLASSLOADERS) { - final Location location = frameProxy.location(); + Location location = frameProxy.location(); if (location != null && DebuggerUtilsEx.isAssignableFrom("java.lang.ClassLoader", location.declaringType())) { return StepRequest.STEP_OUT; } @@ -321,5 +323,4 @@ public int getNextStepDepth(final SuspendContextImpl context) { } return STOP; } - } diff --git a/java-debugger-impl/src/main/java/com/intellij/java/debugger/impl/ui/DebuggerPanelsManager.java b/java-debugger-impl/src/main/java/com/intellij/java/debugger/impl/ui/DebuggerPanelsManager.java index 9517c960dd..9a3a5f5420 100644 --- a/java-debugger-impl/src/main/java/com/intellij/java/debugger/impl/ui/DebuggerPanelsManager.java +++ b/java-debugger-impl/src/main/java/com/intellij/java/debugger/impl/ui/DebuggerPanelsManager.java @@ -42,92 +42,101 @@ @ServiceAPI(value = ComponentScope.PROJECT, lazy = false) @ServiceImpl public class DebuggerPanelsManager { - private final Project myProject; + private final Project myProject; - @Inject - public DebuggerPanelsManager(Project project) { - myProject = project; - if (project.isDefault()) { - return; - } - - myProject.getMessageBus().connect(myProject).subscribe(RunContentWithExecutorListener.class, new RunContentWithExecutorListener() { - @Override - public void contentSelected(@Nullable RunContentDescriptor descriptor, @Nonnull Executor executor) { - if (executor == DefaultDebugExecutor.getDebugExecutorInstance()) { - DebuggerSession session = descriptor == null ? null : getSession(myProject, descriptor); - if (session != null) { - getContextManager().setState(session.getContextManager().getContext(), session.getState(), DebuggerSession.Event.CONTEXT, null); - } - else { - getContextManager().setState(DebuggerContextImpl.EMPTY_CONTEXT, - DebuggerSession.State.DISPOSED, - DebuggerSession.Event.CONTEXT, - null); - } + @Inject + public DebuggerPanelsManager(Project project) { + myProject = project; + if (project.isDefault()) { + return; } - } - - @Override - public void contentRemoved(@Nullable RunContentDescriptor descriptor, @Nonnull Executor executor) { - } - }); - } - - private DebuggerStateManager getContextManager() { - return DebuggerManagerEx.getInstanceEx(myProject).getContextManager(); - } - @Nullable - public RunContentDescriptor attachVirtualMachine(@Nonnull ExecutionEnvironment environment, - RunProfileState state, - RemoteConnection remoteConnection, - boolean pollConnection) throws ExecutionException { - return attachVirtualMachine(new DefaultDebugUIEnvironment(environment, state, remoteConnection, pollConnection)); - } + myProject.getMessageBus().connect(myProject).subscribe(RunContentWithExecutorListener.class, new RunContentWithExecutorListener() { + @Override + public void contentSelected(@Nullable RunContentDescriptor descriptor, @Nonnull Executor executor) { + if (executor == DefaultDebugExecutor.getDebugExecutorInstance()) { + DebuggerSession session = descriptor == null ? null : getSession(myProject, descriptor); + if (session != null) { + getContextManager().setState( + session.getContextManager().getContext(), + session.getState(), + DebuggerSession.Event.CONTEXT + ); + } + else { + getContextManager().setState( + DebuggerContextImpl.EMPTY_CONTEXT, + DebuggerSession.State.DISPOSED, + DebuggerSession.Event.CONTEXT + ); + } + } + } - @Nullable - public RunContentDescriptor attachVirtualMachine(DebugUIEnvironment environment) throws ExecutionException { - final DebugEnvironment modelEnvironment = environment.getEnvironment(); - final DebuggerSession debuggerSession = DebuggerManagerEx.getInstanceEx(myProject).attachVirtualMachine(modelEnvironment); - if (debuggerSession == null) { - return null; + @Override + public void contentRemoved(@Nullable RunContentDescriptor descriptor, @Nonnull Executor executor) { + } + }); } - final DebugProcessImpl debugProcess = debuggerSession.getProcess(); - if (debugProcess.isDetached() || debugProcess.isDetaching()) { - debuggerSession.dispose(); - return null; + private DebuggerStateManager getContextManager() { + return DebuggerManagerEx.getInstanceEx(myProject).getContextManager(); } - if (modelEnvironment.isRemote()) { - // optimization: that way BatchEvaluator will not try to lookup the class file in remote VM - // which is an expensive operation when executed first time - debugProcess.putUserData(BatchEvaluator.REMOTE_SESSION_KEY, Boolean.TRUE); + + @Nullable + public RunContentDescriptor attachVirtualMachine( + @Nonnull ExecutionEnvironment environment, + RunProfileState state, + RemoteConnection remoteConnection, + boolean pollConnection + ) throws ExecutionException { + return attachVirtualMachine(new DefaultDebugUIEnvironment(environment, state, remoteConnection, pollConnection)); } - XDebugSession debugSession = XDebuggerManager.getInstance(myProject) - .startSessionAndShowTab(modelEnvironment.getSessionName(), - environment.getReuseContent(), - new XDebugProcessStarter() { - @Override - @Nonnull - public XDebugProcess start(@Nonnull XDebugSession session) { - return JavaDebugProcess.create(session, debuggerSession); - } - }); - return debugSession.getRunContentDescriptor(); - } + @Nullable + public RunContentDescriptor attachVirtualMachine(DebugUIEnvironment environment) throws ExecutionException { + DebugEnvironment modelEnvironment = environment.getEnvironment(); + DebuggerSession debuggerSession = DebuggerManagerEx.getInstanceEx(myProject).attachVirtualMachine(modelEnvironment); + if (debuggerSession == null) { + return null; + } - public static DebuggerPanelsManager getInstance(Project project) { - return project.getComponent(DebuggerPanelsManager.class); - } + DebugProcessImpl debugProcess = debuggerSession.getProcess(); + if (debugProcess.isDetached() || debugProcess.isDetaching()) { + debuggerSession.dispose(); + return null; + } + if (modelEnvironment.isRemote()) { + // optimization: that way BatchEvaluator will not try to lookup the class file in remote VM + // which is an expensive operation when executed first time + debugProcess.putUserData(BatchEvaluator.REMOTE_SESSION_KEY, Boolean.TRUE); + } + + XDebugSession debugSession = XDebuggerManager.getInstance(myProject) + .startSessionAndShowTab( + modelEnvironment.getSessionName(), + environment.getReuseContent(), + new XDebugProcessStarter() { + @Override + @Nonnull + public XDebugProcess start(@Nonnull XDebugSession session) { + return JavaDebugProcess.create(session, debuggerSession); + } + } + ); + return debugSession.getRunContentDescriptor(); + } - private static DebuggerSession getSession(Project project, RunContentDescriptor descriptor) { - for (JavaDebugProcess process : XDebuggerManager.getInstance(project).getDebugProcesses(JavaDebugProcess.class)) { - if (Comparing.equal(process.getProcessHandler(), descriptor.getProcessHandler())) { - return process.getDebuggerSession(); - } + public static DebuggerPanelsManager getInstance(Project project) { + return project.getComponent(DebuggerPanelsManager.class); + } + + private static DebuggerSession getSession(Project project, RunContentDescriptor descriptor) { + for (JavaDebugProcess process : XDebuggerManager.getInstance(project).getDebugProcesses(JavaDebugProcess.class)) { + if (Comparing.equal(process.getProcessHandler(), descriptor.getProcessHandler())) { + return process.getDebuggerSession(); + } + } + return null; } - return null; - } }