diff --git a/java/compiler/impl/src/com/intellij/compiler/CompilerConfigurationImpl.java b/java/compiler/impl/src/com/intellij/compiler/CompilerConfigurationImpl.java index 95fb5b6d587b..8f30f69772d4 100644 --- a/java/compiler/impl/src/com/intellij/compiler/CompilerConfigurationImpl.java +++ b/java/compiler/impl/src/com/intellij/compiler/CompilerConfigurationImpl.java @@ -535,7 +535,6 @@ public class CompilerConfigurationImpl extends CompilerConfiguration implements } myProcessorPath = pathBuilder.toString(); - myProcessorPath = annotationProcessingSettings.getAttributeValue("processorPath", ""); myProcessorsMap.clear(); for (Element processorChild : ((Collection)annotationProcessingSettings.getChildren("processor"))) { final String name = processorChild.getAttributeValue("name"); diff --git a/java/compiler/impl/src/com/intellij/compiler/ant/BuildTargetsFactoryImpl.java b/java/compiler/impl/src/com/intellij/compiler/ant/BuildTargetsFactoryImpl.java index aa3b7e98cf47..4065ab8fcb7e 100644 --- a/java/compiler/impl/src/com/intellij/compiler/ant/BuildTargetsFactoryImpl.java +++ b/java/compiler/impl/src/com/intellij/compiler/ant/BuildTargetsFactoryImpl.java @@ -21,7 +21,6 @@ package com.intellij.compiler.ant; import com.intellij.compiler.ant.j2ee.BuildExplodedTarget; -import com.intellij.compiler.ant.j2ee.BuildJarTarget; import com.intellij.compiler.ant.j2ee.CompositeBuildTarget; import com.intellij.compiler.ant.taskdefs.Target; import com.intellij.openapi.compiler.make.BuildRecipe; @@ -42,10 +41,6 @@ public class BuildTargetsFactoryImpl extends BuildTargetsFactory { return new BuildExplodedTarget(parameters, buildRecipe, description); } - public Target createBuildJarTarget(final ExplodedAndJarTargetParameters parameters, final BuildRecipe buildRecipe, final String description) { - return new BuildJarTarget(parameters, buildRecipe, description); - } - public Generator createComment(final String comment) { return new Comment(comment); diff --git a/java/compiler/impl/src/com/intellij/compiler/ant/j2ee/BuildJarTarget.java b/java/compiler/impl/src/com/intellij/compiler/ant/j2ee/BuildJarTarget.java deleted file mode 100644 index b5d3bd0892e9..000000000000 --- a/java/compiler/impl/src/com/intellij/compiler/ant/j2ee/BuildJarTarget.java +++ /dev/null @@ -1,175 +0,0 @@ -/* - * Copyright 2000-2009 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -/** - * @author cdr - */ -package com.intellij.compiler.ant.j2ee; - -import com.intellij.compiler.ant.BuildProperties; -import com.intellij.compiler.ant.ExplodedAndJarTargetParameters; -import com.intellij.compiler.ant.GenerationUtils; -import com.intellij.compiler.ant.Tag; -import com.intellij.compiler.ant.taskdefs.*; -import com.intellij.compiler.make.ExplodedAndJarBuildGenerator; -import com.intellij.openapi.compiler.make.*; -import com.intellij.openapi.deployment.DeploymentUtil; -import com.intellij.openapi.extensions.Extensions; -import com.intellij.openapi.module.Module; -import com.intellij.openapi.util.Ref; -import org.jetbrains.annotations.NonNls; - -import java.io.File; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; - -public class BuildJarTarget extends Target { - - public BuildJarTarget(final ExplodedAndJarTargetParameters parameters, - final BuildRecipe buildRecipe, - final String description) { - super(parameters.getBuildJarTargetName(), null, description, null); - final File moduleBaseDir = parameters.getChunk().getBaseDir(); - - BuildConfiguration buildConfiguration = parameters.getBuildConfiguration(); - //noinspection HardCodedStringLiteral - final File jarDir = new File(buildConfiguration.isJarEnabled() ? new File(buildConfiguration.getJarPath()).getParentFile() : moduleBaseDir, "/temp"); - String tempDir = GenerationUtils.toRelativePath(jarDir.getPath(), parameters.getChunk(), parameters.getGenerationOptions()); - final String tempDirProperty = BuildProperties.getTempDirForModuleProperty(parameters.getContainingModule().getName()); - final boolean[] tempDirUsed = new boolean[] { false }; - - final ExplodedAndJarBuildGenerator[] generators = Extensions.getExtensions(DefaultExplodedAndJarBuildGenerator.EP_NAME); - final List zipFileSetTags = new ArrayList(); - buildRecipe.visitInstructions(new BuildInstructionVisitor() { - public boolean visitInstruction(final BuildInstruction instruction) throws Exception { - for (final ExplodedAndJarBuildGenerator generator : generators) { - final Ref ref = new Ref(false); - final ZipFileSet[] tags = generator.generateTagsForJarTarget(instruction, parameters, ref); - if (tags != null) { - if (ref.get() != null && ref.get()) { - tempDirUsed[0] = true; - } - zipFileSetTags.addAll(Arrays.asList(tags)); - return true; - } - } - final Ref ref = Ref.create(false); - zipFileSetTags.addAll(Arrays.asList(DefaultExplodedAndJarBuildGenerator.INSTANCE.generateTagsForJarTarget(instruction, parameters, ref))); - if (ref.get() != null && ref.get()) { - tempDirUsed[0] = true; - } - return super.visitInstruction(instruction); - } - }, false); - if (tempDirUsed[0]) { - add(new Property(tempDirProperty, tempDir)); - add(new Mkdir(BuildProperties.propertyRef(tempDirProperty))); - } - final List prepareTags = new ArrayList(); - buildRecipe.visitInstructions(new BuildInstructionVisitor() { - public boolean visitInstruction(final BuildInstruction instruction) throws Exception { - for (final ExplodedAndJarBuildGenerator generator : generators) { - final Tag[] tags = generator.generateJarBuildPrepareTags(instruction, parameters); - if (tags != null) { - prepareTags.addAll(Arrays.asList(tags)); - return true; - } - } - prepareTags.addAll(Arrays.asList(DefaultExplodedAndJarBuildGenerator.INSTANCE.generateJarBuildPrepareTags(instruction, parameters))); - return super.visitInstruction(instruction); - } - }, false); - for (Tag tag : prepareTags) { - add(tag); - } - final String destFile = BuildProperties.propertyRef(parameters.getJarPathParameter()); - final @NonNls String jarDirProperty = "jar.dir"; - add(new Dirname(jarDirProperty, destFile)); - add(new Mkdir(BuildProperties.propertyRef(jarDirProperty))); - final Jar jarTag = new Jar(destFile, "preserve"); - add(jarTag); - final java.util.jar.Manifest manifest = DeploymentUtil.getInstance().createManifest(buildRecipe); - - if (manifest != null) { - final Manifest manifestTag = new Manifest(); - jarTag.add(manifestTag); - manifestTag.applyAttributes(manifest); - } - - for (ZipFileSet zipFileSet : zipFileSetTags) { - jarTag.add(zipFileSet); - } - if (tempDirUsed[0]) { - add(new Delete(BuildProperties.propertyRef(tempDirProperty))); - } - - // emit copy commands for dependencies - buildRecipe.visitInstructions(new BuildInstructionVisitor() { - private int myJarDirCount = 2; - - public boolean visitFileCopyInstruction(FileCopyInstruction instruction) throws Exception { - if (!instruction.isExternalDependencyInstruction()) return true; - final File sourceFile = instruction.getFile(); - final String outputRelativePath = DeploymentUtil.appendToPath("/",instruction.getOutputRelativePath()); - final Module instructionModule = instruction.getModule(); - String sourceLocation = GenerationUtils.toRelativePath(sourceFile.getPath(), moduleBaseDir, instructionModule, - parameters.getGenerationOptions()); - String jarPathPropertyRef = BuildProperties.propertyRef(parameters.getJarPathParameter()); - - final Copy copy; - if (instruction.isDirectory()) { - copy = new Copy(DeploymentUtil.appendToPath(jarPathPropertyRef,outputRelativePath)); - copy.add(new FileSet(sourceLocation)); - } - else { - copy = new Copy(sourceLocation, DeploymentUtil.appendToPath(jarPathPropertyRef,outputRelativePath)); - } - - add(copy); - return true; - } - - public boolean visitJarAndCopyBuildInstruction(JarAndCopyBuildInstruction instruction) throws Exception { - if (!instruction.isExternalDependencyInstruction()) return true; - String jarPathPropertyRef = BuildProperties.propertyRef(parameters.getJarPathParameter()); - String pathToCreateJar = jarPathPropertyRef + DeploymentUtil.appendToPath("/",instruction.getOutputRelativePath()); - @NonNls final String jarDir = "jar.dir" + myJarDirCount++; - add(new Dirname(jarDir, pathToCreateJar)); - add(new Mkdir(BuildProperties.propertyRef(jarDir))); - add(DefaultExplodedAndJarBuildGenerator.generateJarTag(instruction, pathToCreateJar, moduleBaseDir, parameters.getGenerationOptions())); - return true; - } - - @Override - public boolean visitCompoundBuildInstruction(final CompoundBuildInstruction instruction) throws Exception { - if (!instruction.isExternalDependencyInstruction()) return true; - String outputPath = DeploymentUtil.appendToPath(BuildProperties.propertyRef(parameters.getJarPathParameter()), instruction.getOutputRelativePath()); - if (instruction.getBuildProperties().isJarEnabled()) { - String jarPath = BuildProperties.propertyRef(parameters.getCompoundBuildInstructionNaming().getJarPathProperty(instruction)); - add(new Copy(jarPath, outputPath)); - } - else { - AntCall call = new AntCall(parameters.getCompoundBuildInstructionNaming().getBuildJarTargetName(instruction)); - call.add(new Param(parameters.getJarPathParameter(), outputPath)); - add(call); - } - return true; - } - }, false); - } - -} \ No newline at end of file diff --git a/java/compiler/impl/src/com/intellij/compiler/ant/j2ee/CompositeBuildTarget.java b/java/compiler/impl/src/com/intellij/compiler/ant/j2ee/CompositeBuildTarget.java index d793eebe1014..46fdb2a75163 100644 --- a/java/compiler/impl/src/com/intellij/compiler/ant/j2ee/CompositeBuildTarget.java +++ b/java/compiler/impl/src/com/intellij/compiler/ant/j2ee/CompositeBuildTarget.java @@ -41,7 +41,6 @@ public class CompositeBuildTarget extends CompositeGenerator { final String depends, @Nullable String jarPath) { final File moduleBaseDir = parameters.getChunk().getBaseDir(); - final Module containingModule = parameters.getContainingModule(); final Target buildTarget = new Target(targetName, depends, targetDescription, null); final BuildConfiguration buildConfiguration = parameters.getBuildConfiguration(); diff --git a/java/compiler/impl/src/com/intellij/compiler/ant/j2ee/DefaultExplodedAndJarBuildGenerator.java b/java/compiler/impl/src/com/intellij/compiler/ant/j2ee/DefaultExplodedAndJarBuildGenerator.java index aeb088abd1ad..e27520f60659 100644 --- a/java/compiler/impl/src/com/intellij/compiler/ant/j2ee/DefaultExplodedAndJarBuildGenerator.java +++ b/java/compiler/impl/src/com/intellij/compiler/ant/j2ee/DefaultExplodedAndJarBuildGenerator.java @@ -19,11 +19,8 @@ import com.intellij.compiler.ant.*; import com.intellij.compiler.ant.taskdefs.*; import com.intellij.compiler.make.ExplodedAndJarBuildGenerator; import com.intellij.compiler.make.MakeUtil; -import com.intellij.openapi.compiler.DummyCompileContext; import com.intellij.openapi.compiler.make.*; import com.intellij.openapi.module.Module; -import com.intellij.openapi.util.Ref; -import com.intellij.util.PathUtil; import com.intellij.util.SmartList; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; @@ -77,23 +74,6 @@ public class DefaultExplodedAndJarBuildGenerator extends ExplodedAndJarBuildGene return true; } - public boolean visitCompoundBuildInstruction(CompoundBuildInstruction instruction) throws RuntimeException { - if (instruction.isExternalDependencyInstruction()) return true; - final String outputRelativePath = "/" + instruction.getOutputRelativePath(); - final String outputPath = BuildProperties.propertyRef(parameters.getExplodedPathParameter()) + outputRelativePath; - - final Tag tag; - if (instruction.getBuildProperties().isExplodedEnabled()) { - tag = new Copy(outputPath); - tag.add(new FileSet(BuildProperties.propertyRef(parameters.getCompoundBuildInstructionNaming().getExplodedPathProperty(instruction)))); - } - else { - tag = new AntCall(parameters.getCompoundBuildInstructionNaming().getBuildExplodedTargetName(instruction)); - tag.add(new Param(parameters.getExplodedPathParameter(), outputPath)); - } - tags.add(tag); - return true; - } }); return tags.toArray(new Tag[tags.size()]); } @@ -124,108 +104,4 @@ public class DefaultExplodedAndJarBuildGenerator extends ExplodedAndJarBuildGene } - - @NotNull - public ZipFileSet[] generateTagsForJarTarget(@NotNull final BuildInstruction instruction, @NotNull final ExplodedAndJarTargetParameters parameters, - final Ref tempDirUsed) - throws Exception { - final List zipFileSetTags = new SmartList(); - final String tempDirProperty = BuildProperties.getTempDirForModuleProperty(parameters.getContainingModule().getName()); - final File moduleBaseDir = parameters.getChunk().getBaseDir(); - instruction.accept(new BuildInstructionVisitor() { - public boolean visitFileCopyInstruction(FileCopyInstruction instruction) throws RuntimeException { - if (instruction.isExternalDependencyInstruction()) return true; - final File sourceFile = instruction.getFile(); - final Module instructionModule = instruction.getModule(); - final String sourceLocation = GenerationUtils.toRelativePath(sourceFile.getPath(), moduleBaseDir, instructionModule, - parameters.getGenerationOptions()); - final ZipFileSet fileSet = new ZipFileSet(sourceLocation, instruction.getOutputRelativePath(), instruction.isDirectory()); - - zipFileSetTags.add(fileSet); - return true; - } - - public boolean visitJarAndCopyBuildInstruction(JarAndCopyBuildInstruction instruction) throws RuntimeException { - if (instruction.isExternalDependencyInstruction()) return true; - tempDirUsed.set(true); - final String jarName = new File(instruction.getOutputRelativePath()).getName(); - final String destJarPath = BuildProperties.propertyRef(tempDirProperty)+"/"+jarName; - - zipFileSetTags.add(new ZipFileSet(destJarPath, instruction.getOutputRelativePath(), false)); - return true; - } - - public boolean visitCompoundBuildInstruction(CompoundBuildInstruction instruction) throws RuntimeException { - if (instruction.isExternalDependencyInstruction()) return true; - // gather child module dependencies - final BuildRecipe childModuleRecipe = instruction.getChildInstructions(DummyCompileContext.getInstance()); - childModuleRecipe.visitInstructions(new BuildInstructionVisitor() { - public boolean visitFileCopyInstruction(FileCopyInstruction instruction) throws RuntimeException { - if (!instruction.isExternalDependencyInstruction()) return true; - final File file = instruction.getFile(); - final Module instructionModule = instruction.getModule(); - String sourceLocation = GenerationUtils.toRelativePath(file.getPath(), moduleBaseDir, instructionModule, - parameters.getGenerationOptions()); - final String relPath = PathUtil.getCanonicalPath("/tmp/"+instruction.getOutputRelativePath()).substring(1); - final ZipFileSet zipFileSet = new ZipFileSet(sourceLocation, relPath, false); - zipFileSetTags.add(zipFileSet); - return true; - } - - public boolean visitJarAndCopyBuildInstruction(JarAndCopyBuildInstruction instruction) throws RuntimeException { - if (!instruction.isExternalDependencyInstruction()) return true; - final String relPath = PathUtil.getCanonicalPath("/tmp/"+instruction.getOutputRelativePath()).substring(1); - tempDirUsed.set(true); - final ZipFileSet zipFileSet = new ZipFileSet(BuildProperties.propertyRef(tempDirProperty) + "/" + relPath, relPath, false); - zipFileSetTags.add(zipFileSet); - return true; - } - }, false); - - if (instruction.getBuildProperties().isJarEnabled()) { - final ZipFileSet zipFileSet = new ZipFileSet(BuildProperties.propertyRef(parameters.getCompoundBuildInstructionNaming().getJarPathProperty(instruction)), instruction.getOutputRelativePath(), false); - zipFileSetTags.add(zipFileSet); - } - else { - final String jarName = new File(instruction.getOutputRelativePath()).getName(); - final String destJarPath = BuildProperties.propertyRef(tempDirProperty)+"/"+jarName; - tempDirUsed.set(true); - zipFileSetTags.add(new ZipFileSet(destJarPath, instruction.getOutputRelativePath(), false)); - } - return true; - } - }); - return zipFileSetTags.toArray(new ZipFileSet[zipFileSetTags.size()]); - } - - @NotNull - public Tag[] generateJarBuildPrepareTags(@NotNull final BuildInstruction instruction, @NotNull final ExplodedAndJarTargetParameters parameters) - throws Exception { - final List prepareTags = new SmartList(); - final String tempDirProperty = BuildProperties.getTempDirForModuleProperty(parameters.getContainingModule().getName()); - final File moduleBaseDir = parameters.getChunk().getBaseDir(); - instruction.accept(new BuildInstructionVisitor() { - - public boolean visitJarAndCopyBuildInstruction(JarAndCopyBuildInstruction instruction) throws RuntimeException { - if (instruction.isExternalDependencyInstruction()) return true; - final String jarName = new File(instruction.getOutputRelativePath()).getName(); - final String destJarPath = BuildProperties.propertyRef(tempDirProperty)+"/"+jarName; - prepareTags.add(generateJarTag(instruction, destJarPath, moduleBaseDir, parameters.getGenerationOptions())); - return true; - } - - public boolean visitCompoundBuildInstruction(CompoundBuildInstruction instruction) throws RuntimeException { - if (instruction.isExternalDependencyInstruction()) return true; - if (!instruction.getBuildProperties().isJarEnabled()) { - final String jarName = new File(instruction.getOutputRelativePath()).getName(); - final String destJarPath = BuildProperties.propertyRef(tempDirProperty)+"/"+jarName; - final AntCall makeJar = new AntCall(parameters.getCompoundBuildInstructionNaming().getBuildJarTargetName(instruction)); - prepareTags.add(makeJar); - makeJar.add(new Param(parameters.getJarPathParameter(), destJarPath)); - } - return true; - } - }); - return prepareTags.toArray(new Tag[prepareTags.size()]); - } } diff --git a/java/compiler/impl/src/com/intellij/compiler/impl/CompileDriver.java b/java/compiler/impl/src/com/intellij/compiler/impl/CompileDriver.java index cce777214891..f63641d9a7f6 100644 --- a/java/compiler/impl/src/com/intellij/compiler/impl/CompileDriver.java +++ b/java/compiler/impl/src/com/intellij/compiler/impl/CompileDriver.java @@ -478,7 +478,8 @@ public class CompileDriver { // in case another project was opened in the frame while the compiler was working (See SCR# 28591) statusBar.setInfo(statusMessage); if (duration > ONE_MINUTE_MS) { - ToolWindowManager.getInstance(myProject).notifyByBalloon(ToolWindowId.MESSAGES_WINDOW, MessageType.INFO, statusMessage); + final MessageType messageType = errorCount > 0 ? MessageType.ERROR : warningCount > 0 ? MessageType.WARNING : MessageType.INFO; + ToolWindowManager.getInstance(myProject).notifyByBalloon(ToolWindowId.MESSAGES_WINDOW, messageType, statusMessage); } } if (_status != ExitStatus.UP_TO_DATE && compileContext.getMessageCount(null) > 0) { diff --git a/java/compiler/impl/src/com/intellij/compiler/impl/TranslatingCompilerFilesMonitor.java b/java/compiler/impl/src/com/intellij/compiler/impl/TranslatingCompilerFilesMonitor.java index bf8174d7f8ea..c43bbd4bc3fb 100644 --- a/java/compiler/impl/src/com/intellij/compiler/impl/TranslatingCompilerFilesMonitor.java +++ b/java/compiler/impl/src/com/intellij/compiler/impl/TranslatingCompilerFilesMonitor.java @@ -169,18 +169,22 @@ public class TranslatingCompilerFilesMonitor implements ApplicationComponent { if (_forceCompile || pathsToRecompile != null && !pathsToRecompile.isEmpty()) { while (scopeSrcIterator.hasNext()) { final VirtualFile file = scopeSrcIterator.next(); - if (!file.isValid() || configuration.isExcludedFromCompilation(file) || !compiler.isCompilableFile(file, context)) { + if (!file.isValid()) { continue; } final int fileId = getFileId(file); if (_forceCompile) { - toCompile.add(file); - if (pathsToRecompile == null || !pathsToRecompile.contains(fileId)) { - addSourceForRecompilation(projectId, file, null); + if (compiler.isCompilableFile(file, context) && !configuration.isExcludedFromCompilation(file)) { + toCompile.add(file); + if (pathsToRecompile == null || !pathsToRecompile.contains(fileId)) { + addSourceForRecompilation(projectId, file, null); + } } } else if (pathsToRecompile.contains(fileId)) { - toCompile.add(file); + if (compiler.isCompilableFile(file, context) && !configuration.isExcludedFromCompilation(file)) { + toCompile.add(file); + } } } } diff --git a/java/compiler/impl/src/com/intellij/compiler/impl/javaCompiler/AnnotationProcessingCompiler.java b/java/compiler/impl/src/com/intellij/compiler/impl/javaCompiler/AnnotationProcessingCompiler.java index 8754e36642cb..70407ba1eb40 100644 --- a/java/compiler/impl/src/com/intellij/compiler/impl/javaCompiler/AnnotationProcessingCompiler.java +++ b/java/compiler/impl/src/com/intellij/compiler/impl/javaCompiler/AnnotationProcessingCompiler.java @@ -63,9 +63,13 @@ public class AnnotationProcessingCompiler implements SourceProcessingCompiler{ final List items = new ArrayList(files.length); final Set excludedModules = config.getExcludedModules(); for (final VirtualFile file : files) { - if (excludedModules.size() == 0 || !excludedModules.contains(context.getModuleByFile(file))) { - items.add(new MyProcessingItem(file)); + if (excludedModules.size() != 0 && excludedModules.contains(context.getModuleByFile(file))) { + continue; } + if (config.isExcludedFromCompilation(file)) { + continue; + } + items.add(new MyProcessingItem(file)); } return items.toArray(new ProcessingItem[items.size()]); } diff --git a/java/compiler/impl/src/com/intellij/compiler/impl/packagingCompiler/CompoundBuildInstructionImpl.java b/java/compiler/impl/src/com/intellij/compiler/impl/packagingCompiler/CompoundBuildInstructionImpl.java deleted file mode 100644 index 86474fa1e508..000000000000 --- a/java/compiler/impl/src/com/intellij/compiler/impl/packagingCompiler/CompoundBuildInstructionImpl.java +++ /dev/null @@ -1,214 +0,0 @@ -/* - * Copyright 2000-2009 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.intellij.compiler.impl.packagingCompiler; - -import com.intellij.openapi.compiler.CompileContext; -import com.intellij.openapi.compiler.CompilerBundle; -import com.intellij.openapi.compiler.CompilerMessageCategory; -import com.intellij.openapi.compiler.make.*; -import com.intellij.openapi.deployment.DeploymentUtil; -import com.intellij.openapi.diagnostic.Logger; -import com.intellij.openapi.util.Ref; -import com.intellij.openapi.util.io.FileUtil; -import com.intellij.util.PathUtil; -import com.intellij.util.io.ZipUtil; -import gnu.trove.THashSet; -import org.jetbrains.annotations.NonNls; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -import java.io.*; -import java.util.Collection; -import java.util.Set; -import java.util.jar.JarFile; -import java.util.jar.JarOutputStream; -import java.util.jar.Manifest; - -public class CompoundBuildInstructionImpl extends BuildInstructionBase implements CompoundBuildInstruction { - private static final Logger LOG = Logger.getInstance("#com.intellij.compiler.impl.packagingCompiler.CompoundBuildInstructionImpl"); - - private final BuildConfiguration myBuildConfiguration; - private final BuildParticipant myBuildParticipant; - @NonNls private static final String TMP_FILE_SUFFIX = ".tmp"; - - public CompoundBuildInstructionImpl(BuildParticipant buildParticipant, String outputRelativePath) { - super(outputRelativePath, buildParticipant.getModule()); - myBuildConfiguration = buildParticipant.getBuildConfiguration(); - myBuildParticipant = buildParticipant; - } - - public BuildParticipant getBuildParticipant() { - return myBuildParticipant; - } - - public boolean accept(BuildInstructionVisitor visitor) throws Exception { - return visitor.visitCompoundBuildInstruction(this); - } - - public void addFilesToJar(@NotNull final CompileContext context, - @NotNull final File jarFile, - @NotNull final JarOutputStream outputStream, - BuildRecipe dependencies, - @Nullable final Set writtenRelativePaths, - @Nullable final FileFilter fileFilter) throws IOException { - // create temp jars, and add these into upper level jar - // todo optimization: cache created jars - final File tempFile; - final BuildRecipe childDependencies = new BuildRecipeImpl(); - if (myBuildConfiguration.isJarEnabled()) { - tempFile = new File(myBuildConfiguration.getJarPath()); - final BuildRecipe childModuleRecipe = getChildInstructions(context); - childModuleRecipe.visitInstructions(new BuildInstructionVisitor() { - public boolean visitInstruction(BuildInstruction instruction) throws RuntimeException { - if (instruction.isExternalDependencyInstruction()) { - childDependencies.addInstruction(instruction); - } - return true; - } - }, false); - } - else { - tempFile = File.createTempFile("jar___", TMP_FILE_SUFFIX); - tempFile.deleteOnExit(); - makeJar(context, tempFile, childDependencies, fileFilter, true); - childDependencies.visitInstructions(new BuildInstructionVisitor() { - public boolean visitFileCopyInstruction(FileCopyInstruction instruction) throws Exception { - File file = new File(PathUtil.getCanonicalPath(DeploymentUtil.appendToPath(tempFile.getPath(), instruction.getOutputRelativePath()))); - addFileToDelete(file); - return true; - } - }, false); - } - ZipUtil.addFileToZip(outputStream, tempFile, getOutputRelativePath(), writtenRelativePaths, fileFilter); - try { - childDependencies.visitInstructionsWithExceptions(new BuildInstructionVisitor() { - public boolean visitFileCopyInstruction(FileCopyInstruction instruction) throws Exception { - File file = instruction.getFile(); - String dependencyRelativePath = PathUtil.getCanonicalPath(DeploymentUtil.appendToPath(getOutputRelativePath(), instruction.getOutputRelativePath())); - - ZipUtil.addFileOrDirRecursively(outputStream, jarFile, file, dependencyRelativePath, fileFilter, writtenRelativePaths); - return true; - } - - public boolean visitJarAndCopyBuildInstruction(JarAndCopyBuildInstruction instruction) throws Exception { - if (instruction.getJarFile() == null) { - File tempJar = File.createTempFile("___",TMP_FILE_SUFFIX); - addFileToDelete(tempJar); - instruction.makeJar(context, tempJar, fileFilter); - } - File jarFile = instruction.getJarFile(); - String dependencyRelativePath = PathUtil.getCanonicalPath(DeploymentUtil.appendToPath(getOutputRelativePath(), instruction.getOutputRelativePath())); - - ZipUtil.addFileToZip(outputStream, jarFile, dependencyRelativePath, writtenRelativePaths, fileFilter); - return true; - } - }, false); - } - catch (IOException e) { - throw e; - } - catch (RuntimeException e) { - throw e; - } - catch (Exception e) { - } - } - - // return jarFile and possible jars linked via manifest - public void makeJar(final CompileContext context, - final File jarFile, - final BuildRecipe dependencies, - final FileFilter fileFilter, - final boolean processExternalDependencies) throws IOException { - final BuildRecipe buildRecipe = getChildInstructions(context); - final Manifest manifest = DeploymentUtil.getInstance().createManifest(buildRecipe); - if (manifest == null) { - File file = DeploymentUtil.getInstance().findUserSuppliedManifestFile(buildRecipe); - LOG.assertTrue(file != null); - context.addMessage(CompilerMessageCategory.WARNING, CompilerBundle.message("message.text.using.user.supplied.manifest", file.getAbsolutePath()), null, -1, -1); - } - FileUtil.createParentDirs(jarFile); - final BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(jarFile)); - final JarOutputStream jarOutputStream = manifest == null ? new JarOutputStream(out) : new JarOutputStream(out, manifest); - - final Set tempWrittenRelativePaths = new THashSet(); - if (manifest != null) { - tempWrittenRelativePaths.add(JarFile.MANIFEST_NAME); - } - try { - buildRecipe.visitInstructionsWithExceptions(new BuildInstructionVisitor() { - public boolean visitInstruction(BuildInstruction instruction) throws IOException { - if (processExternalDependencies || !instruction.isExternalDependencyInstruction()) { - instruction.addFilesToJar(context, jarFile, jarOutputStream, dependencies, tempWrittenRelativePaths, fileFilter); - } - return true; - } - }, false); - } - catch (IOException e) { - throw e; - } - catch (RuntimeException e) { - throw e; - } - catch (Exception e) { - } - finally { - jarOutputStream.close(); - } - } - - public BuildRecipe getChildInstructions(CompileContext context) { - return myBuildParticipant.getBuildInstructions(context); - } - - public BuildConfiguration getBuildProperties() { - return myBuildConfiguration; - } - - public String toString() { - return "Java EE build instruction: " + myBuildParticipant + " -> " + getOutputRelativePath(); - } - - public File findFileByRelativePath(String relativePath) { - if (!relativePath.startsWith(getOutputRelativePath())) return null; - final String pathFromFile = relativePath.substring(getOutputRelativePath().length()); - final Ref file = new Ref(); - final BuildRecipe buildRecipe = getChildInstructions(null); - buildRecipe.visitInstructions(new BuildInstructionVisitor() { - public boolean visitInstruction(BuildInstruction instruction) throws RuntimeException { - final File found = instruction.findFileByRelativePath(pathFromFile); - if (found != null) { - file.set(found); - return false; - } - return true; - } - }, false); - return file.get(); - } - - public void collectFilesToDelete(final Collection filesToDelete) { - super.collectFilesToDelete(filesToDelete); - BuildRecipe childInstructions = getChildInstructions(null); - childInstructions.visitInstructions(new BuildInstructionVisitor() { - public boolean visitInstruction(BuildInstruction instruction) throws Exception { - ((BuildInstructionBase)instruction).collectFilesToDelete(filesToDelete); - return true; - } - }, false); - } -} diff --git a/java/compiler/impl/src/com/intellij/compiler/impl/packagingCompiler/FileCopyInstructionImpl.java b/java/compiler/impl/src/com/intellij/compiler/impl/packagingCompiler/FileCopyInstructionImpl.java index 3f4575f9fba9..4596c36c4cda 100644 --- a/java/compiler/impl/src/com/intellij/compiler/impl/packagingCompiler/FileCopyInstructionImpl.java +++ b/java/compiler/impl/src/com/intellij/compiler/impl/packagingCompiler/FileCopyInstructionImpl.java @@ -15,25 +15,16 @@ */ package com.intellij.compiler.impl.packagingCompiler; -import com.intellij.openapi.compiler.CompileContext; import com.intellij.openapi.compiler.CompilerBundle; import com.intellij.openapi.compiler.make.BuildInstructionVisitor; -import com.intellij.openapi.compiler.make.BuildRecipe; import com.intellij.openapi.compiler.make.FileCopyInstruction; import com.intellij.openapi.compiler.make.PackagingFileFilter; -import com.intellij.openapi.deployment.DeploymentUtil; import com.intellij.openapi.module.Module; import com.intellij.openapi.module.ModuleUtil; -import com.intellij.util.io.ZipUtil; -import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.io.File; -import java.io.FileFilter; -import java.io.IOException; import java.util.List; -import java.util.Set; -import java.util.jar.JarOutputStream; public class FileCopyInstructionImpl extends BuildInstructionBase implements FileCopyInstruction { private File myFile; @@ -68,41 +59,6 @@ public class FileCopyInstructionImpl extends BuildInstructionBase implements Fil return visitor.visitFileCopyInstruction(this); } - public File findFileByRelativePath(String relativePath) { - if (!relativePath.startsWith(getOutputRelativePath())) return null; - final String pathFromFile = relativePath.substring(getOutputRelativePath().length()); - if (!myIsDirectory) { - return "".equals(pathFromFile) ? myFile : null; - } - final File file = DeploymentUtil.canonicalRelativePath(myFile, pathFromFile); - - return file.exists() ? file : null; - } - - public void addFilesToJar(@NotNull CompileContext context, - @NotNull File jarFile, - @NotNull JarOutputStream outputStream, - BuildRecipe dependencies, - @Nullable Set writtenRelativePaths, - @Nullable FileFilter fileFilter) throws IOException { - final String outputRelativePath = getOutputRelativePath(); - - File file = getFile(); - if (isExternalDependencyInstruction()) { - // copy dependent file along with jar file - final File toFile = DeploymentUtil.canonicalRelativePath(jarFile, outputRelativePath); - DeploymentUtil.getInstance().copyFile(file, toFile, context, null, fileFilter); - dependencies.addInstruction(this); - } - else { - boolean ok = ZipUtil.addFileOrDirRecursively(outputStream, jarFile, file, outputRelativePath, fileFilter, writtenRelativePaths); - if (!ok) { - DeploymentUtil.reportRecursiveCopying(context, file.getPath(), jarFile.getPath(), "", - CompilerBundle.message("message.text.setup.jar.outside.directory.path", file.getPath())); - } - } - } - public String toString() { if (myChangedSet == null) { if (getModule() != null) { diff --git a/java/compiler/impl/src/com/intellij/compiler/impl/packagingCompiler/JarAndCopyBuildInstructionImpl.java b/java/compiler/impl/src/com/intellij/compiler/impl/packagingCompiler/JarAndCopyBuildInstructionImpl.java index 889363da27a3..3cac617a4a6d 100644 --- a/java/compiler/impl/src/com/intellij/compiler/impl/packagingCompiler/JarAndCopyBuildInstructionImpl.java +++ b/java/compiler/impl/src/com/intellij/compiler/impl/packagingCompiler/JarAndCopyBuildInstructionImpl.java @@ -15,26 +15,14 @@ */ package com.intellij.compiler.impl.packagingCompiler; -import com.intellij.openapi.compiler.CompileContext; -import com.intellij.openapi.compiler.CompilerBundle; -import com.intellij.openapi.compiler.make.*; +import com.intellij.openapi.compiler.make.BuildInstructionVisitor; +import com.intellij.openapi.compiler.make.JarAndCopyBuildInstruction; +import com.intellij.openapi.compiler.make.PackagingFileFilter; import com.intellij.openapi.module.Module; -import com.intellij.openapi.module.ModuleUtil; -import com.intellij.openapi.util.io.FileUtil; -import com.intellij.openapi.deployment.DeploymentUtil; -import com.intellij.util.io.ZipUtil; -import gnu.trove.THashSet; import org.jetbrains.annotations.NonNls; -import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; -import java.io.*; -import java.util.Set; -import java.util.List; -import java.util.ArrayList; -import java.util.jar.JarOutputStream; -import java.util.jar.Manifest; -import java.util.jar.JarFile; +import java.io.File; /** * Created by IntelliJ IDEA. @@ -44,9 +32,6 @@ import java.util.jar.JarFile; * To change this template use File | Settings | File Templates. */ public class JarAndCopyBuildInstructionImpl extends FileCopyInstructionImpl implements JarAndCopyBuildInstruction { - private File myJarFile; - private final List myTempJars = new ArrayList(1); - @NonNls private static final String TMP_FILE_SUFFIX = ".tmp"; public JarAndCopyBuildInstructionImpl(Module module, File directoryToJar, String outputRelativePath, @Nullable PackagingFileFilter fileFilter) { super(directoryToJar, false, module, outputRelativePath, fileFilter); @@ -56,63 +41,6 @@ public class JarAndCopyBuildInstructionImpl extends FileCopyInstructionImpl impl super(directoryToJar, false, module, outputRelativePath); } - public void addFilesToJar(@NotNull CompileContext context, - @NotNull File jarFile, - @NotNull JarOutputStream outputStream, - BuildRecipe dependencies, - @Nullable Set writtenRelativePaths, - @Nullable FileFilter fileFilter) throws IOException { - // create temp jars, and add these into upper level jar - // todo optimization: cache created jars - @NonNls final String moduleName = getModule() == null ? "jar" : ModuleUtil.getModuleNameInReadAction(getModule()); - final File tempFile = File.createTempFile(moduleName+"___",TMP_FILE_SUFFIX); - myTempJars.add(tempFile); - makeJar(context, tempFile, fileFilter); - - final String outputRelativePath = getOutputRelativePath(); - - File file = getJarFile(); - if (isExternalDependencyInstruction()) { - // copy dependent file along with jar file - final File toFile = DeploymentUtil.canonicalRelativePath(jarFile, outputRelativePath); - DeploymentUtil.getInstance().copyFile(file, toFile, context, null, fileFilter); - dependencies.addInstruction(this); - } - else { - ZipUtil.addFileToZip(outputStream, file, outputRelativePath, writtenRelativePaths, fileFilter); - } - } - - public void makeJar(@NotNull CompileContext context, @NotNull File jarFile, @Nullable FileFilter fileFilter) throws IOException { - if (jarFile.equals(myJarFile)) return; - if (myJarFile != null && myJarFile.exists()) { - // optimization: file already jarred, copy it over - DeploymentUtil.getInstance().copyFile(myJarFile, jarFile, context, null, fileFilter); - } - else { - FileUtil.createParentDirs(jarFile); - Manifest manifest = new Manifest(); - ManifestBuilder.setGlobalAttributes(manifest.getMainAttributes()); - - final JarOutputStream jarOutputStream = new JarOutputStream(new BufferedOutputStream(new FileOutputStream(jarFile)), manifest); - - try { - final THashSet writtenPaths = new THashSet(); - writtenPaths.add(JarFile.MANIFEST_NAME); - boolean ok = ZipUtil.addDirToZipRecursively(jarOutputStream, jarFile, getFile(), "", fileFilter, writtenPaths); - if (!ok) { - String dirPath = getFile().getPath(); - DeploymentUtil.reportRecursiveCopying(context, dirPath, jarFile.getPath(), "", - CompilerBundle.message("message.text.setup.jar.outside.directory.path", dirPath)); - } - } - finally { - jarOutputStream.close(); - } - } - myJarFile = jarFile; - } - public boolean accept(BuildInstructionVisitor visitor) throws Exception { return visitor.visitJarAndCopyBuildInstruction(this); } @@ -121,12 +49,4 @@ public class JarAndCopyBuildInstructionImpl extends FileCopyInstructionImpl impl return "JAR and copy: " + getFile() + "->"+getOutputRelativePath(); } - public File getJarFile() { - return myJarFile; - } - - public void deleteTemporaryJars() { - FileUtil.asyncDelete(myTempJars); - myTempJars.clear(); - } } diff --git a/java/compiler/impl/src/com/intellij/compiler/impl/packagingCompiler/JarInfo.java b/java/compiler/impl/src/com/intellij/compiler/impl/packagingCompiler/JarInfo.java index 8ae8dd1dc6d8..1948cc05980a 100644 --- a/java/compiler/impl/src/com/intellij/compiler/impl/packagingCompiler/JarInfo.java +++ b/java/compiler/impl/src/com/intellij/compiler/impl/packagingCompiler/JarInfo.java @@ -18,7 +18,6 @@ package com.intellij.compiler.impl.packagingCompiler; import com.intellij.openapi.util.Pair; import com.intellij.openapi.vfs.VirtualFile; -import org.jetbrains.annotations.Nullable; import java.util.ArrayList; import java.util.LinkedHashSet; @@ -31,17 +30,11 @@ public class JarInfo { private List> myPackedFiles; private LinkedHashSet> myPackedJars; private List myDestinations; - private List myClasspath; public JarInfo() { - this(null); - } - - public JarInfo(List classpath) { myDestinations = new ArrayList(); myPackedFiles = new ArrayList>(); myPackedJars = new LinkedHashSet>(); - myClasspath = classpath; } public void addDestination(DestinationInfo info) { @@ -74,11 +67,6 @@ public class JarInfo { return list; } - @Nullable - public List getClasspath() { - return myClasspath; - } - public List getAllDestinations() { return myDestinations; } diff --git a/java/compiler/impl/src/com/intellij/compiler/impl/packagingCompiler/JarsBuilder.java b/java/compiler/impl/src/com/intellij/compiler/impl/packagingCompiler/JarsBuilder.java index 0ab3a56ca5e5..64b8518924de 100644 --- a/java/compiler/impl/src/com/intellij/compiler/impl/packagingCompiler/JarsBuilder.java +++ b/java/compiler/impl/src/com/intellij/compiler/impl/packagingCompiler/JarsBuilder.java @@ -20,7 +20,6 @@ import com.intellij.openapi.compiler.CompileContext; import com.intellij.openapi.compiler.CompilerBundle; import com.intellij.openapi.compiler.CompilerMessageCategory; import com.intellij.openapi.deployment.DeploymentUtil; -import com.intellij.openapi.deployment.DeploymentUtilImpl; import com.intellij.openapi.util.Pair; import com.intellij.openapi.util.io.FileUtil; import com.intellij.openapi.vfs.VfsUtil; @@ -162,19 +161,14 @@ public class JarsBuilder { File jarFile = createTempFile(); myBuiltJars.put(jar, jarFile); - Manifest manifest = createManifest(jar); - DeploymentUtilImpl.setManifestAttributes(manifest.getMainAttributes(), jar.getClasspath()); + Manifest manifest = null; final JarOutputStream jarOutputStream = createJarOutputStream(jarFile, manifest); try { final THashSet writtenPaths = new THashSet(); - writtenPaths.add(JarFile.MANIFEST_NAME); for (Pair pair : jar.getPackedFiles()) { File file = VfsUtil.virtualToIoFile(pair.getSecond()); - String relativePath = pair.getFirst(); - if (!JarFile.MANIFEST_NAME.equalsIgnoreCase(relativePath)) { - addFileToJar(jarOutputStream, file, relativePath, writtenPaths); - } + addFileToJar(jarOutputStream, file, pair.getFirst(), writtenPaths); } for (Pair nestedJar : jar.getPackedJars()) { @@ -198,7 +192,7 @@ public class JarsBuilder { protected JarOutputStream createJarOutputStream(final File jarFile, final Manifest manifest) throws IOException { FileUtil.createParentDirs(jarFile); - return new JarOutputStream(new BufferedOutputStream(new FileOutputStream(jarFile)), manifest); + return new JarOutputStream(new BufferedOutputStream(new FileOutputStream(jarFile))); } protected File createTempFile() throws IOException { diff --git a/java/compiler/impl/src/com/intellij/compiler/impl/packagingCompiler/OldProcessingItemsBuilderContext.java b/java/compiler/impl/src/com/intellij/compiler/impl/packagingCompiler/OldProcessingItemsBuilderContext.java index 488473cce1e8..0e0a16253988 100644 --- a/java/compiler/impl/src/com/intellij/compiler/impl/packagingCompiler/OldProcessingItemsBuilderContext.java +++ b/java/compiler/impl/src/com/intellij/compiler/impl/packagingCompiler/OldProcessingItemsBuilderContext.java @@ -16,14 +16,12 @@ package com.intellij.compiler.impl.packagingCompiler; import com.intellij.openapi.compiler.CompileContext; -import com.intellij.openapi.compiler.make.BuildParticipant; import com.intellij.openapi.compiler.make.BuildConfiguration; +import com.intellij.openapi.compiler.make.BuildParticipant; import com.intellij.openapi.compiler.make.BuildRecipe; import com.intellij.openapi.module.Module; -import com.intellij.openapi.vfs.VirtualFile; -import com.intellij.openapi.deployment.DeploymentUtilImpl; import com.intellij.openapi.util.MultiValuesMap; -import com.intellij.packaging.impl.compiler.ArtifactPackagingProcessingItem; +import com.intellij.openapi.vfs.VirtualFile; import java.util.*; @@ -72,8 +70,7 @@ public class OldProcessingItemsBuilderContext extends ProcessingItemsBuilderCont JarInfo jarInfo = getCachedJar(buildConfiguration); boolean addJarContent = jarInfo == null; if (jarInfo == null) { - List classpath = DeploymentUtilImpl.getExternalDependenciesClasspath(buildRecipe); - jarInfo = new JarInfo(classpath); + jarInfo = new JarInfo(); putCachedJar(buildConfiguration, jarInfo); } jarInfo.addDestination(destinationInfo); diff --git a/java/compiler/impl/src/com/intellij/compiler/impl/packagingCompiler/ProcessingItemsBuilder.java b/java/compiler/impl/src/com/intellij/compiler/impl/packagingCompiler/ProcessingItemsBuilder.java index 038c111f0b68..845e5f6348f0 100644 --- a/java/compiler/impl/src/com/intellij/compiler/impl/packagingCompiler/ProcessingItemsBuilder.java +++ b/java/compiler/impl/src/com/intellij/compiler/impl/packagingCompiler/ProcessingItemsBuilder.java @@ -274,40 +274,6 @@ public class ProcessingItemsBuilder extends BuildInstructionVisitor { } } - public boolean visitCompoundBuildInstruction(final CompoundBuildInstruction instruction) throws Exception { - String outputPath = DeploymentUtil.appendToPath(myOutputPaths.peek(), instruction.getOutputRelativePath()); - myOutputPaths.push(outputPath); - BuildRecipe childInstructions = instruction.getChildInstructions(myContext.getCompileContext()); - NestedJarInfo oldNestedJar = null; - if (myNestedJars != null) { - if (instruction.isExternalDependencyInstruction()) { - oldNestedJar = myNestedJars.pop(); - } - DestinationInfo destinationInfo; - if (!myNestedJars.isEmpty()) { - NestedJarInfo nestedJar = myNestedJars.peek(); - destinationInfo = new JarDestinationInfo(trimParentPrefix(instruction.getOutputRelativePath()), nestedJar.myJarInfo, nestedJar.myDestination); - } - else { - String jarPath = getCanonicalConcat(myBuildConfiguration.getJarPath(), instruction.getOutputRelativePath()); - destinationInfo = createExplodedDestination(jarPath); - } - myNestedJars.push(myContext.createNestedJarInfo(destinationInfo, instruction.getBuildProperties(), childInstructions)); - } - - buildItems(childInstructions); - - if (myNestedJars != null) { - myNestedJars.pop(); - if (oldNestedJar != null) { - myNestedJars.push(oldNestedJar); - } - } - myOutputPaths.pop(); - - return true; - } - public static class NestedJarInfo { private final JarInfo myJarInfo; private final DestinationInfo myDestination; diff --git a/java/compiler/impl/src/com/intellij/compiler/make/ExplodedAndJarBuildGenerator.java b/java/compiler/impl/src/com/intellij/compiler/make/ExplodedAndJarBuildGenerator.java index 0fe4aa104d7a..a4e462a14c3d 100644 --- a/java/compiler/impl/src/com/intellij/compiler/make/ExplodedAndJarBuildGenerator.java +++ b/java/compiler/impl/src/com/intellij/compiler/make/ExplodedAndJarBuildGenerator.java @@ -37,15 +37,4 @@ public abstract class ExplodedAndJarBuildGenerator { return null; } - @Nullable - public ZipFileSet[] generateTagsForJarTarget(@NotNull BuildInstruction instruction, @NotNull ExplodedAndJarTargetParameters parameters, - final Ref tempDirUsed) throws Exception { - return null; - } - - @Nullable - public Tag[] generateJarBuildPrepareTags(@NotNull BuildInstruction instruction, @NotNull ExplodedAndJarTargetParameters parameters) throws Exception { - return null; - } - } diff --git a/java/compiler/impl/src/com/intellij/openapi/deployment/DeploymentUtilImpl.java b/java/compiler/impl/src/com/intellij/openapi/deployment/DeploymentUtilImpl.java index 2f7c5359566f..3db688537350 100644 --- a/java/compiler/impl/src/com/intellij/openapi/deployment/DeploymentUtilImpl.java +++ b/java/compiler/impl/src/com/intellij/openapi/deployment/DeploymentUtilImpl.java @@ -29,7 +29,6 @@ import com.intellij.openapi.module.ModuleUtil; import com.intellij.openapi.roots.*; import com.intellij.openapi.roots.libraries.Library; import com.intellij.openapi.util.Computable; -import com.intellij.openapi.util.Ref; import com.intellij.openapi.util.SystemInfo; import com.intellij.openapi.util.io.FileUtil; import com.intellij.openapi.util.text.StringUtil; @@ -48,8 +47,6 @@ import java.io.FileFilter; import java.io.IOException; import java.util.*; import java.util.jar.Attributes; -import java.util.jar.JarFile; -import java.util.jar.Manifest; /** * @author Alexey Kudravtsev @@ -285,18 +282,6 @@ public class DeploymentUtilImpl extends DeploymentUtil { return relativePath; } - public @Nullable File findUserSuppliedManifestFile(@NotNull BuildRecipe buildRecipe) { - final Ref ref = Ref.create(null); - buildRecipe.visitInstructions(new BuildInstructionVisitor() { - public boolean visitInstruction(BuildInstruction instruction) throws Exception { - final File file = instruction.findFileByRelativePath(JarFile.MANIFEST_NAME); - ref.set(file); - return file == null; - } - }, false); - return ref.get(); - } - public void checkConfigFile(final ConfigFile descriptor, final CompileContext compileContext, final Module module) { if (new File(VfsUtil.urlToPath(descriptor.getUrl())).exists()) { String message = getConfigFileErrorMessage(descriptor); @@ -312,17 +297,6 @@ public class DeploymentUtilImpl extends DeploymentUtil { } } - public @Nullable Manifest createManifest(@NotNull BuildRecipe buildRecipe) { - if (findUserSuppliedManifestFile(buildRecipe) != null) { - return null; - } - - final List classpathElements = getExternalDependenciesClasspath(buildRecipe); - final Manifest manifest = new Manifest(); - setManifestAttributes(manifest.getMainAttributes(), classpathElements); - return manifest; - } - public static void setManifestAttributes(final Attributes mainAttributes, final @Nullable List classpathElements) { if (classpathElements != null && classpathElements.size() > 0) { StringBuilder builder; diff --git a/java/compiler/impl/src/com/intellij/openapi/deployment/LibraryLinkImpl.java b/java/compiler/impl/src/com/intellij/openapi/deployment/LibraryLinkImpl.java index fc97f77fef0c..3bb67c3c1ed4 100644 --- a/java/compiler/impl/src/com/intellij/openapi/deployment/LibraryLinkImpl.java +++ b/java/compiler/impl/src/com/intellij/openapi/deployment/LibraryLinkImpl.java @@ -22,7 +22,6 @@ import com.intellij.openapi.project.Project; import com.intellij.openapi.roots.OrderRootType; import com.intellij.openapi.roots.impl.libraries.LibraryEx; import com.intellij.openapi.roots.libraries.Library; -import com.intellij.openapi.roots.libraries.LibraryTable; import com.intellij.openapi.roots.ui.configuration.FacetsProvider; import com.intellij.openapi.roots.ui.configuration.ModulesProvider; import com.intellij.openapi.util.Comparing; @@ -40,13 +39,9 @@ import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.ArrayList; -import java.util.HashMap; import java.util.List; -import java.util.Map; public class LibraryLinkImpl extends LibraryLink { - private static final Map methodToDescriptionForDirs = new HashMap(); - private static final Map methodToDescriptionForFiles = new HashMap(); @NonNls public static final String LEVEL_ATTRIBUTE_NAME = "level"; @NonNls public static final String URL_ELEMENT_NAME = "url"; @NonNls private static final String TEMP_ELEMENT_NAME = "temp"; @@ -54,17 +49,6 @@ public class LibraryLinkImpl extends LibraryLink { @NonNls private static final String JAR_SUFFIX = ".jar"; - static { - methodToDescriptionForDirs.put(PackagingMethod.DO_NOT_PACKAGE, CompilerBundle.message("packaging.method.description.do.not.package")); - methodToDescriptionForDirs.put(PackagingMethod.COPY_FILES, CompilerBundle.message("packaging.method.description.copy.directories")); - methodToDescriptionForDirs.put(PackagingMethod.JAR_AND_COPY_FILE, CompilerBundle.message("packaging.method.description.jar.and.copy.file")); - methodToDescriptionForDirs.put(PackagingMethod.JAR_AND_COPY_FILE_AND_LINK_VIA_MANIFEST, CompilerBundle.message("packaging.method.description.jar.and.copy.file.and.link.via.manifest")); - - methodToDescriptionForFiles.put(PackagingMethod.DO_NOT_PACKAGE, CompilerBundle.message("packaging.method.description.do.not.package")); - methodToDescriptionForFiles.put(PackagingMethod.COPY_FILES, CompilerBundle.message("packaging.method.description.copy.files")); - methodToDescriptionForFiles.put(PackagingMethod.COPY_FILES_AND_LINK_VIA_MANIFEST, CompilerBundle.message("packaging.method.description.copy.files.and.link.via.manifest")); - } - private static final Logger LOG = Logger.getInstance("#com.intellij.openapi.deployment.LibraryLink"); private LibraryInfo myLibraryInfo; private final Project myProject; @@ -137,26 +121,6 @@ public class LibraryLinkImpl extends LibraryLink { return FileUtil.toSystemDependentName(path); } - public String getDescription() { - String levelName = myLibraryInfo.getLevel(); - if (levelName.equals(MODULE_LEVEL)) { - return CompilerBundle.message("library.link.description.module.library"); - } - final LibraryTable table = findTable(levelName, myProject); - return table == null ? "???" : table.getPresentation().getDisplayName(false); - } - - public String getDescriptionForPackagingMethod(PackagingMethod method) { - if (hasDirectoriesOnly()) { - final String text = methodToDescriptionForDirs.get(method); - return text != null ? text : methodToDescriptionForFiles.get(method); - } - else { - final String text = methodToDescriptionForFiles.get(method); - return text != null ? text : methodToDescriptionForDirs.get(method); - } - } - public List getUrls() { fixLibraryInfo(); return myLibraryInfo.getUrls(); diff --git a/java/compiler/impl/src/com/intellij/openapi/deployment/ModuleLinkImpl.java b/java/compiler/impl/src/com/intellij/openapi/deployment/ModuleLinkImpl.java index 730a2d74acb0..e3e63069c05d 100644 --- a/java/compiler/impl/src/com/intellij/openapi/deployment/ModuleLinkImpl.java +++ b/java/compiler/impl/src/com/intellij/openapi/deployment/ModuleLinkImpl.java @@ -29,11 +29,8 @@ import com.intellij.openapi.util.InvalidDataException; import com.intellij.openapi.util.WriteExternalException; import org.jdom.Element; import org.jetbrains.annotations.NonNls; -import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.NotNull; - -import java.util.HashMap; -import java.util.Map; +import org.jetbrains.annotations.Nullable; public class ModuleLinkImpl extends ModuleLink { private static final Logger LOG = Logger.getInstance("#com.intellij.openapi.deployment.ModuleLink"); @@ -41,15 +38,6 @@ public class ModuleLinkImpl extends ModuleLink { @NonNls private static final String TEMP_ELEMENT_NAME = "temp"; private Module myModule; private String myModuleName; - private static final Map methodToDescription = new HashMap(); - - static { - methodToDescription.put(PackagingMethod.DO_NOT_PACKAGE, CompilerBundle.message("packaging.method.description.do.not.package")); - methodToDescription.put(PackagingMethod.COPY_FILES, CompilerBundle.message("packaging.method.description.copy.module.output")); - methodToDescription.put(PackagingMethod.JAR_AND_COPY_FILE, CompilerBundle.message("packaging.method.description.jar.module.and.copy")); - methodToDescription.put(PackagingMethod.JAR_AND_COPY_FILE_AND_LINK_VIA_MANIFEST, CompilerBundle.message("packaging.method.description.jar.module.link.via.manifest.and.copy")); - methodToDescription.put(PackagingMethod.INCLUDE_MODULE_IN_BUILD, CompilerBundle.message("packaging.method.description.include.module.in.build")); - } public ModuleLinkImpl(@NotNull Module module, @NotNull Module parentModule) { super(parentModule); @@ -99,15 +87,6 @@ public class ModuleLinkImpl extends ModuleLink { return getName(); } - public String getDescription() { - final Module module = getModule(); - return module == null ? "" : module.getModuleType().getName(); - } - - public String getDescriptionForPackagingMethod(PackagingMethod method) { - return methodToDescription.get(method); - } - public boolean resolveElement(ModulesProvider provider, final FacetsProvider facetsProvider) { return getModule(provider) != null; } diff --git a/java/compiler/impl/src/com/intellij/openapi/deployment/OrderEntryInfo.java b/java/compiler/impl/src/com/intellij/openapi/deployment/OrderEntryInfo.java deleted file mode 100644 index 09e1b2e03095..000000000000 --- a/java/compiler/impl/src/com/intellij/openapi/deployment/OrderEntryInfo.java +++ /dev/null @@ -1,103 +0,0 @@ -/* - * Copyright 2000-2009 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.intellij.openapi.deployment; - -import com.intellij.openapi.util.InvalidDataException; -import com.intellij.openapi.util.JDOMExternalizable; -import com.intellij.openapi.util.JDOMExternalizer; -import com.intellij.openapi.util.WriteExternalException; -import com.intellij.util.containers.HashMap; -import org.jdom.Element; -import org.jetbrains.annotations.NonNls; - -import java.util.List; -import java.util.Map; -import java.util.Set; - -/** - * @author cdr - * @deprecated - */ -class OrderEntryInfo implements JDOMExternalizable { - public boolean copy; - public String URI=""; - private final Map attributes = new HashMap(); - @NonNls protected static final String ATTRIBUTE_ELEMENT_NAME = "attribute"; - @NonNls protected static final String NAME_ATTR_NAME = "name"; - @NonNls protected static final String VALUE_ATTR_NAME = "value"; - @NonNls protected static final String ATTRIBUTES_ELEMENT_NAME = "attributes"; - - public void writeExternal(Element element) throws WriteExternalException { - JDOMExternalizer.write(element,"copy",copy); - JDOMExternalizer.write(element,"URI",URI); - writeAttributes(element); - } - - private void writeAttributes(Element element) { - if (attributes.size() == 0) return; - Element root = new Element(ATTRIBUTES_ELEMENT_NAME); - element.addContent(root); - Set names = attributes.keySet(); - for (String name : names) { - String value = attributes.get(name); - Element attr = new Element(ATTRIBUTE_ELEMENT_NAME); - attr.setAttribute(NAME_ATTR_NAME, name); - attr.setAttribute(VALUE_ATTR_NAME, value); - root.addContent(attr); - } - } - private void readAttributes(Element element) { - Element attrs = element.getChild(ATTRIBUTES_ELEMENT_NAME); - if (attrs == null) return; - List roots = attrs.getChildren(ATTRIBUTE_ELEMENT_NAME); - if (roots.size() == 0) return; - for (Object root : roots) { - Element attr = (Element)root; - String name = attr.getAttributeValue(NAME_ATTR_NAME); - String value = attr.getAttributeValue(VALUE_ATTR_NAME); - attributes.put(name, value); - } - } - - public void readExternal(Element element) throws InvalidDataException { - copy = JDOMExternalizer.readBoolean(element,"copy"); - URI = JDOMExternalizer.readString(element,"URI"); - readAttributes(element); - } - - public boolean equals(Object o) { - if (this == o) return true; - if (!(o instanceof OrderEntryInfo)) return false; - - final OrderEntryInfo orderEntryInfo = (OrderEntryInfo)o; - - if (copy != orderEntryInfo.copy) return false; - if (URI != null ? !URI.equals(orderEntryInfo.URI) : orderEntryInfo.URI != null) return false; - - return true; - } - - public int hashCode() { - int result; - result = copy ? 1 : 0; - result = 29 * result + (URI != null ? URI.hashCode() : 0); - return result; - } - - public Map getAttributes() { - return attributes; - } -} diff --git a/java/compiler/impl/src/com/intellij/openapi/deployment/PackagingConfigurationImpl.java b/java/compiler/impl/src/com/intellij/openapi/deployment/PackagingConfigurationImpl.java deleted file mode 100644 index 7b42d0eb45b0..000000000000 --- a/java/compiler/impl/src/com/intellij/openapi/deployment/PackagingConfigurationImpl.java +++ /dev/null @@ -1,207 +0,0 @@ -/* - * Copyright 2000-2009 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.intellij.openapi.deployment; - -import com.intellij.facet.impl.DefaultFacetsProvider; -import com.intellij.openapi.diagnostic.Logger; -import com.intellij.openapi.module.Module; -import com.intellij.openapi.roots.libraries.Library; -import com.intellij.openapi.roots.ui.configuration.DefaultModulesProvider; -import com.intellij.openapi.roots.ui.configuration.FacetsProvider; -import com.intellij.openapi.roots.ui.configuration.ModulesProvider; -import com.intellij.openapi.util.InvalidDataException; -import com.intellij.openapi.util.WriteExternalException; -import gnu.trove.TObjectHashingStrategy; -import org.jdom.Element; -import org.jetbrains.annotations.NonNls; -import org.jetbrains.annotations.NotNull; - -import java.util.*; - -/** - * @author Alexey Kudravtsev - */ -public class PackagingConfigurationImpl implements PackagingConfiguration { - private static final Logger LOG = Logger.getInstance("#com.intellij.javaee.module.J2EEModuleContainerImpl"); - protected ModulesProvider myDefaultModulesProvider; - protected final Module myParentModule; - protected final Set myContents = new LinkedHashSet(); - - @NonNls public static final String TYPE_ATTRIBUTE_NAME = "type"; - @NonNls public static final String CONTAINER_ELEMENT_NAME = "containerElement"; - @NonNls public static final String MODULE_TYPE = "module"; - @NonNls public static final String LIBRARY_TYPE = "library"; - public static final TObjectHashingStrategy IGNORING_ATTRIBUTES_EQUALITY = new ElementIgnoringAttributesEquality(); - - public PackagingConfigurationImpl(@NotNull Module module) { - myParentModule = module; - myDefaultModulesProvider = new DefaultModulesProvider(module.getProject()); - } - - public PackagingConfigurationImpl createNewInstance() { - return new PackagingConfigurationImpl(myParentModule); - } - - public void removeLibrary(final Library library) { - for (ContainerElement content : myContents) { - if (content instanceof LibraryLink && library.equals(((LibraryLink)content).getLibrary())) { - removeContainerElement(content); - break; - } - } - } - - public void readExternal(Element element) throws InvalidDataException { - clearContainer(); - LOG.assertTrue(myParentModule != null); - - final List children = element.getChildren(CONTAINER_ELEMENT_NAME); - for (Element child : children) { - final String type = child.getAttributeValue(TYPE_ATTRIBUTE_NAME); - ContainerElement containerElement; - containerElement = createElement(child, myParentModule, type); - - containerElement.readExternal(child); - - addElement(containerElement); - } - } - - protected ContainerElement createElement(final @NotNull Element child, final @NotNull Module module, final String type) throws InvalidDataException { - if (MODULE_TYPE.equals(type)) { - return new ModuleLinkImpl((String)null, module); - } - else if (LIBRARY_TYPE.equals(type)) { - return new LibraryLinkImpl(null, module); - } - else { - throw new InvalidDataException("invalid type: " + type + " " + child); - } - } - - public void writeExternal(Element element) throws WriteExternalException { - for (final ContainerElement containerElement : myContents) { - final Element child = new Element(CONTAINER_ELEMENT_NAME); - final String type = getElementType(containerElement); - child.setAttribute(TYPE_ATTRIBUTE_NAME, type); - containerElement.writeExternal(child); - element.addContent(child); - } - } - - protected String getElementType(final ContainerElement containerElement) throws WriteExternalException { - if (containerElement instanceof ModuleLink) { - return MODULE_TYPE; - } - else if (containerElement instanceof LibraryLink) { - return LIBRARY_TYPE; - } - else { - throw new WriteExternalException("invalid type: " + containerElement); - } - } - - public ModuleLink[] getContainingModules() { - - final List moduleLinks = new ArrayList(); - - ContainerElement[] elements = getElements(); - for (ContainerElement element : elements) { - if (element instanceof ModuleLink) { - moduleLinks.add((ModuleLink)element); - } - } - - return moduleLinks.toArray(new ModuleLink[moduleLinks.size()]); - } - - public LibraryLink[] getContainingLibraries() { - final List libraryLinks = new ArrayList(); - ContainerElement[] elements = getElements(); - for (ContainerElement element : elements) { - if (element instanceof LibraryLink) { - libraryLinks.add((LibraryLink)element); - } - } - return libraryLinks.toArray(new LibraryLink[libraryLinks.size()]); - } - - public ContainerElement[] getElements() { - return getElements(myDefaultModulesProvider, DefaultFacetsProvider.INSTANCE, true, false, false); - } - - public ContainerElement[] getElements(ModulesProvider provider, final FacetsProvider facetsProvider, - final boolean includeResolved, final boolean includeUnresolved, final boolean includeNonPackaged) { - ArrayList result = new ArrayList(); - for (final ContainerElement containerElement : myContents) { - final boolean resolved = containerElement.resolveElement(provider, facetsProvider); - if ((resolved && includeResolved || !resolved && includeUnresolved) - && (includeNonPackaged || containerElement.getPackagingMethod() != PackagingMethod.DO_NOT_PACKAGE)) { - result.add(containerElement); - } - } - return result.toArray(new ContainerElement[result.size()]); - } - - public void setElements(ContainerElement[] elements) { - clearContainer(); - myContents.addAll(Arrays.asList(elements)); - } - - protected void removeModuleLinkInternal(Module module) { - for (final ContainerElement containerElement : myContents) { - if (containerElement instanceof ModuleLink && ((ModuleLink)containerElement).getModule() == module) { - removeContainerElement(containerElement); - break; - } - } - } - - public boolean removeContainerElement(final ContainerElement containerElement) { - return myContents.remove(containerElement); - } - - public Module[] getContainingIdeaModules() { - ModuleLink[] containingModules = getContainingModules(); - List result = new ArrayList(containingModules.length); - for (ModuleLink containingModule : containingModules) { - final Module module = containingModule.getModule(); - if (module != null) { - result.add(module); - } - } - return result.toArray(new Module[result.size()]); - } - - protected void clearContainer() { - myContents.clear(); - } - - public void addOrReplaceElement(final ContainerElement element) { - for (Iterator it = myContents.iterator(); it.hasNext();) { - ContainerElement content = it.next(); - if (content.equalsIgnoreAttributes(element)) { - it.remove(); - } - } - addElement(element); - } - - public void addElement(ContainerElement element) { - myContents.add(element); - } - -} diff --git a/java/compiler/impl/src/com/intellij/packaging/impl/compiler/IncrementalArtifactsCompiler.java b/java/compiler/impl/src/com/intellij/packaging/impl/compiler/IncrementalArtifactsCompiler.java index 978a951cc8de..6f4081e7a81e 100644 --- a/java/compiler/impl/src/com/intellij/packaging/impl/compiler/IncrementalArtifactsCompiler.java +++ b/java/compiler/impl/src/com/intellij/packaging/impl/compiler/IncrementalArtifactsCompiler.java @@ -15,17 +15,16 @@ */ package com.intellij.packaging.impl.compiler; -import com.intellij.compiler.impl.CompilerUtil; +import com.intellij.compiler.CompilerManagerImpl; import com.intellij.compiler.impl.CompilerCacheManager; +import com.intellij.compiler.impl.CompilerUtil; import com.intellij.compiler.impl.FileProcessingCompilerStateCache; import com.intellij.compiler.impl.packagingCompiler.*; -import com.intellij.compiler.CompilerManagerImpl; +import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.application.ReadAction; import com.intellij.openapi.application.Result; -import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.compiler.*; import com.intellij.openapi.deployment.DeploymentUtil; -import com.intellij.openapi.deployment.DeploymentUtilImpl; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.progress.ProcessCanceledException; import com.intellij.openapi.project.Project; @@ -52,9 +51,11 @@ import gnu.trove.THashSet; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; -import java.io.*; +import java.io.DataInput; +import java.io.File; +import java.io.FileFilter; +import java.io.IOException; import java.util.*; -import java.util.jar.Manifest; /** * @author nik @@ -291,8 +292,6 @@ public class IncrementalArtifactsCompiler implements PackagingCompiler { } } - createManifestFiles(builderContext.getManifestFiles()); - JarsBuilder builder = new JarsBuilder(changedJars, fileFilter, context); final boolean processed = builder.buildJars(writtenPaths); if (!processed) { @@ -330,39 +329,6 @@ public class IncrementalArtifactsCompiler implements PackagingCompiler { return true; } - private static void createManifestFiles(final List manifestFileInfos) throws IOException { - for (ManifestFileInfo manifestFileInfo : manifestFileInfos) { - File outputFile = new File(FileUtil.toSystemDependentName(manifestFileInfo.getOutputPath())); - Manifest manifest; - if (outputFile.exists()) { - FileInputStream stream = new FileInputStream(outputFile); - try { - manifest = new Manifest(stream); - } - finally { - stream.close(); - } - } - else { - manifest = new Manifest(); - } - - DeploymentUtilImpl.setManifestAttributes(manifest.getMainAttributes(), manifestFileInfo.getClasspath()); - - FileUtil.createParentDirs(outputFile); - FileOutputStream out = null; - try { - out = new FileOutputStream(outputFile); - manifest.write(out); - } - finally { - if (out != null) { - out.close(); - } - } - } - } - private static void processDestinations(final List items) { for (ArtifactPackagingProcessingItem item : items) { item.setProcessed(); diff --git a/java/compiler/impl/src/com/intellij/packaging/impl/elements/ArchiveElementType.java b/java/compiler/impl/src/com/intellij/packaging/impl/elements/ArchiveElementType.java new file mode 100644 index 000000000000..d5abb844fe8e --- /dev/null +++ b/java/compiler/impl/src/com/intellij/packaging/impl/elements/ArchiveElementType.java @@ -0,0 +1,68 @@ +/* + * Copyright 2000-2009 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.intellij.packaging.impl.elements; + +import com.intellij.openapi.compiler.CompilerBundle; +import com.intellij.openapi.project.Project; +import com.intellij.openapi.ui.Messages; +import com.intellij.openapi.util.text.StringUtil; +import com.intellij.packaging.elements.CompositePackagingElement; +import com.intellij.packaging.elements.CompositePackagingElementType; +import com.intellij.packaging.elements.PackagingElement; +import com.intellij.packaging.impl.ui.properties.ArchiveElementPropertiesPanel; +import com.intellij.packaging.ui.ArtifactEditorContext; +import com.intellij.packaging.ui.PackagingElementPropertiesPanel; +import com.intellij.util.Icons; +import org.jetbrains.annotations.NotNull; + +import javax.swing.*; + +/** +* @author nik +*/ +class ArchiveElementType extends CompositePackagingElementType { + ArchiveElementType() { + super("archive", CompilerBundle.message("element.type.name.archive")); + } + + @Override + public Icon getCreateElementIcon() { + return Icons.JAR_ICON; + } + + @NotNull + @Override + public ArchivePackagingElement createEmpty(@NotNull Project project) { + return new ArchivePackagingElement(); + } + + @Override + public PackagingElementPropertiesPanel createElementPropertiesPanel(@NotNull ArchivePackagingElement element, + @NotNull ArtifactEditorContext context) { + final String name = element.getArchiveFileName(); + if (name.length() >= 4 && name.charAt(name.length() - 4) == '.' && StringUtil.endsWithIgnoreCase(name, "ar")) { + return new ArchiveElementPropertiesPanel(element, context); + } + return null; + } + + public PackagingElement createComposite(@NotNull ArtifactEditorContext context, CompositePackagingElement parent) { + final String initialValue = PackagingElementFactoryImpl.suggestFileName(parent, "archive", ".jar"); + final String path = Messages.showInputDialog(context.getProject(), "Enter archive name: ", "New Archive", null, initialValue, new FilePathValidator()); + if (path == null) return null; + return PackagingElementFactoryImpl.createDirectoryOrArchiveWithParents(path, true); + } +} diff --git a/java/compiler/impl/src/com/intellij/packaging/impl/elements/DirectoryCopyElementType.java b/java/compiler/impl/src/com/intellij/packaging/impl/elements/DirectoryCopyElementType.java new file mode 100644 index 000000000000..af4bb30a93d5 --- /dev/null +++ b/java/compiler/impl/src/com/intellij/packaging/impl/elements/DirectoryCopyElementType.java @@ -0,0 +1,71 @@ +/* + * Copyright 2000-2009 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.intellij.packaging.impl.elements; + +import com.intellij.openapi.fileChooser.FileChooserDescriptor; +import com.intellij.openapi.fileChooser.FileChooserDialog; +import com.intellij.openapi.fileChooser.FileChooserFactory; +import com.intellij.openapi.project.Project; +import com.intellij.openapi.util.IconLoader; +import com.intellij.openapi.vfs.VirtualFile; +import com.intellij.packaging.artifacts.Artifact; +import com.intellij.packaging.elements.CompositePackagingElement; +import com.intellij.packaging.elements.PackagingElementType; +import com.intellij.packaging.ui.ArtifactEditorContext; +import org.jetbrains.annotations.NotNull; + +import javax.swing.*; +import java.util.ArrayList; +import java.util.List; + +/** +* @author nik +*/ +public class DirectoryCopyElementType extends PackagingElementType { + public static final Icon COPY_OF_FOLDER_ICON = IconLoader.getIcon("/nodes/copyOfFolder.png"); + + DirectoryCopyElementType() { + super("dir-copy", "Directory Content"); + } + + @Override + public Icon getCreateElementIcon() { + return COPY_OF_FOLDER_ICON; + } + + @Override + public boolean canCreate(@NotNull ArtifactEditorContext context, @NotNull Artifact artifact) { + return true; + } + + @NotNull + public List chooseAndCreate(@NotNull ArtifactEditorContext context, @NotNull Artifact artifact, + @NotNull CompositePackagingElement parent) { + final FileChooserDescriptor descriptor = new FileChooserDescriptor(false, true, false, false, false, true); + final FileChooserDialog chooser = FileChooserFactory.getInstance().createFileChooser(descriptor, context.getProject()); + final VirtualFile[] files = chooser.choose(null, context.getProject()); + final List list = new ArrayList(); + for (VirtualFile file : files) { + list.add(new DirectoryCopyPackagingElement(file.getPath())); + } + return list; + } + + @NotNull + public DirectoryCopyPackagingElement createEmpty(@NotNull Project project) { + return new DirectoryCopyPackagingElement(); + } +} diff --git a/java/compiler/impl/src/com/intellij/packaging/impl/elements/DirectoryElementType.java b/java/compiler/impl/src/com/intellij/packaging/impl/elements/DirectoryElementType.java new file mode 100644 index 000000000000..d3b9a5dd4609 --- /dev/null +++ b/java/compiler/impl/src/com/intellij/packaging/impl/elements/DirectoryElementType.java @@ -0,0 +1,69 @@ +/* + * Copyright 2000-2009 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.intellij.packaging.impl.elements; + +import com.intellij.openapi.compiler.CompilerBundle; +import com.intellij.openapi.project.Project; +import com.intellij.openapi.ui.Messages; +import com.intellij.openapi.util.IconLoader; +import com.intellij.packaging.elements.CompositePackagingElement; +import com.intellij.packaging.elements.CompositePackagingElementType; +import com.intellij.packaging.elements.PackagingElement; +import com.intellij.packaging.impl.artifacts.ArtifactUtil; +import com.intellij.packaging.impl.ui.properties.DirectoryElementPropertiesPanel; +import com.intellij.packaging.ui.ArtifactEditorContext; +import com.intellij.packaging.ui.PackagingElementPropertiesPanel; +import org.jetbrains.annotations.NotNull; + +import javax.swing.*; + +/** +* @author nik +*/ +class DirectoryElementType extends CompositePackagingElementType { + private static final Icon ICON = IconLoader.getIcon("/actions/newFolder.png"); + + DirectoryElementType() { + super("directory", CompilerBundle.message("element.type.name.directory")); + } + + @Override + public Icon getCreateElementIcon() { + return ICON; + } + + @NotNull + public DirectoryPackagingElement createEmpty(@NotNull Project project) { + return new DirectoryPackagingElement(); + } + + @Override + public PackagingElementPropertiesPanel createElementPropertiesPanel(@NotNull DirectoryPackagingElement element, + @NotNull ArtifactEditorContext context) { + if (ArtifactUtil.isArchiveName(element.getDirectoryName())) { + return new DirectoryElementPropertiesPanel(element, context); + } + return null; + } + + public PackagingElement createComposite(@NotNull ArtifactEditorContext context, CompositePackagingElement parent) { + final String initialValue = PackagingElementFactoryImpl.suggestFileName(parent, "folder", ""); + String path = Messages.showInputDialog(context.getProject(), "Enter directory name: ", "New Directory", null, initialValue, new FilePathValidator()); + if (path == null) return null; + return PackagingElementFactoryImpl.createDirectoryOrArchiveWithParents(path, false); + } + +} diff --git a/java/compiler/impl/src/com/intellij/packaging/impl/elements/FileCopyElementType.java b/java/compiler/impl/src/com/intellij/packaging/impl/elements/FileCopyElementType.java new file mode 100644 index 000000000000..675751389c75 --- /dev/null +++ b/java/compiler/impl/src/com/intellij/packaging/impl/elements/FileCopyElementType.java @@ -0,0 +1,71 @@ +/* + * Copyright 2000-2009 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.intellij.packaging.impl.elements; + +import com.intellij.openapi.fileChooser.FileChooserDescriptor; +import com.intellij.openapi.fileChooser.FileChooserDialog; +import com.intellij.openapi.fileChooser.FileChooserFactory; +import com.intellij.openapi.project.Project; +import com.intellij.openapi.util.IconLoader; +import com.intellij.openapi.vfs.VirtualFile; +import com.intellij.packaging.artifacts.Artifact; +import com.intellij.packaging.elements.CompositePackagingElement; +import com.intellij.packaging.elements.PackagingElementType; +import com.intellij.packaging.ui.ArtifactEditorContext; +import org.jetbrains.annotations.NotNull; + +import javax.swing.*; +import java.util.ArrayList; +import java.util.List; + +/** +* @author nik +*/ +public class FileCopyElementType extends PackagingElementType { + public static final Icon ICON = IconLoader.getIcon("/fileTypes/text.png"); + + FileCopyElementType() { + super("file-copy", "File"); + } + + @Override + public Icon getCreateElementIcon() { + return ICON; + } + + @Override + public boolean canCreate(@NotNull ArtifactEditorContext context, @NotNull Artifact artifact) { + return true; + } + + @NotNull + public List chooseAndCreate(@NotNull ArtifactEditorContext context, @NotNull Artifact artifact, + @NotNull CompositePackagingElement parent) { + final FileChooserDescriptor descriptor = new FileChooserDescriptor(true, false, true, true, false, true); + final FileChooserDialog chooser = FileChooserFactory.getInstance().createFileChooser(descriptor, context.getProject()); + final VirtualFile[] files = chooser.choose(null, context.getProject()); + final List list = new ArrayList(); + for (VirtualFile file : files) { + list.add(new FileCopyPackagingElement(file.getPath())); + } + return list; + } + + @NotNull + public FileCopyPackagingElement createEmpty(@NotNull Project project) { + return new FileCopyPackagingElement(); + } +} diff --git a/java/compiler/impl/src/com/intellij/packaging/impl/elements/FilePathValidator.java b/java/compiler/impl/src/com/intellij/packaging/impl/elements/FilePathValidator.java new file mode 100644 index 000000000000..c31e006c1e00 --- /dev/null +++ b/java/compiler/impl/src/com/intellij/packaging/impl/elements/FilePathValidator.java @@ -0,0 +1,45 @@ +/* + * Copyright 2000-2009 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.intellij.packaging.impl.elements; + +import com.intellij.openapi.ui.InputValidator; +import com.intellij.openapi.util.io.FileUtil; +import com.intellij.openapi.util.text.StringUtil; +import com.intellij.util.PathUtil; + +import java.util.List; + +/** + * @author nik + */ +class FilePathValidator implements InputValidator { + public boolean checkInput(String inputString) { + final List fileNames = StringUtil.split(FileUtil.toSystemIndependentName(inputString), "/"); + if (fileNames.isEmpty()) { + return false; + } + for (String fileName : fileNames) { + if (!PathUtil.isValidFileName(fileName)) { + return false; + } + } + return true; + } + + public boolean canClose(String inputString) { + return checkInput(inputString); + } +} diff --git a/java/compiler/impl/src/com/intellij/packaging/impl/elements/PackagingElementFactoryImpl.java b/java/compiler/impl/src/com/intellij/packaging/impl/elements/PackagingElementFactoryImpl.java index e4569f661bc9..53c7dcbf22d8 100644 --- a/java/compiler/impl/src/com/intellij/packaging/impl/elements/PackagingElementFactoryImpl.java +++ b/java/compiler/impl/src/com/intellij/packaging/impl/elements/PackagingElementFactoryImpl.java @@ -15,11 +15,7 @@ */ package com.intellij.packaging.impl.elements; -import com.intellij.openapi.compiler.CompilerBundle; import com.intellij.openapi.extensions.Extensions; -import com.intellij.openapi.fileChooser.FileChooserDescriptor; -import com.intellij.openapi.fileChooser.FileChooserDialog; -import com.intellij.openapi.fileChooser.FileChooserFactory; import com.intellij.openapi.module.Module; import com.intellij.openapi.project.Project; import com.intellij.openapi.roots.OrderRootType; @@ -27,27 +23,19 @@ import com.intellij.openapi.roots.impl.libraries.LibraryImpl; import com.intellij.openapi.roots.impl.libraries.LibraryTableImplUtil; import com.intellij.openapi.roots.libraries.Library; import com.intellij.openapi.roots.libraries.LibraryTable; -import com.intellij.openapi.ui.Messages; -import com.intellij.openapi.util.IconLoader; import com.intellij.openapi.util.io.FileUtil; import com.intellij.openapi.util.text.StringUtil; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.packaging.artifacts.Artifact; import com.intellij.packaging.artifacts.ArtifactPointerManager; import com.intellij.packaging.elements.*; -import com.intellij.packaging.impl.artifacts.ArtifactUtil; -import com.intellij.packaging.impl.ui.properties.ArchiveElementPropertiesPanel; -import com.intellij.packaging.impl.ui.properties.DirectoryElementPropertiesPanel; import com.intellij.packaging.ui.ArtifactEditorContext; -import com.intellij.packaging.ui.PackagingElementPropertiesPanel; import com.intellij.util.ArrayUtil; -import com.intellij.util.Icons; import com.intellij.util.PathUtil; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; -import javax.swing.*; import java.util.ArrayList; import java.util.Collections; import java.util.List; @@ -229,7 +217,7 @@ public class PackagingElementFactoryImpl extends PackagingElementFactory { } @NotNull - private static String suggestFileName(@NotNull CompositePackagingElement parent, @NonNls @NotNull String prefix, @NonNls @NotNull String suffix) { + public static String suggestFileName(@NotNull CompositePackagingElement parent, @NonNls @NotNull String prefix, @NonNls @NotNull String suffix) { String name = prefix + suffix; int i = 2; while (findArchiveOrDirectoryByName(parent, name) != null) { @@ -282,144 +270,12 @@ public class PackagingElementFactoryImpl extends PackagingElementFactory { return Collections.singletonList(root); } - private static class DirectoryElementType extends CompositePackagingElementType { - private static final Icon ICON = IconLoader.getIcon("/actions/newFolder.png"); - - private DirectoryElementType() { - super("directory", CompilerBundle.message("element.type.name.directory")); - } - - @Override - public Icon getCreateElementIcon() { - return ICON; - } - - @NotNull - public DirectoryPackagingElement createEmpty(@NotNull Project project) { - return new DirectoryPackagingElement(); - } - - @Override - public PackagingElementPropertiesPanel createElementPropertiesPanel(@NotNull DirectoryPackagingElement element, - @NotNull ArtifactEditorContext context) { - if (ArtifactUtil.isArchiveName(element.getDirectoryName())) { - return new DirectoryElementPropertiesPanel(element, context); - } - return null; - } - - public DirectoryPackagingElement createComposite(@NotNull ArtifactEditorContext context, CompositePackagingElement parent) { - final String initialValue = suggestFileName(parent, "folder", ""); - final String name = Messages.showInputDialog(context.getProject(), "Enter directory name: ", "New Directory", null, initialValue, null); - if (name == null) return null; - return new DirectoryPackagingElement(name); - } - } - - private static class ArchiveElementType extends CompositePackagingElementType { - private ArchiveElementType() { - super("archive", CompilerBundle.message("element.type.name.archive")); - } - - @Override - public Icon getCreateElementIcon() { - return Icons.JAR_ICON; - } - - @NotNull - @Override - public ArchivePackagingElement createEmpty(@NotNull Project project) { - return new ArchivePackagingElement(); - } - - @Override - public PackagingElementPropertiesPanel createElementPropertiesPanel(@NotNull ArchivePackagingElement element, - @NotNull ArtifactEditorContext context) { - final String name = element.getArchiveFileName(); - if (name.length() >= 4 && name.charAt(name.length() - 4) == '.' && StringUtil.endsWithIgnoreCase(name, "ar")) { - return new ArchiveElementPropertiesPanel(element, context); - } - return null; - } - - public ArchivePackagingElement createComposite(@NotNull ArtifactEditorContext context, CompositePackagingElement parent) { - final String initialValue = suggestFileName(parent, "archive", ".jar"); - final String name = Messages.showInputDialog(context.getProject(), "Enter archive name: ", "New Archive", null, initialValue, null); - if (name == null) return null; - return new ArchivePackagingElement(name); - } - } - - public static class FileCopyElementType extends PackagingElementType { - public static final Icon ICON = IconLoader.getIcon("/fileTypes/text.png"); - - private FileCopyElementType() { - super("file-copy", "File"); - } - - @Override - public Icon getCreateElementIcon() { - return ICON; - } - - @Override - public boolean canCreate(@NotNull ArtifactEditorContext context, @NotNull Artifact artifact) { - return true; - } - - @NotNull - public List chooseAndCreate(@NotNull ArtifactEditorContext context, @NotNull Artifact artifact, - @NotNull CompositePackagingElement parent) { - final FileChooserDescriptor descriptor = new FileChooserDescriptor(true, false, true, true, false, true); - final FileChooserDialog chooser = FileChooserFactory.getInstance().createFileChooser(descriptor, context.getProject()); - final VirtualFile[] files = chooser.choose(null, context.getProject()); - final List list = new ArrayList(); - for (VirtualFile file : files) { - list.add(new FileCopyPackagingElement(file.getPath())); - } - return list; - } - - @NotNull - public FileCopyPackagingElement createEmpty(@NotNull Project project) { - return new FileCopyPackagingElement(); - } - } - - public static class DirectoryCopyElementType extends PackagingElementType { - public static final Icon COPY_OF_FOLDER_ICON = IconLoader.getIcon("/nodes/copyOfFolder.png"); - - private DirectoryCopyElementType() { - super("dir-copy", "Directory Content"); - } - - @Override - public Icon getCreateElementIcon() { - return COPY_OF_FOLDER_ICON; - } - - @Override - public boolean canCreate(@NotNull ArtifactEditorContext context, @NotNull Artifact artifact) { - return true; - } - - @NotNull - public List chooseAndCreate(@NotNull ArtifactEditorContext context, @NotNull Artifact artifact, - @NotNull CompositePackagingElement parent) { - final FileChooserDescriptor descriptor = new FileChooserDescriptor(false, true, false, false, false, true); - final FileChooserDialog chooser = FileChooserFactory.getInstance().createFileChooser(descriptor, context.getProject()); - final VirtualFile[] files = chooser.choose(null, context.getProject()); - final List list = new ArrayList(); - for (VirtualFile file : files) { - list.add(new DirectoryCopyPackagingElement(file.getPath())); - } - return list; - } - - @NotNull - public DirectoryCopyPackagingElement createEmpty(@NotNull Project project) { - return new DirectoryCopyPackagingElement(); - } + public static PackagingElement createDirectoryOrArchiveWithParents(@NotNull String path, final boolean archive) { + path = FileUtil.toSystemIndependentName(path); + final String parentPath = PathUtil.getParentPath(path); + final String fileName = PathUtil.getFileName(path); + final PackagingElement element = archive ? new ArchivePackagingElement(fileName) : new DirectoryPackagingElement(fileName); + return getInstance().createParentDirectories(parentPath, element); } private static class ArtifactRootElementType extends PackagingElementType> { diff --git a/java/compiler/impl/src/com/intellij/packaging/impl/ui/DirectoryCopyPresentation.java b/java/compiler/impl/src/com/intellij/packaging/impl/ui/DirectoryCopyPresentation.java index c48b1b2458e2..874a16d79841 100644 --- a/java/compiler/impl/src/com/intellij/packaging/impl/ui/DirectoryCopyPresentation.java +++ b/java/compiler/impl/src/com/intellij/packaging/impl/ui/DirectoryCopyPresentation.java @@ -20,7 +20,7 @@ import com.intellij.openapi.compiler.CompilerBundle; import com.intellij.openapi.util.io.FileUtil; import com.intellij.openapi.vfs.LocalFileSystem; import com.intellij.openapi.vfs.VirtualFile; -import com.intellij.packaging.impl.elements.PackagingElementFactoryImpl; +import com.intellij.packaging.impl.elements.DirectoryCopyElementType; import com.intellij.packaging.ui.PackagingElementPresentation; import com.intellij.packaging.ui.PackagingElementWeights; import com.intellij.ui.SimpleTextAttributes; @@ -56,7 +56,7 @@ public class DirectoryCopyPresentation extends PackagingElementPresentation { } public void render(@NotNull PresentationData presentationData, SimpleTextAttributes mainAttributes, SimpleTextAttributes commentAttributes) { - presentationData.setIcons(PackagingElementFactoryImpl.DirectoryCopyElementType.COPY_OF_FOLDER_ICON); + presentationData.setIcons(DirectoryCopyElementType.COPY_OF_FOLDER_ICON); if (myFile == null || !myFile.isDirectory()) { mainAttributes = SimpleTextAttributes.ERROR_ATTRIBUTES; final VirtualFile parentFile = LocalFileSystem.getInstance().findFileByPath(FileUtil.toSystemIndependentName(mySourcePath)); diff --git a/java/compiler/impl/src/com/intellij/packaging/impl/ui/FileCopyPresentation.java b/java/compiler/impl/src/com/intellij/packaging/impl/ui/FileCopyPresentation.java index 621ae5fcfb63..1dffcc9986ad 100644 --- a/java/compiler/impl/src/com/intellij/packaging/impl/ui/FileCopyPresentation.java +++ b/java/compiler/impl/src/com/intellij/packaging/impl/ui/FileCopyPresentation.java @@ -19,7 +19,7 @@ import com.intellij.ide.projectView.PresentationData; import com.intellij.openapi.util.io.FileUtil; import com.intellij.openapi.vfs.LocalFileSystem; import com.intellij.openapi.vfs.VirtualFile; -import com.intellij.packaging.impl.elements.PackagingElementFactoryImpl; +import com.intellij.packaging.impl.elements.FileCopyElementType; import com.intellij.packaging.ui.ArtifactEditorContext; import com.intellij.packaging.ui.PackagingElementPresentation; import com.intellij.packaging.ui.PackagingElementWeights; @@ -65,12 +65,12 @@ public class FileCopyPresentation extends PackagingElementPresentation { public void render(@NotNull PresentationData presentationData, SimpleTextAttributes mainAttributes, SimpleTextAttributes commentAttributes) { if (myFile != null && !myFile.isDirectory() || myContext.isManifestFile(mySourcePath)) { - presentationData.setIcons(myFile != null ? myFile.getIcon() : PackagingElementFactoryImpl.FileCopyElementType.ICON); + presentationData.setIcons(myFile != null ? myFile.getIcon() : FileCopyElementType.ICON); presentationData.addText(myOutputFileName, mainAttributes); presentationData.addText(" (" + mySourcePath + ")", commentAttributes); } else { - presentationData.setIcons(PackagingElementFactoryImpl.FileCopyElementType.ICON); + presentationData.setIcons(FileCopyElementType.ICON); presentationData.addText(myOutputFileName, SimpleTextAttributes.ERROR_ATTRIBUTES); final VirtualFile parentFile = LocalFileSystem.getInstance().findFileByPath(FileUtil.toSystemIndependentName(mySourcePath)); presentationData.addText("(" + mySourcePath + ")", diff --git a/java/compiler/openapi/src/com/intellij/compiler/ant/BuildTargetsFactory.java b/java/compiler/openapi/src/com/intellij/compiler/ant/BuildTargetsFactory.java index 1cdd1bc9621e..395e9e4839ed 100644 --- a/java/compiler/openapi/src/com/intellij/compiler/ant/BuildTargetsFactory.java +++ b/java/compiler/openapi/src/com/intellij/compiler/ant/BuildTargetsFactory.java @@ -37,8 +37,6 @@ public abstract class BuildTargetsFactory { public abstract Target createBuildExplodedTarget(ExplodedAndJarTargetParameters parameters, BuildRecipe buildRecipe, String description); - public abstract Target createBuildJarTarget(ExplodedAndJarTargetParameters parameters, BuildRecipe buildRecipe, String description); - public abstract Generator createComment(String comment); //for test diff --git a/java/compiler/openapi/src/com/intellij/compiler/ant/CompoundBuildInstructionNaming.java b/java/compiler/openapi/src/com/intellij/compiler/ant/CompoundBuildInstructionNaming.java deleted file mode 100644 index dd21f72a40a0..000000000000 --- a/java/compiler/openapi/src/com/intellij/compiler/ant/CompoundBuildInstructionNaming.java +++ /dev/null @@ -1,37 +0,0 @@ -/* - * Copyright 2000-2009 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.intellij.compiler.ant; - -import org.jetbrains.annotations.NonNls; -import com.intellij.openapi.compiler.make.CompoundBuildInstruction; - -/** - * @author nik - */ -public abstract class CompoundBuildInstructionNaming { - @NonNls - public abstract String getBuildExplodedTargetName(CompoundBuildInstruction instruction); - - @NonNls - public abstract String getBuildJarTargetName(CompoundBuildInstruction instruction); - - @NonNls - public abstract String getExplodedPathProperty(CompoundBuildInstruction instruction); - - @NonNls - public abstract String getJarPathProperty(CompoundBuildInstruction instruction); -} diff --git a/java/compiler/openapi/src/com/intellij/compiler/ant/ExplodedAndJarTargetParameters.java b/java/compiler/openapi/src/com/intellij/compiler/ant/ExplodedAndJarTargetParameters.java index 69838af50ad0..2e40f4bd0b63 100644 --- a/java/compiler/openapi/src/com/intellij/compiler/ant/ExplodedAndJarTargetParameters.java +++ b/java/compiler/openapi/src/com/intellij/compiler/ant/ExplodedAndJarTargetParameters.java @@ -17,7 +17,6 @@ package com.intellij.compiler.ant; import com.intellij.openapi.compiler.make.BuildConfiguration; -import com.intellij.openapi.compiler.make.CompoundBuildInstruction; import com.intellij.openapi.module.Module; /** @@ -34,19 +33,13 @@ public class ExplodedAndJarTargetParameters { private final String myExplodedPathProperty; private final String myJarPathProperty; private final BuildConfiguration myBuildConfiguration; - private final CompoundBuildInstructionNaming myCompoundBuildInstructionNaming; - public ExplodedAndJarTargetParameters(final ModuleChunk chunk, - final Module containingModule, - final GenerationOptions generationOptions, - final BuildConfiguration buildConfiguration, - final String explodedPathParameter, - final String jarPathParameter, - final String buildExplodedTargetName, - final String buildJarTargetName, - final String explodedPathProperty, - final String jarPathProperty, final CompoundBuildInstructionNaming compoundBuildInstructionNaming) { - myCompoundBuildInstructionNaming = compoundBuildInstructionNaming; + public ExplodedAndJarTargetParameters(final ModuleChunk chunk, final Module containingModule, final GenerationOptions generationOptions, + final BuildConfiguration buildConfiguration, final String explodedPathParameter, final String jarPathParameter, + final String buildExplodedTargetName, + final String buildJarTargetName, + final String explodedPathProperty, + final String jarPathProperty) { myBuildConfiguration = buildConfiguration; myChunk = chunk; myContainingModule = containingModule; @@ -95,10 +88,6 @@ public class ExplodedAndJarTargetParameters { return myJarPathProperty; } - public CompoundBuildInstructionNaming getCompoundBuildInstructionNaming() { - return myCompoundBuildInstructionNaming; - } - public BuildConfiguration getBuildConfiguration() { return myBuildConfiguration; } diff --git a/java/compiler/openapi/src/com/intellij/openapi/compiler/make/BuildInstruction.java b/java/compiler/openapi/src/com/intellij/openapi/compiler/make/BuildInstruction.java index 6ed0383e069e..5c796e2c1048 100644 --- a/java/compiler/openapi/src/com/intellij/openapi/compiler/make/BuildInstruction.java +++ b/java/compiler/openapi/src/com/intellij/openapi/compiler/make/BuildInstruction.java @@ -15,31 +15,13 @@ */ package com.intellij.openapi.compiler.make; -import com.intellij.openapi.compiler.CompileContext; import com.intellij.openapi.module.Module; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -import java.io.File; -import java.io.FileFilter; -import java.io.IOException; -import java.util.Set; -import java.util.jar.JarOutputStream; public interface BuildInstruction { String getOutputRelativePath(); Module getModule(); - @Deprecated - void addFilesToJar(@NotNull CompileContext context, - @NotNull File jarFile, - @NotNull JarOutputStream outputStream, - BuildRecipe dependencies, - @Nullable Set writtenRelativePaths, - @Nullable FileFilter fileFilter) throws IOException; - boolean accept(BuildInstructionVisitor visitor) throws Exception; boolean isExternalDependencyInstruction(); - File findFileByRelativePath(String relativePath); } diff --git a/java/compiler/openapi/src/com/intellij/openapi/compiler/make/BuildInstructionVisitor.java b/java/compiler/openapi/src/com/intellij/openapi/compiler/make/BuildInstructionVisitor.java index ca86e52d1177..0a10fcf6445c 100644 --- a/java/compiler/openapi/src/com/intellij/openapi/compiler/make/BuildInstructionVisitor.java +++ b/java/compiler/openapi/src/com/intellij/openapi/compiler/make/BuildInstructionVisitor.java @@ -26,7 +26,4 @@ public abstract class BuildInstructionVisitor { public boolean visitJarAndCopyBuildInstruction(JarAndCopyBuildInstruction instruction) throws Exception { return visitFileCopyInstruction(instruction); } - public boolean visitCompoundBuildInstruction(CompoundBuildInstruction instruction) throws Exception { - return visitInstruction(instruction); - } } \ No newline at end of file diff --git a/java/compiler/openapi/src/com/intellij/openapi/compiler/make/BuildParticipantBase.java b/java/compiler/openapi/src/com/intellij/openapi/compiler/make/BuildParticipantBase.java index 7511a6698a82..909800187653 100644 --- a/java/compiler/openapi/src/com/intellij/openapi/compiler/make/BuildParticipantBase.java +++ b/java/compiler/openapi/src/com/intellij/openapi/compiler/make/BuildParticipantBase.java @@ -56,22 +56,7 @@ public abstract class BuildParticipantBase extends BuildParticipant { final ConfigFile[] deploymentDescriptors = getDeploymentDescriptors(); ApplicationManager.getApplication().runReadAction(new Runnable() { public void run() { - for (ConfigFile descriptor : deploymentDescriptors) { - VirtualFile virtualFile = descriptor.getVirtualFile(); - if (virtualFile != null) { - ConfigFileMetaData metaData = descriptor.getMetaData(); - final File file = VfsUtil.virtualToIoFile(virtualFile); - final String fileName; - if (metaData.isFileNameFixed()) { - fileName = metaData.getFileName(); - } - else { - fileName = virtualFile.getName(); - } - instructions.addFileCopyInstruction(file, false, myModule, metaData.getDirectoryPath() + "/" + fileName, null); - } - - } + registerDescriptorCopyingInstructions(BuildParticipantBase.this.myModule, deploymentDescriptors, instructions); final CustomConfigFile[] customDescriptors = getCustomDescriptors(); @@ -87,6 +72,25 @@ public abstract class BuildParticipantBase extends BuildParticipant { }); } + public static void registerDescriptorCopyingInstructions(Module module, ConfigFile[] deploymentDescriptors, BuildRecipe instructions) { + for (ConfigFile descriptor : deploymentDescriptors) { + VirtualFile virtualFile = descriptor.getVirtualFile(); + if (virtualFile != null) { + ConfigFileMetaData metaData = descriptor.getMetaData(); + final File file = VfsUtil.virtualToIoFile(virtualFile); + final String fileName; + if (metaData.isFileNameFixed()) { + fileName = metaData.getFileName(); + } + else { + fileName = virtualFile.getName(); + } + instructions.addFileCopyInstruction(file, false, module, metaData.getDirectoryPath() + "/" + fileName, null); + } + + } + } + protected CustomConfigFile[] getCustomDescriptors() { return CustomConfigFile.EMPTY_ARRAY; } diff --git a/java/compiler/openapi/src/com/intellij/openapi/compiler/make/CompoundBuildInstruction.java b/java/compiler/openapi/src/com/intellij/openapi/compiler/make/CompoundBuildInstruction.java deleted file mode 100644 index 0d99a5864bfb..000000000000 --- a/java/compiler/openapi/src/com/intellij/openapi/compiler/make/CompoundBuildInstruction.java +++ /dev/null @@ -1,28 +0,0 @@ -/* - * Copyright 2000-2009 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.intellij.openapi.compiler.make; - - -import com.intellij.openapi.compiler.CompileContext; - -public interface CompoundBuildInstruction extends BuildInstruction { - - BuildConfiguration getBuildProperties(); - - BuildRecipe getChildInstructions(CompileContext context); - - BuildParticipant getBuildParticipant(); -} \ No newline at end of file diff --git a/java/compiler/openapi/src/com/intellij/openapi/compiler/make/JarAndCopyBuildInstruction.java b/java/compiler/openapi/src/com/intellij/openapi/compiler/make/JarAndCopyBuildInstruction.java index 4cfccd9a60f9..96a920531678 100644 --- a/java/compiler/openapi/src/com/intellij/openapi/compiler/make/JarAndCopyBuildInstruction.java +++ b/java/compiler/openapi/src/com/intellij/openapi/compiler/make/JarAndCopyBuildInstruction.java @@ -15,21 +15,8 @@ */ package com.intellij.openapi.compiler.make; -import com.intellij.openapi.compiler.CompileContext; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - import java.io.File; -import java.io.FileFilter; -import java.io.IOException; public interface JarAndCopyBuildInstruction extends FileCopyInstruction { - @Deprecated - void makeJar(@NotNull CompileContext context, - @NotNull File jarFile, - @Nullable FileFilter fileFilter) throws IOException; - File getJarFile(); - @Deprecated - void deleteTemporaryJars(); } \ No newline at end of file diff --git a/java/compiler/openapi/src/com/intellij/openapi/deployment/ContainerElement.java b/java/compiler/openapi/src/com/intellij/openapi/deployment/ContainerElement.java index 401816c6f582..8ba21442f123 100644 --- a/java/compiler/openapi/src/com/intellij/openapi/deployment/ContainerElement.java +++ b/java/compiler/openapi/src/com/intellij/openapi/deployment/ContainerElement.java @@ -104,10 +104,6 @@ public abstract class ContainerElement implements JDOMExternalizable, Cloneable, return 0; } - public abstract String getDescription(); - - public abstract String getDescriptionForPackagingMethod(PackagingMethod method); - public ContainerElement clone() { throw new UnsupportedOperationException(); } diff --git a/java/compiler/openapi/src/com/intellij/openapi/deployment/DeploymentUtil.java b/java/compiler/openapi/src/com/intellij/openapi/deployment/DeploymentUtil.java index 05e37d52c9ed..2d452613d74f 100644 --- a/java/compiler/openapi/src/com/intellij/openapi/deployment/DeploymentUtil.java +++ b/java/compiler/openapi/src/com/intellij/openapi/deployment/DeploymentUtil.java @@ -36,7 +36,6 @@ import java.io.File; import java.io.FileFilter; import java.io.IOException; import java.util.Set; -import java.util.jar.Manifest; public abstract class DeploymentUtil { public static DeploymentUtil getInstance() { @@ -93,8 +92,6 @@ public abstract class DeploymentUtil { public abstract void reportDeploymentDescriptorDoesNotExists(ConfigFile descriptor, CompileContext context, Module module); - @Nullable public abstract Manifest createManifest(@NotNull BuildRecipe buildRecipe); - public abstract void addJavaModuleOutputs(@NotNull Module module, @NotNull ModuleLink[] containingModules, @NotNull BuildRecipe instructions, @@ -110,14 +107,6 @@ public abstract class DeploymentUtil { @NotNull CompileContext context, String explodedPath); - public static boolean checkFileExists(final File file, CompileContext context) { - if (!file.exists()) { - context.addMessage(CompilerMessageCategory.ERROR, CompilerBundle.message("compiler.message.text.file.does.not.exist", file),null,-1,-1); - return false; - } - return true; - } - public static String concatPaths(String... paths) { final StringBuilder builder = new StringBuilder(); for (String path : paths) { @@ -194,8 +183,6 @@ public abstract class DeploymentUtil { } } - public abstract @Nullable File findUserSuppliedManifestFile(@NotNull BuildRecipe buildRecipe); - public abstract void checkConfigFile(final ConfigFile descriptor, final CompileContext compileContext, final Module module); } diff --git a/java/compiler/openapi/src/com/intellij/openapi/deployment/PackagingConfiguration.java b/java/compiler/openapi/src/com/intellij/openapi/deployment/PackagingConfiguration.java deleted file mode 100644 index e04624ebed94..000000000000 --- a/java/compiler/openapi/src/com/intellij/openapi/deployment/PackagingConfiguration.java +++ /dev/null @@ -1,40 +0,0 @@ -/* - * Copyright 2000-2009 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.intellij.openapi.deployment; - -import com.intellij.openapi.module.Module; -import com.intellij.openapi.util.JDOMExternalizable; -import com.intellij.openapi.roots.ui.configuration.ModulesProvider; -import com.intellij.openapi.roots.ui.configuration.FacetsProvider; - -public interface PackagingConfiguration extends JDOMExternalizable { - ModuleLink[] getContainingModules(); - - LibraryLink[] getContainingLibraries(); - - ContainerElement[] getElements(); - - void setElements(ContainerElement[] elements); - - Module[] getContainingIdeaModules(); - - ContainerElement[] getElements(ModulesProvider provider, FacetsProvider facetsProvider, - boolean includeResolved, boolean includeUnresolved, boolean includeNonPackaged); - - void addOrReplaceElement(ContainerElement element); - - boolean removeContainerElement(ContainerElement containerElement); -} \ No newline at end of file diff --git a/java/compiler/openapi/src/com/intellij/packaging/elements/CompositePackagingElementType.java b/java/compiler/openapi/src/com/intellij/packaging/elements/CompositePackagingElementType.java index 861e85cb4bfb..66025980b4c4 100644 --- a/java/compiler/openapi/src/com/intellij/packaging/elements/CompositePackagingElementType.java +++ b/java/compiler/openapi/src/com/intellij/packaging/elements/CompositePackagingElementType.java @@ -39,11 +39,11 @@ public abstract class CompositePackagingElementType parent); + protected abstract PackagingElement createComposite(@NotNull ArtifactEditorContext context, CompositePackagingElement parent); @NotNull - public List chooseAndCreate(@NotNull ArtifactEditorContext context, @NotNull Artifact artifact, @NotNull CompositePackagingElement parent) { - final E composite = createComposite(context, parent); + public List> chooseAndCreate(@NotNull ArtifactEditorContext context, @NotNull Artifact artifact, @NotNull CompositePackagingElement parent) { + final PackagingElement composite = createComposite(context, parent); return composite != null ? Collections.singletonList(composite) : Collections.emptyList(); } } diff --git a/java/compiler/openapi/src/com/intellij/packaging/elements/PackagingElementType.java b/java/compiler/openapi/src/com/intellij/packaging/elements/PackagingElementType.java index 22efed1b0247..48cc0c2af441 100644 --- a/java/compiler/openapi/src/com/intellij/packaging/elements/PackagingElementType.java +++ b/java/compiler/openapi/src/com/intellij/packaging/elements/PackagingElementType.java @@ -57,8 +57,8 @@ public abstract class PackagingElementType> { public abstract boolean canCreate(@NotNull ArtifactEditorContext context, @NotNull Artifact artifact); @NotNull - public abstract List chooseAndCreate(@NotNull ArtifactEditorContext context, @NotNull Artifact artifact, - @NotNull CompositePackagingElement parent); + public abstract List> chooseAndCreate(@NotNull ArtifactEditorContext context, @NotNull Artifact artifact, + @NotNull CompositePackagingElement parent); @NotNull public abstract E createEmpty(@NotNull Project project); diff --git a/java/debugger/impl/src/com/intellij/debugger/engine/DebugProcessImpl.java b/java/debugger/impl/src/com/intellij/debugger/engine/DebugProcessImpl.java index 478dc3bd8065..5a61e615206f 100644 --- a/java/debugger/impl/src/com/intellij/debugger/engine/DebugProcessImpl.java +++ b/java/debugger/impl/src/com/intellij/debugger/engine/DebugProcessImpl.java @@ -46,8 +46,11 @@ import com.intellij.execution.CantRunException; import com.intellij.execution.ExecutionException; import com.intellij.execution.ExecutionResult; import com.intellij.execution.Executor; +import com.intellij.execution.configurations.CommandLineState; import com.intellij.execution.configurations.RemoteConnection; import com.intellij.execution.configurations.RunProfileState; +import com.intellij.execution.filters.ExceptionFilter; +import com.intellij.execution.filters.TextConsoleBuilder; import com.intellij.execution.process.ProcessAdapter; import com.intellij.execution.process.ProcessEvent; import com.intellij.execution.process.ProcessListener; @@ -1621,6 +1624,12 @@ public abstract class DebugProcessImpl implements DebugProcess { try { synchronized (myProcessListeners) { + if (state instanceof CommandLineState) { + final TextConsoleBuilder consoleBuilder = ((CommandLineState)state).getConsoleBuilder(); + if (consoleBuilder != null) { + consoleBuilder.addFilter(new ExceptionFilter(session.getSearchScope())); + } + } myExecutionResult = state.execute(executor, runner); if (myExecutionResult == null) { fail(); diff --git a/java/debugger/impl/src/com/intellij/debugger/impl/DebuggerSession.java b/java/debugger/impl/src/com/intellij/debugger/impl/DebuggerSession.java index c40f7e2f8915..a2e37db95d34 100644 --- a/java/debugger/impl/src/com/intellij/debugger/impl/DebuggerSession.java +++ b/java/debugger/impl/src/com/intellij/debugger/impl/DebuggerSession.java @@ -341,11 +341,10 @@ public class DebuggerSession implements AbstractDebuggerSession { @Nullable protected ExecutionResult attach(@NotNull final Executor executor, @NotNull final ProgramRunner runner, final ModuleRunProfile profile, final RunProfileState state, final RemoteConnection remoteConnection, final boolean pollConnection) throws ExecutionException { - final ExecutionResult executionResult = myDebugProcess.attachVirtualMachine(executor, runner, this, state, remoteConnection, pollConnection); final String addressDisplayName = DebuggerBundle.getAddressDisplayName(remoteConnection); final String transportName = DebuggerBundle.getTransportName(remoteConnection); final Module[] modules = profile.getModules(); - if (modules == null || modules.length == 0) { + if (modules.length == 0) { mySearchScope = GlobalSearchScope.allScope(getProject()); } else { @@ -356,6 +355,7 @@ public class DebuggerSession implements AbstractDebuggerSession { } mySearchScope = scope; } + final ExecutionResult executionResult = myDebugProcess.attachVirtualMachine(executor, runner, this, state, remoteConnection, pollConnection); getContextManager().setState(SESSION_EMPTY_CONTEXT, STATE_WAITING_ATTACH, EVENT_START_WAIT_ATTACH, DebuggerBundle.message("status.waiting.attach", addressDisplayName, transportName)); return executionResult; } diff --git a/java/debugger/impl/src/com/intellij/debugger/ui/DebuggerSessionTab.java b/java/debugger/impl/src/com/intellij/debugger/ui/DebuggerSessionTab.java index 04809be06b06..23fed950326e 100644 --- a/java/debugger/impl/src/com/intellij/debugger/ui/DebuggerSessionTab.java +++ b/java/debugger/impl/src/com/intellij/debugger/ui/DebuggerSessionTab.java @@ -33,6 +33,8 @@ import com.intellij.debugger.ui.impl.watch.*; import com.intellij.execution.*; import com.intellij.execution.configurations.RunProfile; import com.intellij.execution.executors.DefaultDebugExecutor; +import com.intellij.execution.filters.ExceptionFilter; +import com.intellij.execution.filters.TextConsoleBuilder; import com.intellij.execution.filters.TextConsoleBuilderFactory; import com.intellij.execution.runners.ExecutionEnvironment; import com.intellij.execution.runners.ProgramRunner; @@ -511,7 +513,9 @@ public class DebuggerSessionTab extends DebuggerLogConsoleManagerBase implements public void addThreadDump(List threads) { final Project project = getProject(); - final ConsoleView consoleView = TextConsoleBuilderFactory.getInstance().createBuilder(project).getConsole(); + final TextConsoleBuilder consoleBuilder = TextConsoleBuilderFactory.getInstance().createBuilder(project); + consoleBuilder.addFilter(new ExceptionFilter(myDebuggerSession.getSearchScope())); + final ConsoleView consoleView = consoleBuilder.getConsole(); final DefaultActionGroup toolbarActions = new DefaultActionGroup(); final ThreadDumpPanel panel = new ThreadDumpPanel(project, consoleView, toolbarActions, threads); diff --git a/java/execution/openapi/src/com/intellij/execution/filters/ExceptionFilter.java b/java/execution/openapi/src/com/intellij/execution/filters/ExceptionFilter.java index 6d4cd562f3ff..18b846685bd9 100644 --- a/java/execution/openapi/src/com/intellij/execution/filters/ExceptionFilter.java +++ b/java/execution/openapi/src/com/intellij/execution/filters/ExceptionFilter.java @@ -39,9 +39,16 @@ public class ExceptionFilter implements Filter, DumbAware { private static final String AT_PREFIX = AT + " "; private static final String STANDALONE_AT = " " + AT + " "; private static final TextAttributes HYPERLINK_ATTRIBUTES = EditorColorsManager.getInstance().getGlobalScheme().getAttributes(CodeInsightColors.HYPERLINK_ATTRIBUTES); + private final GlobalSearchScope mySearchScope; public ExceptionFilter(@NotNull final Project project) { myProject = project; + mySearchScope = GlobalSearchScope.allScope(myProject); + } + + public ExceptionFilter(@NotNull final GlobalSearchScope scope) { + myProject = scope.getProject(); + mySearchScope = scope; } public Result applyFilter(final String line, final int textEndOffset) { @@ -81,7 +88,7 @@ public class ExceptionFilter implements Filter, DumbAware { try{ final int lineNumber = Integer.parseInt(lineString); final PsiManager manager = PsiManager.getInstance(myProject); - PsiClass aClass = JavaPsiFacade.getInstance(manager.getProject()).findClass(className, GlobalSearchScope.allScope(myProject)); + PsiClass aClass = JavaPsiFacade.getInstance(manager.getProject()).findClass(className, mySearchScope); if (aClass == null) return null; final PsiFile file = (PsiFile) aClass.getContainingFile().getNavigationElement(); if (file == null) return null; diff --git a/java/idea-ui/src/com/intellij/ide/util/frameworkSupport/AddFrameworkSupportDialog.java b/java/idea-ui/src/com/intellij/ide/util/frameworkSupport/AddFrameworkSupportDialog.java index 453743c3b6a8..ca1104b9a3e9 100644 --- a/java/idea-ui/src/com/intellij/ide/util/frameworkSupport/AddFrameworkSupportDialog.java +++ b/java/idea-ui/src/com/intellij/ide/util/frameworkSupport/AddFrameworkSupportDialog.java @@ -6,7 +6,6 @@ package com.intellij.ide.util.frameworkSupport; import com.intellij.CommonBundle; import com.intellij.ide.util.newProjectWizard.AddSupportForFrameworksPanel; -import com.intellij.ide.util.frameworkSupport.FrameworkSupportProvider; import com.intellij.openapi.application.Result; import com.intellij.openapi.application.WriteAction; import com.intellij.openapi.module.Module; @@ -80,6 +79,11 @@ public class AddFrameworkSupportDialog extends DialogWrapper { super.doOKAction(); } + @Override + protected String getHelpId() { + return "reference.frameworks.support.dialog"; + } + protected JComponent createCenterPanel() { return myAddSupportPanel.getMainPanel(); } diff --git a/java/idea-ui/src/com/intellij/openapi/roots/ui/configuration/ModuleEditor.java b/java/idea-ui/src/com/intellij/openapi/roots/ui/configuration/ModuleEditor.java index 082be71429f9..02a10416ee55 100644 --- a/java/idea-ui/src/com/intellij/openapi/roots/ui/configuration/ModuleEditor.java +++ b/java/idea-ui/src/com/intellij/openapi/roots/ui/configuration/ModuleEditor.java @@ -27,6 +27,7 @@ import com.intellij.openapi.options.ConfigurationException; import com.intellij.openapi.project.Project; import com.intellij.openapi.roots.ModifiableRootModel; import com.intellij.openapi.roots.ModuleRootManager; +import com.intellij.openapi.roots.ModuleRootModel; import com.intellij.openapi.roots.OrderEntry; import com.intellij.openapi.roots.impl.ModuleRootManagerImpl; import com.intellij.openapi.roots.libraries.Library; @@ -144,6 +145,13 @@ public abstract class ModuleEditor implements Place.Navigator, Disposable { return myModifiableRootModelProxy; } + public ModuleRootModel getRootModel() { + if (myModifiableRootModel != null) { + return getModifiableRootModelProxy(); + } + return ModuleRootManager.getInstance(myModule); + } + public boolean isModified() { for (ModuleConfigurationEditor moduleElementsEditor : myEditors) { if (moduleElementsEditor.isModified()) { diff --git a/java/idea-ui/src/com/intellij/openapi/roots/ui/configuration/ModulesConfigurator.java b/java/idea-ui/src/com/intellij/openapi/roots/ui/configuration/ModulesConfigurator.java index 5005d8fc7cc9..4b1f04bdead8 100644 --- a/java/idea-ui/src/com/intellij/openapi/roots/ui/configuration/ModulesConfigurator.java +++ b/java/idea-ui/src/com/intellij/openapi/roots/ui/configuration/ModulesConfigurator.java @@ -151,11 +151,11 @@ public class ModulesConfigurator implements ModulesProvider, ModuleEditor.Change final ModuleEditor editor = getModuleEditor(module); ModuleRootModel rootModel = null; if (editor != null) { - rootModel = editor.getModifiableRootModel(); + rootModel = editor.getRootModel(); } if (rootModel == null && getModule(module.getName()) != null) { createModuleEditor(module); - rootModel = getModuleEditor(module).getModifiableRootModel(); + rootModel = getModuleEditor(module).getRootModel(); } return rootModel; diff --git a/java/java-impl/src/com/intellij/codeInsight/completion/DefaultInsertHandler.java b/java/java-impl/src/com/intellij/codeInsight/completion/DefaultInsertHandler.java index c664bb90d14a..15ddcf324179 100644 --- a/java/java-impl/src/com/intellij/codeInsight/completion/DefaultInsertHandler.java +++ b/java/java-impl/src/com/intellij/codeInsight/completion/DefaultInsertHandler.java @@ -93,8 +93,10 @@ public class DefaultInsertHandler extends TemplateInsertHandler implements Clone myDocument = myEditor.getDocument(); TailType tailType = getTailType(completionChar); + if (completionChar == Lookup.COMPLETE_STATEMENT_SELECT_CHAR) { + tailType = TailType.SMART_COMPLETION; + } - //adjustContextAfterLookupStringInsertion(); myState = new InsertHandlerState(myContext.getSelectionEndOffset(), myContext.getSelectionEndOffset()); final boolean needLeftParenth = isToInsertParenth(); @@ -412,7 +414,6 @@ public class DefaultInsertHandler extends TemplateInsertHandler implements Clone case '#': case '\"': case '[': return TailType.createSimpleTailType(completionChar); - case Lookup.COMPLETE_STATEMENT_SELECT_CHAR: return TailType.SMART_COMPLETION; //case '!': if (!(myLookupItem.getObject() instanceof PsiVariable)) return TailType.EXCLAMATION; } final TailType attr = myLookupItem.getTailType(); diff --git a/java/java-impl/src/com/intellij/codeInsight/completion/JavaSmartCompletionContributor.java b/java/java-impl/src/com/intellij/codeInsight/completion/JavaSmartCompletionContributor.java index 1742e1f3ee54..6dcfb2c8a4ef 100644 --- a/java/java-impl/src/com/intellij/codeInsight/completion/JavaSmartCompletionContributor.java +++ b/java/java-impl/src/com/intellij/codeInsight/completion/JavaSmartCompletionContributor.java @@ -620,7 +620,11 @@ public class JavaSmartCompletionContributor extends CompletionContributor { element instanceof PsiThisExpression || element instanceof PsiSuperExpression || element instanceof PsiTypeElement || element instanceof PsiClassObjectAccessExpression) { - context.getOffsetMap().addOffset(CompletionInitializationContext.IDENTIFIER_END_OFFSET, element.getTextRange().getEndOffset()); + int newEnd = element.getTextRange().getEndOffset(); + if (element instanceof PsiMethodCallExpression) { + newEnd = ((PsiMethodCallExpression)element).getMethodExpression().getElement().getTextRange().getEndOffset(); + } + context.getOffsetMap().addOffset(CompletionInitializationContext.IDENTIFIER_END_OFFSET, newEnd); element = element.getParent(); } } diff --git a/java/java-impl/src/com/intellij/codeInsight/daemon/impl/analysis/AnnotationsHighlightUtil.java b/java/java-impl/src/com/intellij/codeInsight/daemon/impl/analysis/AnnotationsHighlightUtil.java index fc9510218389..3adb241fd2e1 100644 --- a/java/java-impl/src/com/intellij/codeInsight/daemon/impl/analysis/AnnotationsHighlightUtil.java +++ b/java/java-impl/src/com/intellij/codeInsight/daemon/impl/analysis/AnnotationsHighlightUtil.java @@ -148,7 +148,7 @@ public class AnnotationsHighlightUtil { if (annotation == annotationToCheck) continue; PsiJavaCodeReferenceElement nameRef = annotation.getNameReferenceElement(); if (nameRef == null) continue; - PsiClass aClass = (PsiClass)nameRef.resolve(); + PsiElement aClass = nameRef.resolve(); if (resolved.equals(aClass)) { return HighlightInfo.createHighlightInfo(HighlightInfoType.ERROR, element, JavaErrorMessages.message("annotation.duplicate.annotation")); } diff --git a/java/java-impl/src/com/intellij/codeInspection/wrongPackageStatement/AdjustPackageNameFix.java b/java/java-impl/src/com/intellij/codeInspection/wrongPackageStatement/AdjustPackageNameFix.java index e7ff1cc5980c..127df5de62d9 100644 --- a/java/java-impl/src/com/intellij/codeInspection/wrongPackageStatement/AdjustPackageNameFix.java +++ b/java/java-impl/src/com/intellij/codeInspection/wrongPackageStatement/AdjustPackageNameFix.java @@ -68,12 +68,11 @@ public class AdjustPackageNameFix implements LocalQuickFix { } } else { + final PsiPackageStatement packageStatement = factory.createPackageStatement(myTargetPackage.getQualifiedName()); if (myStatement != null) { - PsiJavaCodeReferenceElement packageReferenceElement = factory.createPackageReferenceElement(myTargetPackage); - myStatement.getPackageReference().replace(packageReferenceElement); + myStatement.getPackageReference().replace(packageStatement.getPackageReference()); } else { - PsiPackageStatement packageStatement = factory.createPackageStatement(myTargetPackage.getQualifiedName()); myFile.addAfter(packageStatement, null); } } diff --git a/java/java-impl/src/com/intellij/psi/impl/source/codeStyle/ImportHelper.java b/java/java-impl/src/com/intellij/psi/impl/source/codeStyle/ImportHelper.java index 4e6d243b4867..7168c8a5213b 100644 --- a/java/java-impl/src/com/intellij/psi/impl/source/codeStyle/ImportHelper.java +++ b/java/java-impl/src/com/intellij/psi/impl/source/codeStyle/ImportHelper.java @@ -232,9 +232,13 @@ public class ImportHelper{ Map> classNames = new THashMap>(); JavaPsiFacade facade = JavaPsiFacade.getInstance(file.getProject()); - for (String onDemand : onDemands) { + for (int i = onDemands.size()-1; i>=0; i--) { + String onDemand = onDemands.get(i); PsiPackage aPackage = facade.findPackage(onDemand); - if (aPackage == null) continue; + if (aPackage == null) { + onDemands.remove(i); + continue; + } PsiClass[] psiClasses = aPackage.getClasses(resolveScope); Set set = new THashSet(psiClasses.length); for (PsiClass psiClass : psiClasses) { diff --git a/java/java-impl/src/com/intellij/psi/impl/source/resolve/ClassResolverProcessor.java b/java/java-impl/src/com/intellij/psi/impl/source/resolve/ClassResolverProcessor.java index e6a93bc62c45..2ee48785b5e6 100644 --- a/java/java-impl/src/com/intellij/psi/impl/source/resolve/ClassResolverProcessor.java +++ b/java/java-impl/src/com/intellij/psi/impl/source/resolve/ClassResolverProcessor.java @@ -93,7 +93,9 @@ public class ClassResolverProcessor extends BaseScopeProcessor implements NameHi } private static boolean isOnDemand(PsiElement fileContext, PsiClass psiClass) { - if (fileContext instanceof PsiImportStatementBase && ((PsiImportStatementBase)fileContext).isOnDemand()) return true; + if (fileContext instanceof PsiImportStatementBase) { + return ((PsiImportStatementBase)fileContext).isOnDemand(); + } String fqn = psiClass.getQualifiedName(); if (fqn == null) return false; return "java.lang".equals(StringUtil.getPackageName(fqn)); @@ -106,6 +108,7 @@ public class ClassResolverProcessor extends BaseScopeProcessor implements NameHi if (!myClassName.equals(name)) { return true; } + boolean accessible = myPlace == null || checkAccessibility(aClass); if (myCandidates == null) { myCandidates = new SmartList(); } @@ -126,6 +129,15 @@ public class ClassResolverProcessor extends BaseScopeProcessor implements NameHi return true; } + boolean infoAccessible = info.isAccessible(); + if (infoAccessible && !accessible) { + return true; + } + if (!infoAccessible && accessible) { + myCandidates.remove(i); + continue; + } + // single import wins over on-demand boolean myOnDemand = isOnDemand(myCurrentFileContext, aClass); boolean otherOnDemand = isOnDemand(info.getCurrentFileResolveScope(), otherClass); @@ -137,7 +149,6 @@ public class ClassResolverProcessor extends BaseScopeProcessor implements NameHi } } - boolean accessible = myPlace == null || checkAccessibility(aClass); myHasAccessibleCandidate |= accessible; myHasInaccessibleCandidate |= !accessible; myCandidates.add(new ClassCandidateInfo(aClass, state.get(PsiSubstitutor.KEY), !accessible, myCurrentFileContext)); diff --git a/java/java-impl/src/com/intellij/refactoring/changeSignature/ChangeSignatureUtil.java b/java/java-impl/src/com/intellij/refactoring/changeSignature/ChangeSignatureUtil.java index 0519add70b61..708bb92ebf5e 100644 --- a/java/java-impl/src/com/intellij/refactoring/changeSignature/ChangeSignatureUtil.java +++ b/java/java-impl/src/com/intellij/refactoring/changeSignature/ChangeSignatureUtil.java @@ -43,7 +43,7 @@ public class ChangeSignatureUtil { if (elementsToRemove == null) { elementsToRemove = new ArrayList(); for (int i = 0; i < shouldRemoveChild.length; i++) { - if (shouldRemoveChild[i]) { + if (shouldRemoveChild[i] && i < elements.size()) { elementsToRemove.add(elements.get(i)); } } diff --git a/java/java-impl/src/com/intellij/refactoring/introduceVariable/IntroduceVariableBase.java b/java/java-impl/src/com/intellij/refactoring/introduceVariable/IntroduceVariableBase.java index a5ffe21786be..a4c5aa45b129 100644 --- a/java/java-impl/src/com/intellij/refactoring/introduceVariable/IntroduceVariableBase.java +++ b/java/java-impl/src/com/intellij/refactoring/introduceVariable/IntroduceVariableBase.java @@ -179,8 +179,11 @@ public abstract class IntroduceVariableBase extends IntroduceHandlerBase impleme final Component rendererComponent = super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus); final StringBuffer buf = new StringBuffer(); - ((PsiExpression)value).accept(new PsiExpressionTrimRenderer(buf)); - setText(buf.toString()); + final PsiExpression expr = (PsiExpression)value; + if (expr.isValid()) { + expr.accept(new PsiExpressionTrimRenderer(buf)); + setText(buf.toString()); + } return rendererComponent; } }); diff --git a/java/java-impl/src/com/intellij/refactoring/memberPushDown/PushDownConflicts.java b/java/java-impl/src/com/intellij/refactoring/memberPushDown/PushDownConflicts.java index c233598aa2d6..e0dcbe78bc33 100644 --- a/java/java-impl/src/com/intellij/refactoring/memberPushDown/PushDownConflicts.java +++ b/java/java-impl/src/com/intellij/refactoring/memberPushDown/PushDownConflicts.java @@ -99,7 +99,7 @@ public class PushDownConflicts { } if (!InheritanceUtil.isInheritorOrSelf(aClass, targetClass, true)) { - myConflicts.putValue(aClass, RefactoringBundle.message("pushed.members.will.not.be.visible.from.certain.call.sites")); + myConflicts.putValue(referenceExpression, RefactoringBundle.message("pushed.members.will.not.be.visible.from.certain.call.sites")); break Members; } } diff --git a/java/java-impl/src/com/intellij/refactoring/util/RefactoringUtil.java b/java/java-impl/src/com/intellij/refactoring/util/RefactoringUtil.java index 2437bc0ef0ce..be67e1e2bdb2 100644 --- a/java/java-impl/src/com/intellij/refactoring/util/RefactoringUtil.java +++ b/java/java-impl/src/com/intellij/refactoring/util/RefactoringUtil.java @@ -1115,7 +1115,7 @@ public class RefactoringUtil { final Set used = new HashSet(); for (final PsiElement element : elements) { if (element == null) continue; - element.accept(new JavaRecursiveElementWalkingVisitor() { + element.accept(new JavaRecursiveElementVisitor() { //pull up extends cls class with type params @Override public void visitReferenceElement(PsiJavaCodeReferenceElement reference) { super.visitReferenceElement(reference); diff --git a/java/java-tests/testData/codeInsight/completion/smartType/ConstructorArgsSmartEnter-out.java b/java/java-tests/testData/codeInsight/completion/smartType/ConstructorArgsSmartEnter-out.java new file mode 100644 index 000000000000..484b537fe6de --- /dev/null +++ b/java/java-tests/testData/codeInsight/completion/smartType/ConstructorArgsSmartEnter-out.java @@ -0,0 +1,11 @@ +import java.util.ArrayList; +import java.util.List; + +public class MyJavaClass { + + { + + List l = new ArrayList(239); + + } +} diff --git a/java/java-tests/testData/codeInsight/completion/smartType/ConstructorArgsSmartEnter.java b/java/java-tests/testData/codeInsight/completion/smartType/ConstructorArgsSmartEnter.java new file mode 100644 index 000000000000..f28c82c5dc47 --- /dev/null +++ b/java/java-tests/testData/codeInsight/completion/smartType/ConstructorArgsSmartEnter.java @@ -0,0 +1,9 @@ +import java.util.List; + +public class MyJavaClass { + + { + + List l = new ArraL239 + } +} diff --git a/java/java-tests/testData/codeInsight/completion/smartType/TabMethodCall-out.java b/java/java-tests/testData/codeInsight/completion/smartType/TabMethodCall-out.java new file mode 100644 index 000000000000..d7c1a56d988c --- /dev/null +++ b/java/java-tests/testData/codeInsight/completion/smartType/TabMethodCall-out.java @@ -0,0 +1,9 @@ +public class MyJavaClass { + + boolean ffff() {} + + { + + boolean b = ffff(239); + } +} diff --git a/java/java-tests/testData/codeInsight/completion/smartType/TabMethodCall.java b/java/java-tests/testData/codeInsight/completion/smartType/TabMethodCall.java new file mode 100644 index 000000000000..da21a4bd4aa8 --- /dev/null +++ b/java/java-tests/testData/codeInsight/completion/smartType/TabMethodCall.java @@ -0,0 +1,9 @@ +public class MyJavaClass { + + boolean ffff() {} + + { + + boolean b = equals(239); + } +} diff --git a/java/java-tests/testData/inspection/deadCode/SCR6067/expected.xml b/java/java-tests/testData/inspection/deadCode/SCR6067/expected.xml new file mode 100644 index 000000000000..dd7067eb5d9e --- /dev/null +++ b/java/java-tests/testData/inspection/deadCode/SCR6067/expected.xml @@ -0,0 +1,9 @@ + + + + A.java + 2 + Constructor is never used + + + diff --git a/java/java-tests/testData/inspection/deadCode/SCR6067/ext_src/B.java b/java/java-tests/testData/inspection/deadCode/SCR6067/ext_src/B.java new file mode 100644 index 000000000000..8bb0e59c94fb --- /dev/null +++ b/java/java-tests/testData/inspection/deadCode/SCR6067/ext_src/B.java @@ -0,0 +1,4 @@ +class B { + A a=new A(0); +} + diff --git a/java/java-tests/testData/inspection/deadCode/SCR6067/src/A.java b/java/java-tests/testData/inspection/deadCode/SCR6067/src/A.java new file mode 100644 index 000000000000..08342c54e92a --- /dev/null +++ b/java/java-tests/testData/inspection/deadCode/SCR6067/src/A.java @@ -0,0 +1,8 @@ +class A { + A() { + } + A(int k) { + System.out.println(k); + } +} + diff --git a/java/java-tests/testData/inspection/deadCode/SCR9690/expected.xml b/java/java-tests/testData/inspection/deadCode/SCR9690/expected.xml new file mode 100644 index 000000000000..d704d58ed391 --- /dev/null +++ b/java/java-tests/testData/inspection/deadCode/SCR9690/expected.xml @@ -0,0 +1,4 @@ + + + + diff --git a/java/java-tests/testData/inspection/deadCode/SCR9690/ext_src/B.java b/java/java-tests/testData/inspection/deadCode/SCR9690/ext_src/B.java new file mode 100644 index 000000000000..10373621f638 --- /dev/null +++ b/java/java-tests/testData/inspection/deadCode/SCR9690/ext_src/B.java @@ -0,0 +1,3 @@ +class B extends A { +} + diff --git a/java/java-tests/testData/inspection/deadCode/SCR9690/src/A.java b/java/java-tests/testData/inspection/deadCode/SCR9690/src/A.java new file mode 100644 index 000000000000..6a64ecd92e19 --- /dev/null +++ b/java/java-tests/testData/inspection/deadCode/SCR9690/src/A.java @@ -0,0 +1,5 @@ +abstract class A { + A() { + } +} + diff --git a/java/java-tests/testData/inspection/deadCode/Serializable/expected.xml b/java/java-tests/testData/inspection/deadCode/Serializable/expected.xml new file mode 100644 index 000000000000..5e933496b9cf --- /dev/null +++ b/java/java-tests/testData/inspection/deadCode/Serializable/expected.xml @@ -0,0 +1,3 @@ + + + \ No newline at end of file diff --git a/java/java-tests/testData/inspection/deadCode/Serializable/ext_src/External.java b/java/java-tests/testData/inspection/deadCode/Serializable/ext_src/External.java new file mode 100644 index 000000000000..9e17ba18d453 --- /dev/null +++ b/java/java-tests/testData/inspection/deadCode/Serializable/ext_src/External.java @@ -0,0 +1,5 @@ +public class External { + { + new Test(); + } +} \ No newline at end of file diff --git a/java/java-tests/testData/inspection/deadCode/Serializable/src/Test.java b/java/java-tests/testData/inspection/deadCode/Serializable/src/Test.java new file mode 100644 index 000000000000..5afb0ecb21d5 --- /dev/null +++ b/java/java-tests/testData/inspection/deadCode/Serializable/src/Test.java @@ -0,0 +1,6 @@ +public class Test implements java.io.Serializable { + private void writeObject(java.io.ObjectOutputStream out) {} + private void readObject(java.io.ObjectInputStream in) {} + public Object writeReplace() { return null; } + public Object readResolve() { return null; } +} \ No newline at end of file diff --git a/java/java-tests/testData/inspection/deadCode/UIFormUsage/expected.xml b/java/java-tests/testData/inspection/deadCode/UIFormUsage/expected.xml new file mode 100644 index 000000000000..5e933496b9cf --- /dev/null +++ b/java/java-tests/testData/inspection/deadCode/UIFormUsage/expected.xml @@ -0,0 +1,3 @@ + + + \ No newline at end of file diff --git a/java/java-tests/testData/inspection/deadCode/UIFormUsage/src/p1/Form.form b/java/java-tests/testData/inspection/deadCode/UIFormUsage/src/p1/Form.form new file mode 100644 index 000000000000..4e8359dfd015 --- /dev/null +++ b/java/java-tests/testData/inspection/deadCode/UIFormUsage/src/p1/Form.form @@ -0,0 +1,12 @@ + +
+ + + + + + + + + +
diff --git a/java/java-tests/testData/inspection/deadCode/UIFormUsage/src/p1/Form.java b/java/java-tests/testData/inspection/deadCode/UIFormUsage/src/p1/Form.java new file mode 100644 index 000000000000..bbe91f687f72 --- /dev/null +++ b/java/java-tests/testData/inspection/deadCode/UIFormUsage/src/p1/Form.java @@ -0,0 +1,8 @@ +package p1; + +public class Form { + private JLabel myLabel; + + private void createUIComponents() { + } +} \ No newline at end of file diff --git a/java/java-tests/testData/inspection/deadCode/additionalAnnotations/expected.xml b/java/java-tests/testData/inspection/deadCode/additionalAnnotations/expected.xml new file mode 100644 index 000000000000..79e1a0fd0a57 --- /dev/null +++ b/java/java-tests/testData/inspection/deadCode/additionalAnnotations/expected.xml @@ -0,0 +1,4 @@ + + + + diff --git a/java/java-tests/testData/inspection/deadCode/additionalAnnotations/src/Test.java b/java/java-tests/testData/inspection/deadCode/additionalAnnotations/src/Test.java new file mode 100644 index 000000000000..22ee9d72f991 --- /dev/null +++ b/java/java-tests/testData/inspection/deadCode/additionalAnnotations/src/Test.java @@ -0,0 +1,9 @@ +@Annotated +public class Test { + @Annotated + public void foo(){} + + @Annotated + public int myPublicField; + +} \ No newline at end of file diff --git a/java/java-tests/testData/inspection/deadCode/annotationInterface/expected.xml b/java/java-tests/testData/inspection/deadCode/annotationInterface/expected.xml new file mode 100644 index 000000000000..79e1a0fd0a57 --- /dev/null +++ b/java/java-tests/testData/inspection/deadCode/annotationInterface/expected.xml @@ -0,0 +1,4 @@ + + + + diff --git a/java/java-tests/testData/inspection/deadCode/annotationInterface/src/Test.java b/java/java-tests/testData/inspection/deadCode/annotationInterface/src/Test.java new file mode 100644 index 000000000000..d2865d1331aa --- /dev/null +++ b/java/java-tests/testData/inspection/deadCode/annotationInterface/src/Test.java @@ -0,0 +1,6 @@ +import java.lang.annotation.*; + +@Target({ElementType.METHOD, ElementType.FIELD, ElementType.PARAMETER, ElementType.LOCAL_VARIABLE}) +public @interface Test { + String value() default ""; +} \ No newline at end of file diff --git a/java/java-tests/testData/inspection/deadCode/chainOfCalls/expected.xml b/java/java-tests/testData/inspection/deadCode/chainOfCalls/expected.xml new file mode 100644 index 000000000000..79e1a0fd0a57 --- /dev/null +++ b/java/java-tests/testData/inspection/deadCode/chainOfCalls/expected.xml @@ -0,0 +1,4 @@ + + + + diff --git a/java/java-tests/testData/inspection/deadCode/chainOfCalls/src/A.java b/java/java-tests/testData/inspection/deadCode/chainOfCalls/src/A.java new file mode 100644 index 000000000000..6240d7f5e2e2 --- /dev/null +++ b/java/java-tests/testData/inspection/deadCode/chainOfCalls/src/A.java @@ -0,0 +1,5 @@ +public class A { + public A() { + + } +} \ No newline at end of file diff --git a/java/java-tests/testData/inspection/deadCode/chainOfCalls/src/B.java b/java/java-tests/testData/inspection/deadCode/chainOfCalls/src/B.java new file mode 100644 index 000000000000..f619d5e5222a --- /dev/null +++ b/java/java-tests/testData/inspection/deadCode/chainOfCalls/src/B.java @@ -0,0 +1,5 @@ +public class B implements I{ + public void projectOpened() { + new A(); + } +} \ No newline at end of file diff --git a/java/java-tests/testData/inspection/deadCode/chainOfCalls/src/I.java b/java/java-tests/testData/inspection/deadCode/chainOfCalls/src/I.java new file mode 100644 index 000000000000..c00581affca7 --- /dev/null +++ b/java/java-tests/testData/inspection/deadCode/chainOfCalls/src/I.java @@ -0,0 +1,3 @@ +public interface I { + void projectOpened(); +} \ No newline at end of file diff --git a/java/java-tests/testData/inspection/deadCode/chainOfCalls/src/Test.java b/java/java-tests/testData/inspection/deadCode/chainOfCalls/src/Test.java new file mode 100644 index 000000000000..c0c7b07c4aaf --- /dev/null +++ b/java/java-tests/testData/inspection/deadCode/chainOfCalls/src/Test.java @@ -0,0 +1,6 @@ +class Test { + public static void main(String[] args){ + I i = null; + i.projectOpened(); + } +} \ No newline at end of file diff --git a/java/java-tests/testData/inspection/deadCode/chainOfCalls/src/comps.xml b/java/java-tests/testData/inspection/deadCode/chainOfCalls/src/comps.xml new file mode 100644 index 000000000000..b93ca3a53f01 --- /dev/null +++ b/java/java-tests/testData/inspection/deadCode/chainOfCalls/src/comps.xml @@ -0,0 +1 @@ +B \ No newline at end of file diff --git a/java/java-tests/testData/inspection/deadCode/chainOfSuppressions/expected.xml b/java/java-tests/testData/inspection/deadCode/chainOfSuppressions/expected.xml new file mode 100644 index 000000000000..79e1a0fd0a57 --- /dev/null +++ b/java/java-tests/testData/inspection/deadCode/chainOfSuppressions/expected.xml @@ -0,0 +1,4 @@ + + + + diff --git a/java/java-tests/testData/inspection/deadCode/chainOfSuppressions/src/A.java b/java/java-tests/testData/inspection/deadCode/chainOfSuppressions/src/A.java new file mode 100644 index 000000000000..997e142d2e4c --- /dev/null +++ b/java/java-tests/testData/inspection/deadCode/chainOfSuppressions/src/A.java @@ -0,0 +1,18 @@ +public class A { + public static void main(String[] args) { + new A(); + } + + private void a(){ + } + + private void b(){ + a(); + } + + @java.lang.SuppressWarnings({"UnusedDeclaration"}) + private void c(){ + b(); + } +} + diff --git a/java/java-tests/testData/inspection/deadCode/constructorCalls/expected.xml b/java/java-tests/testData/inspection/deadCode/constructorCalls/expected.xml new file mode 100644 index 000000000000..79e1a0fd0a57 --- /dev/null +++ b/java/java-tests/testData/inspection/deadCode/constructorCalls/expected.xml @@ -0,0 +1,4 @@ + + + + diff --git a/java/java-tests/testData/inspection/deadCode/constructorCalls/src/A.java b/java/java-tests/testData/inspection/deadCode/constructorCalls/src/A.java new file mode 100644 index 000000000000..b01999a86300 --- /dev/null +++ b/java/java-tests/testData/inspection/deadCode/constructorCalls/src/A.java @@ -0,0 +1,4 @@ +public class A { + public A(int i) { + } +} \ No newline at end of file diff --git a/java/java-tests/testData/inspection/deadCode/constructorCalls/src/B.java b/java/java-tests/testData/inspection/deadCode/constructorCalls/src/B.java new file mode 100644 index 000000000000..77c142dc9a07 --- /dev/null +++ b/java/java-tests/testData/inspection/deadCode/constructorCalls/src/B.java @@ -0,0 +1,5 @@ +public class B { + public static void main(String[] args){ + System.out.println(new A(1)); + } +} \ No newline at end of file diff --git a/java/java-tests/testData/inspection/deadCode/constructorCalls1/expected.xml b/java/java-tests/testData/inspection/deadCode/constructorCalls1/expected.xml new file mode 100644 index 000000000000..79e1a0fd0a57 --- /dev/null +++ b/java/java-tests/testData/inspection/deadCode/constructorCalls1/expected.xml @@ -0,0 +1,4 @@ + + + + diff --git a/java/java-tests/testData/inspection/deadCode/constructorCalls1/src/Test.java b/java/java-tests/testData/inspection/deadCode/constructorCalls1/src/Test.java new file mode 100644 index 000000000000..ab4c4fbaf432 --- /dev/null +++ b/java/java-tests/testData/inspection/deadCode/constructorCalls1/src/Test.java @@ -0,0 +1,9 @@ +public class Test { + public static void main(String[] args){ + System.out.println(new A(1)); + } + + private class A { + public A(int i){} + } +} \ No newline at end of file diff --git a/java/java-tests/testData/inspection/deadCode/constructorReachableFromFieldInitializer/expected.xml b/java/java-tests/testData/inspection/deadCode/constructorReachableFromFieldInitializer/expected.xml new file mode 100644 index 000000000000..79e1a0fd0a57 --- /dev/null +++ b/java/java-tests/testData/inspection/deadCode/constructorReachableFromFieldInitializer/expected.xml @@ -0,0 +1,4 @@ + + + + diff --git a/java/java-tests/testData/inspection/deadCode/constructorReachableFromFieldInitializer/src/test/AMatcher.java b/java/java-tests/testData/inspection/deadCode/constructorReachableFromFieldInitializer/src/test/AMatcher.java new file mode 100644 index 000000000000..a34d1fd0f8dc --- /dev/null +++ b/java/java-tests/testData/inspection/deadCode/constructorReachableFromFieldInitializer/src/test/AMatcher.java @@ -0,0 +1,8 @@ +package test; + +public class AMatcher implements Matcher{ + private static final BracePair [] PAIRS = new BracePair[]{new BracePair()}; + public BracePair[] getPairs() { + return PAIRS; + } +} diff --git a/java/java-tests/testData/inspection/deadCode/constructorReachableFromFieldInitializer/src/test/BracePair.java b/java/java-tests/testData/inspection/deadCode/constructorReachableFromFieldInitializer/src/test/BracePair.java new file mode 100644 index 000000000000..5e444a3e265c --- /dev/null +++ b/java/java-tests/testData/inspection/deadCode/constructorReachableFromFieldInitializer/src/test/BracePair.java @@ -0,0 +1,7 @@ +package test; + +public class BracePair { + + public BracePair() { + } +} diff --git a/java/java-tests/testData/inspection/deadCode/constructorReachableFromFieldInitializer/src/test/Matcher.java b/java/java-tests/testData/inspection/deadCode/constructorReachableFromFieldInitializer/src/test/Matcher.java new file mode 100644 index 000000000000..ad370de57b73 --- /dev/null +++ b/java/java-tests/testData/inspection/deadCode/constructorReachableFromFieldInitializer/src/test/Matcher.java @@ -0,0 +1,5 @@ +package test; + +public interface Matcher { + BracePair[] getPairs(); +} diff --git a/java/java-tests/testData/inspection/deadCode/constructorReachableFromFieldInitializer/src/test/Test.java b/java/java-tests/testData/inspection/deadCode/constructorReachableFromFieldInitializer/src/test/Test.java new file mode 100644 index 000000000000..c54db3d285f2 --- /dev/null +++ b/java/java-tests/testData/inspection/deadCode/constructorReachableFromFieldInitializer/src/test/Test.java @@ -0,0 +1,12 @@ +package test; + +public class Test { + + public Test(Matcher m) { + BracePair[] bracePairs = m.getPairs(); + } + + public static void main(String[] args) { + System.out.println(new Test(new AMatcher())); + } +} diff --git a/java/java-tests/testData/inspection/deadCode/enumInstantiation/expected.xml b/java/java-tests/testData/inspection/deadCode/enumInstantiation/expected.xml new file mode 100644 index 000000000000..79e1a0fd0a57 --- /dev/null +++ b/java/java-tests/testData/inspection/deadCode/enumInstantiation/expected.xml @@ -0,0 +1,4 @@ + + + + diff --git a/java/java-tests/testData/inspection/deadCode/enumInstantiation/ext_src/Test1.java b/java/java-tests/testData/inspection/deadCode/enumInstantiation/ext_src/Test1.java new file mode 100644 index 000000000000..d0490b228bfe --- /dev/null +++ b/java/java-tests/testData/inspection/deadCode/enumInstantiation/ext_src/Test1.java @@ -0,0 +1,7 @@ +public void Test1 { + void foo() { + if (Test.FIRST.invert() != Test.SECOND) { + //assert + } + } +} \ No newline at end of file diff --git a/java/java-tests/testData/inspection/deadCode/enumInstantiation/src/Test.java b/java/java-tests/testData/inspection/deadCode/enumInstantiation/src/Test.java new file mode 100644 index 000000000000..0db3984de042 --- /dev/null +++ b/java/java-tests/testData/inspection/deadCode/enumInstantiation/src/Test.java @@ -0,0 +1,8 @@ +public enum Test +{ + FIRST, SECOND; + + public Test invert() { + return this == FIRST ? SECOND : FIRST; + } +} \ No newline at end of file diff --git a/java/java-tests/testData/inspection/deadCode/junitEntryPoint/expected.xml b/java/java-tests/testData/inspection/deadCode/junitEntryPoint/expected.xml new file mode 100644 index 000000000000..fe20bdd54e60 --- /dev/null +++ b/java/java-tests/testData/inspection/deadCode/junitEntryPoint/expected.xml @@ -0,0 +1,16 @@ + + + + Test.java + 14 + + Method is never used. + + + Test.java + 8 + + Method is never used. + + + diff --git a/java/java-tests/testData/inspection/deadCode/junitEntryPoint/src/A.java b/java/java-tests/testData/inspection/deadCode/junitEntryPoint/src/A.java new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/java/java-tests/testData/inspection/deadCode/junitEntryPoint/src/I.java b/java/java-tests/testData/inspection/deadCode/junitEntryPoint/src/I.java new file mode 100644 index 000000000000..30e18dcba1d4 --- /dev/null +++ b/java/java-tests/testData/inspection/deadCode/junitEntryPoint/src/I.java @@ -0,0 +1,3 @@ +public interface I { + A create(); +} \ No newline at end of file diff --git a/java/java-tests/testData/inspection/deadCode/junitEntryPoint/src/IImpl.java b/java/java-tests/testData/inspection/deadCode/junitEntryPoint/src/IImpl.java new file mode 100644 index 000000000000..d045ab0f2ae9 --- /dev/null +++ b/java/java-tests/testData/inspection/deadCode/junitEntryPoint/src/IImpl.java @@ -0,0 +1,5 @@ +public class IImpl extends I { + public A create() { + return new A(); + } +} \ No newline at end of file diff --git a/java/java-tests/testData/inspection/deadCode/junitEntryPoint/src/Test.java b/java/java-tests/testData/inspection/deadCode/junitEntryPoint/src/Test.java new file mode 100644 index 000000000000..11eec16b2bf9 --- /dev/null +++ b/java/java-tests/testData/inspection/deadCode/junitEntryPoint/src/Test.java @@ -0,0 +1,15 @@ +public class Test { + public static junit.framework.Test suite() { + I i = new IImpl(); + A a = i.create(); + return null; + } + + public void testSmth() {} + + public void setUp() {} + + public void tearDown(){} + + public void notATest(){} +} \ No newline at end of file diff --git a/java/java-tests/testData/inspection/deadCode/junitEntryPointCustomRunWith/expected.xml b/java/java-tests/testData/inspection/deadCode/junitEntryPointCustomRunWith/expected.xml new file mode 100644 index 000000000000..c63c9258595e --- /dev/null +++ b/java/java-tests/testData/inspection/deadCode/junitEntryPointCustomRunWith/expected.xml @@ -0,0 +1,2 @@ + + diff --git a/java/java-tests/testData/inspection/deadCode/junitEntryPointCustomRunWith/src/Test.java b/java/java-tests/testData/inspection/deadCode/junitEntryPointCustomRunWith/src/Test.java new file mode 100644 index 000000000000..34bd45976763 --- /dev/null +++ b/java/java-tests/testData/inspection/deadCode/junitEntryPointCustomRunWith/src/Test.java @@ -0,0 +1,10 @@ +@org.junit.runner.RunWith(UnresolvedRunner.class) +public class Test { + public void testSmth() {} + + public void setUp() {} + + public void tearDown(){} + + public void notATestButCanBeRunnedWithCustomRunner(){} +} \ No newline at end of file diff --git a/java/java-tests/testData/inspection/deadCode/mutableCalls/expected.xml b/java/java-tests/testData/inspection/deadCode/mutableCalls/expected.xml new file mode 100644 index 000000000000..98f48aedf800 --- /dev/null +++ b/java/java-tests/testData/inspection/deadCode/mutableCalls/expected.xml @@ -0,0 +1,16 @@ + + + + A.java + 2 + unused declaration + Method has usage(s) but they all belong to recursive calls chain that has no members reachable from entry points. + + + A.java + 5 + unused declaration + Method has usage(s) but they all belong to recursive calls chain that has no members reachable from entry points. + + + diff --git a/java/java-tests/testData/inspection/deadCode/mutableCalls/src/A.java b/java/java-tests/testData/inspection/deadCode/mutableCalls/src/A.java new file mode 100644 index 000000000000..b8e36ccd839f --- /dev/null +++ b/java/java-tests/testData/inspection/deadCode/mutableCalls/src/A.java @@ -0,0 +1,9 @@ +public class A { + private void a(){ + b(); + } + private void b(){ + a(); + } +} + diff --git a/java/java-tests/testData/inspection/deadCode/nonJavaReferences/expected.xml b/java/java-tests/testData/inspection/deadCode/nonJavaReferences/expected.xml new file mode 100644 index 000000000000..7454782b31aa --- /dev/null +++ b/java/java-tests/testData/inspection/deadCode/nonJavaReferences/expected.xml @@ -0,0 +1,9 @@ + + + + Test.java + 2 + Field has no usages. + + + diff --git a/java/java-tests/testData/inspection/deadCode/nonJavaReferences/ext_src/res.xml b/java/java-tests/testData/inspection/deadCode/nonJavaReferences/ext_src/res.xml new file mode 100644 index 000000000000..38009bb43e19 --- /dev/null +++ b/java/java-tests/testData/inspection/deadCode/nonJavaReferences/ext_src/res.xml @@ -0,0 +1 @@ +Test \ No newline at end of file diff --git a/java/java-tests/testData/inspection/deadCode/nonJavaReferences/src/Test.java b/java/java-tests/testData/inspection/deadCode/nonJavaReferences/src/Test.java new file mode 100644 index 000000000000..3da4a7e08a27 --- /dev/null +++ b/java/java-tests/testData/inspection/deadCode/nonJavaReferences/src/Test.java @@ -0,0 +1,3 @@ +public class Test { + public static final String LOG = Test.class.getName(); +} \ No newline at end of file diff --git a/java/java-tests/testData/inspection/deadCode/packageLocal/expected.xml b/java/java-tests/testData/inspection/deadCode/packageLocal/expected.xml new file mode 100644 index 000000000000..77f16e9c5fd3 --- /dev/null +++ b/java/java-tests/testData/inspection/deadCode/packageLocal/expected.xml @@ -0,0 +1,10 @@ + + + + A.java + 3 + unused declaration + Class is not instantiated. + + + diff --git a/java/java-tests/testData/inspection/deadCode/packageLocal/src/A.java b/java/java-tests/testData/inspection/deadCode/packageLocal/src/A.java new file mode 100644 index 000000000000..69d866df0b84 --- /dev/null +++ b/java/java-tests/testData/inspection/deadCode/packageLocal/src/A.java @@ -0,0 +1,8 @@ +class A { +} +class B{ + private void b(){ + new B(); + } +} + diff --git a/java/java-tests/testData/inspection/deadCode/reachableFromFieldArrayInitializer/expected.xml b/java/java-tests/testData/inspection/deadCode/reachableFromFieldArrayInitializer/expected.xml new file mode 100644 index 000000000000..79e1a0fd0a57 --- /dev/null +++ b/java/java-tests/testData/inspection/deadCode/reachableFromFieldArrayInitializer/expected.xml @@ -0,0 +1,4 @@ + + + + diff --git a/java/java-tests/testData/inspection/deadCode/reachableFromFieldArrayInitializer/src/Interface.java b/java/java-tests/testData/inspection/deadCode/reachableFromFieldArrayInitializer/src/Interface.java new file mode 100644 index 000000000000..7fc48ac44173 --- /dev/null +++ b/java/java-tests/testData/inspection/deadCode/reachableFromFieldArrayInitializer/src/Interface.java @@ -0,0 +1,3 @@ +interface Interface { + int[] getField(); +} \ No newline at end of file diff --git a/java/java-tests/testData/inspection/deadCode/reachableFromFieldArrayInitializer/src/Test.java b/java/java-tests/testData/inspection/deadCode/reachableFromFieldArrayInitializer/src/Test.java new file mode 100644 index 000000000000..e429f1e033d9 --- /dev/null +++ b/java/java-tests/testData/inspection/deadCode/reachableFromFieldArrayInitializer/src/Test.java @@ -0,0 +1,16 @@ +public class Test implements Interface{ + public static int[] myField = new int[] {init()}; + + public static int init() { + return 1; + } + + public static void main(String[] args){ + Interface i = new Test(); + System.out.println(i.getField()); + } + + public int[] getField() { + return myField; + } +} \ No newline at end of file diff --git a/java/java-tests/testData/inspection/deadCode/reachableFromFieldInitializer/expected.xml b/java/java-tests/testData/inspection/deadCode/reachableFromFieldInitializer/expected.xml new file mode 100644 index 000000000000..79e1a0fd0a57 --- /dev/null +++ b/java/java-tests/testData/inspection/deadCode/reachableFromFieldInitializer/expected.xml @@ -0,0 +1,4 @@ + + + + diff --git a/java/java-tests/testData/inspection/deadCode/reachableFromFieldInitializer/src/Interface.java b/java/java-tests/testData/inspection/deadCode/reachableFromFieldInitializer/src/Interface.java new file mode 100644 index 000000000000..2f95988ae793 --- /dev/null +++ b/java/java-tests/testData/inspection/deadCode/reachableFromFieldInitializer/src/Interface.java @@ -0,0 +1,3 @@ +interface Interface { + int getField(); +} \ No newline at end of file diff --git a/java/java-tests/testData/inspection/deadCode/reachableFromFieldInitializer/src/Test.java b/java/java-tests/testData/inspection/deadCode/reachableFromFieldInitializer/src/Test.java new file mode 100644 index 000000000000..3e54764d40a8 --- /dev/null +++ b/java/java-tests/testData/inspection/deadCode/reachableFromFieldInitializer/src/Test.java @@ -0,0 +1,16 @@ +public class Test implements Interface{ + public int myField = init(); + + public int init() { + return 1; + } + + public static void main(String[] args){ + Interface i = new Test(); + System.out.println(i.getField()); + } + + public int getField() { + return myField; + } +} \ No newline at end of file diff --git a/java/java-tests/testData/inspection/deadCode/reachableFromMain/expected.xml b/java/java-tests/testData/inspection/deadCode/reachableFromMain/expected.xml new file mode 100644 index 000000000000..79e1a0fd0a57 --- /dev/null +++ b/java/java-tests/testData/inspection/deadCode/reachableFromMain/expected.xml @@ -0,0 +1,4 @@ + + + + diff --git a/java/java-tests/testData/inspection/deadCode/reachableFromMain/src/A.java b/java/java-tests/testData/inspection/deadCode/reachableFromMain/src/A.java new file mode 100644 index 000000000000..5ccf286a4d4c --- /dev/null +++ b/java/java-tests/testData/inspection/deadCode/reachableFromMain/src/A.java @@ -0,0 +1,10 @@ +public class A { + public static void main(String[] args) { + B.b(); + } + private static class B{ + public static B b(){ + return new B(); + } + } +} diff --git a/java/java-tests/testData/inspection/deadCode/reachableFromXml/expected.xml b/java/java-tests/testData/inspection/deadCode/reachableFromXml/expected.xml new file mode 100644 index 000000000000..79e1a0fd0a57 --- /dev/null +++ b/java/java-tests/testData/inspection/deadCode/reachableFromXml/expected.xml @@ -0,0 +1,4 @@ + + + + diff --git a/java/java-tests/testData/inspection/deadCode/reachableFromXml/src/A.java b/java/java-tests/testData/inspection/deadCode/reachableFromXml/src/A.java new file mode 100644 index 000000000000..09332aebc23f --- /dev/null +++ b/java/java-tests/testData/inspection/deadCode/reachableFromXml/src/A.java @@ -0,0 +1,5 @@ +public class A { + public A() { + + } +} diff --git a/java/java-tests/testData/inspection/deadCode/reachableFromXml/src/comps.xml b/java/java-tests/testData/inspection/deadCode/reachableFromXml/src/comps.xml new file mode 100644 index 000000000000..525dcadd86cc --- /dev/null +++ b/java/java-tests/testData/inspection/deadCode/reachableFromXml/src/comps.xml @@ -0,0 +1 @@ +A \ No newline at end of file diff --git a/java/java-tests/testData/inspection/deadCode/singleton/expected.xml b/java/java-tests/testData/inspection/deadCode/singleton/expected.xml new file mode 100644 index 000000000000..d704d58ed391 --- /dev/null +++ b/java/java-tests/testData/inspection/deadCode/singleton/expected.xml @@ -0,0 +1,4 @@ + + + + diff --git a/java/java-tests/testData/inspection/deadCode/singleton/src/Main.java b/java/java-tests/testData/inspection/deadCode/singleton/src/Main.java new file mode 100644 index 000000000000..38f90d23111e --- /dev/null +++ b/java/java-tests/testData/inspection/deadCode/singleton/src/Main.java @@ -0,0 +1,5 @@ +public class Main { + public static void main(String args[]) { + Singleton.getInstance(); + } +} \ No newline at end of file diff --git a/java/java-tests/testData/inspection/deadCode/singleton/src/Singleton.java b/java/java-tests/testData/inspection/deadCode/singleton/src/Singleton.java new file mode 100644 index 000000000000..52782ddd4f30 --- /dev/null +++ b/java/java-tests/testData/inspection/deadCode/singleton/src/Singleton.java @@ -0,0 +1,7 @@ +pubic class Singleton { + private static Singleton ourInstance = new Singleton(); + + public Singleton getInstance() { + return ourInstance; + } +} \ No newline at end of file diff --git a/java/java-tests/testData/inspection/deadCode/staticMethods/expected.xml b/java/java-tests/testData/inspection/deadCode/staticMethods/expected.xml new file mode 100644 index 000000000000..8001750bcb2a --- /dev/null +++ b/java/java-tests/testData/inspection/deadCode/staticMethods/expected.xml @@ -0,0 +1,10 @@ + + + + A.java + 3 + unused declaration + Method is never used. + + + diff --git a/java/java-tests/testData/inspection/deadCode/staticMethods/src/A.java b/java/java-tests/testData/inspection/deadCode/staticMethods/src/A.java new file mode 100644 index 000000000000..78115bb94cfb --- /dev/null +++ b/java/java-tests/testData/inspection/deadCode/staticMethods/src/A.java @@ -0,0 +1,7 @@ +public class A { + private A(){} + public static A getInstance(){ + return new A(); + } +} + diff --git a/java/java-tests/testData/inspection/deadCode/suppress/expected.xml b/java/java-tests/testData/inspection/deadCode/suppress/expected.xml new file mode 100644 index 000000000000..79e1a0fd0a57 --- /dev/null +++ b/java/java-tests/testData/inspection/deadCode/suppress/expected.xml @@ -0,0 +1,4 @@ + + + + diff --git a/java/java-tests/testData/inspection/deadCode/suppress/ext_src/B.java b/java/java-tests/testData/inspection/deadCode/suppress/ext_src/B.java new file mode 100644 index 000000000000..8bb0e59c94fb --- /dev/null +++ b/java/java-tests/testData/inspection/deadCode/suppress/ext_src/B.java @@ -0,0 +1,4 @@ +class B { + A a=new A(0); +} + diff --git a/java/java-tests/testData/inspection/deadCode/suppress/src/A.java b/java/java-tests/testData/inspection/deadCode/suppress/src/A.java new file mode 100644 index 000000000000..f18bc0dd1d68 --- /dev/null +++ b/java/java-tests/testData/inspection/deadCode/suppress/src/A.java @@ -0,0 +1,9 @@ +class A { + @java.lang.SuppressWarnings({"UnusedDeclaration"}) + A() { + } + A(int k) { + System.out.println(k); + } +} + diff --git a/java/java-tests/testData/inspection/deadCode/suppress1/expected.xml b/java/java-tests/testData/inspection/deadCode/suppress1/expected.xml new file mode 100644 index 000000000000..79e1a0fd0a57 --- /dev/null +++ b/java/java-tests/testData/inspection/deadCode/suppress1/expected.xml @@ -0,0 +1,4 @@ + + + + diff --git a/java/java-tests/testData/inspection/deadCode/suppress1/src/A.java b/java/java-tests/testData/inspection/deadCode/suppress1/src/A.java new file mode 100644 index 000000000000..434165fbcfec --- /dev/null +++ b/java/java-tests/testData/inspection/deadCode/suppress1/src/A.java @@ -0,0 +1,8 @@ +class A { + @java.lang.SuppressWarnings({"UnusedDeclaration"}) + A() { + new B(); + } + +} + diff --git a/java/java-tests/testData/inspection/deadCode/suppress1/src/B.java b/java/java-tests/testData/inspection/deadCode/suppress1/src/B.java new file mode 100644 index 000000000000..971c2dc3b07f --- /dev/null +++ b/java/java-tests/testData/inspection/deadCode/suppress1/src/B.java @@ -0,0 +1,3 @@ +class B { + B(){} +} \ No newline at end of file diff --git a/java/java-tests/testData/inspection/deadCode/suppress2/expected.xml b/java/java-tests/testData/inspection/deadCode/suppress2/expected.xml new file mode 100644 index 000000000000..79e1a0fd0a57 --- /dev/null +++ b/java/java-tests/testData/inspection/deadCode/suppress2/expected.xml @@ -0,0 +1,4 @@ + + + + diff --git a/java/java-tests/testData/inspection/deadCode/suppress2/src/A.java b/java/java-tests/testData/inspection/deadCode/suppress2/src/A.java new file mode 100644 index 000000000000..0a6b69a4084d --- /dev/null +++ b/java/java-tests/testData/inspection/deadCode/suppress2/src/A.java @@ -0,0 +1,8 @@ +class A { + @java.lang.SuppressWarnings({"UnusedDeclaration"}) + A() { + B bb = new B(); + } + +} + diff --git a/java/java-tests/testData/inspection/deadCode/suppress2/src/B.java b/java/java-tests/testData/inspection/deadCode/suppress2/src/B.java new file mode 100644 index 000000000000..513679493084 --- /dev/null +++ b/java/java-tests/testData/inspection/deadCode/suppress2/src/B.java @@ -0,0 +1,3 @@ +class B { + +} \ No newline at end of file diff --git a/java/java-tests/testData/refactoring/changeSignature/RemoveVarargParameter.java b/java/java-tests/testData/refactoring/changeSignature/RemoveVarargParameter.java new file mode 100644 index 000000000000..49a38df4e172 --- /dev/null +++ b/java/java-tests/testData/refactoring/changeSignature/RemoveVarargParameter.java @@ -0,0 +1,12 @@ +class Test { + void foo(int i, int ... ja){ + } + + void bar() { + foo(0); + foo(0, 1); + foo(0, 1, 2); + foo(0, new int[]{3, 4}); + foo(0, new int[0]); + } +} \ No newline at end of file diff --git a/java/java-tests/testData/refactoring/changeSignature/RemoveVarargParameter_after.java b/java/java-tests/testData/refactoring/changeSignature/RemoveVarargParameter_after.java new file mode 100644 index 000000000000..a44dd40a4296 --- /dev/null +++ b/java/java-tests/testData/refactoring/changeSignature/RemoveVarargParameter_after.java @@ -0,0 +1,12 @@ +class Test { + void foo(int i){ + } + + void bar() { + foo(0); + foo(0); + foo(0); + foo(0); + foo(0); + } +} \ No newline at end of file diff --git a/java/java-tests/testData/refactoring/extractSuperClass/extendsList/after/Test.java b/java/java-tests/testData/refactoring/extractSuperClass/extendsList/after/Test.java new file mode 100644 index 000000000000..2a30c682c945 --- /dev/null +++ b/java/java-tests/testData/refactoring/extractSuperClass/extendsList/after/Test.java @@ -0,0 +1,2 @@ +public abstract class Test implements java.util.List { +} \ No newline at end of file diff --git a/java/java-tests/testData/refactoring/extractSuperClass/extendsList/after/TestSubclass.java b/java/java-tests/testData/refactoring/extractSuperClass/extendsList/after/TestSubclass.java new file mode 100644 index 000000000000..5f886aec588b --- /dev/null +++ b/java/java-tests/testData/refactoring/extractSuperClass/extendsList/after/TestSubclass.java @@ -0,0 +1,2 @@ +public abstract class TestSubclass extends Test { +} \ No newline at end of file diff --git a/java/java-tests/testData/refactoring/extractSuperClass/extendsList/before/Test.java b/java/java-tests/testData/refactoring/extractSuperClass/extendsList/before/Test.java new file mode 100644 index 000000000000..1f87b267522f --- /dev/null +++ b/java/java-tests/testData/refactoring/extractSuperClass/extendsList/before/Test.java @@ -0,0 +1,2 @@ +public abstract class Test implements java.util.List{ +} \ No newline at end of file diff --git a/java/java-tests/testSrc/com/intellij/codeInsight/completion/SmartTypeCompletionTest.java b/java/java-tests/testSrc/com/intellij/codeInsight/completion/SmartTypeCompletionTest.java index f3cb5c7f2be9..b921932746c6 100644 --- a/java/java-tests/testSrc/com/intellij/codeInsight/completion/SmartTypeCompletionTest.java +++ b/java/java-tests/testSrc/com/intellij/codeInsight/completion/SmartTypeCompletionTest.java @@ -399,7 +399,7 @@ public class SmartTypeCompletionTest extends LightCompletionTestCase { public void testIntConstInSwitch() throws Exception { doTest(); } public void testDoubleEmptyArray() throws Exception { - configureByFile(BASE_PATH + "/"+getTestName(false)+".java"); + configureByTestName(); checkResultByFile(BASE_PATH + "/"+getTestName(false) + ".java"); assertEquals(2, myItems.length); } @@ -453,24 +453,24 @@ public class SmartTypeCompletionTest extends LightCompletionTestCase { public void testArrayIndexTailType() throws Throwable { doTest(); } public void testHonorSelection() throws Throwable { - configureByFile(BASE_PATH + "/" + getTestName(false) + ".java"); + configureByTestName(); select(); - checkResultByFile(BASE_PATH + "/" + getTestName(false) + "-out.java"); + checkResultByTestName(); } public void testTypeParametersInheritors() throws Throwable { - configureByFile(BASE_PATH + "/" + getTestName(false) + ".java"); + configureByTestName(); assertStringItems("Foo", "Bar", "Goo"); select(); - checkResultByFile(BASE_PATH + "/" + getTestName(false) + "-out.java"); + checkResultByTestName(); } public void testVoidExpectedType() throws Throwable { - configureByFile(BASE_PATH + "/" + getTestName(false) + ".java"); + configureByTestName(); assertStringItems("notify", "notifyAll", "wait", "wait", "wait", "equals", "getClass", "hashCode", "toString"); type('e'); - select(); - checkResultByFile(BASE_PATH + "/" + getTestName(false) + "-out.java"); + select(); + checkResultByTestName(); } public void testDoubleSemicolonPenetration() throws Throwable { doTest(); } @@ -488,9 +488,9 @@ public class SmartTypeCompletionTest extends LightCompletionTestCase { } public void testSmartFinish() throws Throwable { - configureByFile(BASE_PATH + "/" + getTestName(false) + ".java"); + configureByTestName(); select(Lookup.COMPLETE_STATEMENT_SELECT_CHAR); - checkResultByFile(BASE_PATH + "/" + getTestName(false) + "-out.java"); + checkResultByTestName(); } public void testSillyAssignmentInTernary() throws Throwable { doTest(); } @@ -504,7 +504,7 @@ public class SmartTypeCompletionTest extends LightCompletionTestCase { public void testSameNamedFieldAndLocal() throws Throwable { doTest(); } public void testAbstractClassTwice() throws Throwable { - configureByFile(BASE_PATH + "/" + getTestName(false) + ".java"); + configureByTestName(); final int offset = myEditor.getCaretModel().getOffset(); select(); myEditor.getCaretModel().moveToOffset(offset); @@ -514,12 +514,12 @@ public class SmartTypeCompletionTest extends LightCompletionTestCase { public void testConstantTwice() throws Throwable { doTest(); } public void testConstantTwice2() throws Throwable { - configureByFile(BASE_PATH + "/" + getTestName(false) + ".java"); + configureByTestName(); assertEquals(2, myItems.length); } public void testNoKeyConstant() throws Throwable { - configureByFile(BASE_PATH + "/" + getTestName(false) + ".java"); + configureByTestName(); assertEquals(2, myItems.length); assertEquals("A_KEY", myItems[0].getLookupString()); assertEquals("Key.create", myItems[1].getLookupString()); @@ -570,19 +570,19 @@ public class SmartTypeCompletionTest extends LightCompletionTestCase { public void testAfterNewInTernary() throws Throwable { doTest(); } public void testSuggestAnythingWhenWildcardExpected() throws Throwable { - configureByFile(BASE_PATH + "/" + getTestName(false) + ".java"); + configureByTestName(); assertStringItems("X", "Y", "Z"); } public void testNewVararg() throws Throwable { - configureByFile(BASE_PATH + "/" + getTestName(false) + ".java"); + configureByTestName(); assertStringItems("Foo", "Foo"); assertEquals(0, myItems[0].as(PsiTypeLookupItem.class).getBracketsCount()); assertEquals(1, myItems[1].as(PsiTypeLookupItem.class).getBracketsCount()); } public void testInsideStringLiteral() throws Throwable { - configureByFile(BASE_PATH + "/" + getTestName(false) + ".java"); + configureByTestName(); assertNull(myItems); checkResultByFile(BASE_PATH + "/" + getTestName(false) + ".java"); @@ -593,12 +593,12 @@ public class SmartTypeCompletionTest extends LightCompletionTestCase { public void testCastGenericQualifier() throws Throwable { doTest(); } public void testEverythingDoubles() throws Throwable { - configureByFile(BASE_PATH + "/" + getTestName(false) + ".java"); + configureByTestName(); assertStringItems("hashCode", "indexOf", "lastIndexOf", "size"); } public void testNonStaticInnerClass() throws Throwable { - configureByFile(BASE_PATH + "/" + getTestName(false) + ".java"); + configureByTestName(); assertNull(myItems); checkResultByFile(BASE_PATH + "/" + getTestName(false) + ".java"); } @@ -626,7 +626,7 @@ public class SmartTypeCompletionTest extends LightCompletionTestCase { public void testSuggestNull() throws Throwable { doTest(); } public void testNoNullAfterDot() throws Throwable { - configureByFile(BASE_PATH + "/" + getTestName(false) + ".java"); + configureByTestName(); assertNull(myItems); checkResultByFile(BASE_PATH + "/" + getTestName(false) + ".java"); } @@ -691,44 +691,44 @@ public class SmartTypeCompletionTest extends LightCompletionTestCase { public void testCastToArray() throws Throwable { doTest(); } public void testDontAutoCastWhenAlreadyCasted() throws Throwable { - configureByFile(BASE_PATH + "/" + getTestName(false) + ".java"); + configureByTestName(); assertEquals("s", myItems[0].getLookupString()); assertEquals("String.copyValueOf", myItems[1].getLookupString()); select(); - checkResultByFile(BASE_PATH + "/" + getTestName(false) + "-out.java"); + checkResultByTestName(); } public void testAutoCastWhenAlreadyCasted() throws Throwable { doTest(); } public void testCommaDoublePenetration() throws Throwable { - configureByFile(BASE_PATH + "/" + getTestName(false) + ".java"); + configureByTestName(); select(','); - checkResultByFile(BASE_PATH + "/" + getTestName(false) + "-out.java"); + checkResultByTestName(); } public void testSuperMethodArguments() throws Throwable { - configureByFile(BASE_PATH + "/" + getTestName(false) + ".java"); + configureByTestName(); getLookup().setCurrentItem(getLookup().getItems().get(1)); select(); - checkResultByFile(BASE_PATH + "/" + getTestName(false) + "-out.java"); + checkResultByTestName(); } public void testDelegateMethodArguments() throws Throwable { - configureByFile(BASE_PATH + "/" + getTestName(false) + ".java"); + configureByTestName(); getLookup().setCurrentItem(getLookup().getItems().get(1)); select(); - checkResultByFile(BASE_PATH + "/" + getTestName(false) + "-out.java"); + checkResultByTestName(); } public void testSuperConstructorArguments() throws Throwable { - configureByFile(BASE_PATH + "/" + getTestName(false) + ".java"); + configureByTestName(); getLookup().setCurrentItem(getLookup().getItems().get(2)); select(); - checkResultByFile(BASE_PATH + "/" + getTestName(false) + "-out.java"); + checkResultByTestName(); } private void doAntiTest() throws Exception { - configureByFile(BASE_PATH + "/" + getTestName(false) + ".java"); + configureByTestName(); assertNull(myItems); checkResultByFile(BASE_PATH + "/" + getTestName(false) + ".java"); } @@ -856,6 +856,22 @@ public class SmartTypeCompletionTest extends LightCompletionTestCase { doTest(); } + public void testTabMethodCall() throws Exception { + configureByTestName(); + select(Lookup.REPLACE_SELECT_CHAR); + checkResultByTestName(); + } + + public void testConstructorArgsSmartEnter() throws Exception { + configureByTestName(); + select(Lookup.COMPLETE_STATEMENT_SELECT_CHAR); + checkResultByTestName(); + } + + private void configureByTestName() throws Exception { + configureByFile(BASE_PATH + "/" + getTestName(false) + ".java"); + } + public void testIDEADEV13148() throws Exception { configureByFile(BASE_PATH + "/IDEADEV13148.java"); testByCount(0); @@ -901,9 +917,9 @@ public class SmartTypeCompletionTest extends LightCompletionTestCase { public void _testCallVarargArgument() throws Throwable { doTest(); } public void testTabToReplaceClassKeyword() throws Throwable { - configureByFile(BASE_PATH + "/" + getTestName(false) + ".java"); + configureByTestName(); selectItem(myItems[0], Lookup.REPLACE_SELECT_CHAR); - checkResultByFile(BASE_PATH + "/" + getTestName(false) + "-out.java"); + checkResultByTestName(); } public void testNoTypeParametersForToArray() throws Throwable { @@ -935,7 +951,7 @@ public class SmartTypeCompletionTest extends LightCompletionTestCase { public void testWildcardedInstanceof3() throws Throwable { doTest(); } public void testTypeVariableInstanceOf() throws Throwable { - configureByFile(BASE_PATH + "/" + getTestName(false) + ".java"); + configureByTestName(); performAction(); assertStringItems("Bar", "Goo"); } @@ -945,7 +961,7 @@ public class SmartTypeCompletionTest extends LightCompletionTestCase { } public void testInsideGenericClassLiteral() throws Throwable { - configureByFile(BASE_PATH + "/" + getTestName(false) + ".java"); + configureByTestName(); testByCount(3, "String.class", "StringBuffer.class", "StringBuilder.class"); } @@ -958,7 +974,7 @@ public class SmartTypeCompletionTest extends LightCompletionTestCase { } public void testInnerEnum() throws Exception { - configureByFile(BASE_PATH + "/"+getTestName(false)+".java"); + configureByTestName(); getLookup().setCurrentItem(ContainerUtil.find(myItems, new Condition() { public boolean value(final LookupElement lookupItem) { @@ -966,18 +982,18 @@ public class SmartTypeCompletionTest extends LightCompletionTestCase { } })); select('\n'); - checkResultByFile(BASE_PATH + "/"+getTestName(false) + "-out.java"); + checkResultByTestName(); } private void doTest(boolean performAction, boolean selectItem) throws Exception { - configureByFile(BASE_PATH + "/" + getTestName(false) + ".java"); + configureByTestName(); if (performAction) { performAction(); } if (selectItem) { selectItem(myItems[0]); } - checkResultByFile(BASE_PATH + "/" + getTestName(false) + "-out.java"); + checkResultByTestName(); } private void doActionTest() throws Exception { @@ -1007,11 +1023,11 @@ public class SmartTypeCompletionTest extends LightCompletionTestCase { } try { - configureByFile(BASE_PATH + "/" + getTestName(false) + ".java"); + configureByTestName(); if (myItems != null && myItems.length == 1) { select(c); } - checkResultByFile(BASE_PATH + "/" + getTestName(false) + "-out.java"); + checkResultByTestName(); } finally { if (c != Lookup.NORMAL_SELECT_CHAR) { @@ -1021,6 +1037,10 @@ public class SmartTypeCompletionTest extends LightCompletionTestCase { } + private void checkResultByTestName() throws Exception { + checkResultByFile(BASE_PATH + "/" + getTestName(false) + "-out.java"); + } + protected void setUp() throws Exception { super.setUp(); myPrevLanguageLevel = LanguageLevelProjectExtension.getInstance(getJavaFacade().getProject()).getLanguageLevel(); diff --git a/java/java-tests/testSrc/com/intellij/codeInspection/DeadCodeTest.java b/java/java-tests/testSrc/com/intellij/codeInspection/DeadCodeTest.java new file mode 100644 index 000000000000..d90f59a5ab52 --- /dev/null +++ b/java/java-tests/testSrc/com/intellij/codeInspection/DeadCodeTest.java @@ -0,0 +1,166 @@ +package com.intellij.codeInspection; + +import com.intellij.JavaTestUtil; +import com.intellij.codeInspection.deadCode.DeadCodeInspection; +import com.intellij.openapi.roots.LanguageLevelProjectExtension; +import com.intellij.pom.java.LanguageLevel; +import com.intellij.psi.JavaPsiFacade; +import com.intellij.testFramework.InspectionTestCase; + +/** + * @author max + */ +public class DeadCodeTest extends InspectionTestCase { + private DeadCodeInspection myTool; + + @Override + protected String getTestDataPath() { + return JavaTestUtil.getJavaTestDataPath() + "/inspection"; + } + + protected void setUp() throws Exception { + super.setUp(); + myTool = new DeadCodeInspection(); + LanguageLevelProjectExtension.getInstance(getProject()).setLanguageLevel(LanguageLevel.JDK_1_3); + } + + private void doTest() throws Exception { + doTest("deadCode/" + getTestName(true), myTool); + } + + public void testSCR6067() throws Exception { + boolean old = myTool.ADD_NONJAVA_TO_ENTRIES; + myTool.ADD_NONJAVA_TO_ENTRIES = false; + doTest(); + myTool.ADD_NONJAVA_TO_ENTRIES = old; + } + + public void testsingleton() throws Exception { + boolean old = myTool.ADD_NONJAVA_TO_ENTRIES; + myTool.ADD_NONJAVA_TO_ENTRIES = false; + doTest(); + myTool.ADD_NONJAVA_TO_ENTRIES = old; + } + + public void testSCR9690() throws Exception { + boolean old = myTool.ADD_NONJAVA_TO_ENTRIES; + myTool.ADD_NONJAVA_TO_ENTRIES = false; + doTest(); + myTool.ADD_NONJAVA_TO_ENTRIES = old; + } + + public void testUIFormUsage() throws Exception { + boolean old = myTool.ADD_NONJAVA_TO_ENTRIES; + myTool.ADD_NONJAVA_TO_ENTRIES = false; + doTest(); + myTool.ADD_NONJAVA_TO_ENTRIES = old; + } + + public void testSerializable() throws Exception { + doTest(); + } + + public void testpackageLocal() throws Exception { + doTest(); + } + + public void testreachableFromMain() throws Exception{ + boolean old = myTool.ADD_MAINS_TO_ENTRIES; + myTool.ADD_MAINS_TO_ENTRIES = true; + doTest(); + myTool.ADD_MAINS_TO_ENTRIES = old; + } + + public void testmutableCalls() throws Exception{ + doTest(); + } + + public void teststaticMethods() throws Exception{ + doTest(); + } + + //-------------- suppressed ---------------- + + private void doTest15() throws Exception { + final JavaPsiFacade facade = getJavaFacade(); + final LanguageLevel effectiveLanguageLevel = LanguageLevelProjectExtension.getInstance(facade.getProject()).getLanguageLevel(); + LanguageLevelProjectExtension.getInstance(facade.getProject()).setLanguageLevel(LanguageLevel.JDK_1_5); + doTest(); + LanguageLevelProjectExtension.getInstance(facade.getProject()).setLanguageLevel(effectiveLanguageLevel); + } + + public void testsuppress() throws Exception{ + doTest15(); + } + + public void testsuppress1() throws Exception { + doTest15(); + } + + public void testsuppress2() throws Exception { + doTest15(); + } + + public void testchainOfSuppressions() throws Exception{ + doTest15(); + } + + public void testreachableFromXml() throws Exception { + doTest(); + } + + public void testchainOfCalls() throws Exception { + doTest(); + } + + public void testreachableFromFieldInitializer() throws Exception { + doTest(); + } + + public void testreachableFromFieldArrayInitializer() throws Exception { + doTest(); + } + + public void testconstructorReachableFromFieldInitializer() throws Exception { + doTest(); + } + + public void testadditionalAnnotations() throws Exception { + final String testAnnotation = "Annotated"; + myTool.ADDITIONAL_ANNOTATIONS.add(testAnnotation); + try { + doTest(); + } + finally { + myTool.ADDITIONAL_ANNOTATIONS.remove(testAnnotation); + } + } + + public void testannotationInterface() throws Exception { + doTest15(); + } + + public void testjunitEntryPoint() throws Exception { + doTest(); + } + + public void testjunitEntryPointCustomRunWith() throws Exception { + doTest(); + } + + public void testconstructorCalls() throws Exception { + doTest(); + } + + public void testconstructorCalls1() throws Exception { + doTest(); + } + + public void testnonJavaReferences() throws Exception { + doTest(); + } + + public void testenumInstantiation() throws Exception { + doTest(); + } +} diff --git a/java/java-tests/testSrc/com/intellij/refactoring/ChangeSignatureTest.java b/java/java-tests/testSrc/com/intellij/refactoring/ChangeSignatureTest.java index 98394457514b..8fa39d06946a 100644 --- a/java/java-tests/testSrc/com/intellij/refactoring/ChangeSignatureTest.java +++ b/java/java-tests/testSrc/com/intellij/refactoring/ChangeSignatureTest.java @@ -129,6 +129,10 @@ public class ChangeSignatureTest extends LightCodeInsightTestCase { }, false); } + public void testRemoveVarargParameter() throws Exception { + doTest(null, null, null, new ParameterInfoImpl[]{new ParameterInfoImpl(0)}, new ThrownExceptionInfo[0], false); + } + public void testEnumConstructor() throws Exception { doTest(null, new ParameterInfoImpl[] { new ParameterInfoImpl(-1, "i", PsiType.INT, "10") diff --git a/java/java-tests/testSrc/com/intellij/refactoring/ExtractSuperClassTest.java b/java/java-tests/testSrc/com/intellij/refactoring/ExtractSuperClassTest.java index fb8ad8a0dee1..9e1469609d04 100644 --- a/java/java-tests/testSrc/com/intellij/refactoring/ExtractSuperClassTest.java +++ b/java/java-tests/testSrc/com/intellij/refactoring/ExtractSuperClassTest.java @@ -53,6 +53,10 @@ public class ExtractSuperClassTest extends CodeInsightTestCase { doTest("B", "AB"); } + public void testExtendsList() throws Exception { + doTest("Test", "TestSubclass", new PullUpTest.MemberDescriptor("List", PsiClass.class)); + } + @Override protected Sdk getTestProjectJdk() { return JavaSdkImpl.getMockJdk15("mock 1.5"); diff --git a/java/java-tests/testSrc/com/intellij/refactoring/PullUpTest.java b/java/java-tests/testSrc/com/intellij/refactoring/PullUpTest.java index 1ebe088a1859..1d75d59410eb 100644 --- a/java/java-tests/testSrc/com/intellij/refactoring/PullUpTest.java +++ b/java/java-tests/testSrc/com/intellij/refactoring/PullUpTest.java @@ -104,8 +104,22 @@ public class PullUpTest extends LightCodeInsightTestCase { final Class clazz = membersToFind[i].myClass; final String name = membersToFind[i].myName; PsiMember member = null; + boolean overrides = false; + PsiReferenceList refList = null; if (PsiClass.class.isAssignableFrom(clazz)) { member = sourceClass.findInnerClassByName(name, false); + if (member == null) { + final PsiClass[] supers = sourceClass.getSupers(); + for (PsiClass superTypeClass : supers) { + if (superTypeClass.getName().equals(name)) { + member = superTypeClass; + overrides = true; + refList = superTypeClass.isInterface() ? sourceClass.getImplementsList() : sourceClass.getExtendsList(); + break; + } + } + } + } else if (PsiMethod.class.isAssignableFrom(clazz)) { final PsiMethod[] methods = sourceClass.findMethodsByName(name, false); assertEquals(1, methods.length); @@ -115,7 +129,7 @@ public class PullUpTest extends LightCodeInsightTestCase { } assertNotNull(member); - infos[i] = new MemberInfo(member); + infos[i] = new MemberInfo(member, overrides, refList); infos[i].setToAbstract(membersToFind[i].myAbstract); } return infos; diff --git a/java/openapi/src/com/intellij/codeInsight/AnnotationUtil.java b/java/openapi/src/com/intellij/codeInsight/AnnotationUtil.java index 35479714e097..8f072750f153 100644 --- a/java/openapi/src/com/intellij/codeInsight/AnnotationUtil.java +++ b/java/openapi/src/com/intellij/codeInsight/AnnotationUtil.java @@ -244,7 +244,10 @@ public class AnnotationUtil { fqns = new ArrayList(); final PsiAnnotation[] annos = modList.getAnnotations(); for (PsiAnnotation anno : annos) { - fqns.add(anno.getQualifiedName()); + final String qName = anno.getQualifiedName(); + if (qName != null) { + fqns.add(qName); + } } if (fqns.isEmpty()) return false; } diff --git a/platform/lang-api/src/com/intellij/codeInsight/lookup/RealLookupElementPresentation.java b/platform/lang-api/src/com/intellij/codeInsight/lookup/RealLookupElementPresentation.java index 94ff732debac..99e82716a660 100644 --- a/platform/lang-api/src/com/intellij/codeInsight/lookup/RealLookupElementPresentation.java +++ b/platform/lang-api/src/com/intellij/codeInsight/lookup/RealLookupElementPresentation.java @@ -4,18 +4,20 @@ import com.intellij.openapi.util.text.StringUtil; import org.jetbrains.annotations.Nullable; import javax.swing.*; +import java.awt.*; /** * @author peter */ public class RealLookupElementPresentation extends LookupElementPresentation { private final int myMaximumWidth; - private final int myFontWidth; + private final FontMetrics myNormalMetrics; + private final FontMetrics myBoldMetrics; - public RealLookupElementPresentation(int maximumWidth, int fontWidth) { - super(); + public RealLookupElementPresentation(int maximumWidth, FontMetrics normalMetrics, FontMetrics boldMetrics) { myMaximumWidth = maximumWidth; - myFontWidth = fontWidth; + myNormalMetrics = normalMetrics; + myBoldMetrics = boldMetrics; } @Override @@ -23,20 +25,20 @@ public class RealLookupElementPresentation extends LookupElementPresentation { return true; } - public int getRemainingTextLength() { - return (myMaximumWidth - calculateWidth(this, myFontWidth)) / myFontWidth; + public boolean hasEnoughSpaceFor(@Nullable String text, boolean bold) { + return myMaximumWidth >= calculateWidth(this, myNormalMetrics, myBoldMetrics) + getStringWidth(text, bold ? myBoldMetrics : myNormalMetrics); } - public static int calculateWidth(LookupElementPresentation presentation, final int fontWidth) { + public static int calculateWidth(LookupElementPresentation presentation, FontMetrics normalMetrics, FontMetrics boldMetrics) { int result = 0; - result += getStringWidth(presentation.getItemText(), fontWidth); - result += getStringWidth(presentation.getTailText(), fontWidth); + result += getStringWidth(presentation.getItemText(), presentation.isItemTextBold() ? boldMetrics : normalMetrics); + result += getStringWidth(presentation.getTailText(), normalMetrics); final String typeText = presentation.getTypeText(); if (StringUtil.isNotEmpty(typeText)) { - result += getStringWidth("XXX", fontWidth); //3 spaces for nice tail-type separation - result += getStringWidth(typeText, fontWidth); + result += getStringWidth("XXX", normalMetrics); //3 spaces for nice tail-type separation + result += getStringWidth(typeText, normalMetrics); } - result += fontWidth; //for unforeseen Swing size adjustments + result += getStringWidth("W", boldMetrics); //for unforeseen Swing size adjustments final Icon typeIcon = presentation.getTypeIcon(); if (typeIcon != null) { result += typeIcon.getIconWidth(); @@ -44,9 +46,9 @@ public class RealLookupElementPresentation extends LookupElementPresentation { return result; } - public static int getStringWidth(@Nullable final String text, final int fontWidth) { + public static int getStringWidth(@Nullable final String text, FontMetrics metrics) { if (text != null) { - return text.length() * fontWidth; + return metrics.stringWidth(text); } return 0; } diff --git a/platform/lang-api/src/com/intellij/execution/configurations/CommandLineState.java b/platform/lang-api/src/com/intellij/execution/configurations/CommandLineState.java index 8f37a41fb1ff..15ac3bf74bf0 100644 --- a/platform/lang-api/src/com/intellij/execution/configurations/CommandLineState.java +++ b/platform/lang-api/src/com/intellij/execution/configurations/CommandLineState.java @@ -73,7 +73,7 @@ public abstract class CommandLineState implements RunnableState { return new AnAction[]{new PauseOutputAction(console, processHandler)}; } - protected TextConsoleBuilder getConsoleBuilder() { + public TextConsoleBuilder getConsoleBuilder() { return myConsoleBuilder; } diff --git a/platform/lang-impl/src/com/intellij/codeInsight/completion/CompletionProgressIndicator.java b/platform/lang-impl/src/com/intellij/codeInsight/completion/CompletionProgressIndicator.java index 267dca7c5815..d53b026b7417 100644 --- a/platform/lang-impl/src/com/intellij/codeInsight/completion/CompletionProgressIndicator.java +++ b/platform/lang-impl/src/com/intellij/codeInsight/completion/CompletionProgressIndicator.java @@ -48,7 +48,9 @@ import org.jetbrains.annotations.TestOnly; import javax.swing.*; import java.awt.event.KeyAdapter; import java.awt.event.KeyEvent; +import java.util.Collections; import java.util.EventObject; +import java.util.List; /** * @author peter @@ -124,13 +126,27 @@ public class CompletionProgressIndicator extends ProgressIndicatorBase implement private void scheduleAdvertising() { ApplicationManager.getApplication().executeOnPooledThread(new Runnable() { public void run() { - if (myEditor.isDisposed()) return; //tests? - for (final CompletionContributor contributor : CompletionContributor.forParameters(myParameters)) { + if (isOutdated()) return; //tests? + final List list = ApplicationManager.getApplication().runReadAction(new Computable>() { + public List compute() { + if (isOutdated()) { + return Collections.emptyList(); + } + + return CompletionContributor.forParameters(myParameters); + } + }); + for (final CompletionContributor contributor : list) { if (myLookup.getAdvertisementText() != null) return; if (!myLookup.isCalculating() && !myLookup.isVisible()) return; String s = ApplicationManager.getApplication().runReadAction(new Computable() { + @Nullable public String compute() { + if (isOutdated()) { + return null; + } + return contributor.advertise(myParameters); } }); @@ -140,7 +156,7 @@ public class CompletionProgressIndicator extends ProgressIndicatorBase implement myLookup.setAdvertisementText(s); ApplicationManager.getApplication().invokeLater(new Runnable() { public void run() { - if (myEditor.isDisposed() || myEditor.getComponent().getRootPane() == null) { + if (isOutdated() || myEditor.getComponent().getRootPane() == null) { return; } updateLookup(); @@ -153,6 +169,10 @@ public class CompletionProgressIndicator extends ProgressIndicatorBase implement }); } + private boolean isOutdated() { + return myEditor.isDisposed() || myDisposed; + } + private void trackModifiers() { final JComponent contentComponent = myEditor.getContentComponent(); contentComponent.addKeyListener(new KeyAdapter() { @@ -242,7 +262,7 @@ public class CompletionProgressIndicator extends ProgressIndicatorBase implement private void updateLookup() { ApplicationManager.getApplication().assertIsDispatchThread(); - if (myEditor.isDisposed() || myDisposed) return; + if (isOutdated()) return; if (!myInitialized) { myInitialized = true; diff --git a/platform/lang-impl/src/com/intellij/codeInsight/daemon/impl/DaemonCodeAnalyzerImpl.java b/platform/lang-impl/src/com/intellij/codeInsight/daemon/impl/DaemonCodeAnalyzerImpl.java index df53d7956fa7..084803b292c7 100644 --- a/platform/lang-impl/src/com/intellij/codeInsight/daemon/impl/DaemonCodeAnalyzerImpl.java +++ b/platform/lang-impl/src/com/intellij/codeInsight/daemon/impl/DaemonCodeAnalyzerImpl.java @@ -593,7 +593,7 @@ public class DaemonCodeAnalyzerImpl extends DaemonCodeAnalyzer implements JDOMEx @NotNull @TestOnly - public static List getFileLeveleHighlights(Project project,PsiFile file ) { + public static List getFileLevelHighlights(Project project,PsiFile file ) { return UpdateHighlightersUtil.getFileLeveleHighlights(project, file); } } diff --git a/platform/lang-impl/src/com/intellij/codeInsight/daemon/impl/LocalInspectionsPass.java b/platform/lang-impl/src/com/intellij/codeInsight/daemon/impl/LocalInspectionsPass.java index d9e4d1588473..b09bc0095ec1 100644 --- a/platform/lang-impl/src/com/intellij/codeInsight/daemon/impl/LocalInspectionsPass.java +++ b/platform/lang-impl/src/com/intellij/codeInsight/daemon/impl/LocalInspectionsPass.java @@ -470,22 +470,23 @@ public class LocalInspectionsPass extends ProgressableTextEditorHighlightingPass InspectionManager inspectionManager = InspectionManager.getInstance(injectedPsi.getProject()); final ProblemsHolder problemsHolder = new ProblemsHolder(inspectionManager, injectedPsi); final PsiElement host = injectedPsi.getContext(); - for (LocalInspectionTool tool : tools) { - if (host != null && InspectionManagerEx.inspectionResultSuppressed(host, tool)) { - continue; - } - final PsiElementVisitor visitor = tool.buildVisitor(problemsHolder, true); - assert !(visitor instanceof PsiRecursiveElementVisitor) : "The visitor returned from LocalInspectionTool.buildVisitor() must not be recursive. "+tool; - injectedPsi.accept(new PsiRecursiveElementWalkingVisitor() { - @Override public void visitElement(PsiElement element) { + + final PsiElement[] elements = getElementsIntersectingRange(injectedPsi, 0, injectedPsi.getTextLength()); + if (elements.length != 0) { + for (LocalInspectionTool tool : tools) { + if (host != null && InspectionManagerEx.inspectionResultSuppressed(host, tool)) { + continue; + } + final PsiElementVisitor visitor = tool.buildVisitor(problemsHolder, true); + assert !(visitor instanceof PsiRecursiveElementVisitor) : "The visitor returned from LocalInspectionTool.buildVisitor() must not be recursive. "+tool; + for (PsiElement element : elements) { element.accept(visitor); - super.visitElement(element); + } + List problems = problemsHolder.getResults(); + if (problems != null && !problems.isEmpty()) { + InjectedPsiInspectionResult res = new InjectedPsiInspectionResult(tool, injectedPsi, new SmartList(problems)); + result.add(res); } - }); - List problems = problemsHolder.getResults(); - if (problems != null && !problems.isEmpty()) { - InjectedPsiInspectionResult res = new InjectedPsiInspectionResult(tool, injectedPsi, new SmartList(problems)); - result.add(res); } } } diff --git a/platform/lang-impl/src/com/intellij/codeInsight/lookup/impl/LookupCellRenderer.java b/platform/lang-impl/src/com/intellij/codeInsight/lookup/impl/LookupCellRenderer.java index f752b376ba5e..5a2b6609608a 100644 --- a/platform/lang-impl/src/com/intellij/codeInsight/lookup/impl/LookupCellRenderer.java +++ b/platform/lang-impl/src/com/intellij/codeInsight/lookup/impl/LookupCellRenderer.java @@ -31,6 +31,7 @@ import com.intellij.ui.SimpleTextAttributes; import com.intellij.ui.popup.PopupIcons; import com.intellij.util.ui.EmptyIcon; import com.intellij.util.ui.UIUtil; +import org.jetbrains.annotations.Nullable; import javax.swing.*; import javax.swing.border.EmptyBorder; @@ -40,7 +41,9 @@ public class LookupCellRenderer implements ListCellRenderer { private Icon myEmptyIcon = new EmptyIcon(5); private final Font NORMAL_FONT; private final Font BOLD_FONT; - private final int myFontWidth; + private final FontMetrics myNormalMetrics; + private final FontMetrics myBoldMetrics; + private final int myMaxWidth; public static final Color BACKGROUND_COLOR = new Color(235, 244, 254); private static final Color FOREGROUND_COLOR = Color.black; @@ -97,7 +100,9 @@ public class LookupCellRenderer implements ListCellRenderer { eastPanel.add(myArrowLabel, BorderLayout.EAST); myPanel.add(eastPanel, BorderLayout.EAST); - myFontWidth = myLookup.getEditor().getComponent().getFontMetrics(BOLD_FONT).charWidth('W'); + myNormalMetrics = myLookup.getEditor().getComponent().getFontMetrics(NORMAL_FONT); + myBoldMetrics = myLookup.getEditor().getComponent().getFontMetrics(BOLD_FONT); + myMaxWidth = myNormalMetrics.stringWidth(StringUtil.repeatSymbol('W', MAX_LENGTH)); UIUtil.removeQuaquaVisualMarginsIn(myPanel); } @@ -114,7 +119,7 @@ public class LookupCellRenderer implements ListCellRenderer { final Color background = getItemBackground(list, index, isSelected); int allowedWidth = list.getFixedCellWidth() - getCommonIconWidth(); - final LookupElementPresentation presentation = new RealLookupElementPresentation(allowedWidth, myFontWidth); + final LookupElementPresentation presentation = new RealLookupElementPresentation(allowedWidth, myNormalMetrics, myBoldMetrics); item.renderElement(presentation); myNameComponent.clear(); @@ -163,12 +168,37 @@ public class LookupCellRenderer implements ListCellRenderer { return; } - myTailComponent.append(trimLabelText(tailText, allowedWidth), attributes); + myTailComponent.append(trimLabelText(tailText, allowedWidth, myNormalMetrics), attributes); } - private String trimLabelText(String tailText, int maxWidth) { - final int maxLen = maxWidth / myFontWidth; - return tailText.length() <= maxLen ? tailText : tailText.substring(0, maxLen) + ELLIPSIS; + private static String trimLabelText(@Nullable String text, int maxWidth, FontMetrics metrics) { + if (text == null || StringUtil.isEmpty(text)) { + return ""; + } + + final int strWidth = RealLookupElementPresentation.getStringWidth(text, metrics); + if (strWidth <= maxWidth) { + return text; + } + + if (RealLookupElementPresentation.getStringWidth(ELLIPSIS, metrics) > maxWidth) { + return ""; + } + + int i = 0; + int j = text.length(); + while (i + 1 < j) { + int mid = (i + j) / 2; + final String candidate = text.substring(0, mid) + ELLIPSIS; + final int width = RealLookupElementPresentation.getStringWidth(candidate, metrics); + if (width <= maxWidth) { + i = mid; + } else { + j = mid; + } + } + + return text.substring(0, i) + ELLIPSIS; } private static Color getTailTextColor(boolean isSelected, LookupElementPresentation presentation, Color defaultForeground) { @@ -194,8 +224,9 @@ public class LookupCellRenderer implements ListCellRenderer { style |= SimpleTextAttributes.STYLE_STRIKEOUT; } - final String name = trimLabelText(presentation.getItemText(), allowedWidth); - int used = getStringWidth(name); + final FontMetrics metrics = bold ? myBoldMetrics : myNormalMetrics; + final String name = trimLabelText(presentation.getItemText(), allowedWidth, metrics); + int used = RealLookupElementPresentation.getStringWidth(name, metrics); final SimpleTextAttributes baseAttrs = new SimpleTextAttributes(style, foreground); @@ -213,15 +244,11 @@ public class LookupCellRenderer implements ListCellRenderer { return used; } - private int getStringWidth(String name) { - return RealLookupElementPresentation.getStringWidth(name, myFontWidth); - } - private int setTypeTextLabel(LookupElement item, final Color background, Color foreground, final LookupElementPresentation presentation, int allowedWidth) { final String givenText = presentation.getTypeText(); - final String labelText = trimLabelText(givenText == null ? "" : " " + givenText, allowedWidth); + final String labelText = trimLabelText(StringUtil.isEmpty(givenText) ? "" : " " + givenText, allowedWidth, myNormalMetrics); - int used = getStringWidth(labelText); + int used = RealLookupElementPresentation.getStringWidth(labelText, myNormalMetrics); final Icon icon = presentation.getTypeIcon(); if (icon != null) { @@ -238,7 +265,7 @@ public class LookupCellRenderer implements ListCellRenderer { sampleBackground = proposedBackground; } myTypeLabel.append(" "); - used += myFontWidth * 2; + used += myNormalMetrics.stringWidth("WW"); } else { myTypeLabel.append(labelText); } @@ -271,14 +298,14 @@ public class LookupCellRenderer implements ListCellRenderer { myEmptyIcon = new EmptyIcon(icon.getIconWidth(), 2); } - int maxWidth = Math.min(RealLookupElementPresentation.calculateWidth(p, myFontWidth), MAX_LENGTH * myFontWidth); + int maxWidth = Math.min(RealLookupElementPresentation.calculateWidth(p, myNormalMetrics, myBoldMetrics), myMaxWidth); return maxWidth + getCommonIconWidth(); } private int getCommonIconWidth() { return myEmptyIcon.getIconWidth() + myNameComponent.getIconTextGap() + PopupIcons.HAS_NEXT_ICON_GRAYED.getIconWidth() //actions - + myFontWidth; //tail-type separation + + myNormalMetrics.stringWidth("W"); //tail-type separation } public int getIconIndent() { diff --git a/platform/lang-impl/src/com/intellij/diagnostic/logging/LogSearchComponent.form b/platform/lang-impl/src/com/intellij/diagnostic/logging/LogSearchComponent.form index 23b6edb96dbf..700fbcbc4387 100644 --- a/platform/lang-impl/src/com/intellij/diagnostic/logging/LogSearchComponent.form +++ b/platform/lang-impl/src/com/intellij/diagnostic/logging/LogSearchComponent.form @@ -1,6 +1,6 @@
- + @@ -10,7 +10,7 @@ - + @@ -18,7 +18,7 @@ - + @@ -29,6 +29,14 @@ + + + + + + + + diff --git a/platform/lang-impl/src/com/intellij/execution/impl/ConsoleViewImpl.java b/platform/lang-impl/src/com/intellij/execution/impl/ConsoleViewImpl.java index 665873fb1979..be38bcbad49c 100644 --- a/platform/lang-impl/src/com/intellij/execution/impl/ConsoleViewImpl.java +++ b/platform/lang-impl/src/com/intellij/execution/impl/ConsoleViewImpl.java @@ -46,6 +46,7 @@ import com.intellij.openapi.editor.ex.MarkupModelEx; import com.intellij.openapi.editor.highlighter.EditorHighlighter; import com.intellij.openapi.editor.highlighter.HighlighterClient; import com.intellij.openapi.editor.highlighter.HighlighterIterator; +import com.intellij.openapi.editor.impl.EditorFactoryImpl; import com.intellij.openapi.editor.markup.HighlighterLayer; import com.intellij.openapi.editor.markup.HighlighterTargetArea; import com.intellij.openapi.editor.markup.RangeHighlighter; @@ -180,7 +181,8 @@ public final class ConsoleViewImpl extends JPanel implements ConsoleView, Observ } }; - private final CompositeFilter myMessageFilter; + private final CompositeFilter myPredefinedMessageFilter; + private final CompositeFilter myCustomFilter; private ArrayList myHistory = new ArrayList(); private int myHistorySize = 20; @@ -238,12 +240,11 @@ public final class ConsoleViewImpl extends JPanel implements ConsoleView, Observ myProject = project; myFileType = fileType; - myMessageFilter = new CompositeFilter(project); - final ConsoleFilterProvider[] filterProviders = Extensions.getExtensions(ConsoleFilterProvider.FILTER_PROVIDERS); - for (ConsoleFilterProvider filterProvider : filterProviders) { - final Filter[] defaultFilters = filterProvider.getDefaultFilters(project); - for (Filter filter : defaultFilters) { - addMessageFilter(filter); + myCustomFilter = new CompositeFilter(project); + myPredefinedMessageFilter = new CompositeFilter(project); + for (ConsoleFilterProvider filterProvider : Extensions.getExtensions(ConsoleFilterProvider.FILTER_PROVIDERS)) { + for (Filter filter : filterProvider.getDefaultFilters(project)) { + myPredefinedMessageFilter.addFilter(filter); } } @@ -274,15 +275,11 @@ public final class ConsoleViewImpl extends JPanel implements ConsoleView, Observ myEditor.getMarkupModel().removeAllHighlighters(); document = myEditor.getDocument(); } - ApplicationManager.getApplication().runWriteAction(new DocumentRunnable(document, myProject) { + CommandProcessor.getInstance().executeCommand(myProject, new Runnable() { public void run() { - CommandProcessor.getInstance().executeCommand(myProject, new Runnable() { - public void run() { - document.deleteString(0, document.getTextLength()); - } - }, null, DocCommandGroupId.noneGroupId(document)); + document.deleteString(0, document.getTextLength()); } - }); + }, null, DocCommandGroupId.noneGroupId(document)); } public void scrollTo(final int offset) { @@ -462,18 +459,14 @@ public final class ConsoleViewImpl extends JPanel implements ConsoleView, Observ final int oldLineCount = document.getLineCount(); final boolean isAtEndOfDocument = myEditor.getCaretModel().getOffset() == document.getTextLength(); boolean cycleUsed = USE_CYCLIC_BUFFER && document.getTextLength() + text.length() > CYCLIC_BUFFER_SIZE; - ApplicationManager.getApplication().runWriteAction(new DocumentRunnable(document, myProject) { + CommandProcessor.getInstance().executeCommand(myProject, new Runnable() { public void run() { - CommandProcessor.getInstance().executeCommand(myProject, new Runnable() { - public void run() { - document.insertString(document.getTextLength(), text); - synchronized (LOCK) { - fireChange(); - } - } - }, null, DocCommandGroupId.noneGroupId(document)); + document.insertString(document.getTextLength(), text); + synchronized (LOCK) { + fireChange(); + } } - }); + }, null, DocCommandGroupId.noneGroupId(document)); myPsiDisposedCheck.performCheck(); final int newLineCount = document.getLineCount(); if (cycleUsed) { @@ -540,7 +533,7 @@ public final class ConsoleViewImpl extends JPanel implements ConsoleView, Observ } public void addMessageFilter(final Filter filter) { - myMessageFilter.addFilter(filter); + myCustomFilter.addFilter(filter); } public void printHyperlink(final String hyperlinkText, final HyperlinkInfo info) { @@ -568,8 +561,8 @@ public final class ConsoleViewImpl extends JPanel implements ConsoleView, Observ } private Editor doCreateEditor() { - final EditorFactory editorFactory = EditorFactory.getInstance(); - final Document editorDocument = editorFactory.createDocument(""); + final EditorFactoryImpl editorFactory = (EditorFactoryImpl) EditorFactory.getInstance(); + final Document editorDocument = editorFactory.createDocument(true); editorDocument.addDocumentListener(new DocumentListener() { public void beforeDocumentChange(DocumentEvent event) { } @@ -789,28 +782,29 @@ public final class ConsoleViewImpl extends JPanel implements ConsoleView, Observ } private void highlightHyperlinks(final int line1, final int line2){ - if (myMessageFilter != null){ - ApplicationManager.getApplication().assertIsDispatchThread(); - PsiDocumentManager.getInstance(myProject).commitAllDocuments(); - final Document document = myEditor.getDocument(); - final CharSequence chars = document.getCharsSequence(); - final TextAttributes hyperlinkAttributes = getHyperlinkAttributes(); + ApplicationManager.getApplication().assertIsDispatchThread(); + PsiDocumentManager.getInstance(myProject).commitAllDocuments(); + final Document document = myEditor.getDocument(); + final CharSequence chars = document.getCharsSequence(); + final TextAttributes hyperlinkAttributes = getHyperlinkAttributes(); - for(int line = line1; line <= line2; line++) { - if (line < 0) continue; - final int startOffset = document.getLineStartOffset(line); - int endOffset = document.getLineEndOffset(line); - if (endOffset < document.getTextLength()){ - endOffset++; // add '\n' - } - final String text = chars.subSequence(startOffset, endOffset).toString(); - final Filter.Result result = myMessageFilter.applyFilter(text, endOffset); - if (result != null){ - final int highlightStartOffset = result.highlightStartOffset; - final int highlightEndOffset = result.highlightEndOffset; - final HyperlinkInfo hyperlinkInfo = result.hyperlinkInfo; - addHyperlink(highlightStartOffset, highlightEndOffset, result.highlightAttributes, hyperlinkInfo, hyperlinkAttributes); - } + for(int line = line1; line <= line2; line++) { + if (line < 0) continue; + final int startOffset = document.getLineStartOffset(line); + int endOffset = document.getLineEndOffset(line); + if (endOffset < document.getTextLength()){ + endOffset++; // add '\n' + } + final String text = chars.subSequence(startOffset, endOffset).toString(); + Filter.Result result = myCustomFilter.applyFilter(text, endOffset); + if (result == null) { + result = myPredefinedMessageFilter.applyFilter(text, endOffset); + } + if (result != null){ + final int highlightStartOffset = result.highlightStartOffset; + final int highlightEndOffset = result.highlightEndOffset; + final HyperlinkInfo hyperlinkInfo = result.hyperlinkInfo; + addHyperlink(highlightStartOffset, highlightEndOffset, result.highlightAttributes, hyperlinkInfo, hyperlinkAttributes); } } } @@ -1284,13 +1278,9 @@ public final class ConsoleViewImpl extends JPanel implements ConsoleView, Observ consoleView.myContentSize += charCountToAdd; } - ApplicationManager.getApplication().runWriteAction(new Runnable() { - public void run() { - document.insertString(startOffset, s); - editor.getCaretModel().moveToOffset(startOffset + s.length()); - editor.getScrollingModel().scrollToCaret(ScrollType.RELATIVE); - } - }); + document.insertString(startOffset, s); + editor.getCaretModel().moveToOffset(startOffset + s.length()); + editor.getScrollingModel().scrollToCaret(ScrollType.RELATIVE); } /** @@ -1346,14 +1336,10 @@ public final class ConsoleViewImpl extends JPanel implements ConsoleView, Observ consoleView.myContentSize += charCountToReplace; } - ApplicationManager.getApplication().runWriteAction(new Runnable() { - public void run() { - document.replaceString(startOffset, endOffset, s); - editor.getCaretModel().moveToOffset(startOffset + s.length()); - editor.getScrollingModel().scrollToCaret(ScrollType.RELATIVE); - editor.getSelectionModel().removeSelection(); - } - }); + document.replaceString(startOffset, endOffset, s); + editor.getCaretModel().moveToOffset(startOffset + s.length()); + editor.getScrollingModel().scrollToCaret(ScrollType.RELATIVE); + editor.getSelectionModel().removeSelection(); } /** @@ -1395,18 +1381,14 @@ public final class ConsoleViewImpl extends JPanel implements ConsoleView, Observ consoleView.myContentSize -= charCountToDelete; } - ApplicationManager.getApplication().runWriteAction(new Runnable() { - public void run() { - document.deleteString(startOffset, endOffset); - editor.getCaretModel().moveToOffset(startOffset); - editor.getScrollingModel().scrollToCaret(ScrollType.RELATIVE); - editor.getSelectionModel().removeSelection(); - } - }); + document.deleteString(startOffset, endOffset); + editor.getCaretModel().moveToOffset(startOffset); + editor.getScrollingModel().scrollToCaret(ScrollType.RELATIVE); + editor.getSelectionModel().removeSelection(); } //util methods for add, replace, delete methods - private int getStartOffset(int offset, TokenInfo info) { + private static int getStartOffset(int offset, TokenInfo info) { int startOffset; if (offset >= info.startOffset && offset < info.endOffset) { startOffset = offset; @@ -1418,7 +1400,7 @@ public final class ConsoleViewImpl extends JPanel implements ConsoleView, Observ return startOffset; } - private int getEndOffset(int offset, TokenInfo info) { + private static int getEndOffset(int offset, TokenInfo info) { int endOffset; if (offset > info.endOffset) { endOffset = info.endOffset; diff --git a/platform/lang-impl/src/com/intellij/ide/bookmarks/Bookmark.java b/platform/lang-impl/src/com/intellij/ide/bookmarks/Bookmark.java index 74df33c5b475..9fb0104421d1 100644 --- a/platform/lang-impl/src/com/intellij/ide/bookmarks/Bookmark.java +++ b/platform/lang-impl/src/com/intellij/ide/bookmarks/Bookmark.java @@ -32,12 +32,12 @@ import com.intellij.openapi.fileEditor.FileDocumentManager; import com.intellij.openapi.fileEditor.OpenFileDescriptor; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.IconLoader; -import com.intellij.openapi.util.Iconable; import com.intellij.openapi.util.text.StringUtil; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.psi.PsiDocumentManager; import com.intellij.psi.PsiFile; import com.intellij.psi.PsiManager; +import com.intellij.ui.LightColors; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; @@ -45,7 +45,7 @@ import javax.swing.*; import java.awt.*; public class Bookmark { - public static final Icon TICK = IconLoader.getIcon("/gutter/check.png"); + private static final Icon TICK = IconLoader.getIcon("/gutter/check.png"); private final VirtualFile myFile; private final OpenFileDescriptor myTarget; @@ -53,6 +53,8 @@ public class Bookmark { private final Project myProject; private String myDescription; + private char myMnemonic = 0; + public static final Font MNEMONIC_FONT = new Font("Monospaced", 0, 11); public Bookmark(Project project, VirtualFile file, String description) { this(project, file, -1, description); @@ -71,7 +73,7 @@ public class Bookmark { myHighlighter.setGutterIconRenderer(new GutterIconRenderer() { @NotNull public Icon getIcon() { - return TICK; + return Bookmark.this.getIcon(); } public String getTooltipText() { @@ -100,12 +102,7 @@ public class Bookmark { } public Icon getIcon() { - if (myFile.isDirectory()) { - return PsiManager.getInstance(myProject).findDirectory(myFile).getIcon(Iconable.ICON_FLAG_CLOSED); - } - else { - return PsiManager.getInstance(myProject).findFile(myFile).getIcon(Iconable.ICON_FLAG_CLOSED); - } + return myMnemonic == 0 ? TICK : new MnemonicIcon(myMnemonic); } public String getDescription() { @@ -116,6 +113,14 @@ public class Bookmark { myDescription = description; } + public char getMnemonic() { + return myMnemonic; + } + + public void setMnemonic(char mnemonic) { + myMnemonic = Character.toUpperCase(mnemonic); + } + public VirtualFile getFile() { return myFile; } @@ -155,19 +160,48 @@ public class Bookmark { if (psiFile == null) return presentableUrl; - StructureViewBuilder builder = LanguageStructureViewBuilder.INSTANCE.getStructureViewBuilder(psiFile); - if (builder instanceof TreeBasedStructureViewBuilder) { - StructureViewModel model = ((TreeBasedStructureViewBuilder)builder).createStructureViewModel(); - Object element = model.getCurrentEditorElement(); - if (element instanceof NavigationItem) { - ItemPresentation presentation = ((NavigationItem)element).getPresentation(); - if (presentation != null) { - presentableUrl = ((NavigationItem)element).getName() + " " + presentation.getLocationString(); - } - } - } + StructureViewBuilder builder = LanguageStructureViewBuilder.INSTANCE.getStructureViewBuilder(psiFile); + if (builder instanceof TreeBasedStructureViewBuilder) { + StructureViewModel model = ((TreeBasedStructureViewBuilder)builder).createStructureViewModel(); + Object element = model.getCurrentEditorElement(); + if (element instanceof NavigationItem) { + ItemPresentation presentation = ((NavigationItem)element).getPresentation(); + if (presentation != null) { + presentableUrl = ((NavigationItem)element).getName() + " " + presentation.getLocationString(); + } + } + } - return IdeBundle.message("bookmark.file.X.line.Y", presentableUrl, - (myHighlighter.getDocument().getLineNumber(myHighlighter.getStartOffset()) + 1)); - } + return IdeBundle + .message("bookmark.file.X.line.Y", presentableUrl, (myHighlighter.getDocument().getLineNumber(myHighlighter.getStartOffset()) + 1)); + } + + private static class MnemonicIcon implements Icon { + private final char myMnemonic; + + private MnemonicIcon(char mnemonic) { + myMnemonic = mnemonic; + } + + public void paintIcon(Component c, Graphics g, int x, int y) { + g.setColor(LightColors.YELLOW); + g.fillRect(x, y, getIconWidth(), getIconHeight()); + + g.setColor(Color.gray); + g.drawRect(x, y, getIconWidth(), getIconHeight()); + + g.setColor(Color.black); + g.setFont(MNEMONIC_FONT); + + g.drawString(Character.toString(myMnemonic), x + 2, y + getIconHeight() - 2); + } + + public int getIconWidth() { + return 10; + } + + public int getIconHeight() { + return 12; + } + } } diff --git a/platform/lang-impl/src/com/intellij/ide/bookmarks/BookmarkManager.java b/platform/lang-impl/src/com/intellij/ide/bookmarks/BookmarkManager.java index b70dec36df83..bdd93f96f2d8 100644 --- a/platform/lang-impl/src/com/intellij/ide/bookmarks/BookmarkManager.java +++ b/platform/lang-impl/src/com/intellij/ide/bookmarks/BookmarkManager.java @@ -84,10 +84,11 @@ public class BookmarkManager implements PersistentStateComponent { addTextBookmark(virtualFile, lineIndex, getAutoDescription(editor, lineIndex)); } - public void addTextBookmark(VirtualFile file, int lineIndex, String description) { + public Bookmark addTextBookmark(VirtualFile file, int lineIndex, String description) { Bookmark b = new Bookmark(myProject, file, lineIndex, description); myBus.syncPublisher(BookmarksListener.TOPIC).bookmarkAdded(b); myBookmarks.add(0, b); + return b; } public static String getAutoDescription(final Editor editor, final int lineIndex) { @@ -103,13 +104,15 @@ public class BookmarkManager implements PersistentStateComponent { return autoDescription; } - public void addFileBookmark(VirtualFile file, String description) { - if (file == null) return; - if (findFileBookmark(file) != null) return; + @Nullable + public Bookmark addFileBookmark(VirtualFile file, String description) { + if (file == null) return null; + if (findFileBookmark(file) != null) return null; Bookmark b = new Bookmark(myProject, file, description); myBookmarks.add(0, b); myBus.syncPublisher(BookmarksListener.TOPIC).bookmarkAdded(b); + return b; } @@ -142,6 +145,23 @@ public class BookmarkManager implements PersistentStateComponent { return null; } + @Nullable + public Bookmark findBookmarkForMnemonic(char m) { + final char mm = Character.toUpperCase(m); + for (Bookmark bookmark : myBookmarks) { + if (mm == bookmark.getMnemonic()) return bookmark; + } + return null; + } + + public boolean hasBookmarksWithMnemonics() { + for (Bookmark bookmark : myBookmarks) { + if (bookmark.getMnemonic() != 0) return true; + } + + return false; + } + public void removeBookmark(Bookmark bookmark) { myBookmarks.remove(bookmark); bookmark.release(); @@ -173,22 +193,28 @@ public class BookmarkManager implements PersistentStateComponent { String url = bookmarkElement.getAttributeValue("url"); String line = bookmarkElement.getAttributeValue("line"); String description = bookmarkElement.getAttributeValue("description"); + String mnemonic = bookmarkElement.getAttributeValue("mnemonic"); + Bookmark b = null; VirtualFile file = VirtualFileManager.getInstance().findFileByUrl(url); if (file != null) { if (line != null) { try { int lineIndex = Integer.parseInt(line); - addTextBookmark(file, lineIndex, description); + b = addTextBookmark(file, lineIndex, description); } catch (NumberFormatException e) { // Ignore. Will miss bookmark if line number cannot be parsed } } else { - addFileBookmark(file, description); + b = addFileBookmark(file, description); } } + + if (b != null && mnemonic != null && mnemonic.length() == 1) { + setMnemonic(b, mnemonic.charAt(0)); + } } } } @@ -209,6 +235,11 @@ public class BookmarkManager implements PersistentStateComponent { bookmarkElement.setAttribute("line", String.valueOf(line)); } + char mnemonic = bookmark.getMnemonic(); + if (mnemonic != 0) { + bookmarkElement.setAttribute("mnemonic", String.valueOf(mnemonic)); + } + element.addContent(bookmarkElement); } } @@ -286,6 +317,19 @@ public class BookmarkManager implements PersistentStateComponent { return bookmarks; } + public void setMnemonic(Bookmark bookmark, char c) { + final Bookmark old = findBookmarkForMnemonic(c); + if (old != null) removeBookmark(old); + + bookmark.setMnemonic(c); + myBus.syncPublisher(BookmarksListener.TOPIC).bookmarkChanged(bookmark); + } + + public void setDescription(Bookmark bookmark, String description) { + bookmark.setDescription(description); + myBus.syncPublisher(BookmarksListener.TOPIC).bookmarkChanged(bookmark); + } + private class MyEditorMouseListener extends EditorMouseAdapter { public void mouseClicked(final EditorMouseEvent e) { diff --git a/platform/lang-impl/src/com/intellij/ide/bookmarks/BookmarksListener.java b/platform/lang-impl/src/com/intellij/ide/bookmarks/BookmarksListener.java index 3047326044a1..398ba6ef72cb 100644 --- a/platform/lang-impl/src/com/intellij/ide/bookmarks/BookmarksListener.java +++ b/platform/lang-impl/src/com/intellij/ide/bookmarks/BookmarksListener.java @@ -26,4 +26,6 @@ public interface BookmarksListener { void bookmarkAdded(Bookmark b); void bookmarkRemoved(Bookmark b); + + void bookmarkChanged(Bookmark b); } diff --git a/platform/lang-impl/src/com/intellij/ide/bookmarks/actions/BookmarksAction.java b/platform/lang-impl/src/com/intellij/ide/bookmarks/actions/BookmarksAction.java index a317b6fd5439..19e2368911b8 100644 --- a/platform/lang-impl/src/com/intellij/ide/bookmarks/actions/BookmarksAction.java +++ b/platform/lang-impl/src/com/intellij/ide/bookmarks/actions/BookmarksAction.java @@ -52,6 +52,7 @@ import com.intellij.ui.*; import com.intellij.ui.speedSearch.FilteringListModel; import com.intellij.util.Alarm; import com.intellij.util.Function; +import com.intellij.util.ui.UIUtil; import org.jetbrains.annotations.Nullable; import javax.swing.*; @@ -106,35 +107,6 @@ public class BookmarksAction extends AnAction implements DumbAware { pathLabel.setFont(font.deriveFont((float)10)); final JList list = new JList(model); - list.addKeyListener(new KeyAdapter() { - public void keyPressed(KeyEvent e) { - if (e.getKeyCode() == KeyEvent.VK_DELETE) { - int index = list.getSelectedIndex(); - if (index == -1 || index >= list.getModel().getSize()) { - return; - } - Object[] values = list.getSelectedValues(); - for (Object value : values) { - if (value instanceof BookmarkItem) { - BookmarkItem item = (BookmarkItem)value; - model.removeElement(item); - if (model.getSize() > 0) { - if (model.getSize() == index) { - list.setSelectedIndex(model.getSize() - 1); - } - else if (model.getSize() > index) { - list.setSelectedIndex(index); - } - } - else { - list.clearSelection(); - } - BookmarkManager.getInstance(project).removeBookmark(item.myBookmark); - } - } - } - } - }); final PreviewPanel previewPanel = new PreviewPanel(project); @@ -236,7 +208,7 @@ public class BookmarksAction extends AnAction implements DumbAware { final JComponent toolBar = actionToolbar.getComponent(); toolBar.setOpaque(false); - JBPopup popup = new PopupChooserBuilder(list). + final JBPopup popup = new PopupChooserBuilder(list). setTitle("Bookmarks"). setMovable(true). setAutoselectOnMouseMove(false). @@ -250,6 +222,48 @@ public class BookmarksAction extends AnAction implements DumbAware { } }).createPopup(); + list.addKeyListener(new KeyAdapter() { + public void keyPressed(KeyEvent e) { + if (e.getKeyCode() == KeyEvent.VK_DELETE) { + int index = list.getSelectedIndex(); + if (index == -1 || index >= list.getModel().getSize()) { + return; + } + Object[] values = list.getSelectedValues(); + for (Object value : values) { + if (value instanceof BookmarkItem) { + BookmarkItem item = (BookmarkItem)value; + model.removeElement(item); + if (model.getSize() > 0) { + if (model.getSize() == index) { + list.setSelectedIndex(model.getSize() - 1); + } + else if (model.getSize() > index) { + list.setSelectedIndex(index); + } + } + else { + list.clearSelection(); + } + BookmarkManager.getInstance(project).removeBookmark(item.myBookmark); + } + } + } + else if (e.getModifiersEx() == 0) { + char mnemonic = e.getKeyChar(); + final Bookmark bookmark = BookmarkManager.getInstance(project).findBookmarkForMnemonic(mnemonic); + if (bookmark != null) { + popup.cancel(); + IdeFocusManager.getInstance(project).doWhenFocusSettlesDown(new Runnable() { + public void run() { + bookmark.navigate(); + } + }); + } + } + } + }); + editDescriptionAction.setPopup(popup); popup.showCenteredInCurrentWindow(project); } @@ -270,6 +284,7 @@ public class BookmarksAction extends AnAction implements DumbAware { private interface ItemWrapper { void setupRenderer(ColoredListCellRenderer renderer, Project project, boolean selected); + void updateMnemonicLabel(JLabel label); void execute(Project project); @@ -294,6 +309,10 @@ public class BookmarksAction extends AnAction implements DumbAware { renderer.append(speedSearchText()); } + public void updateMnemonicLabel(JLabel label) { + label.setText(""); + } + public String speedSearchText() { return "Bookmark this place"; } @@ -327,6 +346,10 @@ public class BookmarksAction extends AnAction implements DumbAware { renderer.append(speedSearchText()); } + public void updateMnemonicLabel(JLabel label) { + label.setText(""); + } + public String speedSearchText() { return "Remove Bookmark"; } @@ -366,6 +389,7 @@ public class BookmarksAction extends AnAction implements DumbAware { renderer.setIcon(fileOrDir.getIcon(Iconable.ICON_FLAG_CLOSED)); } + FileStatus fileStatus = FileStatusManager.getInstance(project).getStatus(file); TextAttributes attributes = new TextAttributes(fileStatus.getColor(), null, null, EffectType.LINE_UNDERSCORE, Font.PLAIN); renderer.append(file.getName(), SimpleTextAttributes.fromTextAttributes(attributes)); @@ -395,6 +419,16 @@ public class BookmarksAction extends AnAction implements DumbAware { } } + public void updateMnemonicLabel(JLabel label) { + final char mnemonic = myBookmark.getMnemonic(); + if (mnemonic != 0) { + label.setText(Character.toString(mnemonic) + '.'); + } + else { + label.setText(""); + } + } + public String speedSearchText() { return myBookmark.getFile().getName() + " " + myBookmark.getDescription(); } @@ -443,18 +477,42 @@ public class BookmarksAction extends AnAction implements DumbAware { } } - private static class ItemRenderer extends ColoredListCellRenderer { + private static class ItemRenderer extends JPanel implements ListCellRenderer { private final Project myProject; + private ColoredListCellRenderer myRenderer; private ItemRenderer(Project project) { + super(new BorderLayout()); myProject = project; + + setBackground(UIUtil.getListBackground()); + + final JLabel label = new JLabel(); + label.setFont(Bookmark.MNEMONIC_FONT); + + label.setPreferredSize(new JLabel("W.").getPreferredSize()); + label.setOpaque(false); + + if (BookmarkManager.getInstance(project).hasBookmarksWithMnemonics()) { + add(label, BorderLayout.WEST); + } + + myRenderer = new ColoredListCellRenderer() { + @Override + protected void customizeCellRenderer(JList list, Object value, int index, boolean selected, boolean hasFocus) { + if (value instanceof ItemWrapper) { + final ItemWrapper wrapper = (ItemWrapper)value; + wrapper.setupRenderer(this, myProject, selected); + wrapper.updateMnemonicLabel(label); + } + } + }; + add(myRenderer, BorderLayout.CENTER); } - @Override - protected void customizeCellRenderer(JList list, Object value, int index, boolean selected, boolean hasFocus) { - if (value instanceof ItemWrapper) { - ((ItemWrapper)value).setupRenderer(this, myProject, selected); - } + public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) { + myRenderer.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus); + return this; } } @@ -599,8 +657,8 @@ public class BookmarksAction extends AnAction implements DumbAware { return true; } }); - - b.setDescription(description); + + BookmarkManager.getInstance(myProject).setDescription(b, description); myPopup.setUiVisible(true); myPopup.setSize(myPopup.getContent().getPreferredSize()); diff --git a/platform/lang-impl/src/com/intellij/ide/bookmarks/actions/MnemonicChooser.java b/platform/lang-impl/src/com/intellij/ide/bookmarks/actions/MnemonicChooser.java new file mode 100644 index 000000000000..a8b78eeb7d20 --- /dev/null +++ b/platform/lang-impl/src/com/intellij/ide/bookmarks/actions/MnemonicChooser.java @@ -0,0 +1,118 @@ +/* + * Copyright 2000-2009 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/* + * @author max + */ +package com.intellij.ide.bookmarks.actions; + +import com.intellij.openapi.ui.VerticalFlowLayout; +import com.intellij.ui.LightColors; +import com.intellij.ui.components.panels.NonOpaquePanel; +import com.intellij.util.ui.UIUtil; + +import javax.swing.*; +import javax.swing.border.LineBorder; +import java.awt.*; +import java.awt.event.KeyAdapter; +import java.awt.event.KeyEvent; +import java.awt.event.MouseAdapter; +import java.awt.event.MouseEvent; + +public class MnemonicChooser extends JPanel { + public MnemonicChooser() { + super(new VerticalFlowLayout()); + JPanel numbers = new NonOpaquePanel(new GridLayout(2, 5, 2, 2)); + for (char i = '1'; i <= '9'; i++) { + numbers.add(new MnemonicLabel(i)); + } + numbers.add(new MnemonicLabel('0')); + + + JPanel letters = new NonOpaquePanel(new GridLayout(5, 6, 2, 2)); + for (char c = 'A'; c <= 'Z'; c++) { + letters.add(new MnemonicLabel(c)); + } + + add(numbers); + add(new JSeparator()); + add(letters); + setBackground(UIUtil.getListBackground()); + + addKeyListener(new KeyAdapter() { + @Override + public void keyPressed(KeyEvent e) { + if (e.getKeyCode() == KeyEvent.VK_ESCAPE) { + onCancelled(); + } + else if (e.getModifiersEx() == 0) { + final char typed = Character.toUpperCase(e.getKeyChar()); + if (typed >= '0' && typed <= '9' || typed >= 'A' && typed <= 'Z') { + onMnemonicChosen(typed); + } + } + } + }); + + setFocusable(true); + } + + protected boolean isOccupied(char c) { + return false; + } + + protected void onMnemonicChosen(char c) { + + } + + protected void onCancelled() { + + } + + private Color backgroundForMnemonic(char c) { + return isOccupied(c) ? LightColors.YELLOW : LightColors.SLIGHTLY_GRAY; + } + + private class MnemonicLabel extends JLabel { + private MnemonicLabel(final char c) { + setOpaque(true); + setText(Character.toString(c)); + setBorder(new LineBorder(Color.lightGray, 1)); + setHorizontalAlignment(CENTER); + + setBackground(backgroundForMnemonic(c)); + + addMouseListener(new MouseAdapter() { + @Override + public void mouseEntered(MouseEvent e) { + setForeground(UIUtil.getListSelectionForeground()); + setBackground(UIUtil.getListSelectionBackground()); + } + + @Override + public void mouseExited(MouseEvent e) { + setForeground(UIUtil.getListForeground()); + setBackground(backgroundForMnemonic(c)); + } + + @Override + public void mouseClicked(MouseEvent e) { + onMnemonicChosen(c); + } + }); + } + } +} diff --git a/platform/lang-impl/src/com/intellij/ide/bookmarks/actions/ToggleBookmarkWithMnemonicAction.java b/platform/lang-impl/src/com/intellij/ide/bookmarks/actions/ToggleBookmarkWithMnemonicAction.java new file mode 100644 index 000000000000..baec626954db --- /dev/null +++ b/platform/lang-impl/src/com/intellij/ide/bookmarks/actions/ToggleBookmarkWithMnemonicAction.java @@ -0,0 +1,89 @@ +/* + * Copyright 2000-2009 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/* + * @author max + */ +package com.intellij.ide.bookmarks.actions; + +import com.intellij.ide.IdeBundle; +import com.intellij.ide.bookmarks.Bookmark; +import com.intellij.ide.bookmarks.BookmarkManager; +import com.intellij.openapi.actionSystem.AnActionEvent; +import com.intellij.openapi.actionSystem.DataContext; +import com.intellij.openapi.actionSystem.PlatformDataKeys; +import com.intellij.openapi.project.Project; +import com.intellij.openapi.ui.popup.ComponentPopupBuilder; +import com.intellij.openapi.ui.popup.JBPopup; +import com.intellij.openapi.ui.popup.JBPopupFactory; + +public class ToggleBookmarkWithMnemonicAction extends ToggleBookmarkAction { + public ToggleBookmarkWithMnemonicAction() { + getTemplatePresentation().setText(IdeBundle.message("action.toggle.bookmark.mnemonic")); + } + + @Override + public void actionPerformed(AnActionEvent e) { + super.actionPerformed(e); + + DataContext dataContext = e.getDataContext(); + final Project project = PlatformDataKeys.PROJECT.getData(dataContext); + if (project == null) return; + final BookmarkInContextInfo info = new BookmarkInContextInfo(dataContext, project).invoke(); + final Bookmark bookmark = info.getBookmarkAtPlace(); + final BookmarkManager bookmarks = BookmarkManager.getInstance(project); + if (bookmark != null) { + final JBPopup[] popup = new JBPopup[1]; + MnemonicChooser mc = new MnemonicChooser() { + @Override + protected void onMnemonicChosen(char c) { + popup[0].cancel(); + bookmarks.setMnemonic(bookmark, c); + } + + @Override + protected void onCancelled() { + popup[0].cancel(); + bookmarks.removeBookmark(bookmark); + } + + @Override + protected boolean isOccupied(char c) { + return bookmarks.findBookmarkForMnemonic(c) != null; + } + }; + + final ComponentPopupBuilder builder = JBPopupFactory.getInstance().createComponentPopupBuilder(mc, mc); + popup[0] = builder. + setTitle("Choose Mnemonic"). + setFocusable(true). + setRequestFocus(true). + setMovable(false). + setCancelKeyEnabled(false). + setAdText(bookmarks.hasBookmarksWithMnemonics() ? "Yellow cells in use" : null). + setResizable(false) + .createPopup(); + + popup[0].showInBestPositionFor(dataContext); + } + } + + public void update(AnActionEvent event) { + super.update(event); + + event.getPresentation().setText(IdeBundle.message("action.toggle.bookmark.mnemonic")); + } +} diff --git a/platform/lang-impl/src/com/intellij/ide/projectView/impl/ProjectTreeBuilder.java b/platform/lang-impl/src/com/intellij/ide/projectView/impl/ProjectTreeBuilder.java index 1b1bf4b6bc2d..ffb1cf174eba 100644 --- a/platform/lang-impl/src/com/intellij/ide/projectView/impl/ProjectTreeBuilder.java +++ b/platform/lang-impl/src/com/intellij/ide/projectView/impl/ProjectTreeBuilder.java @@ -145,6 +145,10 @@ public class ProjectTreeBuilder extends BaseProjectTreeBuilder { updateForFile(b.getFile()); } + public void bookmarkChanged(Bookmark b) { + updateForFile(b.getFile()); + } + private void updateForFile(VirtualFile file) { PsiElement element = findPsi(file); if (element != null) { diff --git a/platform/lang-impl/src/com/intellij/ide/projectView/impl/nodes/PsiDirectoryNode.java b/platform/lang-impl/src/com/intellij/ide/projectView/impl/nodes/PsiDirectoryNode.java index 289e283c0558..208223f8b3e6 100644 --- a/platform/lang-impl/src/com/intellij/ide/projectView/impl/nodes/PsiDirectoryNode.java +++ b/platform/lang-impl/src/com/intellij/ide/projectView/impl/nodes/PsiDirectoryNode.java @@ -210,7 +210,7 @@ public class PsiDirectoryNode extends BasePsiNode { if (bookmarkAtFile != null) { RowIcon composite = new RowIcon(2); composite.setIcon(original, 0); - composite.setIcon(Bookmark.TICK, 1); + composite.setIcon(bookmarkAtFile.getIcon(), 1); return addReadMark(composite, file.isWritable()); } diff --git a/platform/lang-impl/src/com/intellij/ide/projectView/impl/nodes/PsiFileNode.java b/platform/lang-impl/src/com/intellij/ide/projectView/impl/nodes/PsiFileNode.java index 3baa92c10bb1..3c5844747f33 100644 --- a/platform/lang-impl/src/com/intellij/ide/projectView/impl/nodes/PsiFileNode.java +++ b/platform/lang-impl/src/com/intellij/ide/projectView/impl/nodes/PsiFileNode.java @@ -120,7 +120,7 @@ public class PsiFileNode extends BasePsiNode{ } public boolean canRepresent(final Object element) { - return super.canRepresent(element) || getValue().getVirtualFile() == element; + return super.canRepresent(element) || getValue() != null && getValue().getVirtualFile() == element; } @Override diff --git a/platform/lang-impl/src/com/intellij/profile/codeInspection/ui/InspectionToolsConfigurable.java b/platform/lang-impl/src/com/intellij/profile/codeInspection/ui/InspectionToolsConfigurable.java index 363cbb42b5b4..2eacdd56cf48 100644 --- a/platform/lang-impl/src/com/intellij/profile/codeInspection/ui/InspectionToolsConfigurable.java +++ b/platform/lang-impl/src/com/intellij/profile/codeInspection/ui/InspectionToolsConfigurable.java @@ -230,7 +230,9 @@ public abstract class InspectionToolsConfigurable extends BaseConfigurable imple }); myShareProfileCheckBox.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { - getSelectedPanel().setProfileShared(myShareProfileCheckBox.isSelected()); + final SingleInspectionProfilePanel panel = getSelectedPanel(); + LOG.assertTrue(panel != null, "No settings panel for: " + getSelectedObject()); + panel.setProfileShared(myShareProfileCheckBox.isSelected()); myProfiles.repaint(); } }); @@ -315,7 +317,9 @@ public abstract class InspectionToolsConfigurable extends BaseConfigurable imple } public void selectInspectionTool(String selectedToolShortName) { - getSelectedPanel().selectInspectionTool(selectedToolShortName); + final SingleInspectionProfilePanel panel = getSelectedPanel(); + LOG.assertTrue(panel != null, "No settings panel for: " + getSelectedObject()); + panel.selectInspectionTool(selectedToolShortName); } protected SingleInspectionProfilePanel getSelectedPanel() { diff --git a/platform/lang-impl/src/com/intellij/refactoring/ui/ConflictsDialog.java b/platform/lang-impl/src/com/intellij/refactoring/ui/ConflictsDialog.java index de0f0cda0e4d..32778e1dcca5 100644 --- a/platform/lang-impl/src/com/intellij/refactoring/ui/ConflictsDialog.java +++ b/platform/lang-impl/src/com/intellij/refactoring/ui/ConflictsDialog.java @@ -40,9 +40,8 @@ import org.jetbrains.annotations.Nullable; import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; -import java.util.ArrayList; import java.util.Collection; -import java.util.List; +import java.util.LinkedHashSet; import java.util.regex.Pattern; public class ConflictsDialog extends DialogWrapper{ @@ -55,7 +54,7 @@ public class ConflictsDialog extends DialogWrapper{ public ConflictsDialog(Project project, MultiMap conflictDescriptions) { super(project, true); myProject = project; - List conflicts = new ArrayList(); + final LinkedHashSet conflicts = new LinkedHashSet(); for (String conflict : conflictDescriptions.values()) { conflicts.add(conflict); @@ -182,7 +181,8 @@ public class ConflictsDialog extends DialogWrapper{ } private UsagePresentation getPresentation(final UsagePresentation usagePresentation, PsiElement element) { - final String conflictDescription = " (" + Pattern.compile("<[^<>]*>").matcher(StringUtil.join(myElementConflictDescription.get(element), "\n")).replaceAll("") + ")"; + final Collection elementConflicts = new LinkedHashSet(myElementConflictDescription.get(element)); + final String conflictDescription = " (" + Pattern.compile("<[^<>]*>").matcher(StringUtil.join(elementConflicts, "\n")).replaceAll("") + ")"; return new UsagePresentation() { @NotNull public TextChunk[] getText() { @@ -207,7 +207,7 @@ public class ConflictsDialog extends DialogWrapper{ } private class DescriptionOnlyUsage implements Usage { - private final String myConflictDescription = Pattern.compile("<[^<>]*>").matcher(StringUtil.join(myElementConflictDescription.get(null), "\n")).replaceAll(""); + private final String myConflictDescription = Pattern.compile("<[^<>]*>").matcher(StringUtil.join(new LinkedHashSet(myElementConflictDescription.get(null)), "\n")).replaceAll(""); @NotNull public UsagePresentation getPresentation() { diff --git a/platform/lang-impl/src/com/intellij/ui/tabs/FileColorConfigurationEditDialog.java b/platform/lang-impl/src/com/intellij/ui/tabs/FileColorConfigurationEditDialog.java index acb906b554c1..0e31bccfc52a 100644 --- a/platform/lang-impl/src/com/intellij/ui/tabs/FileColorConfigurationEditDialog.java +++ b/platform/lang-impl/src/com/intellij/ui/tabs/FileColorConfigurationEditDialog.java @@ -41,10 +41,8 @@ import java.util.List; public class FileColorConfigurationEditDialog extends DialogWrapper { private FileColorConfiguration myConfiguration; private JComboBox myScopeComboBox; - private JCheckBox myShareCheckbox; private FileColorManagerImpl myManager; private HashMap myColorToButtonMap; - private boolean myShared; public FileColorConfigurationEditDialog(@NotNull final FileColorManagerImpl manager, @Nullable final FileColorConfiguration configuration) { super(true); @@ -88,6 +86,17 @@ public class FileColorConfigurationEditDialog extends DialogWrapper { pathLabel.setLabelFor(myScopeComboBox); pathPanel.add(pathLabel, BorderLayout.WEST); pathPanel.add(myScopeComboBox, BorderLayout.CENTER); + + /* + final JButton newScope = new JButton("Add scope..."); + newScope.addActionListener(new ActionListener() { + public void actionPerformed(ActionEvent e) { + // TBD: refresh scope list + } + }); + pathPanel.add(newScope, BorderLayout.EAST); + */ + result.add(pathPanel); final JPanel colorPanel = new JPanel(); @@ -99,13 +108,6 @@ public class FileColorConfigurationEditDialog extends DialogWrapper { colorPanel.add(Box.createHorizontalGlue()); result.add(colorPanel); - final JPanel checkboxPanel = new JPanel(new BorderLayout()); - checkboxPanel.setBorder(BorderFactory.createEmptyBorder(5, 0, 5, 0)); - myShareCheckbox = new JCheckBox("Share configuration", myConfiguration == null ? false : myManager.isShared(myConfiguration)); - myShareCheckbox.setMnemonic('S'); - checkboxPanel.add(myShareCheckbox, BorderLayout.WEST); - result.add(checkboxPanel); - return result; } @@ -121,22 +123,23 @@ public class FileColorConfigurationEditDialog extends DialogWrapper { } } - public boolean isShared() { - return myShareCheckbox.isSelected(); - } - public FileColorConfiguration getConfiguration() { return myConfiguration; } private JComponent createColorButtonsPanel(final FileColorConfiguration configuration) { - final JPanel result = new JPanel(); - result.setLayout(new BoxLayout(result, BoxLayout.X_AXIS)); - result.setBackground(Color.WHITE); + final JPanel result = new JPanel(new BorderLayout()); result.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5)); + final JPanel inner = new JPanel(); + inner.setLayout(new BoxLayout(inner, BoxLayout.X_AXIS)); + inner.setBorder( + BorderFactory.createCompoundBorder(BorderFactory.createLineBorder(Color.LIGHT_GRAY, 1), BorderFactory.createEmptyBorder(5, 5, 5, 5))); + inner.setBackground(Color.WHITE); + result.add(inner, BorderLayout.CENTER); + final ButtonGroup group = new ButtonGroup(); - + myColorToButtonMap = new HashMap(); final Collection names = myManager.getColorNames(); @@ -150,9 +153,9 @@ public class FileColorConfigurationEditDialog extends DialogWrapper { colorButton.setBackground(Color.WHITE); colorButton.setBorder(BorderFactory.createEmptyBorder(5, 10, 5, 10)); group.add(colorButton); - result.add(colorButton); + inner.add(colorButton); myColorToButtonMap.put(name, colorButton); - result.add(Box.createHorizontalStrut(5)); + inner.add(Box.createHorizontalStrut(5)); } if (configuration != null) { diff --git a/platform/lang-impl/src/com/intellij/ui/tabs/FileColorManagerImpl.java b/platform/lang-impl/src/com/intellij/ui/tabs/FileColorManagerImpl.java index acadb7fa2257..7cb079d8479a 100644 --- a/platform/lang-impl/src/com/intellij/ui/tabs/FileColorManagerImpl.java +++ b/platform/lang-impl/src/com/intellij/ui/tabs/FileColorManagerImpl.java @@ -41,14 +41,14 @@ import java.util.List; id = "other", file = "$WORKSPACE_FILE$")}) public class FileColorManagerImpl extends FileColorManager implements PersistentStateComponent { - private boolean myEnabled = false; + private boolean myEnabled = true; private FileColorsModel myModel; private FileColorSharedConfigurationManager mySharedConfigurationManager; private Project myProject; - private boolean myEnabledForTabs; + private boolean myEnabledForTabs = true; private static Map ourDefaultColors; diff --git a/platform/lang-impl/src/com/intellij/ui/tabs/FileColorsConfigurable.java b/platform/lang-impl/src/com/intellij/ui/tabs/FileColorsConfigurable.java index f0ebd168f0e2..6b94efcf1721 100644 --- a/platform/lang-impl/src/com/intellij/ui/tabs/FileColorsConfigurable.java +++ b/platform/lang-impl/src/com/intellij/ui/tabs/FileColorsConfigurable.java @@ -64,11 +64,11 @@ public class FileColorsConfigurable implements Configurable, NonDefaultProjectCo } public void apply() throws ConfigurationException { - myPanel.apply(); + if (myPanel != null) myPanel.apply(); } public void reset() { - myPanel.reset(); + if (myPanel != null) myPanel.reset(); } public void disposeUIResources() { diff --git a/platform/lang-impl/src/com/intellij/ui/tabs/FileColorsConfigurablePanel.java b/platform/lang-impl/src/com/intellij/ui/tabs/FileColorsConfigurablePanel.java index 59c18ae11a85..9aa1827a4f92 100644 --- a/platform/lang-impl/src/com/intellij/ui/tabs/FileColorsConfigurablePanel.java +++ b/platform/lang-impl/src/com/intellij/ui/tabs/FileColorsConfigurablePanel.java @@ -53,29 +53,11 @@ public class FileColorsConfigurablePanel extends JPanel implements Disposable { myEnabledCheckBox.setMnemonic('F'); topPanel.add(myEnabledCheckBox); - myTabsEnabledCheckBox = new JCheckBox("Enable Colors in Editor Tabs"); + myTabsEnabledCheckBox = new JCheckBox("Use colors in Editor Tabs"); myTabsEnabledCheckBox.setMnemonic('T'); topPanel.add(myTabsEnabledCheckBox); topPanel.add(Box.createHorizontalGlue()); - final JButton addButton = new JButton("Add..."); - addButton.setMnemonic('A'); - addButton.addActionListener(new ActionListener() { - public void actionPerformed(ActionEvent e) { - final FileColorConfigurationEditDialog dialog = new FileColorConfigurationEditDialog(myManager, null); - dialog.show(); - - if (dialog.getExitCode() == 0) { - if (dialog.isShared()) { - mySharedTable.addConfiguration(dialog.getConfiguration()); - } else { - myLocalTable.addConfiguration(dialog.getConfiguration()); - } - } - } - }); - - topPanel.add(addButton); add(topPanel, BorderLayout.NORTH); final JPanel mainPanel = new JPanel(new GridLayout(2, 1)); @@ -102,7 +84,7 @@ public class FileColorsConfigurablePanel extends JPanel implements Disposable { //localPanel.add(new JLabel("Local colors:"), BorderLayout.NORTH); localPanel.add(StripeTable.createScrollPane(myLocalTable), BorderLayout.CENTER); localPanel.add(Box.createVerticalStrut(10), BorderLayout.SOUTH); - localPanel.add(buildButtons(myLocalTable, "Share", new ActionListener() { + localPanel.add(buildButtons(manager, myLocalTable, "Share", new ActionListener() { public void actionPerformed(ActionEvent e) { share(); } @@ -128,7 +110,7 @@ public class FileColorsConfigurablePanel extends JPanel implements Disposable { sharedPanel.setBorder(BorderFactory.createTitledBorder("Shared colors:")); //sharedPanel.add(new JLabel("Shared colors:"), BorderLayout.NORTH); sharedPanel.add(StripeTable.createScrollPane(mySharedTable), BorderLayout.CENTER); - sharedPanel.add(buildButtons(mySharedTable, "Unshare", new ActionListener() { + sharedPanel.add(buildButtons(manager, mySharedTable, "Unshare", new ActionListener() { public void actionPerformed(ActionEvent e) { unshare(); } @@ -151,6 +133,23 @@ public class FileColorsConfigurablePanel extends JPanel implements Disposable { add(warningPanel, BorderLayout.SOUTH); } + private static JButton createAddButton(final FileColorSettingsTable table, final FileColorManagerImpl manager) { + final JButton addButton = new JButton("Add..."); + addButton.setMaximumSize(new Dimension(Integer.MAX_VALUE, addButton.getMaximumSize().height)); + addButton.addActionListener(new ActionListener() { + public void actionPerformed(ActionEvent e) { + final FileColorConfigurationEditDialog dialog = new FileColorConfigurationEditDialog(manager, null); + dialog.show(); + + if (dialog.getExitCode() == 0) { + table.addConfiguration(dialog.getConfiguration()); + } + } + }); + + return addButton; + } + private void unshare() { final int rowCount = mySharedTable.getSelectedRowCount(); if (rowCount > 0) { @@ -177,10 +176,15 @@ public class FileColorsConfigurablePanel extends JPanel implements Disposable { } } - private static Component buildButtons(final FileColorSettingsTable table, final String shareButtonText, final ActionListener shareButtonListener) { + private static Component buildButtons(final FileColorManagerImpl manager, + final FileColorSettingsTable table, + final String shareButtonText, + final ActionListener shareButtonListener) { final JPanel result = new JPanel(); result.setLayout(new BoxLayout(result, BoxLayout.Y_AXIS)); + result.add(createAddButton(table, manager)); + final JButton removeButton = new JButton("Remove"); result.add(removeButton); removeButton.setMaximumSize(new Dimension(Integer.MAX_VALUE, removeButton.getMaximumSize().height)); diff --git a/platform/lang-impl/src/com/intellij/util/indexing/FileBasedIndex.java b/platform/lang-impl/src/com/intellij/util/indexing/FileBasedIndex.java index 646901f738a1..93ce6f2c0d53 100644 --- a/platform/lang-impl/src/com/intellij/util/indexing/FileBasedIndex.java +++ b/platform/lang-impl/src/com/intellij/util/indexing/FileBasedIndex.java @@ -832,27 +832,35 @@ public class FileBasedIndex implements ApplicationComponent { void process(final int inputId, V value); } - public void processAllValues(final ID indexId, AllValuesProcessor processor, @NotNull Project project) { + public void processAllValues(final ID indexId, final AllValuesProcessor processor, @NotNull Project project) { try { ensureUpToDate(indexId, project, null); final UpdatableIndex index = getIndex(indexId); if (index == null) { return; } - try { - index.getReadLock().lock(); - for (K dataKey : index.getAllKeys()) { - final ValueContainer container = index.getData(dataKey); - for (final Iterator it = container.getValueIterator(); it.hasNext();) { - final V value = it.next(); - for (final ValueContainer.IntIterator inputsIt = container.getInputIdsIterator(value); inputsIt.hasNext();) { - processor.process(inputsIt.next(), value); + final Ref storageEx = new Ref(null); + index.processAllKeys(new Processor() { + public boolean process(K dataKey) { + try { + final ValueContainer container = index.getData(dataKey); + for (final Iterator it = container.getValueIterator(); it.hasNext();) { + final V value = it.next(); + for (final ValueContainer.IntIterator inputsIt = container.getInputIdsIterator(value); inputsIt.hasNext();) { + processor.process(inputsIt.next(), value); + } } + return true; + } + catch (StorageException e) { + storageEx.set(e); + return false; } } - } - finally { - index.getReadLock().unlock(); + }); + final StorageException ex = storageEx.get(); + if (ex != null) { + throw ex; } } catch (StorageException e) { @@ -1030,51 +1038,66 @@ public class FileBasedIndex implements ApplicationComponent { } } - // returns false if doc was not indexed because the file does not fit in scope - private boolean indexUnsavedDocument(final Document document, final ID requestedIndexId, Project project, GlobalSearchScope filter) throws StorageException { - final VirtualFile vFile = myFileDocumentManager.getFile(document); - if (!(vFile instanceof VirtualFileWithId) || !vFile.isValid()) { - return true; - } - if (filter != null && !filter.accept(vFile)) { - return false; - } - final PsiFile dominantContentFile = findDominantPsiForDocument(document, project); - - DocumentContent content; - if (dominantContentFile != null && dominantContentFile.getModificationStamp() != document.getModificationStamp()) { - content = new PsiContent(document, dominantContentFile); - } - else { - content = new AuthenticContent(document); - } - - final long currentDocStamp = content.getModificationStamp(); - if (currentDocStamp != myLastIndexedDocStamps.getAndSet(document, requestedIndexId, currentDocStamp).longValue()) { - final FileContent newFc = new FileContent(vFile, content.getText(), vFile.getCharset()); - - if (dominantContentFile != null) { - dominantContentFile.putUserData(PsiFileImpl.BUILDING_STUB, true); - newFc.putUserData(PSI_FILE, dominantContentFile); - } - - if (content instanceof AuthenticContent) { - newFc.putUserData(EDITOR_HIGHLIGHTER, document instanceof DocumentImpl - ? ((DocumentImpl)document).getEditorHighlighterForCachesBuilding() : null); - } - - if (getInputFilter(requestedIndexId).acceptInput(vFile)) { - newFc.putUserData(PROJECT, project); - final int inputId = Math.abs(getFileId(vFile)); - getIndex(requestedIndexId).update(inputId, newFc); - } - - if (dominantContentFile != null) { - dominantContentFile.putUserData(PsiFileImpl.BUILDING_STUB, null); - } - } +// returns false if doc was not indexed because the file does not fit in scope +private boolean indexUnsavedDocument(final Document document, final ID requestedIndexId, final Project project, + GlobalSearchScope filter) throws StorageException { + final VirtualFile vFile = myFileDocumentManager.getFile(document); + if (!(vFile instanceof VirtualFileWithId) || !vFile.isValid()) { return true; } + if (filter != null && !filter.accept(vFile)) { + return false; + } + final PsiFile dominantContentFile = findDominantPsiForDocument(document, project); + + final DocumentContent content; + if (dominantContentFile != null && dominantContentFile.getModificationStamp() != document.getModificationStamp()) { + content = new PsiContent(document, dominantContentFile); + } + else { + content = new AuthenticContent(document); + } + + final long currentDocStamp = content.getModificationStamp(); + if (currentDocStamp != myLastIndexedDocStamps.getAndSet(document, requestedIndexId, currentDocStamp).longValue()) { + final Ref exRef = new Ref(null); + ProgressManager.getInstance().executeNonCancelableSection(new Runnable() { + public void run() { + try { + final FileContent newFc = new FileContent(vFile, content.getText(), vFile.getCharset()); + + if (dominantContentFile != null) { + dominantContentFile.putUserData(PsiFileImpl.BUILDING_STUB, true); + newFc.putUserData(PSI_FILE, dominantContentFile); + } + + if (content instanceof AuthenticContent) { + newFc.putUserData(EDITOR_HIGHLIGHTER, document instanceof DocumentImpl + ? ((DocumentImpl)document).getEditorHighlighterForCachesBuilding() : null); + } + + if (getInputFilter(requestedIndexId).acceptInput(vFile)) { + newFc.putUserData(PROJECT, project); + final int inputId = Math.abs(getFileId(vFile)); + getIndex(requestedIndexId).update(inputId, newFc); + } + + if (dominantContentFile != null) { + dominantContentFile.putUserData(PsiFileImpl.BUILDING_STUB, null); + } + } + catch (StorageException e) { + exRef.set(e); + } + } + }); + final StorageException storageException = exRef.get(); + if (storageException != null) { + throw storageException; + } + } + return true; +} public static final Key PSI_FILE = new Key("PSI for stubs"); public static final Key EDITOR_HIGHLIGHTER = new Key("Editor"); @@ -1249,7 +1272,21 @@ public class FileBasedIndex implements ApplicationComponent { final UpdatableIndex index = getIndex(indexId); assert index != null; - index.update(inputId, currentFC); + final Ref exRef = new Ref(null); + ProgressManager.getInstance().executeNonCancelableSection(new Runnable() { + public void run() { + try { + index.update(inputId, currentFC); + } + catch (StorageException e) { + exRef.set(e); + } + } + }); + final StorageException storageException = exRef.get(); + if (storageException != null) { + throw storageException; + } ApplicationManager.getApplication().runReadAction(new Runnable() { public void run() { if (file.isValid()) { diff --git a/platform/lang-impl/src/com/intellij/util/ui/classpath/ChooseLibrariesDialog.java b/platform/lang-impl/src/com/intellij/util/ui/classpath/ChooseLibrariesDialog.java new file mode 100644 index 000000000000..caf671f2bdd2 --- /dev/null +++ b/platform/lang-impl/src/com/intellij/util/ui/classpath/ChooseLibrariesDialog.java @@ -0,0 +1,345 @@ +package com.intellij.util.ui.classpath; + +import com.intellij.ide.CommonActionsManager; +import com.intellij.ide.DefaultTreeExpander; +import com.intellij.ide.TreeExpander; +import com.intellij.ide.util.treeView.AbstractTreeBuilder; +import com.intellij.ide.util.treeView.AbstractTreeStructure; +import com.intellij.ide.util.treeView.NodeDescriptor; +import com.intellij.openapi.actionSystem.ActionManager; +import com.intellij.openapi.actionSystem.ActionPlaces; +import com.intellij.openapi.actionSystem.DefaultActionGroup; +import com.intellij.openapi.application.Application; +import com.intellij.openapi.application.ApplicationManager; +import com.intellij.openapi.module.Module; +import com.intellij.openapi.module.ModuleManager; +import com.intellij.openapi.project.Project; +import com.intellij.openapi.project.ProjectManager; +import com.intellij.openapi.roots.LibraryOrderEntry; +import com.intellij.openapi.roots.ModuleRootManager; +import com.intellij.openapi.roots.OrderEntry; +import com.intellij.openapi.roots.impl.libraries.LibraryTableImplUtil; +import com.intellij.openapi.roots.libraries.Library; +import com.intellij.openapi.roots.libraries.LibraryTable; +import com.intellij.openapi.roots.libraries.LibraryTablesRegistrar; +import com.intellij.openapi.roots.ui.util.OrderEntryCellAppearanceUtils; +import com.intellij.openapi.ui.DialogWrapper; +import com.intellij.openapi.util.Disposer; +import com.intellij.openapi.util.text.StringUtil; +import com.intellij.ui.ScrollPaneFactory; +import com.intellij.ui.SimpleColoredComponent; +import com.intellij.ui.treeStructure.SimpleNode; +import com.intellij.ui.treeStructure.SimpleTree; +import com.intellij.ui.treeStructure.WeightBasedComparator; +import com.intellij.util.CommonProcessors; +import com.intellij.util.Icons; +import com.intellij.util.Processor; +import com.intellij.util.ui.UIUtil; +import gnu.trove.THashMap; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +import javax.swing.*; +import javax.swing.event.TreeSelectionEvent; +import javax.swing.event.TreeSelectionListener; +import javax.swing.tree.DefaultMutableTreeNode; +import javax.swing.tree.DefaultTreeModel; +import java.awt.*; +import java.awt.event.KeyEvent; +import java.awt.event.MouseAdapter; +import java.awt.event.MouseEvent; +import java.util.*; +import java.util.List; + +/** + * @author Gregory.Shrago + */ + +public class ChooseLibrariesDialog extends DialogWrapper{ + + private SimpleTree myTree = new SimpleTree(); + private AbstractTreeBuilder myBuilder; + + private List myResult; + private Map myLibraryMap = new THashMap(); + + protected ChooseLibrariesDialog(final Project project, final String title) { + super(project, false); + setTitle(title); + init(); + updateOKAction(); + } + + @Override + protected String getDimensionServiceKey() { + return "#com.intellij.javaee.module.view.dataSource.ChooseLibrariesDialog"; + } + + @Override + protected void doOKAction() { + processSelection(new CommonProcessors.CollectProcessor(myResult = new ArrayList())); + super.doOKAction(); + } + + private void updateOKAction() { + setOKActionEnabled(!processSelection(new CommonProcessors.FindFirstProcessor())); + } + + @Override + public JComponent getPreferredFocusedComponent() { + return myTree; + } + + @NotNull + public List getSelectedLibraries() { + return myResult == null? Collections.emptyList() : myResult; + } + + private boolean processSelection(final Processor processor) { + for (Object element : myBuilder.getSelectedElements()) { + if (element instanceof Library) { + if (!processor.process((Library)element)) return false; + } + } + return true; + } + + protected boolean acceptsElement(final Object element) { + return true; + } + + @Override + protected JComponent createNorthPanel() { + final DefaultActionGroup group = new DefaultActionGroup(); + final TreeExpander expander = new DefaultTreeExpander(myTree); + final CommonActionsManager actionsManager = CommonActionsManager.getInstance(); + group.add(actionsManager.createExpandAllAction(expander, myTree)); + group.add(actionsManager.createCollapseAllAction(expander, myTree)); + final JComponent component = ActionManager.getInstance().createActionToolbar(ActionPlaces.PROJECT_VIEW_TOOLBAR, group, true).getComponent(); + component.setBorder(BorderFactory.createCompoundBorder(BorderFactory.createMatteBorder(0, 0, 1, 0, Color.darkGray), component.getBorder())); + return component; + } + + @Nullable + protected JComponent createCenterPanel() { + myBuilder = new AbstractTreeBuilder(myTree, new DefaultTreeModel(new DefaultMutableTreeNode()), + new MyStructure(ProjectManager.getInstance().getDefaultProject()), + WeightBasedComparator.FULL_INSTANCE); + myBuilder.initRootNode(); + + myTree.setDragEnabled(false); + myTree.getSelectionModel().setSelectionMode(ListSelectionModel.SINGLE_SELECTION); + myTree.setRowHeight(Icons.CLASS_ICON.getIconHeight()); + + myTree.setShowsRootHandles(true); + UIUtil.setLineStyleAngled(myTree); + + myTree.setRootVisible(false); + myTree.getSelectionModel().setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION); + myTree.addTreeSelectionListener(new TreeSelectionListener() { + public void valueChanged(final TreeSelectionEvent e) { + updateOKAction(); + } + }); + myTree.addMouseListener(new MouseAdapter() { + public void mouseClicked(final MouseEvent e) { + if (e.getClickCount() != 2) return; + if (isOKActionEnabled()) { + doOKAction(); + } + } + }); + myTree.getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0), "ENTER"); + myTree.getActionMap().put("ENTER", getOKAction()); + return ScrollPaneFactory.createScrollPane(myTree); + } + + protected void dispose() { + Disposer.dispose(myBuilder); + super.dispose(); + } + + private static class MyNode extends SimpleNode { + private final T myElement; + + private MyNode(Project project, NodeDescriptor parentDescriptor, T element) { + super(project, parentDescriptor); + myElement = element; + } + + public T getElement() { + return myElement; + } + + @Override + public SimpleNode[] getChildren() { + return NO_CHILDREN; + } + + @Override + public int getWeight() { + return 0; + } + + @Override + public Object[] getEqualityObjects() { + return new Object[] {myElement}; + } + } + + private static class RootDescriptor extends MyNode { + protected RootDescriptor(final Project project) { + super(project, null, ApplicationManager.getApplication()); + } + } + + private static class ProjectDescriptor extends MyNode { + protected ProjectDescriptor(final Project project, final Project element) { + super(project, null, element); + } + + @Override + protected void doUpdate() { + setIcons(Icons.PROJECT_ICON, Icons.PROJECT_ICON); + final String nodeText = getElement().getName(); + setNodeText(StringUtil.isNotEmpty(nodeText) ? nodeText : "", null, false); + } + } + + private static class ModuleDescriptor extends MyNode { + protected ModuleDescriptor(final Project project, final NodeDescriptor parentDescriptor, final Module element) { + super(project, parentDescriptor, element); + } + + @Override + protected void doUpdate() { + setIcons(getElement().getModuleType().getNodeIcon(false), getElement().getModuleType().getNodeIcon(true)); + final String nodeText = getElement().getName(); + setNodeText(StringUtil.isNotEmpty(nodeText) ? nodeText : "", null, false); + } + + @Override + public int getWeight() { + return 1; + } + } + + private static class LibraryDescriptor extends MyNode { + private final Icon myIcon; + + protected LibraryDescriptor(final Project project, final NodeDescriptor parentDescriptor, final Library element) { + super(project, parentDescriptor, element); + final SimpleColoredComponent coloredComponent = new SimpleColoredComponent(); + OrderEntryCellAppearanceUtils.forLibrary(getElement()).customize(coloredComponent); + myIcon = coloredComponent.getIcon(); + } + + @Override + protected void doUpdate() { + setIcons(myIcon, myIcon); + final String nodeText = OrderEntryCellAppearanceUtils.forLibrary(getElement()).getText(); + setNodeText(StringUtil.isNotEmpty(nodeText) ? nodeText : "", null, false); + } + } + + private static class NamedDescriptor extends MyNode { + private final int myWeight; + + protected NamedDescriptor(final Project project, final NodeDescriptor parentDescriptor, final LibraryTable table, final int weight) { + super(project, parentDescriptor, table); + myWeight = weight; + } + + @Override + protected void doUpdate() { + setIcons(Icons.DIRECTORY_CLOSED_ICON, Icons.DIRECTORY_OPEN_ICON); + final String nodeText = getElement().getPresentation().getDisplayName(true); + setNodeText(StringUtil.isNotEmpty(nodeText) ? nodeText : "", null, false); + } + + @Override + public int getWeight() { + return myWeight; + } + } + + private class MyStructure extends AbstractTreeStructure { + private final Project myProject; + + public MyStructure(Project project) { + myProject = project; + } + + @Override + public Object getRootElement() { + return ApplicationManager.getApplication(); + } + + @Override + public Object[] getChildElements(Object element) { + final ArrayList result = new ArrayList(); + if (element instanceof Application) { + Collections.addAll(result, ProjectManager.getInstance().getOpenProjects()); + final LibraryTablesRegistrar instance = LibraryTablesRegistrar.getInstance(); + result.add(instance.getLibraryTable()); //1 + result.addAll(instance.getCustomLibraryTables()); //2 + } + else if (element instanceof Project) { + Collections.addAll(result, ModuleManager.getInstance((Project)element).getModules()); + result.add(LibraryTablesRegistrar.getInstance().getLibraryTable((Project)element)); + } + else if (element instanceof LibraryTable) { + Collections.addAll(result, ((LibraryTable)element).getLibraries()); + } + else if (element instanceof Module) { + for (OrderEntry entry : ModuleRootManager.getInstance((Module)element).getOrderEntries()) { + if (entry instanceof LibraryOrderEntry) { + final LibraryOrderEntry libraryOrderEntry = (LibraryOrderEntry)entry; + if (LibraryTableImplUtil.MODULE_LEVEL.equals(libraryOrderEntry.getLibraryLevel())) { + final Library library = libraryOrderEntry.getLibrary(); + result.add(library); + } + } + } + } + final Iterator it = result.iterator(); + while (it.hasNext()) { + if (!acceptsElement(it.next())) it.remove(); + } + for (Object o : result) { + myLibraryMap.put(o, element); + } + return result.toArray(); + } + + @Override + public Object getParentElement(Object element) { + if (element instanceof Application) return null; + if (element instanceof Project) return ApplicationManager.getApplication(); + if (element instanceof Module) return ((Module)element).getProject(); + if (element instanceof LibraryTable) return myLibraryMap.get(element); + if (element instanceof Library) return myLibraryMap.get(element); + throw new AssertionError(); + } + + @NotNull + @Override + public NodeDescriptor createDescriptor(Object element, NodeDescriptor parentDescriptor) { + if (element instanceof Application) return new RootDescriptor(myProject); + if (element instanceof Project) return new ProjectDescriptor(myProject, (Project)element); + if (element instanceof Module) return new ModuleDescriptor(myProject, parentDescriptor, (Module)element); + if (element instanceof LibraryTable) return new NamedDescriptor(myProject, parentDescriptor, (LibraryTable)element, 0); + if (element instanceof Library) return new LibraryDescriptor(myProject, parentDescriptor, (Library)element); + throw new AssertionError(); + } + + @Override + public void commit() { + } + + @Override + public boolean hasSomethingToCommit() { + return false; + } + } +} diff --git a/platform/lang-impl/src/com/intellij/util/ui/classpath/GlobalLibraryReferenceElement.java b/platform/lang-impl/src/com/intellij/util/ui/classpath/GlobalLibraryReferenceElement.java new file mode 100644 index 000000000000..c02c59754706 --- /dev/null +++ b/platform/lang-impl/src/com/intellij/util/ui/classpath/GlobalLibraryReferenceElement.java @@ -0,0 +1,69 @@ +package com.intellij.util.ui.classpath; + +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.NonNls; +import org.jdom.Element; +import com.intellij.openapi.roots.libraries.LibraryTablesRegistrar; +import com.intellij.openapi.roots.libraries.LibraryTable; +import com.intellij.openapi.roots.libraries.Library; +import com.intellij.openapi.roots.OrderRootType; +import com.intellij.openapi.vfs.VirtualFile; + +import java.util.List; +import java.util.Collections; +import java.util.ArrayList; +import java.io.IOException; + +/** + * @author nik + */ +public class GlobalLibraryReferenceElement implements SimpleClasspathElement { + @NonNls public static final String NAME_ATTRIBUTE = "name"; + @NonNls public static final String LEVEL_ATTRIBUTE = "level"; + private final String myLibraryName; + + public GlobalLibraryReferenceElement(@NotNull String libraryName) { + myLibraryName = libraryName; + } + + public GlobalLibraryReferenceElement(@NotNull Element element) { + myLibraryName = element.getAttributeValue(NAME_ATTRIBUTE); + } + + public String getPresentableName() { + return myLibraryName; + } + + public void writeExternal(Element element) { + element.setAttribute(NAME_ATTRIBUTE, myLibraryName); + //todo[nik,greg] remote later. this is needed only for forward compatibility with version before 8 + element.setAttribute(LEVEL_ATTRIBUTE, LibraryTablesRegistrar.APPLICATION_LEVEL); + } + + public Library getLibrary() { + final LibraryTable libraryTable = LibraryTablesRegistrar.getInstance().getLibraryTable(); + return libraryTable.getLibraryByName(myLibraryName); + } + + public String getLibraryName() { + return myLibraryName; + } + + public void serialize(Element element) throws IOException { + element.setAttribute(NAME_ATTRIBUTE, myLibraryName); + //todo[nik,greg] remote later. this is needed only for forward compatibility with version before 8 + element.setAttribute(LEVEL_ATTRIBUTE, LibraryTablesRegistrar.APPLICATION_LEVEL); + } + + public List getClassesRootUrls() { + final Library library = getLibrary(); + if (library != null) { + final List list = new ArrayList(); + for (VirtualFile file : library.getFiles(OrderRootType.CLASSES)) { + list.add(file.getUrl()); + } + return list; + } + return Collections.emptyList(); + } +} diff --git a/platform/lang-impl/src/com/intellij/util/ui/classpath/SimpleClasspathElement.java b/platform/lang-impl/src/com/intellij/util/ui/classpath/SimpleClasspathElement.java new file mode 100644 index 000000000000..b353a925023a --- /dev/null +++ b/platform/lang-impl/src/com/intellij/util/ui/classpath/SimpleClasspathElement.java @@ -0,0 +1,26 @@ +package com.intellij.util.ui.classpath; + +import com.intellij.openapi.roots.libraries.Library; +import org.jdom.Element; +import org.jetbrains.annotations.Nullable; + +import java.io.IOException; +import java.util.List; + +/** + * @author nik + */ +public interface SimpleClasspathElement { + + String getPresentableName(); + + List getClassesRootUrls(); + + @Nullable + Library getLibrary(); + + @Nullable + String getLibraryName(); + + void serialize(Element element) throws IOException; +} diff --git a/platform/lang-impl/src/com/intellij/util/ui/classpath/SimpleClasspathElementFactory.java b/platform/lang-impl/src/com/intellij/util/ui/classpath/SimpleClasspathElementFactory.java new file mode 100644 index 000000000000..883daa1516a6 --- /dev/null +++ b/platform/lang-impl/src/com/intellij/util/ui/classpath/SimpleClasspathElementFactory.java @@ -0,0 +1,71 @@ +package com.intellij.util.ui.classpath; + +import com.intellij.openapi.project.Project; +import com.intellij.openapi.roots.OrderRootType; +import com.intellij.openapi.roots.libraries.Library; +import com.intellij.openapi.roots.libraries.LibraryTable; +import com.intellij.openapi.roots.libraries.LibraryTablesRegistrar; +import com.intellij.openapi.util.text.StringUtil; +import com.intellij.openapi.vfs.VirtualFile; +import org.jdom.Element; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +/** + * @author nik + */ +public class SimpleClasspathElementFactory { + private SimpleClasspathElementFactory() { + } + + + public static List createElements(@Nullable Project project, @NotNull Element element) { + final String name = element.getAttributeValue(GlobalLibraryReferenceElement.NAME_ATTRIBUTE); + final String level = element.getAttributeValue(GlobalLibraryReferenceElement.LEVEL_ATTRIBUTE); + final String url = element.getChildText(SingleRootClasspathElement.URL_ELEMENT); + if (!StringUtil.isEmpty(url)) { + return Collections.singletonList(new SingleRootClasspathElement(url)); + } + if (name == null || level == null) { + return Collections.emptyList(); + } + if (LibraryTablesRegistrar.APPLICATION_LEVEL.equals(level)) { + return Collections.singletonList(new GlobalLibraryReferenceElement(name)); + } + //this is needed only for backward compatibility with version before 8 + if (project != null) { + final LibraryTable libraryTable = LibraryTablesRegistrar.getInstance().getLibraryTableByLevel(level, project); + if (libraryTable != null) { + final Library library = libraryTable.getLibraryByName(name); + if (library != null) { + return createElements(library); + } + } + } + return Collections.emptyList(); + } + + public static List createElements(@NotNull Library library) { + final LibraryTable table = library.getTable(); + if (table != null && LibraryTablesRegistrar.APPLICATION_LEVEL.equals(table.getTableLevel())) { + return Collections.singletonList(new GlobalLibraryReferenceElement(library.getName())); + } + final List elements = new ArrayList(); + for (VirtualFile file : library.getFiles(OrderRootType.CLASSES)) { + elements.add(new SingleRootClasspathElement(file.getUrl())); + } + return elements; + } + + public static List createElements(String... urls) { + final List list = new ArrayList(); + for (String url : urls) { + list.add(new SingleRootClasspathElement(url)); + } + return list; + } +} diff --git a/platform/lang-impl/src/com/intellij/util/ui/classpath/SimpleClasspathPanel.java b/platform/lang-impl/src/com/intellij/util/ui/classpath/SimpleClasspathPanel.java new file mode 100644 index 000000000000..05ee68ba51fa --- /dev/null +++ b/platform/lang-impl/src/com/intellij/util/ui/classpath/SimpleClasspathPanel.java @@ -0,0 +1,406 @@ +/* + * Copyright (c) 2000-2006 JetBrains s.r.o. All Rights Reserved. + */ + +package com.intellij.util.ui.classpath; + +import com.intellij.openapi.Disposable; +import com.intellij.openapi.actionSystem.*; +import com.intellij.openapi.application.ApplicationManager; +import com.intellij.openapi.application.ModalityState; +import com.intellij.openapi.fileChooser.FileChooserDescriptor; +import com.intellij.openapi.fileChooser.ex.FileChooserDialogImpl; +import com.intellij.openapi.project.ProjectBundle; +import com.intellij.openapi.project.ProjectManager; +import com.intellij.openapi.roots.OrderRootType; +import com.intellij.openapi.roots.impl.libraries.LibraryTableImplUtil; +import com.intellij.openapi.roots.libraries.Library; +import com.intellij.openapi.roots.libraries.LibraryTablesRegistrar; +import com.intellij.openapi.roots.ui.util.OrderEntryCellAppearanceUtils; +import com.intellij.openapi.roots.ui.util.SimpleTextCellAppearance; +import com.intellij.openapi.ui.Messages; +import com.intellij.openapi.ui.ex.MultiLineLabel; +import com.intellij.openapi.ui.popup.JBPopup; +import com.intellij.openapi.ui.popup.JBPopupFactory; +import com.intellij.openapi.ui.popup.PopupStep; +import com.intellij.openapi.ui.popup.util.BaseListPopupStep; +import com.intellij.openapi.util.Disposer; +import com.intellij.openapi.util.IconLoader; +import com.intellij.openapi.vfs.VirtualFile; +import com.intellij.ui.ColoredListCellRenderer; +import com.intellij.ui.ReorderableListController; +import com.intellij.ui.ScrollPaneFactory; +import com.intellij.util.Icons; +import com.intellij.util.PathUtil; +import gnu.trove.THashSet; +import org.jetbrains.annotations.NotNull; + +import javax.swing.*; +import javax.swing.event.ListDataEvent; +import javax.swing.event.ListDataListener; +import java.awt.*; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.io.File; +import java.net.MalformedURLException; +import java.net.URL; +import java.net.URLClassLoader; +import java.util.*; +import java.util.List; + +/** + * @author Gregory.Shrago + */ +public class SimpleClasspathPanel extends JPanel { + + private final JList myList = new JList(); + private final DefaultListModel myListModel = new DefaultListModel(); + private URLClassLoader myClassLoader; + private final Disposable myDisposable; + + + public SimpleClasspathPanel(final List classpathElements, final Disposable parentDisposable) { + myDisposable = parentDisposable; + for (Library library : getLibrariesList(classpathElements, parentDisposable)) { + myListModel.addElement(library); + } + init(); + } + + private void init() { + setLayout(new BorderLayout()); + myList.setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION); + myList.setModel(myListModel); + final DefaultActionGroup actionGroup = new DefaultActionGroup(); + final ReorderableListController controller = ReorderableListController.create(myList, actionGroup); + controller.addAction(new AddAction()); + controller.addRemoveAction(ProjectBundle.message("module.remove.action")); + controller.addMoveUpAction(); + controller.addMoveDownAction(); + myList.setCellRenderer(new ColoredListCellRenderer() { + protected void customizeCellRenderer(JList list, Object value, int index, boolean selected, boolean hasFocus) { + if (value instanceof Library) { + final Library library = (Library)value; + if (library.getName() != null && library.getUrls(OrderRootType.CLASSES).length == 0) { + SimpleTextCellAppearance.invalid(library.getName(), Icons.LIBRARY_ICON).customize(this); + } + else { + OrderEntryCellAppearanceUtils.forLibrary(library).customize(this); + } + } + } + }); + add(ActionManager.getInstance().createActionToolbar(ActionPlaces.PROJECT_VIEW_TOOLBAR, actionGroup, true).getComponent(), BorderLayout.NORTH); + final JScrollPane scrollPane = ScrollPaneFactory.createScrollPane(myList); + add(scrollPane, BorderLayout.CENTER); + final FontMetrics fontMetrics = myList.getFontMetrics(myList.getFont()); + scrollPane.setPreferredSize(new Dimension(0, fontMetrics.getHeight() * 12)); + myList.getModel().addListDataListener(new ListDataListener() { + public void intervalAdded(ListDataEvent e) { + } + + public void intervalRemoved(ListDataEvent e) { + listChanged(e); + } + + public void contentsChanged(ListDataEvent e) { + } + }); + } + + private void listChanged(final ListDataEvent e) { + myClassLoader = null; + processClasspathChanged(); + } + + public void processClasspathChanged() { + } + + public List getOrderedLibraries() { + final ArrayList result = new ArrayList(); + for (final Enumeration enumeration = myListModel.elements(); enumeration.hasMoreElements(); ) { + result.add((Library)enumeration.nextElement()); + } + return result; + } + + public Set getVirtualFiles() { + final THashSet result = new THashSet(); + for (final Enumeration enumeration = myListModel.elements(); enumeration.hasMoreElements(); ) { + final Library library = (Library)enumeration.nextElement(); + result.addAll(Arrays.asList(library.getFiles(OrderRootType.CLASSES))); + } + return result; + } + + public URLClassLoader getClasspathLoader(ClassLoader parent) { + if (myClassLoader == null || myClassLoader.getParent() != parent) { + ArrayList urlList = new ArrayList(); + for (Library library : getOrderedLibraries()) { + for (VirtualFile virtualFile : library.getFiles(OrderRootType.CLASSES)) { + final File file = new File(PathUtil.toPresentableUrl(virtualFile.getUrl())); + try { + urlList.add(file.toURL()); + } + catch (MalformedURLException e) { + } + } + } + URL[] urls = urlList.toArray(new URL[urlList.size()]); + myClassLoader = new URLClassLoader(urls, parent); + } + return myClassLoader; + } + + public static void scrollSelectionToVisible(JList list){ + ListSelectionModel selectionModel = list.getSelectionModel(); + int maxSelectionIndex = selectionModel.getMaxSelectionIndex(); + int minSelectionIndex = selectionModel.getMinSelectionIndex(); + if(maxSelectionIndex == -1){ + return; + } + Rectangle cellRect = list.getCellBounds(minSelectionIndex, maxSelectionIndex); + list.scrollRectToVisible(cellRect); + } + + private static Collection ensureApplicationLevel(final Library library, final Set existingFiles, + final Disposable parentDisposable) { + if (library.getTable() == null || !LibraryTablesRegistrar.APPLICATION_LEVEL.equals(library.getTable().getTableLevel())) { + final ArrayList result = new ArrayList(); + for (VirtualFile file : library.getFiles(OrderRootType.CLASSES)) { + if (!existingFiles.add(file)) continue; + final Library newLibrary = LibraryTableImplUtil.createModuleLevelLibrary(null, null); + Disposer.register(parentDisposable, newLibrary); + final Library.ModifiableModel libModel = newLibrary.getModifiableModel(); + libModel.addRoot(file, OrderRootType.CLASSES); + libModel.commit(); + result.add(newLibrary); + } + return result; + } + return Collections.singletonList(library); + } + + private abstract static class PopupAction implements ActionListener { + private final String myTitle; + private final Icon myIcon; + private final int myIndex; + + protected PopupAction(String title, Icon icon, final int index) { + myTitle = title; + myIcon = icon; + myIndex = index; + } + + public String getTitle() { + return myTitle; + } + + public Icon getIcon() { + return myIcon; + } + + public int getIndex() { + return myIndex; + } + + protected void executeImpl() { + } + + public void execute() { + executeImpl(); + } + + public void actionPerformed(ActionEvent e) { + executeImpl(); + } + } + + private class AddAction extends AnAction { + private PopupAction[] myPopupActions; + private Icon[] myIcons; + + public AddAction() { + super(ProjectBundle.message("module.add.action"), null, IconLoader.getIcon("/general/add.png")); + } + + private void initPopupActions() { + if (myPopupActions == null) { + int index = 1; + final List actions = new ArrayList(); + actions.add(new ChooseAndAddAction(index++, "Jar...", Icons.JAR_ICON) { + @NotNull + protected List doChoose() { + final ChooseJarDialog dialog = new ChooseJarDialog(SimpleClasspathPanel.this, getVirtualFiles(), myDisposable); + dialog.doChoose(); + return dialog.getChosenElements(); + } + }); + actions.add(new ChooseAndAddAction(index++, "Library...", Icons.LIBRARY_ICON) { + + @NotNull + protected List doChoose() { + final Set existingFiles = getVirtualFiles(); + final ChooseLibrariesDialog dialog = new ChooseLibrariesDialog(ProjectManager.getInstance().getDefaultProject(), "Choose Existing Libraries") { + @Override + protected boolean acceptsElement(final Object element) { + if (!(element instanceof Library)) return true; + final Library library = (Library)element; + return !existingFiles.containsAll(Arrays.asList(library.getFiles(OrderRootType.CLASSES))); + } + + @Override + protected JComponent createCenterPanel() { + final JPanel panel = new JPanel(new BorderLayout()); + panel.add(super.createCenterPanel(), BorderLayout.CENTER); + final MultiLineLabel label = new MultiLineLabel("Please note that project-level and module-level libraries will not be\n\n" + + " added as a whole but will be converted to jars and folders instead."); + label.setIcon(Messages.getWarningIcon()); + label.setIcon(Messages.getWarningIcon()); + panel.add(label, BorderLayout.SOUTH); + return panel; + } + + }; + dialog.show(); + final List libraries = dialog.getSelectedLibraries(); + final ArrayList result = new ArrayList(); + for (Library o : libraries) { + result.addAll(ensureApplicationLevel(o, existingFiles, myDisposable)); + } + return result; + } + }); + myPopupActions = actions.toArray(new PopupAction[actions.size()]); + + myIcons = new Icon[myPopupActions.length]; + for (int idx = 0; idx < myPopupActions.length; idx++) { + myIcons[idx] = myPopupActions[idx].getIcon(); + } + } + } + + public void actionPerformed(final AnActionEvent e) { + initPopupActions(); + final JBPopup popup = JBPopupFactory.getInstance().createWizardStep(new BaseListPopupStep(null, myPopupActions, myIcons) { + public boolean isMnemonicsNavigationEnabled() { + return true; + } + + public boolean isSelectable(PopupAction value) { + return true; + } + + public PopupStep onChosen(final PopupAction selectedValue, final boolean finalChoice) { + ApplicationManager.getApplication().invokeLater(new Runnable() { + public void run() { + selectedValue.execute(); + } + }, ModalityState.stateForComponent(e.getInputEvent().getComponent())); + return PopupStep.FINAL_CHOICE; + } + + @NotNull + public String getTextFor(PopupAction value) { + return "&" + value.getIndex() + " " + value.getTitle(); + } + }); + popup.showUnderneathOf(e.getInputEvent().getComponent()); + } + + public Object fun(final AnActionEvent s) { + actionPerformed(s); + return null; + } + } + + + private abstract class ChooseAndAddAction extends PopupAction { + public ChooseAndAddAction(int index, String title, Icon icon) { + super(title, icon, index); + } + + protected final void executeImpl() { + final List libraries = doChoose(); + if (libraries.isEmpty()) return; + final int index0 = myListModel.size(); + for (Library library : libraries) { + myListModel.addElement(library); + } + final int index1 = myListModel.size()-1; + final ListSelectionModel selectionModel = myList.getSelectionModel(); + final int rowCount = myList.getModel().getSize(); + selectionModel.setSelectionInterval(rowCount - libraries.size(), rowCount - 1); + scrollSelectionToVisible(myList); + listChanged(new ListDataEvent(myListModel, ListDataEvent.INTERVAL_ADDED, index0, index1)); + } + + @NotNull + protected abstract List doChoose(); + } + + private static class ChooseJarDialog extends FileChooserDialogImpl { + private VirtualFile[] myLastChosen; + private final Disposable myParentDisposable; + + public ChooseJarDialog(Component parent, final Set existingFiles, final Disposable disposable) { + super(new FileChooserDescriptor(false, true, true, false, false, true) { + @Override + public boolean isFileVisible(final VirtualFile file, final boolean showHiddenFiles) { + if (!super.isFileVisible(file, showHiddenFiles)) return false; + return file.isDirectory() || !existingFiles.contains(file); + } + }, parent); + myParentDisposable = disposable; + } + + public List getChosenElements() { + if (myLastChosen == null) { + return Collections.emptyList(); + } + final VirtualFile[] files = myLastChosen; + if (files.length == 0) { + return Collections.emptyList(); + } + final List addedLibraries = new ArrayList(files.length); + for (VirtualFile file : files) { + final Library library = LibraryTableImplUtil.createModuleLevelLibrary(null, null); + Disposer.register(myParentDisposable, library); + final Library.ModifiableModel libModel = library.getModifiableModel(); + libModel.addRoot(file, OrderRootType.CLASSES); + libModel.commit(); + addedLibraries.add(library); + } + return addedLibraries; + } + + public void doChoose() { + myLastChosen = choose(null, null); + } + } + + private static List getLibrariesList(final List classpathElements, final Disposable disposable) { + ArrayList result = new ArrayList(); + for (SimpleClasspathElement classpathElement : classpathElements) { + final Library library = classpathElement.getLibrary(); + if (library != null && library.getTable() != null) { + result.add(library); + } + else { + final Library newLibrary = LibraryTableImplUtil.createModuleLevelLibrary(null, null); + Disposer.register(disposable, newLibrary); + final Library.ModifiableModel libModel = newLibrary.getModifiableModel(); + final String libName = classpathElement.getLibraryName(); + if (libName != null) libModel.setName(libName); + List fileUrls = classpathElement.getClassesRootUrls(); + for (final String fileUrl : fileUrls) { + libModel.addRoot(fileUrl, OrderRootType.CLASSES); + } + libModel.commit(); + result.add(newLibrary); + } + } + return result; + } + +} diff --git a/platform/lang-impl/src/com/intellij/util/ui/classpath/SingleRootClasspathElement.java b/platform/lang-impl/src/com/intellij/util/ui/classpath/SingleRootClasspathElement.java new file mode 100644 index 000000000000..5a716ff18db2 --- /dev/null +++ b/platform/lang-impl/src/com/intellij/util/ui/classpath/SingleRootClasspathElement.java @@ -0,0 +1,51 @@ +package com.intellij.util.ui.classpath; + +import com.intellij.openapi.roots.libraries.Library; +import com.intellij.openapi.vfs.JarFileSystem; +import org.jdom.Element; +import org.jetbrains.annotations.NonNls; +import org.jetbrains.annotations.NotNull; + +import java.io.IOException; +import java.util.Collections; +import java.util.List; + +/** + * @author nik + */ +public class SingleRootClasspathElement implements SimpleClasspathElement { + @NonNls public static final String URL_ELEMENT = "url"; + private final String myUrl; + + public SingleRootClasspathElement(@NotNull String url) { + myUrl = url; + } + + public String getPresentableName() { + String url; + if (myUrl.endsWith(JarFileSystem.JAR_SEPARATOR)) { + url = myUrl.substring(0, myUrl.length() - JarFileSystem.JAR_SEPARATOR.length()); + } + else { + url = myUrl; + } + int startIndex = Math.min(url.lastIndexOf('/') + 1, url.length() - 1); + return url.substring(startIndex); + } + + public Library getLibrary() { + return null; + } + + public String getLibraryName() { + return null; + } + + public void serialize(Element element) throws IOException { + element.addContent(new Element(URL_ELEMENT).setText(myUrl)); + } + + public List getClassesRootUrls() { + return Collections.singletonList(myUrl); + } +} diff --git a/platform/platform-api/src/com/intellij/ide/DefaultTreeExpander.java b/platform/platform-api/src/com/intellij/ide/DefaultTreeExpander.java index fafc81e221c3..c0173f474537 100644 --- a/platform/platform-api/src/com/intellij/ide/DefaultTreeExpander.java +++ b/platform/platform-api/src/com/intellij/ide/DefaultTreeExpander.java @@ -32,17 +32,26 @@ public class DefaultTreeExpander implements TreeExpander { public void expandAll() { TreeUtil.expandAll(myTree); + showSelectionCentered(); } public boolean canExpand() { - return true; + return myTree.isShowing(); } public void collapseAll() { - TreeUtil.collapseAll(myTree, 0); + TreeUtil.collapseAll(myTree, 1); + showSelectionCentered(); + } + + private void showSelectionCentered() { + final int[] rowz = myTree.getSelectionRows(); + if (rowz != null && rowz.length > 0) { + TreeUtil.showRowCentered(myTree, rowz[0], false); + } } public boolean canCollapse() { - return true; + return myTree.isShowing(); } } diff --git a/platform/platform-api/src/com/intellij/ide/util/treeView/AbstractTreeBuilder.java b/platform/platform-api/src/com/intellij/ide/util/treeView/AbstractTreeBuilder.java index ca2444a2e717..f25b77f76091 100644 --- a/platform/platform-api/src/com/intellij/ide/util/treeView/AbstractTreeBuilder.java +++ b/platform/platform-api/src/com/intellij/ide/util/treeView/AbstractTreeBuilder.java @@ -76,15 +76,23 @@ public class AbstractTreeBuilder implements Disposable { } public final void select(final Object element) { - select(element, null); + getUi().userSelect(new Object[] {element}, null, false, true); } public final void select(final Object element, @Nullable final Runnable onDone) { - getUi().select(element, onDone); + getUi().userSelect(new Object[] {element}, onDone, false, true); } public final void select(final Object element, @Nullable final Runnable onDone, boolean addToSelection) { - getUi().select(element, onDone, addToSelection); + getUi().userSelect(new Object[] {element}, onDone, addToSelection, true); + } + + public final void select(final Object[] elements, @Nullable final Runnable onDone) { + getUi().userSelect(elements, onDone, false, true); + } + + public final void select(final Object[] elements, @Nullable final Runnable onDone, boolean addToSelection) { + getUi().userSelect(elements, onDone, addToSelection, true); } public final void expand(Object element, @Nullable Runnable onDone) { @@ -99,13 +107,6 @@ public class AbstractTreeBuilder implements Disposable { getUi().collapseChildren(element, onDone); } - public final void select(final Object[] elements, @Nullable final Runnable onDone) { - getUi().select(elements, onDone); - } - - public final void select(final Object[] elements, @Nullable final Runnable onDone, boolean addToSelection) { - getUi().select(elements, onDone, addToSelection); - } protected AbstractTreeNode createSearchingTreeNodeWrapper() { return new AbstractTreeNodeWrapper(); @@ -454,7 +455,7 @@ public class AbstractTreeBuilder implements Disposable { public boolean select(Class nodeClass, TreeVisitor visitor, @Nullable Runnable onDone, boolean addToSelection) { final Object element = accept(nodeClass, visitor); if (element != null) { - getUi().select(element, onDone, addToSelection); + select(element, onDone, addToSelection); return true; } diff --git a/platform/platform-api/src/com/intellij/ide/util/treeView/AbstractTreeUi.java b/platform/platform-api/src/com/intellij/ide/util/treeView/AbstractTreeUi.java index caa41650ceca..2212a69dfc30 100644 --- a/platform/platform-api/src/com/intellij/ide/util/treeView/AbstractTreeUi.java +++ b/platform/platform-api/src/com/intellij/ide/util/treeView/AbstractTreeUi.java @@ -2414,7 +2414,7 @@ public class AbstractTreeUi { } private void insertNodesInto(final ArrayList toInsert, final DefaultMutableTreeNode parentNode) { - sortChildren(parentNode, toInsert, false, false); + sortChildren(parentNode, toInsert, false, true); final ArrayList all = new ArrayList(toInsert.size() + parentNode.getChildCount()); all.addAll(toInsert); all.addAll(TreeUtil.childrenToArray(parentNode)); @@ -2424,11 +2424,21 @@ public class AbstractTreeUi { int[] newNodeIndices = new int[toInsert.size()]; int eachNewNodeIndex = 0; + TreeMap insertSet = new TreeMap(); for (int i = 0; i < toInsert.size(); i++) { TreeNode eachNewNode = toInsert.get(i); - while (all.get(eachNewNodeIndex) != eachNewNode) eachNewNodeIndex++; + while (all.get(eachNewNodeIndex) != eachNewNode) { + eachNewNodeIndex++; + } newNodeIndices[i] = eachNewNodeIndex; - parentNode.insert((MutableTreeNode)eachNewNode, eachNewNodeIndex); + insertSet.put(eachNewNodeIndex, eachNewNode); + } + + Iterator indices = insertSet.keySet().iterator(); + while (indices.hasNext()) { + Integer eachIndex = indices.next(); + TreeNode eachNode = insertSet.get(eachIndex); + parentNode.insert((MutableTreeNode)eachNode, eachIndex); } myTreeModel.nodesWereInserted(parentNode, newNodeIndices); @@ -2457,7 +2467,9 @@ public class AbstractTreeUi { assert descriptor != null; if (descriptor.getChildrenSortingStamp() >= getComparatorStamp() && !forceSort) return; - getBuilder().sortChildren(myNodeComparator, node, children); + if (children.size() > 0) { + getBuilder().sortChildren(myNodeComparator, node, children); + } if (updateStamp) { descriptor.setChildrenSortingStamp(getComparatorStamp()); @@ -2508,7 +2520,7 @@ public class AbstractTreeUi { } public void select(final Object[] elements, @Nullable final Runnable onDone, boolean addToSelection, boolean deferred) { - _select(elements, onDone, addToSelection, true, false, true, deferred, false); + _select(elements, onDone, addToSelection, true, false, true, deferred, false, false); } void _select(final Object[] elements, @@ -2517,7 +2529,7 @@ public class AbstractTreeUi { final boolean checkCurrentSelection, final boolean checkIfInStructure) { - _select(elements, onDone, addToSelection, checkCurrentSelection, checkIfInStructure, true, false, false); + _select(elements, onDone, addToSelection, checkCurrentSelection, checkIfInStructure, true, false, false, false); } void _select(final Object[] elements, @@ -2527,7 +2539,14 @@ public class AbstractTreeUi { final boolean checkIfInStructure, final boolean scrollToVisible) { - _select(elements, onDone, addToSelection, checkCurrentSelection, checkIfInStructure, scrollToVisible, false, false); + _select(elements, onDone, addToSelection, checkCurrentSelection, checkIfInStructure, scrollToVisible, false, false, false); + } + + public void userSelect(final Object[] elements, + final Runnable onDone, + final boolean addToSelection, + boolean scroll) { + _select(elements, onDone, addToSelection, true, false, scroll, false, true, true); } void _select(final Object[] elements, @@ -2537,7 +2556,14 @@ public class AbstractTreeUi { final boolean checkIfInStructure, final boolean scrollToVisible, final boolean deferred, - final boolean canSmartExpand) { + final boolean canSmartExpand, + final boolean mayQueue) { + + AbstractTreeUpdater updater = getUpdater(); + if (mayQueue && updater != null) { + updater.queueSelection(new SelectionRequest(elements, onDone, addToSelection, checkCurrentSelection, checkIfInStructure, scrollToVisible, deferred, canSmartExpand)); + return; + } boolean willAffectSelection = elements.length > 0 || (elements.length == 0 && addToSelection); if (!willAffectSelection) { diff --git a/platform/platform-api/src/com/intellij/ide/util/treeView/AbstractTreeUpdater.java b/platform/platform-api/src/com/intellij/ide/util/treeView/AbstractTreeUpdater.java index 0e793ee48d14..3b35ae4dd74b 100644 --- a/platform/platform-api/src/com/intellij/ide/util/treeView/AbstractTreeUpdater.java +++ b/platform/platform-api/src/com/intellij/ide/util/treeView/AbstractTreeUpdater.java @@ -62,6 +62,8 @@ public class AbstractTreeUpdater implements Disposable, Activatable { }; } }; + myUpdateQueue.setRestartTimerOnAdd(false); + final UiNotifyConnector uiNotifyConnector = new UiNotifyConnector(component, myUpdateQueue); Disposer.register(this, myUpdateQueue); Disposer.register(this, uiNotifyConnector); @@ -140,10 +142,10 @@ public class AbstractTreeUpdater implements Disposable, Activatable { final DefaultMutableTreeNode eachNode = eachYielding.getCurrentNode(); if (eachNode != null) { if (eachNode.isNodeAncestor(toAdd.getNode())) { - toAdd.expire(); + eachYielding.setUpdateStamp(newUpdateCount); } else { - eachYielding.setUpdateStamp(newUpdateCount); + toAdd.expire(); } } } @@ -235,7 +237,7 @@ public class AbstractTreeUpdater implements Disposable, Activatable { } }; - invokeLater(runnable); + myTreeBuilder.getReady(this).doWhenDone(runnable); } } @@ -329,4 +331,22 @@ public class AbstractTreeUpdater implements Disposable, Activatable { } return false; } + + public final void queueSelection(final SelectionRequest request) { + queue(new Update("UserSelection", Update.LOW_PRIORITY) { + public void run() { + request.execute(myTreeBuilder.getUi()); + } + + @Override + public boolean isExpired() { + return myTreeBuilder.isDisposed(); + } + + @Override + public void setRejected() { + request.reject(); + } + }); + } } diff --git a/platform/platform-api/src/com/intellij/ide/util/treeView/SelectionRequest.java b/platform/platform-api/src/com/intellij/ide/util/treeView/SelectionRequest.java new file mode 100644 index 000000000000..60fad7ec6e5b --- /dev/null +++ b/platform/platform-api/src/com/intellij/ide/util/treeView/SelectionRequest.java @@ -0,0 +1,55 @@ +/* + * Copyright 2000-2009 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.intellij.ide.util.treeView; + +class SelectionRequest { + final Object[] myElements; + final Runnable myOnDone; + final boolean myAddToSelection; + final boolean myCheckCurrentSelection; + final boolean myCheckInInStructure; + final boolean myScrollToVisible; + final boolean myDeferred; + final boolean myCanSmartExpand; + + SelectionRequest(Object[] elements, + Runnable onDone, + boolean addToSelection, + boolean checkCurrentSelection, + boolean checkInInStructure, + boolean scrollToVisible, + boolean deferred, + boolean canSmartExpand) { + myElements = elements; + myOnDone = onDone; + myAddToSelection = addToSelection; + myCheckCurrentSelection = checkCurrentSelection; + myCheckInInStructure = checkInInStructure; + myScrollToVisible = scrollToVisible; + myDeferred = deferred; + myCanSmartExpand = canSmartExpand; + } + + void execute(AbstractTreeUi ui) { + ui._select(myElements, myOnDone, myAddToSelection, myCheckCurrentSelection, myCheckInInStructure, myScrollToVisible, myDeferred, myCanSmartExpand, false); + } + + void reject() { + if (myOnDone != null) { + myOnDone.run(); + } + } +} diff --git a/platform/platform-api/src/com/intellij/util/PathUtil.java b/platform/platform-api/src/com/intellij/util/PathUtil.java index 25cdb5994804..b6b50484eb12 100644 --- a/platform/platform-api/src/com/intellij/util/PathUtil.java +++ b/platform/platform-api/src/com/intellij/util/PathUtil.java @@ -29,6 +29,8 @@ import java.io.File; import java.util.StringTokenizer; public class PathUtil { + private PathUtil() { + } public static String getLocalPath(VirtualFile file) { if (file == null || !file.isValid()) { @@ -125,17 +127,30 @@ public class PathUtil { } public static String suggestFileName(final String text) { - return text.replace(' ', '_') - .replace('.', '_') - .replace(File.separatorChar, '_') - .replace('\t', '_') - .replace('\n', '_') - .replace(':', '_') - .replace('*', '_') - .replace('?', '_') - .replace('<', '_') - .replace('>', '_') - .replace('/', '_') - .replace('"', '_'); + StringBuilder result = new StringBuilder(); + for (int i = 0; i < text.length(); i++) { + char c = text.charAt(i); + if (!isValidFileNameChar(c) || c == '.' || Character.isWhitespace(c)) { + result.append('_'); + } + else { + result.append(c); + } + } + return result.toString(); + } + + public static boolean isValidFileName(@NotNull String fileName) { + for (int i = 0; i < fileName.length(); i++) { + if (!isValidFileNameChar(fileName.charAt(i))) { + return false; + } + } + return true; + } + + private static boolean isValidFileNameChar(char c) { + return c != '/' && c != '\\' && c != '\t' && c != '\n' && c != '\r' && c != ':' && c != ';' && c != '*' && c != '?' + && c != '"' && c != '\'' && c != '<' && c != '>'; } } diff --git a/platform/platform-impl/src/com/intellij/openapi/actionSystem/impl/ActionButton.java b/platform/platform-impl/src/com/intellij/openapi/actionSystem/impl/ActionButton.java index 3fd1c3ed5361..8353229c0cff 100644 --- a/platform/platform-impl/src/com/intellij/openapi/actionSystem/impl/ActionButton.java +++ b/platform/platform-impl/src/com/intellij/openapi/actionSystem/impl/ActionButton.java @@ -131,7 +131,7 @@ public class ActionButton extends JComponent implements ActionButtonComponent { private void actionPerfomed(final AnActionEvent event) { if (myAction instanceof ActionGroup && !(myAction instanceof CustomComponentAction) && ((ActionGroup)myAction).isPopup()) { final ActionManagerImpl am = (ActionManagerImpl)ActionManager.getInstance(); - ActionPopupMenu popupMenu = am.createActionPopupMenu(event.getPlace(), (ActionGroup)myAction, new PresentationFactory() { + ActionPopupMenu popupMenu = am.createActionPopupMenu(event.getPlace(), (ActionGroup)myAction, new MenuItemPresentationFactory() { @Override protected Presentation processPresentation(Presentation presentation) { if (myNoIconsInPopup) { diff --git a/platform/platform-impl/src/com/intellij/openapi/actionSystem/impl/ActionPopupMenuImpl.java b/platform/platform-impl/src/com/intellij/openapi/actionSystem/impl/ActionPopupMenuImpl.java index b004cc8a6a22..b5b9029b8d43 100644 --- a/platform/platform-impl/src/com/intellij/openapi/actionSystem/impl/ActionPopupMenuImpl.java +++ b/platform/platform-impl/src/com/intellij/openapi/actionSystem/impl/ActionPopupMenuImpl.java @@ -55,7 +55,7 @@ final class ActionPopupMenuImpl implements ActionPopupMenu { public MyMenu(String place, @NotNull ActionGroup group, @Nullable PresentationFactory factory) { myPlace = place; myGroup = group; - myPresentationFactory = factory != null ? factory : new PresentationFactory(); + myPresentationFactory = factory != null ? factory : new MenuItemPresentationFactory(); addPopupMenuListener(new MyPopupMenuListener()); } diff --git a/java/compiler/openapi/src/com/intellij/openapi/deployment/ElementIgnoringAttributesEquality.java b/platform/platform-impl/src/com/intellij/openapi/actionSystem/impl/MenuItemPresentationFactory.java similarity index 50% rename from java/compiler/openapi/src/com/intellij/openapi/deployment/ElementIgnoringAttributesEquality.java rename to platform/platform-impl/src/com/intellij/openapi/actionSystem/impl/MenuItemPresentationFactory.java index 4921b1e12145..08f573933bad 100644 --- a/java/compiler/openapi/src/com/intellij/openapi/deployment/ElementIgnoringAttributesEquality.java +++ b/platform/platform-impl/src/com/intellij/openapi/actionSystem/impl/MenuItemPresentationFactory.java @@ -13,24 +13,22 @@ * See the License for the specific language governing permissions and * limitations under the License. */ +package com.intellij.openapi.actionSystem.impl; -package com.intellij.openapi.deployment; +import com.intellij.ide.ui.UISettings; +import com.intellij.openapi.actionSystem.Presentation; +import com.intellij.openapi.util.SystemInfo; -import gnu.trove.TObjectHashingStrategy; - -public class ElementIgnoringAttributesEquality implements TObjectHashingStrategy { - public boolean equals(ContainerElement object, ContainerElement object1) { - if (object1 == null || object == null) { - return object == object1; +/** + * @author Roman.Chernyatchik + */ +public class MenuItemPresentationFactory extends PresentationFactory { + protected Presentation processPresentation(Presentation presentation) { + if (SystemInfo.isMac && !UISettings.getInstance().SHOW_ICONS_IN_MENUS) { + presentation.setIcon(null); + presentation.setDisabledIcon(null); + presentation.setHoveredIcon(null); } - return object.equalsIgnoreAttributes(object1); + return presentation; } - - public int computeHashCode(ContainerElement object) { - String presentableName = object.getPresentableName(); - if (presentableName == null) { - return 0; - } - return presentableName.hashCode(); - } -} \ No newline at end of file +} diff --git a/platform/platform-impl/src/com/intellij/openapi/actionSystem/impl/PresentationFactory.java b/platform/platform-impl/src/com/intellij/openapi/actionSystem/impl/PresentationFactory.java index 7138a5b6d02c..7e5c8cd278b4 100644 --- a/platform/platform-impl/src/com/intellij/openapi/actionSystem/impl/PresentationFactory.java +++ b/platform/platform-impl/src/com/intellij/openapi/actionSystem/impl/PresentationFactory.java @@ -41,4 +41,7 @@ public class PresentationFactory { return presentation; } + public void reset() { + myAction2Presentation.clear(); + } } diff --git a/platform/platform-impl/src/com/intellij/openapi/editor/impl/EditorFactoryImpl.java b/platform/platform-impl/src/com/intellij/openapi/editor/impl/EditorFactoryImpl.java index 36289b2211cb..9c93d7cd93ad 100644 --- a/platform/platform-impl/src/com/intellij/openapi/editor/impl/EditorFactoryImpl.java +++ b/platform/platform-impl/src/com/intellij/openapi/editor/impl/EditorFactoryImpl.java @@ -113,6 +113,13 @@ public class EditorFactoryImpl extends EditorFactory { return document; } + @NotNull + public Document createDocument(boolean allowUpdatesWithoutWriteAction) { + DocumentImpl document = new DocumentImpl(allowUpdatesWithoutWriteAction); + myEditorEventMulticaster.registerDocument(document); + return document; + } + public void refreshAllEditors() { for (Editor editor : myEditors) { ((EditorEx)editor).reinitSettings(); diff --git a/platform/platform-impl/src/com/intellij/openapi/vfs/impl/local/LocalFileSystemImpl.java b/platform/platform-impl/src/com/intellij/openapi/vfs/impl/local/LocalFileSystemImpl.java index 8fb0047b850d..31c2208ee8c8 100644 --- a/platform/platform-impl/src/com/intellij/openapi/vfs/impl/local/LocalFileSystemImpl.java +++ b/platform/platform-impl/src/com/intellij/openapi/vfs/impl/local/LocalFileSystemImpl.java @@ -23,7 +23,6 @@ import com.intellij.openapi.util.SystemInfo; import com.intellij.openapi.util.io.FileUtil; import com.intellij.openapi.vfs.JarFileSystem; import com.intellij.openapi.vfs.VirtualFile; -import com.intellij.openapi.vfs.impl.win32.Win32LocalFileSystem; import com.intellij.openapi.vfs.newvfs.ManagingFS; import com.intellij.openapi.vfs.newvfs.NewVirtualFile; import com.intellij.openapi.vfs.newvfs.RefreshQueue; @@ -124,7 +123,6 @@ public final class LocalFileSystemImpl extends LocalFileSystemBase implements Ap } public void disposeComponent() { - Win32LocalFileSystem.release(); } @TestOnly diff --git a/platform/platform-impl/src/com/intellij/openapi/vfs/impl/win32/Win32Kernel.java b/platform/platform-impl/src/com/intellij/openapi/vfs/impl/win32/Win32Kernel.java index 7c6b33008922..bad5d66e9c16 100644 --- a/platform/platform-impl/src/com/intellij/openapi/vfs/impl/win32/Win32Kernel.java +++ b/platform/platform-impl/src/com/intellij/openapi/vfs/impl/win32/Win32Kernel.java @@ -35,16 +35,19 @@ import java.util.Map; public class Win32Kernel { private static final int MAX_PATH = 0x00000104; + public static final int FILE_ATTRIBUTE_DIRECTORY = 0x00000010; public static final int FILE_ATTRIBUTE_READONLY = 0x0001; - private Kernel32 myKernel = (Kernel32)Native.loadLibrary("kernel32", Kernel32.class, new HashMap() { + private static W32API.HANDLE INVALID_HANDLE_VALUE = new W32API.HANDLE(Pointer.createConstant(0xFFFFFFFFl)); + + private static Kernel32 myKernel = (Kernel32)Native.loadLibrary("kernel32", Kernel32.class, new HashMap() { { put(Library.OPTION_TYPE_MAPPER, W32APITypeMapper.UNICODE); put(Library.OPTION_FUNCTION_MAPPER, W32APIFunctionMapper.UNICODE); }}); - WIN32_FIND_DATA myData = new WIN32_FIND_DATA(); + private final WIN32_FIND_DATA myData = new WIN32_FIND_DATA(); private static class FileInfo { private FileInfo(WIN32_FIND_DATA data) { @@ -56,8 +59,6 @@ public class Win32Kernel { long ftLastWriteTime; } - private static W32API.HANDLE INVALID_HANDLE_VALUE = new W32API.HANDLE(Pointer.createConstant(0xFFFFFFFFl)); - private Map myCache = new HashMap(); public String[] list(String absolutePath) { @@ -65,22 +66,23 @@ public class Win32Kernel { myCache.clear(); ArrayList list = new ArrayList(); - W32API.HANDLE hFind = myKernel.FindFirstFile(absolutePath.replace('/', '\\') + "\\*", myData); + WIN32_FIND_DATA data = myData; + W32API.HANDLE hFind = myKernel.FindFirstFile(absolutePath.replace('/', '\\') + "\\*", data); if (hFind.equals(INVALID_HANDLE_VALUE)) return new String[0]; try { do { - String name = Native.toString(myData.cFileName); + String name = Native.toString(data.cFileName); if (name.equals(".")) { - myCache.put(absolutePath, new FileInfo(myData)); + myCache.put(absolutePath, new FileInfo(data)); continue; } else if (name.equals("..")) { continue; } - myCache.put(absolutePath + "/" + name, new FileInfo(myData)); + myCache.put(absolutePath + "/" + name, new FileInfo(data)); list.add(name); } - while (myKernel.FindNextFile(hFind, myData)); + while (myKernel.FindNextFile(hFind, data)); } finally { myKernel.FindClose(hFind); @@ -91,7 +93,7 @@ public class Win32Kernel { public boolean exists(String path) { myCache.clear(); try { - getData(path); + getInfo(path); return true; } catch (FileNotFoundException e) { @@ -100,35 +102,36 @@ public class Win32Kernel { } public boolean isDirectory(String path) throws FileNotFoundException { - FileInfo data = getData(path); + FileInfo data = getInfo(path); return (data.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) != 0; } public boolean isWritable(String path) throws FileNotFoundException { - return (getData(path).dwFileAttributes & FILE_ATTRIBUTE_READONLY) == 0; + return (getInfo(path).dwFileAttributes & FILE_ATTRIBUTE_READONLY) == 0; } public long getTimeStamp(String path) throws FileNotFoundException { - return getData(path).ftLastWriteTime; + return getInfo(path).ftLastWriteTime; } - private FileInfo getData(String path) throws FileNotFoundException { - FileInfo data = myCache.get(path); - if (data == null) { + private FileInfo getInfo(String path) throws FileNotFoundException { + FileInfo info = myCache.get(path); + if (info == null) { myCache.clear(); - W32API.HANDLE handle = myKernel.FindFirstFile(path.replace('/', '\\'), myData); + WIN32_FIND_DATA data = myData; + W32API.HANDLE handle = myKernel.FindFirstFile(path.replace('/', '\\'), data); if (handle.equals(INVALID_HANDLE_VALUE)) { throw new FileNotFoundException(path); } myKernel.FindClose(handle); - data = new FileInfo(myData); - myCache.put(path, data); + info = new FileInfo(data); + myCache.put(path, info); } - return data; + return info; } public void release() throws Throwable { - myData.release(); + myData.release(); } public interface Kernel32 extends StdCallLibrary { diff --git a/platform/platform-impl/src/com/intellij/openapi/vfs/impl/win32/Win32LocalFileSystem.java b/platform/platform-impl/src/com/intellij/openapi/vfs/impl/win32/Win32LocalFileSystem.java index 1141d8f18d1f..ae06e76cdd98 100644 --- a/platform/platform-impl/src/com/intellij/openapi/vfs/impl/win32/Win32LocalFileSystem.java +++ b/platform/platform-impl/src/com/intellij/openapi/vfs/impl/win32/Win32LocalFileSystem.java @@ -21,6 +21,7 @@ import com.intellij.openapi.vfs.impl.local.LocalFileSystemBase; import org.jetbrains.annotations.NotNull; import java.io.FileNotFoundException; +import java.util.Arrays; import java.util.Collection; import java.util.Set; @@ -31,29 +32,19 @@ public class Win32LocalFileSystem extends LocalFileSystemBase { private static final Logger LOG = Logger.getInstance("#com.intellij.openapi.vfs.impl.win32.Win32LocalFileSystem"); - private static Win32LocalFileSystem ourSystem; + private static final ThreadLocal THREAD_LOCAL = new ThreadLocal() { + @Override + protected Win32LocalFileSystem initialValue() { + return new Win32LocalFileSystem(); + } + }; public static Win32LocalFileSystem getWin32Instance() { - if (ourSystem == null) { - ourSystem = new Win32LocalFileSystem(); - } - return ourSystem; - } - - public static void release() { - Win32LocalFileSystem system = ourSystem; - ourSystem = null; - if (system != null) { - try { - system.myKernel.release(); - } - catch (Throwable throwable) { - LOG.error(throwable); - } - } + return THREAD_LOCAL.get(); } private final Win32Kernel myKernel = new Win32Kernel(); + private boolean checkMe = false; private Win32LocalFileSystem() { } @@ -62,11 +53,15 @@ public class Win32LocalFileSystem extends LocalFileSystemBase { public String[] list(VirtualFile file) { try { String[] strings = myKernel.list(file.getPath()); - //assert Arrays.asList(strings).equals(Arrays.asList(super.list(file))); + if (checkMe && !Arrays.asList(strings).equals(Arrays.asList(super.list(file)))) { + LOG.error(file.getPath()); + } return strings; } catch (Exception e) { -// assert false; + if (checkMe) { + assert false; + } return super.list(file); } } @@ -75,7 +70,9 @@ public class Win32LocalFileSystem extends LocalFileSystemBase { public boolean exists(VirtualFile fileOrDirectory) { if (fileOrDirectory.getParent() == null) return true; boolean b = myKernel.exists(fileOrDirectory.getPath()); - //assert b == super.exists(fileOrDirectory); + if (checkMe && b != super.exists(fileOrDirectory)) { + LOG.error(fileOrDirectory.getPath()); + } return b; } @@ -83,11 +80,12 @@ public class Win32LocalFileSystem extends LocalFileSystemBase { public boolean isDirectory(VirtualFile file) { try { boolean b = myKernel.isDirectory(file.getPath()); - //assert b == super.isDirectory(file); + if (checkMe && b != super.isDirectory(file)) { + LOG.error(file.getPath()); + } return b; } catch (FileNotFoundException e) { -// assert false; return super.isDirectory(file); } } @@ -96,11 +94,12 @@ public class Win32LocalFileSystem extends LocalFileSystemBase { public boolean isWritable(VirtualFile file) { try { boolean b = myKernel.isWritable(file.getPath()); - //assert b == super.isWritable(file); + if (checkMe && b != super.isWritable(file)) { + LOG.error(file.getPath()); + } return b; } catch (FileNotFoundException e) { -// assert false: file; return super.isWritable(file); } } @@ -109,11 +108,13 @@ public class Win32LocalFileSystem extends LocalFileSystemBase { public long getTimeStamp(VirtualFile file) { try { long timeStamp = myKernel.getTimeStamp(file.getPath()); - //assert timeStamp == super.getTimeStamp(file); + if (checkMe && timeStamp != super.getTimeStamp(file)) { + timeStamp = myKernel.getTimeStamp(file.getPath()); + LOG.error(file.getPath()); + } return timeStamp; } catch (FileNotFoundException e) { -// assert false; return super.getTimeStamp(file); } } diff --git a/platform/platform-impl/src/com/intellij/openapi/wm/impl/IdeMenuBar.java b/platform/platform-impl/src/com/intellij/openapi/wm/impl/IdeMenuBar.java index 0e61f323fbdc..78d0432625cd 100644 --- a/platform/platform-impl/src/com/intellij/openapi/wm/impl/IdeMenuBar.java +++ b/platform/platform-impl/src/com/intellij/openapi/wm/impl/IdeMenuBar.java @@ -23,7 +23,7 @@ import com.intellij.ide.ui.customization.CustomActionsSchema; import com.intellij.openapi.actionSystem.*; import com.intellij.openapi.actionSystem.ex.ActionManagerEx; import com.intellij.openapi.actionSystem.impl.ActionMenu; -import com.intellij.openapi.actionSystem.impl.PresentationFactory; +import com.intellij.openapi.actionSystem.impl.MenuItemPresentationFactory; import com.intellij.openapi.actionSystem.impl.WeakTimerListener; import com.intellij.openapi.application.ModalityState; import com.intellij.openapi.keymap.KeymapManager; @@ -42,7 +42,7 @@ public class IdeMenuBar extends JMenuBar{ private final MyTimerListener myTimerListener; private ArrayList myVisibleActions; private ArrayList myNewVisibleActions; - private final PresentationFactory myPresentationFactory; + private final MenuItemPresentationFactory myPresentationFactory; private final DataManager myDataManager; private final ActionManager myActionManager; private UISettingsListener myUISettingsListener; @@ -53,7 +53,7 @@ public class IdeMenuBar extends JMenuBar{ //(DefaultActionGroup)actionManager.getAction(IdeActions.GROUP_MAIN_MENU); myVisibleActions = new ArrayList(); myNewVisibleActions = new ArrayList(); - myPresentationFactory = new PresentationFactory(); + myPresentationFactory = new MenuItemPresentationFactory(); myDataManager = dataManager; } @@ -69,6 +69,7 @@ public class IdeMenuBar extends JMenuBar{ myUISettingsListener = new UISettingsListener() { public void uiSettingsChanged(final UISettings source) { updateMnemonicsVisibility(); + myPresentationFactory.reset(); } }; UISettings.getInstance().addUISettingsListener(myUISettingsListener); diff --git a/platform/platform-resources-en/src/messages/DiagnosticBundle.properties b/platform/platform-resources-en/src/messages/DiagnosticBundle.properties index ce8992946b9b..e6c12801c95b 100644 --- a/platform/platform-resources-en/src/messages/DiagnosticBundle.properties +++ b/platform/platform-resources-en/src/messages/DiagnosticBundle.properties @@ -56,8 +56,9 @@ log.monitor.edit.aliases.title=Edit Log Files Aliases log.monitor.edit.aliases.name=&Alias: log.monitor.edit.aliases.location=&Log File Location: log.monitor.edit.aliases.show.all.checkbox.title=&Show All Files Coverable By Pattern -log.console.filter.show.errors=Show errors only -log.console.filter.show.errors.and.warnings=Show errors and warnings -log.console.filter.show.all=Show all +log.console.filter.show.errors=errors +log.console.filter.show.errors.and.warnings=warnings +log.console.filter.show.all=all title.submitting.error.report=Submitting error report -log.console.filter.show.errors.warnings.and.infos=Show errors, warnings and infos \ No newline at end of file +log.console.filter.show.errors.warnings.and.infos=infos +log.console.filter.show.prefix=Show \ No newline at end of file diff --git a/platform/platform-resources-en/src/messages/IdeBundle.properties b/platform/platform-resources-en/src/messages/IdeBundle.properties index 010d5caa54af..c326d361df4d 100644 --- a/platform/platform-resources-en/src/messages/IdeBundle.properties +++ b/platform/platform-resources-en/src/messages/IdeBundle.properties @@ -68,6 +68,7 @@ title.editor.bookmarks=Editor Bookmarks bookmark.method.at.line={0}, {1}{2}, line {3} action.show.bookmarks=_Show Bookmarks action.toggle.bookmark=Toggle _Bookmark +action.toggle.bookmark.mnemonic=Toggle Bookmark With Mnemonic action.set.bookmark=Set _Bookmark progress.deleting=Deleting select.in.commander=Commander diff --git a/platform/platform-resources/src/idea/DefaultKeymap.xml b/platform/platform-resources/src/idea/DefaultKeymap.xml index 2b600493a36e..c5cf90ecd879 100644 --- a/platform/platform-resources/src/idea/DefaultKeymap.xml +++ b/platform/platform-resources/src/idea/DefaultKeymap.xml @@ -562,6 +562,9 @@ + + + diff --git a/platform/platform-resources/src/idea/LangActions.xml b/platform/platform-resources/src/idea/LangActions.xml index b9c9b642c52c..aee45ce405fc 100644 --- a/platform/platform-resources/src/idea/LangActions.xml +++ b/platform/platform-resources/src/idea/LangActions.xml @@ -86,6 +86,7 @@ + diff --git a/platform/platform-resources/src/idea/PlatformActions.xml b/platform/platform-resources/src/idea/PlatformActions.xml index d7025f877018..48327c5218cd 100644 --- a/platform/platform-resources/src/idea/PlatformActions.xml +++ b/platform/platform-resources/src/idea/PlatformActions.xml @@ -386,6 +386,7 @@ + diff --git a/platform/smRunner/src/com/intellij/execution/testframework/sm/FileUrlProvider.java b/platform/smRunner/src/com/intellij/execution/testframework/sm/FileUrlProvider.java index 22cd2f4e7fac..f559ede447d5 100644 --- a/platform/smRunner/src/com/intellij/execution/testframework/sm/FileUrlProvider.java +++ b/platform/smRunner/src/com/intellij/execution/testframework/sm/FileUrlProvider.java @@ -102,7 +102,14 @@ public class FileUrlProvider implements TestLocationProvider { return null; } - final int lineStartOffset = doc.getLineStartOffset(lineNum - 1); + final int lineCount = doc.getLineCount(); + final int lineStartOffset; + if (lineNum <= lineCount) { + lineStartOffset = doc.getLineStartOffset(lineNum - 1); + } else { + // unknown line + lineStartOffset = 0; + } PsiElement elementAtLine = psiFile.findElementAt(lineStartOffset); if (elementAtLine != null) { diff --git a/platform/smRunner/src/com/intellij/execution/testframework/sm/runner/SMTRunnerTreeBuilder.java b/platform/smRunner/src/com/intellij/execution/testframework/sm/runner/SMTRunnerTreeBuilder.java index 7199036079a6..4ceaaa9c7f2b 100644 --- a/platform/smRunner/src/com/intellij/execution/testframework/sm/runner/SMTRunnerTreeBuilder.java +++ b/platform/smRunner/src/com/intellij/execution/testframework/sm/runner/SMTRunnerTreeBuilder.java @@ -37,7 +37,8 @@ public class SMTRunnerTreeBuilder extends AbstractTestTreeBuilder { new DefaultTreeModel(new DefaultMutableTreeNode(structure.getRootElement())), structure, IndexComparator.INSTANCE); - + + setCanYieldUpdate(true); initRootNode(); } diff --git a/platform/smRunner/src/com/intellij/execution/testframework/sm/runner/ui/SMTestRunnerResultsForm.java b/platform/smRunner/src/com/intellij/execution/testframework/sm/runner/ui/SMTestRunnerResultsForm.java index 2ee4f42cb501..7dfaff2867ec 100644 --- a/platform/smRunner/src/com/intellij/execution/testframework/sm/runner/ui/SMTestRunnerResultsForm.java +++ b/platform/smRunner/src/com/intellij/execution/testframework/sm/runner/ui/SMTestRunnerResultsForm.java @@ -427,9 +427,6 @@ public class SMTestRunnerResultsForm extends TestResultsPanel implements TestFra SMRunnerUtil.runInEventDispatchThread(new Runnable() { public void run() { - //TODO remove manual update! - myTreeBuilder.performUpdate(); - myTreeBuilder.select(testProxy, null); } }, ModalityState.NON_MODAL); diff --git a/platform/testFramework/src/com/intellij/testFramework/ExpectedHighlightingData.java b/platform/testFramework/src/com/intellij/testFramework/ExpectedHighlightingData.java index 542338300654..0dc64e18c254 100644 --- a/platform/testFramework/src/com/intellij/testFramework/ExpectedHighlightingData.java +++ b/platform/testFramework/src/com/intellij/testFramework/ExpectedHighlightingData.java @@ -101,7 +101,7 @@ public class ExpectedHighlightingData { PsiFile file) { myFile = file; myText = document.getText(); - highlightingTypes = new THashMap(); + highlightingTypes = new LinkedHashMap(); highlightingTypes.put(ERROR_MARKER, new ExpectedHighlightingSet(HighlightInfoType.ERROR, HighlightSeverity.ERROR, false, true)); highlightingTypes.put(WARNING_MARKER, new ExpectedHighlightingSet(HighlightInfoType.WARNING, HighlightSeverity.WARNING, false, checkWarnings)); highlightingTypes.put(INFORMATION_MARKER, new ExpectedHighlightingSet(HighlightInfoType.INFO, HighlightSeverity.INFO, false, checkWeakWarnings)); @@ -185,10 +185,7 @@ public class ExpectedHighlightingData { String text = document.getText(); final Set markers = highlightingTypes.keySet(); - String typesRegex = ""; - for (String marker : markers) { - typesRegex += (typesRegex.length() == 0 ? "" : "|") + "(?:" + marker + ")"; - } + String typesRegex = "(?:"+StringUtil.join(markers, ")|(?:")+")"; // er... // any code then (with optional descr="...") then any code then then any code @@ -196,7 +193,7 @@ public class ExpectedHighlightingData { //"(.+?)).*"; Pattern p = Pattern.compile(pat, Pattern.DOTALL); Out: - for (; ;) { + while (true) { Matcher m = p.matcher(text); if (!m.matches()) break; int startOffset = m.start(1); @@ -209,7 +206,7 @@ public class ExpectedHighlightingData { startOffset = m.start(1); expectedHighlightingSet = highlightingTypes.get(marker); } - int pos=3; + int pos = 3; @NonNls String descr = m.group(pos++); if (descr == null) { // no descr means any string by default @@ -241,20 +238,19 @@ public class ExpectedHighlightingData { final Matcher matcher2 = pat2.matcher(rest); LOG.assertTrue(matcher2.matches(), "Cannot find closing "); content = matcher2.group(1); - endOffset = m.start(pos-1) + matcher2.start(2); + endOffset = m.start(pos - 1) + matcher2.start(2); } else { // content = ""; - endOffset = m.start(pos-1); + endOffset = m.start(pos - 1); } document.replaceString(startOffset, endOffset, content); TextAttributes forcedAttributes = null; if (foregroundColor != null) { - forcedAttributes = new TextAttributes(Color.decode(foregroundColor), Color.decode(backgroundColor), - Color.decode(effectColor), EffectType.valueOf(effectType), - Integer.parseInt(fontType)); + forcedAttributes = new TextAttributes(Color.decode(foregroundColor), Color.decode(backgroundColor), Color.decode(effectColor), + EffectType.valueOf(effectType), Integer.parseInt(fontType)); } TextRange textRange = new TextRange(startOffset, startOffset + content.length()); @@ -273,9 +269,9 @@ public class ExpectedHighlightingData { } - HighlightInfo highlightInfo = new HighlightInfo(forcedAttributes, type, textRange.getStartOffset(), textRange.getEndOffset(), descr, - descr, expectedHighlightingSet.severity, expectedHighlightingSet.endOfLine, null, - false); + HighlightInfo highlightInfo = + new HighlightInfo(forcedAttributes, type, textRange.getStartOffset(), textRange.getEndOffset(), descr, descr, + expectedHighlightingSet.severity, expectedHighlightingSet.endOfLine, null, false); expectedHighlightingSet.infos.add(highlightInfo); text = document.getText(); } diff --git a/platform/testFramework/src/com/intellij/testFramework/fixtures/impl/CodeInsightTestFixtureImpl.java b/platform/testFramework/src/com/intellij/testFramework/fixtures/impl/CodeInsightTestFixtureImpl.java index 2b8286963839..af0e7cf89ce0 100644 --- a/platform/testFramework/src/com/intellij/testFramework/fixtures/impl/CodeInsightTestFixtureImpl.java +++ b/platform/testFramework/src/com/intellij/testFramework/fixtures/impl/CodeInsightTestFixtureImpl.java @@ -1133,7 +1133,7 @@ public class CodeInsightTestFixtureImpl extends BaseFixture implements CodeInsig PsiElement element = file.findElementAt(editor.getCaretModel().getOffset()); List result = new ArrayList(); - List infos = DaemonCodeAnalyzerImpl.getFileLeveleHighlights(file.getProject(), file); + List infos = DaemonCodeAnalyzerImpl.getFileLevelHighlights(file.getProject(), file); for (HighlightInfo info : infos) { for (Pair pair : info.quickFixActionRanges) { HighlightInfo.IntentionActionDescriptor actionInGroup = pair.first; diff --git a/platform/usageView/src/com/intellij/usages/impl/UsageViewImpl.java b/platform/usageView/src/com/intellij/usages/impl/UsageViewImpl.java index bcf026ef7206..506d95256237 100644 --- a/platform/usageView/src/com/intellij/usages/impl/UsageViewImpl.java +++ b/platform/usageView/src/com/intellij/usages/impl/UsageViewImpl.java @@ -864,12 +864,14 @@ public class UsageViewImpl implements UsageView, UsageModelTracker.UsageModelTra return myUsageSearcherFactory != null; } - private void checkReadonlyUsages() { + private boolean checkReadonlyUsages() { final Set readOnlyUsages = getReadOnlyUsagesFiles(); if (!readOnlyUsages.isEmpty()) { - ReadonlyStatusHandler.getInstance(myProject).ensureFilesWritable(readOnlyUsages.toArray(new VirtualFile[readOnlyUsages.size()])); + return + !ReadonlyStatusHandler.getInstance(myProject).ensureFilesWritable(readOnlyUsages.toArray(new VirtualFile[readOnlyUsages.size()])).hasReadonlyFiles(); } + return true; } private Set getReadOnlyUsages() { @@ -1268,7 +1270,7 @@ public class UsageViewImpl implements UsageView, UsageModelTracker.UsageModelTra } public void run() { - checkReadonlyUsages(); + if (!checkReadonlyUsages()) return; PsiDocumentManager.getInstance(myProject).commitAllDocuments(); if (myCannotMakeString != null && myChangesDetected) { if (canPerformReRun() && allTargetsAreValid()) { diff --git a/platform/util/src/com/intellij/ui/LightColors.java b/platform/util/src/com/intellij/ui/LightColors.java index 1e6676856bff..39c1b4b8ca9f 100644 --- a/platform/util/src/com/intellij/ui/LightColors.java +++ b/platform/util/src/com/intellij/ui/LightColors.java @@ -29,4 +29,5 @@ public interface LightColors { Color CYAN = new Color(0xccffff); Color SLIGHTLY_GREEN = new Color(0xeeffee); + Color SLIGHTLY_GRAY = new Color(0xf5f5f5); } diff --git a/plugins/InspectionGadgets/src/com/siyeh/InspectionGadgetsBundle.properties b/plugins/InspectionGadgets/src/com/siyeh/InspectionGadgetsBundle.properties index 811d7d92aa0f..cf6ea5d01e0f 100644 --- a/plugins/InspectionGadgets/src/com/siyeh/InspectionGadgetsBundle.properties +++ b/plugins/InspectionGadgets/src/com/siyeh/InspectionGadgetsBundle.properties @@ -1595,7 +1595,10 @@ implicit.array.to.string.quickfix=Wrap with ''{0}'' expression suspicious.indent.after.control.statement.problem.descriptor=#ref statement has suspicous indentation suspicious.indent.after.control.statement.display.name=Suspicious indentation after control statement without braces unpredictable.big.decimal.constructor.call.display.name=Unpredictable BigDecimal constructor call -unpredictable.big.decimal.constructor.call.problem.descriptor=Call to unpredictable #ref constructor #loc +unpredictable.big.decimal.constructor.call.problem.descriptor=Unpredictable new #ref() call #loc +unpredictable.big.decimal.constructor.call.ignore.references.option=Ignore constructor calls with variable or method call arguments +unpredictable.big.decimal.constructor.call.ignore.complex.literals.option=Ignore constructor calls with multiple literals (e.g. 0.1 + 0.2) +unpredictable.big.decimal.constructor.call.quickfix=Replace with ''new BigDecimal("{0}")'' unnecessary.unary.minus.display.name=Unnecessary unary minus unnecessary.unary.minus.problem.descriptor=Unnecessary unary minus unnecessary.unary.minus.quickfix=Remove unary minus and invert parent operation sign @@ -1749,4 +1752,4 @@ multiple.exceptions.declared.on.test.method.problem.descriptor=#ref multiple.exceptions.declared.on.test.method.quickfix=Replace with 'throws Exception' unnecessary.javadoc.link.display.name=Unnecessary JavaDoc link unnecessary.javadoc.link.problem.descriptor=#ref is unnecessary -unnecessary.javadoc.link.quickfix=Remove unnecessary {0} +unnecessary.javadoc.link.quickfix=Remove unnecessary {0} \ No newline at end of file diff --git a/plugins/InspectionGadgets/src/com/siyeh/ig/bugs/MalformedFormatStringInspection.java b/plugins/InspectionGadgets/src/com/siyeh/ig/bugs/MalformedFormatStringInspection.java index 3a7890bec2bb..9c1ff08e2e04 100644 --- a/plugins/InspectionGadgets/src/com/siyeh/ig/bugs/MalformedFormatStringInspection.java +++ b/plugins/InspectionGadgets/src/com/siyeh/ig/bugs/MalformedFormatStringInspection.java @@ -140,6 +140,14 @@ public class MalformedFormatStringInspection extends BaseInspection{ return; } if(validators.length != argumentCount){ + if (argumentCount == 1) { + final PsiExpression argument = + arguments[formatArgPosition + 1]; + final PsiType argumentType = argument.getType(); + if (argumentType instanceof PsiArrayType) { + return; + } + } registerError(formatArgument, validators, Integer.valueOf(argumentCount)); return; diff --git a/plugins/InspectionGadgets/src/com/siyeh/ig/junit/ParameterizedParametersStaticCollectionInspection.java b/plugins/InspectionGadgets/src/com/siyeh/ig/junit/ParameterizedParametersStaticCollectionInspection.java index 25dac097d8ee..3ef7728281ab 100644 --- a/plugins/InspectionGadgets/src/com/siyeh/ig/junit/ParameterizedParametersStaticCollectionInspection.java +++ b/plugins/InspectionGadgets/src/com/siyeh/ig/junit/ParameterizedParametersStaticCollectionInspection.java @@ -37,15 +37,14 @@ import com.siyeh.ig.BaseInspectionVisitor; import com.siyeh.ig.InspectionGadgetsFix; import org.jetbrains.annotations.Nls; import org.jetbrains.annotations.NotNull; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; import java.util.ArrayList; import java.util.Collection; import java.util.List; public class ParameterizedParametersStaticCollectionInspection extends BaseInspection{ - private static final String PARAMETERS_FQN = Parameterized.Parameters.class.getName().replace('$', '.'); + private static final String PARAMETERS_FQN = "org.junit.runners.Parameterized.Parameters"; + private static final String PARAMETERIZED_FQN = "org.junit.runners.Parameterized"; @NotNull protected String buildErrorString(Object... infos) { @@ -58,13 +57,13 @@ public class ParameterizedParametersStaticCollectionInspection extends BaseInspe return new BaseInspectionVisitor() { @Override public void visitClass(PsiClass aClass) { - final PsiAnnotation annotation = AnnotationUtil.findAnnotation(aClass, RunWith.class.getName()); + final PsiAnnotation annotation = AnnotationUtil.findAnnotation(aClass, "org.junit.runner.RunWith"); if (annotation != null) { for (PsiNameValuePair pair : annotation.getParameterList().getAttributes()) { final PsiAnnotationMemberValue value = pair.getValue(); if (value instanceof PsiClassObjectAccessExpression) { final PsiTypeElement typeElement = ((PsiClassObjectAccessExpression)value).getOperand(); - if (typeElement.getType().getCanonicalText().equals(Parameterized.class.getName())) { + if (typeElement.getType().getCanonicalText().equals(PARAMETERIZED_FQN)) { List candidates = new ArrayList(); for (PsiMethod method : aClass.getMethods()) { PsiType returnType = method.getReturnType(); diff --git a/plugins/InspectionGadgets/src/com/siyeh/ig/numeric/UnpredictableBigDecimalConstructorCallInspection.java b/plugins/InspectionGadgets/src/com/siyeh/ig/numeric/UnpredictableBigDecimalConstructorCallInspection.java index f0d7d9127bf1..4fac8299cc4c 100644 --- a/plugins/InspectionGadgets/src/com/siyeh/ig/numeric/UnpredictableBigDecimalConstructorCallInspection.java +++ b/plugins/InspectionGadgets/src/com/siyeh/ig/numeric/UnpredictableBigDecimalConstructorCallInspection.java @@ -1,5 +1,5 @@ /* - * Copyright 2007 Bas Leijdekkers + * Copyright 2007-2009 Bas Leijdekkers * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -15,15 +15,26 @@ */ package com.siyeh.ig.numeric; +import com.intellij.codeInspection.ProblemDescriptor; +import com.intellij.openapi.project.Project; import com.intellij.psi.*; +import com.intellij.util.IncorrectOperationException; import com.siyeh.InspectionGadgetsBundle; import com.siyeh.ig.BaseInspection; import com.siyeh.ig.BaseInspectionVisitor; +import com.siyeh.ig.InspectionGadgetsFix; +import com.siyeh.ig.ui.MultipleCheckboxOptionsPanel; import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +import javax.swing.*; public class UnpredictableBigDecimalConstructorCallInspection extends BaseInspection { + public boolean ignoreReferences = true; + public boolean ignoreComplexLiterals = false; + @NotNull public String getDisplayName() { return InspectionGadgetsBundle.message( @@ -36,11 +47,79 @@ public class UnpredictableBigDecimalConstructorCallInspection "unpredictable.big.decimal.constructor.call.problem.descriptor"); } + @Override + public JComponent createOptionsPanel() { + final MultipleCheckboxOptionsPanel optionsPanel = + new MultipleCheckboxOptionsPanel(this); + optionsPanel.addCheckbox(InspectionGadgetsBundle.message( + "unpredictable.big.decimal.constructor.call.ignore.references.option"), + "ignoreReferences"); + optionsPanel.addCheckbox(InspectionGadgetsBundle.message( + "unpredictable.big.decimal.constructor.call.ignore.complex.literals.option"), + "ignoreComplexLiterals"); + return optionsPanel; + } + + @Override + protected InspectionGadgetsFix buildFix(Object... infos) { + final PsiNewExpression newExpression = (PsiNewExpression) infos[0]; + final PsiExpressionList argumentList = newExpression.getArgumentList(); + if (argumentList == null) { + return null; + } + final PsiExpression[] arguments = argumentList.getExpressions(); + if (arguments.length == 0) { + return null; + } + final PsiExpression firstArgument = arguments[0]; + if (!(firstArgument instanceof PsiLiteralExpression)) { + return null; + } + return new ReplaceDoubleArgumentWithStringFix(firstArgument.getText()); + } + + private class ReplaceDoubleArgumentWithStringFix + extends InspectionGadgetsFix { + + private final String argumentText; + + public ReplaceDoubleArgumentWithStringFix(String argumentText) { + this.argumentText = argumentText; + } + + @NotNull + public String getName() { + return InspectionGadgetsBundle.message( + "unpredictable.big.decimal.constructor.call.quickfix", + argumentText); + } + + @Override + protected void doFix(Project project, ProblemDescriptor descriptor) + throws IncorrectOperationException { + final PsiElement element = descriptor.getPsiElement(); + final PsiNewExpression newExpression = + (PsiNewExpression) element.getParent(); + final PsiExpressionList argumentList = + newExpression.getArgumentList(); + if (argumentList == null) { + return; + } + final PsiExpression[] arguments = argumentList.getExpressions(); + if (arguments.length == 0) { + return; + } + final PsiExpression firstArgument = arguments[0]; + replaceExpression(firstArgument, + '"' + firstArgument.getText() + '"'); + } + } + public BaseInspectionVisitor buildVisitor() { return new UnpredictableBigDecimalConstructorCallVisitor(); } - private static class UnpredictableBigDecimalConstructorCallVisitor + private class UnpredictableBigDecimalConstructorCallVisitor extends BaseInspectionVisitor { @Override public void visitNewExpression(PsiNewExpression expression) { @@ -70,7 +149,45 @@ public class UnpredictableBigDecimalConstructorCallInspection if (type != PsiType.DOUBLE) { return; } - registerNewExpressionError(expression); + final PsiExpressionList argumentList = expression.getArgumentList(); + if (argumentList == null) { + return; + } + final PsiExpression[] arguments = argumentList.getExpressions(); + if (arguments.length == 0) { + return; + } + final PsiExpression firstArgument = arguments[0]; + if (!checkArguments(firstArgument)) { + return; + } + registerNewExpressionError(expression, expression); + } + + private boolean checkArguments(@Nullable PsiExpression firstArgument) { + if (firstArgument == null) { + return false; + } + if (firstArgument instanceof PsiReferenceExpression) { + if (ignoreReferences) { + return false; + } + } else if (firstArgument instanceof PsiBinaryExpression) { + if (ignoreComplexLiterals) { + return false; + } + final PsiBinaryExpression binaryExpression = + (PsiBinaryExpression) firstArgument; + final PsiExpression lhs = binaryExpression.getLOperand(); + if (!checkArguments(lhs)) { + return false; + } + final PsiExpression rhs = binaryExpression.getROperand(); + if (!checkArguments(rhs)) { + return false; + } + } + return true; } } } \ No newline at end of file diff --git a/plugins/copyright/src/com/maddyhome/idea/copyright/ui/ProjectSettingsPanel.java b/plugins/copyright/src/com/maddyhome/idea/copyright/ui/ProjectSettingsPanel.java index 64791592ca4e..68cc209a188f 100644 --- a/plugins/copyright/src/com/maddyhome/idea/copyright/ui/ProjectSettingsPanel.java +++ b/plugins/copyright/src/com/maddyhome/idea/copyright/ui/ProjectSettingsPanel.java @@ -384,7 +384,9 @@ public class ProjectSettingsPanel extends PanelWithButtons { } public void setValue(ScopeSetting scopeSetting, CopyrightProfile copyrightProfile) { + if (copyrightProfile != null) { scopeSetting.setProfile(copyrightProfile); + } } }; diff --git a/plugins/devkit/src/build/ant/ChunkBuildPluginExtension.java b/plugins/devkit/src/build/ant/ChunkBuildPluginExtension.java index 2e43d8d52d82..bd2fa3c05232 100644 --- a/plugins/devkit/src/build/ant/ChunkBuildPluginExtension.java +++ b/plugins/devkit/src/build/ant/ChunkBuildPluginExtension.java @@ -63,7 +63,7 @@ public class ChunkBuildPluginExtension extends ChunkBuildExtension { PluginBuildProperties.getBuildExplodedTargetName(configurationName), PluginBuildProperties.getBuildJarTargetName(configurationName), PluginBuildProperties.getExplodedPathProperty(configurationName), - PluginBuildProperties.getJarPathProperty(configurationName), null); + PluginBuildProperties.getJarPathProperty(configurationName)); final Set libs = new HashSet(); PluginBuildUtil.getLibraries(module, libs); @NonNls String jarPath = chunk.getBaseDir().getPath() + "/" + chunk.getName(); diff --git a/plugins/git4idea/src/git4idea/vfs/GitRootTracker.java b/plugins/git4idea/src/git4idea/vfs/GitRootTracker.java index 4f846f580f40..4d656ff647ea 100644 --- a/plugins/git4idea/src/git4idea/vfs/GitRootTracker.java +++ b/plugins/git4idea/src/git4idea/vfs/GitRootTracker.java @@ -350,8 +350,7 @@ public class GitRootTracker implements VcsListener { } boolean hasUnmapped = ApplicationManager.getApplication().runReadAction(new Computable() { public Boolean compute() { - if (child.isValid()) return false; - return child.findChild(".git") != null && !rootSet.contains(child.getPath()); + return child.isValid() && child.findChild(".git") != null && !rootSet.contains(child.getPath()); } }); if (hasUnmapped) { diff --git a/plugins/junit/src/com/intellij/execution/junit2/inspection/JUnitUnusedCodeExtension.java b/plugins/junit/src/com/intellij/execution/junit2/inspection/JUnitUnusedCodeExtension.java index 023ad9a72798..5c180861674d 100644 --- a/plugins/junit/src/com/intellij/execution/junit2/inspection/JUnitUnusedCodeExtension.java +++ b/plugins/junit/src/com/intellij/execution/junit2/inspection/JUnitUnusedCodeExtension.java @@ -62,16 +62,17 @@ public class JUnitUnusedCodeExtension extends UnusedCodeExtension { } else if (psiElement instanceof PsiMethod) { final PsiMethod psiMethod = (PsiMethod)psiElement; + if (JUnitUtil.getTestMethod(psiElement) != null) return true; final String name = psiMethod.getName(); if (psiMethod.hasModifierProperty(PsiModifier.PUBLIC) && !psiMethod.hasModifierProperty(PsiModifier.ABSTRACT)) { - if (name.startsWith("test") || "suite".equals(name) || "setUp".equals(name) || "tearDown".equals(name)) { + if ("suite".equals(name) || "setUp".equals(name) || "tearDown".equals(name)) { return true; } if (psiMethod.hasModifierProperty(PsiModifier.STATIC)) { if (AnnotationUtil.isAnnotated(psiMethod, Arrays.asList(BeforeClass.class.getName(), AfterClass.class.getName(), Parameterized.Parameters.class.getName().replace('$', '.')))) return true; } else { - if (AnnotationUtil.isAnnotated(psiMethod, Arrays.asList(Before.class.getName(), After.class.getName(), Test.class.getName()))) return true; + if (AnnotationUtil.isAnnotated(psiMethod, Arrays.asList(Before.class.getName(), After.class.getName()))) return true; } } } diff --git a/plugins/junit/src/com/intellij/execution/junit2/states/TestStateUpdater.java b/plugins/junit/src/com/intellij/execution/junit2/states/TestStateUpdater.java index 958b05b0daea..50c1c62c57ab 100644 --- a/plugins/junit/src/com/intellij/execution/junit2/states/TestStateUpdater.java +++ b/plugins/junit/src/com/intellij/execution/junit2/states/TestStateUpdater.java @@ -90,6 +90,7 @@ public class TestStateUpdater implements PacketConsumer { state.setMagitude(myInstanceMagnitude); state.initializeFrom(reader); testProxy.setState(state); + complete(testProxy); } public void setMagnitude(final int magnitude) { @@ -105,21 +106,25 @@ public class TestStateUpdater implements PacketConsumer { } testProxy.setState(state); testProxy.setStatistics(new Statistics(reader)); - final int magnitude = state.getMagnitude(); + complete(testProxy); + } + } - TestProxy parent = testProxy.getParent(); - TestProxy child = testProxy; - while (parent != null) { - final List children = parent.getChildren(); - final TestState parentState = parent.getState(); - LOG.assertTrue(parentState instanceof SuiteState); - if (child.equals(children.get(children.size() - 1))) { - ((SuiteState)parentState).setRunning(false); - } - ((SuiteState)parentState).updateMagnitude(magnitude); - child = parent; - parent = parent.getParent(); + private static void complete(TestProxy testProxy) { + final int magnitude = testProxy.getState().getMagnitude(); + + TestProxy parent = testProxy.getParent(); + TestProxy child = testProxy; + while (parent != null) { + final List children = parent.getChildren(); + final TestState parentState = parent.getState(); + LOG.assertTrue(parentState instanceof SuiteState); + if (child.equals(children.get(children.size() - 1))) { + ((SuiteState)parentState).setRunning(false); } + ((SuiteState)parentState).updateMagnitude(magnitude); + child = parent; + parent = parent.getParent(); } } diff --git a/plugins/maven/src/main/java/org/jetbrains/idea/maven/project/MavenProjectReader.java b/plugins/maven/src/main/java/org/jetbrains/idea/maven/project/MavenProjectReader.java index 68e914c02b2c..a8fc06fde40e 100644 --- a/plugins/maven/src/main/java/org/jetbrains/idea/maven/project/MavenProjectReader.java +++ b/plugins/maven/src/main/java/org/jetbrains/idea/maven/project/MavenProjectReader.java @@ -19,7 +19,6 @@ import com.intellij.openapi.util.Comparing; import com.intellij.openapi.util.Pair; import com.intellij.openapi.util.Ref; import com.intellij.openapi.util.text.StringUtil; -import static com.intellij.openapi.util.text.StringUtil.isEmptyOrSpaces; import com.intellij.openapi.vfs.VfsUtil; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.psi.impl.source.parsing.xml.XmlBuilder; @@ -53,6 +52,8 @@ import java.io.File; import java.io.IOException; import java.util.*; +import static com.intellij.openapi.util.text.StringUtil.isEmptyOrSpaces; + public class MavenProjectReader { private static final String UNKNOWN = MavenId.UNKNOWN_VALUE; @@ -453,8 +454,8 @@ public class MavenProjectReader { } private boolean resolveInheritance(final MavenGeneralSettings generalSettings, - Model model, - VirtualFile file, + final Model model, + final VirtualFile file, final List activeProfiles, final Set recursionGuard, final MavenProjectReaderProjectLocator locator) { @@ -528,7 +529,7 @@ public class MavenProjectReader { Properties context = MavenEmbedderFactory.collectSystemProperties(); ProjectBuilderConfiguration config = new DefaultProjectBuilderConfiguration().setExecutionProperties(context); - model = interpolator.interpolate(model, basedir, config, false); + model = interpolator.interpolate(ModelUtils.cloneModel(model), basedir, config, false); } catch (ModelInterpolationException e) { MavenLog.LOG.warn(e); diff --git a/plugins/maven/src/test/java/org/jetbrains/idea/maven/DependenciesImportingTest.java b/plugins/maven/src/test/java/org/jetbrains/idea/maven/DependenciesImportingTest.java index 7217959e98ab..cf37de561928 100644 --- a/plugins/maven/src/test/java/org/jetbrains/idea/maven/DependenciesImportingTest.java +++ b/plugins/maven/src/test/java/org/jetbrains/idea/maven/DependenciesImportingTest.java @@ -297,6 +297,52 @@ public class DependenciesImportingTest extends MavenImportingTestCase { assertModuleModuleDeps("m1", "m2"); } + public void testInterModuleDependenciesIfThereArePropertiesInArtifactHeaderDefinedInParent() throws Exception { + createProjectPom("${groupProp}" + + "parent" + + "${versionProp}" + + "pom" + + + "" + + " test" + + " 1" + + "" + + + "" + + " m1" + + " m2" + + ""); + + createModulePom("m1", + "" + + " ${groupProp}" + + " parent" + + " ${versionProp}" + + "" + + "m1" + + + "" + + " " + + " ${groupProp}" + + " m2" + + " ${versionProp}" + + " " + + ""); + + createModulePom("m2", + "" + + " ${groupProp}" + + " parent" + + " ${versionProp}" + + "" + + "m2"); + + importProject(); + assertModules("parent", "m1", "m2"); + + assertModuleModuleDeps("m1", "m2"); + } + public void testDependencyOnSelf() throws Exception { importProject("test" + "project" + diff --git a/plugins/maven/src/test/java/org/jetbrains/idea/maven/MavenTestCase.java b/plugins/maven/src/test/java/org/jetbrains/idea/maven/MavenTestCase.java index 92ae22feb07f..227cc81c5aee 100644 --- a/plugins/maven/src/test/java/org/jetbrains/idea/maven/MavenTestCase.java +++ b/plugins/maven/src/test/java/org/jetbrains/idea/maven/MavenTestCase.java @@ -32,6 +32,7 @@ import com.intellij.openapi.vfs.VirtualFile; import com.intellij.testFramework.UsefulTestCase; import com.intellij.testFramework.fixtures.IdeaProjectTestFixture; import com.intellij.testFramework.fixtures.IdeaTestFixtureFactory; +import org.intellij.lang.annotations.Language; import org.jetbrains.idea.maven.embedder.MavenConsole; import org.jetbrains.idea.maven.project.*; import org.jetbrains.idea.maven.utils.MavenProgressIndicator; diff --git a/plugins/maven/src/test/java/org/jetbrains/idea/maven/project/MavenProjectReaderTest.java b/plugins/maven/src/test/java/org/jetbrains/idea/maven/project/MavenProjectReaderTest.java index 87d65a1ce89e..69d7f012fd95 100644 --- a/plugins/maven/src/test/java/org/jetbrains/idea/maven/project/MavenProjectReaderTest.java +++ b/plugins/maven/src/test/java/org/jetbrains/idea/maven/project/MavenProjectReaderTest.java @@ -737,6 +737,28 @@ public class MavenProjectReaderTest extends MavenTestCase { assertEquals("value", p.getName()); } + public void testPropertiesFromParentInParentSection() throws Exception { + createProjectPom("${groupProp}" + + "parent" + + "${versionProp}" + + + "" + + " test" + + " 1" + + ""); + + VirtualFile module = createModulePom("module", + "" + + " ${groupProp}" + + " parent" + + " ${versionProp}" + + "" + + "module"); + + org.apache.maven.project.MavenProject p = readProject(module); + assertEquals("test:module:1", p.getGroupId() + ":" + p.getArtifactId() + ":" + p.getVersion()); + } + public void testInheritingSettingsFromParentAndAlignCorrectly() throws Exception { createProjectPom("test" + "parent" + diff --git a/plugins/spellchecker/src/com/intellij/spellchecker/settings/SpellCheckerSettingsPane.java b/plugins/spellchecker/src/com/intellij/spellchecker/settings/SpellCheckerSettingsPane.java index 379e6eb17b16..98488787ab99 100644 --- a/plugins/spellchecker/src/com/intellij/spellchecker/settings/SpellCheckerSettingsPane.java +++ b/plugins/spellchecker/src/com/intellij/spellchecker/settings/SpellCheckerSettingsPane.java @@ -23,7 +23,7 @@ import com.intellij.openapi.project.Project; import com.intellij.openapi.ui.Messages; import com.intellij.openapi.util.Pair; import com.intellij.openapi.util.io.FileUtil; -import com.intellij.profile.codeInspection.ui.ProjectInspectionToolsConfigurable; +import com.intellij.profile.codeInspection.ui.ErrorsConfigurable; import com.intellij.spellchecker.SpellCheckerManager; import com.intellij.spellchecker.dictionary.Dictionary; import com.intellij.spellchecker.util.SPFileUtil; @@ -66,7 +66,7 @@ public class SpellCheckerSettingsPane implements Disposable { public void hyperlinkUpdate(final HyperlinkEvent e) { if (e.getEventType() == HyperlinkEvent.EventType.ACTIVATED) { final OptionsEditor optionsEditor = OptionsEditor.KEY.getData(DataManager.getInstance().getDataContext()); - final ProjectInspectionToolsConfigurable toolsConfigurable = ProjectInspectionToolsConfigurable.getInstance(project); + final ErrorsConfigurable toolsConfigurable = ErrorsConfigurable.SERVICE.getInstance(project); if (optionsEditor != null && toolsConfigurable != null) { optionsEditor.select(toolsConfigurable).doWhenDone(new Runnable() { public void run() { diff --git a/plugins/testng/src/com/theoryinpractice/testng/configuration/TestNGSuiteConfigurationProducer.java b/plugins/testng/src/com/theoryinpractice/testng/configuration/TestNGSuiteConfigurationProducer.java index 7edeeffb3c22..6ba25c6b15e1 100644 --- a/plugins/testng/src/com/theoryinpractice/testng/configuration/TestNGSuiteConfigurationProducer.java +++ b/plugins/testng/src/com/theoryinpractice/testng/configuration/TestNGSuiteConfigurationProducer.java @@ -48,7 +48,7 @@ public class TestNGSuiteConfigurationProducer extends TestNGConfigurationProduce final PsiFile containingFile = element.getContainingFile(); if (containingFile == null) return null; final VirtualFile virtualFile = containingFile.getVirtualFile(); - if (virtualFile == null) return null; + if (virtualFile == null || !virtualFile.isValid()) return null; if (!TestNGUtil.isTestngXML(virtualFile)) return null; myPsiElement = containingFile; final Project project = location.getProject(); diff --git a/resources/src/idea/IdeaActions.xml b/resources/src/idea/IdeaActions.xml index 6fc92e087289..bc50a097dcba 100644 --- a/resources/src/idea/IdeaActions.xml +++ b/resources/src/idea/IdeaActions.xml @@ -258,7 +258,6 @@ - diff --git a/xml/impl/src/com/intellij/xml/index/ExternalResourcesRootsProvider.java b/xml/impl/src/com/intellij/xml/index/ExternalResourcesRootsProvider.java index 070ed962bb1c..7f85915d727a 100644 --- a/xml/impl/src/com/intellij/xml/index/ExternalResourcesRootsProvider.java +++ b/xml/impl/src/com/intellij/xml/index/ExternalResourcesRootsProvider.java @@ -44,7 +44,9 @@ public class ExternalResourcesRootsProvider implements IndexedRootsProvider { LocalFileSystem localFileSystem = LocalFileSystem.getInstance(); VirtualFile extResources = localFileSystem.findFileByPath(path); HashSet roots = new HashSet(2); - roots.add(standardSchemas.getUrl()); + if (standardSchemas != null) { + roots.add(standardSchemas.getUrl()); + } if (extResources != null) { roots.add(extResources.getUrl()); } diff --git a/xml/impl/src/com/intellij/xml/index/ResourceRelevance.java b/xml/impl/src/com/intellij/xml/index/ResourceRelevance.java index 28ab829df842..f1833e5ab1d2 100644 --- a/xml/impl/src/com/intellij/xml/index/ResourceRelevance.java +++ b/xml/impl/src/com/intellij/xml/index/ResourceRelevance.java @@ -30,11 +30,11 @@ import java.util.List; */ public enum ResourceRelevance { - MAPPED, - SOURCE, - LIBRARY, + NONE, STANDARD, - NONE; + LIBRARY, + SOURCE, + MAPPED; public static ResourceRelevance getRelevance(VirtualFile file, Module module, ProjectFileIndex fileIndex) { Module moduleForFile = fileIndex.getModuleForFile(file);