diff --git a/.idea/libraries/sqlite.xml b/.idea/libraries/sqlite.xml new file mode 100644 index 000000000000..54ed24ede12e --- /dev/null +++ b/.idea/libraries/sqlite.xml @@ -0,0 +1,11 @@ + + + + + + + + + + + \ No newline at end of file diff --git a/build/conf/nsis/strings.nsi b/build/conf/nsis/strings.nsi index 2efe6fe71ad6..e9a9f30140aa 100644 --- a/build/conf/nsis/strings.nsi +++ b/build/conf/nsis/strings.nsi @@ -7,7 +7,7 @@ !define PRODUCT_UNINST_ICON_FILE "idea_uninst.ico" !define PRODUCT_LOGO_FILE "logo.bmp" !define PRODUCT_HEADER_FILE "headerlogo.bmp" -!define ASSOCIATION ".java,.groovy" +!define ASSOCIATION ".java,.groovy,.kt" !define UNINSTALL_WEB_PAGE "https://www.jetbrains.com/idea/uninstall/?edition=IU-__VERSION_MAJOR__.__VERSION_MINOR__" ; if SHOULD_SET_DEFAULT_INSTDIR != 0 then default installation directory will be directory where highest-numbered IDEA build has been installed diff --git a/build/conf/nsis/stringsCE.nsi b/build/conf/nsis/stringsCE.nsi index b3239d1b30c5..98fe712d90bb 100644 --- a/build/conf/nsis/stringsCE.nsi +++ b/build/conf/nsis/stringsCE.nsi @@ -7,7 +7,7 @@ !define PRODUCT_UNINST_ICON_FILE "idea_CEuninst.ico" !define PRODUCT_LOGO_FILE "logoCE.bmp" !define PRODUCT_HEADER_FILE "headerlogoCE.bmp" -!define ASSOCIATION ".java,.groovy" +!define ASSOCIATION ".java,.groovy,.kt" !define UNINSTALL_WEB_PAGE "https://www.jetbrains.com/idea/uninstall/?edition=IC-__VERSION_MAJOR__.__VERSION_MINOR__" ; if SHOULD_SET_DEFAULT_INSTDIR != 0 then default installation directory will be directory where highest-numbered IDEA build has been installed diff --git a/build/scripts/libLicenses.gant b/build/scripts/libLicenses.gant index 552032ffd66c..e7d1bd41f2a3 100644 --- a/build/scripts/libLicenses.gant +++ b/build/scripts/libLicenses.gant @@ -310,6 +310,7 @@ libraryLicense(name: "Velocity", version: "1.7", license: "Apache 2.0", url: "ht libraryLicense(name: "winp", version: "1.23", license: "MIT", url: "http://java.net/projects/winp", licenseUrl: "http://opensource.org/licenses/mit-license.php") libraryLicense(name: "Xalan", libraryName:"Xalan-2.7.1", version: "2.7.1", license: "Apache 2.0", url: "http://xml.apache.org/xalan-j/", licenseUrl: "http://xml.apache.org/xalan-j/") libraryLicense(name: "Xerces", version: "2.11", license: "Apache 2.0", url: "http://xerces.apache.org/xerces2-j/", licenseUrl: "http://xerces.apache.org/xerces2-j/") +libraryLicense(name: "Xerial SQLite JDBC", libraryName: "sqlite", version: "3.6.20.1", license: "Apache 2.0", url: "https://github.com/xerial/sqlite-jdbc") libraryLicense(name: "XML-RPC", libraryName: "XmlRPC", version: "2.0", license: "Apache 2.0", url: "http://ws.apache.org/xmlrpc/xmlrpc2/", licenseUrl: "http://ws.apache.org/xmlrpc/xmlrpc2/license.html") libraryLicense(name: "XML Commons (xml-apis.jar, resolver.jar)", version: "", license: "Apache 2.0, W3C Software License , public domain", url: "http://xml.apache.org/commons/", licenseUrl: "http://xml.apache.org/commons/licenses.html") libraryLicense(name: "XMLBeans", libraryName: "XmlBeans", version: "2.3.0", license: "Apache 2.0", url: "http://xmlbeans.apache.org/", licenseUrl: "http://svn.jetbrains.org/idea/Trunk/bundled/WebServices/resources/lib/xmlbeans-2.3.0/xmlbeans.LICENSE") diff --git a/build/scripts/unpackJdks.gant b/build/scripts/unpackJdks.gant index 3b71c7e0acda..aace7a167f8e 100644 --- a/build/scripts/unpackJdks.gant +++ b/build/scripts/unpackJdks.gant @@ -42,44 +42,48 @@ def unpackJdks() { return } - unpackJdk(osDir, jdkDir, "1.6") - unpackJdk(osDir, jdkDir, "1.8") + unpackJdk(osDir, jdkDir, "jre6", "1.6") + unpackJdk(osDir, jdkDir, "jbsdk8", "1.8") } -private void unpackJdk(File osDir, File jdkDir, String majorVersion) { - def jdkFiles = osDir.listFiles().findAll { it.name.startsWith("jdk$majorVersion") } +private void unpackJdk(File osDir, File jdkDir, String archiveFileNamePrefix, String targetDirectoryName) { + def jdkFiles = osDir.listFiles().findAll { it.name.startsWith(archiveFileNamePrefix) } if (SystemInfo.isWindows) { - def arch = System.getenv("ProgramFiles(x86)") != null ? "x64" : "x32" - jdkFiles = jdkFiles.findAll { it.name.endsWith("_${arch}.zip") } + def arch = System.getenv("ProgramFiles(x86)") != null ? "x64" : "x86" + jdkFiles = jdkFiles.findAll { it.name.endsWith("_${arch}.tar.gz") } } if (jdkFiles.empty) { - projectBuilder.error("Cannot unpack JDK: jdk$majorVersion* not found in $osDir") + projectBuilder.error("Cannot unpack JDK: $archiveFileNamePrefix not found in $osDir") } if (jdkFiles.size() > 1) { projectBuilder.error("Cannot unpack JDK: several matching files are found ($jdkFiles)") } File jdkFile = jdkFiles.first() - def destDir = new File(jdkDir, majorVersion) + def destDir = new File(jdkDir, targetDirectoryName) FileUtil.delete(destDir) - if (jdkFile.name.endsWith(".zip")) { - ant.unzip(src: jdkFile, dest: destDir) - } - else if (jdkFile.name.endsWith(".tar")) { - projectBuilder.info("Extracting $jdkFile to $destDir") - ant.mkdir(dir: destDir) - //'tar' and 'mv' commands are used instead of Ant tasks to ensure that executable flag and symlink will be preserved - ant.exec(executable: "tar", dir: jdkFile.getParent()) { - arg(value: "-xf") - arg(value: jdkFile.name) - arg(value: "--directory") - arg(value: destDir) + projectBuilder.info("Extracting $jdkFile to $destDir") + ant.mkdir(dir: destDir) + + if (jdkFile.name.endsWith(".tar.gz")) { + if (SystemInfo.isWindows) { + ant.untar(src: jdkFile, dest: destDir, compression: 'gzip') } - if (SystemInfo.isMac && !jdkFile.name.contains("apple")) { - new File(destDir, "jre/jdk/Contents").listFiles().each { file -> - ant.exec(executable: "mv", dir: destDir) { - arg(value: file.absolutePath) - arg(value: destDir) + else { + //'tar' and 'mv' commands are used instead of Ant tasks to ensure that executable flag and symlink will be preserved + ant.exec(executable: "tar", dir: jdkFile.getParent()) { + arg(value: "-xf") + arg(value: jdkFile.name) + arg(value: "--directory") + arg(value: destDir) + } + def jdkContents = new File(destDir, "jdk/Contents") + if (SystemInfo.isMac && jdkContents.exists()) { + jdkContents.listFiles().each { file -> + ant.exec(executable: "mv", dir: destDir) { + arg(value: file.absolutePath) + arg(value: destDir) + } } } } @@ -87,5 +91,4 @@ private void unpackJdk(File osDir, File jdkDir, String majorVersion) { else { projectBuilder.error("Cannot unpack JDK: unknown extension of file '${jdkFile.name}'") } -} - +} \ No newline at end of file diff --git a/build/scripts/utils.gant b/build/scripts/utils.gant index bbf5afe448eb..0f2731489601 100644 --- a/build/scripts/utils.gant +++ b/build/scripts/utils.gant @@ -75,8 +75,8 @@ binding.setVariable("isEap", { return "true" == p("component.version.eap") }) -binding.setVariable("mem32", "-server -Xms128m -Xmx512m -XX:MaxPermSize=250m -XX:ReservedCodeCacheSize=240m") -binding.setVariable("mem64", "-Xms128m -Xmx750m -XX:MaxPermSize=350m -XX:ReservedCodeCacheSize=240m") +binding.setVariable("mem32", "-server -Xms128m -Xmx512m -XX:ReservedCodeCacheSize=240m") +binding.setVariable("mem64", "-Xms128m -Xmx750m -XX:ReservedCodeCacheSize=240m") binding.setVariable("common_vmoptions", "-XX:+UseConcMarkSweepGC -XX:SoftRefLRUPolicyMSPerMB=50 -ea " + "-Dsun.io.useCanonCaches=false -Djava.net.preferIPv4Stack=true " + "-XX:+HeapDumpOnOutOfMemoryError -XX:-OmitStackTraceInFastThrow") @@ -428,7 +428,6 @@ binding.setVariable("platformImplementationModules", [ "vcs-impl", "vcs-log-graph", "vcs-log-impl", - "vcs-tests", "xdebugger-impl", "xml-analysis-impl", "xml-psi-impl", @@ -885,7 +884,7 @@ binding.setVariable("bundledJDK64s"){ private bundledJDK(boolean win64) { requireProperty("artifact.linux.no.jdk", "true") requireProperty("artifact.mac.no.jdk", "true") - requireProperty("jdk.oracle.win", "jdk1.8") + requireProperty("jdk.oracle.win", "jdk8u") requireProperty("jdk.win", "openjdk.1.8") requireProperty("jdk.mac", "openjdk.1.8") requireProperty("jdk.linux", "openjdk.1.8") @@ -893,19 +892,18 @@ private bundledJDK(boolean win64) { if (new File("${home}/build/jdk").exists()) { def jdkDir = new File("${home}/build/jdk/win") if (p("jdk.oracle.win") != "false" && (jdkDir.exists() && jdkDir.isDirectory())) { - setProperty("winJDK", getPathToBundledJDK(jdkDir, p("jdk.oracle.win"), (win64 ? "x64.zip": "x32.zip"))) + setProperty("winJDK", getPathToBundledJDK(jdkDir, p("jdk.oracle.win"), (win64 ? "x64.tar.gz": "x86.tar.gz"))) extractRedistJre(winJDK, "${paths.sandbox}/jdk.oracle.win/jre") } - jdkDir = new File("${home}/build/jdk/win/custom") if (p("jdk.win") != "false" && (jdkDir.exists() && jdkDir.isDirectory())) { setProperty("winCustomJDKx32", getPathToBundledJDK(jdkDir, p("jdk.win"), (win64 ? "x64.tar.gz": "x32.tar.gz"))) extractRedistJre(winCustomJDKx32, "${paths.sandbox}/jdk.win") } - jdkDir = new File("${home}/build/jdk/mac/custom") + jdkDir = new File("${home}/build/jdk/mac") if (p("jdk.mac") != "false" && (jdkDir.exists() && jdkDir.isDirectory())) { setProperty("macCustomJDK", getPathToBundledJDK(jdkDir, p("jdk.mac"), ".tar.gz")) } - jdkDir = new File("${home}/build/jdk/linux/custom") + jdkDir = new File("${home}/build/jdk/linux") if (p("jdk.linux") != "false" && (jdkDir.exists() && jdkDir.isDirectory())) { setProperty("linuxJDK", getPathToBundledJDK(jdkDir, p("jdk.linux"), ".tar.gz")) extractRedistJre(linuxJDK, "${paths.sandbox}/jdk.linux") diff --git a/java/compiler/impl/src/com/intellij/compiler/CompilerConfigurationImpl.java b/java/compiler/impl/src/com/intellij/compiler/CompilerConfigurationImpl.java index 7fa8850faee9..4d8bd26f32ee 100644 --- a/java/compiler/impl/src/com/intellij/compiler/CompilerConfigurationImpl.java +++ b/java/compiler/impl/src/com/intellij/compiler/CompilerConfigurationImpl.java @@ -14,10 +14,6 @@ * limitations under the License. */ -/** - * created at Jan 3, 2002 - * @author Jeka - */ package com.intellij.compiler; import com.intellij.CommonBundle; 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 95c190743443..deec5c2f92f5 100644 --- a/java/compiler/impl/src/com/intellij/compiler/impl/CompileDriver.java +++ b/java/compiler/impl/src/com/intellij/compiler/impl/CompileDriver.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2014 JetBrains s.r.o. + * Copyright 2000-2016 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. @@ -14,11 +14,6 @@ * limitations under the License. */ -/** - * @author: Eugene Zhuravlev - * Date: Jan 17, 2003 - * Time: 1:42:26 PM - */ package com.intellij.compiler.impl; import com.intellij.CommonBundle; diff --git a/java/compiler/impl/src/com/intellij/compiler/impl/packagingCompiler/IgnoredFileFilter.java b/java/compiler/impl/src/com/intellij/compiler/impl/packagingCompiler/IgnoredFileFilter.java index 5ad3f5a52c13..1522870cec67 100644 --- a/java/compiler/impl/src/com/intellij/compiler/impl/packagingCompiler/IgnoredFileFilter.java +++ b/java/compiler/impl/src/com/intellij/compiler/impl/packagingCompiler/IgnoredFileFilter.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2009 JetBrains s.r.o. + * Copyright 2000-2016 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. @@ -14,9 +14,6 @@ * limitations under the License. */ -/** - * @author cdr - */ package com.intellij.compiler.impl.packagingCompiler; import com.intellij.openapi.fileTypes.FileTypeManager; diff --git a/java/compiler/impl/src/com/intellij/openapi/projectRoots/impl/MockJdkWrapper.java b/java/compiler/impl/src/com/intellij/openapi/projectRoots/impl/MockJdkWrapper.java index 779df52e49e3..5120843b4e8b 100644 --- a/java/compiler/impl/src/com/intellij/openapi/projectRoots/impl/MockJdkWrapper.java +++ b/java/compiler/impl/src/com/intellij/openapi/projectRoots/impl/MockJdkWrapper.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2012 JetBrains s.r.o. + * Copyright 2000-2016 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. @@ -14,9 +14,6 @@ * limitations under the License. */ -/** - * @author cdr - */ package com.intellij.openapi.projectRoots.impl; import com.intellij.openapi.projectRoots.Sdk; diff --git a/java/compiler/impl/src/com/intellij/packaging/impl/ui/actions/PackageFileAction.java b/java/compiler/impl/src/com/intellij/packaging/impl/ui/actions/PackageFileAction.java index cd3092fdb35f..9b4cca6aba01 100644 --- a/java/compiler/impl/src/com/intellij/packaging/impl/ui/actions/PackageFileAction.java +++ b/java/compiler/impl/src/com/intellij/packaging/impl/ui/actions/PackageFileAction.java @@ -1,5 +1,17 @@ -/** - * @author cdr +/* + * Copyright 2000-2016 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.ui.actions; diff --git a/java/compiler/openapi/src/com/intellij/openapi/compiler/options/ExcludeEntryDescription.java b/java/compiler/openapi/src/com/intellij/openapi/compiler/options/ExcludeEntryDescription.java index b752e8e84dae..b52329c878e3 100644 --- a/java/compiler/openapi/src/com/intellij/openapi/compiler/options/ExcludeEntryDescription.java +++ b/java/compiler/openapi/src/com/intellij/openapi/compiler/options/ExcludeEntryDescription.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2009 JetBrains s.r.o. + * Copyright 2000-2016 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. @@ -14,10 +14,6 @@ * limitations under the License. */ -/** - * created at Jan 3, 2002 - * @author Jeka - */ package com.intellij.openapi.compiler.options; import com.intellij.openapi.Disposable; diff --git a/java/debugger/impl/src/com/intellij/debugger/actions/ExportThreadsAction.java b/java/debugger/impl/src/com/intellij/debugger/actions/ExportThreadsAction.java index 25d95ed86292..da6c5fbe9553 100644 --- a/java/debugger/impl/src/com/intellij/debugger/actions/ExportThreadsAction.java +++ b/java/debugger/impl/src/com/intellij/debugger/actions/ExportThreadsAction.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2015 JetBrains s.r.o. + * Copyright 2000-2016 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. @@ -14,10 +14,6 @@ * limitations under the License. */ -/** - * class ExportThreadsAction - * @author Jeka - */ package com.intellij.debugger.actions; import com.intellij.debugger.DebuggerManagerEx; diff --git a/java/debugger/impl/src/com/intellij/debugger/actions/ThreadDumpAction.java b/java/debugger/impl/src/com/intellij/debugger/actions/ThreadDumpAction.java index 1d9b0e2db551..df157425e2bb 100644 --- a/java/debugger/impl/src/com/intellij/debugger/actions/ThreadDumpAction.java +++ b/java/debugger/impl/src/com/intellij/debugger/actions/ThreadDumpAction.java @@ -14,11 +14,6 @@ * limitations under the License. */ -/** - * class ExportThreadsAction - * @author Eugene Zhuravlev - * @author Sascha Weinreuter - */ package com.intellij.debugger.actions; import com.intellij.debugger.DebuggerBundle; diff --git a/java/debugger/impl/src/com/intellij/debugger/actions/ToggleMethodBreakpointAction.java b/java/debugger/impl/src/com/intellij/debugger/actions/ToggleMethodBreakpointAction.java index 7474f5a42b21..43836ac9549c 100644 --- a/java/debugger/impl/src/com/intellij/debugger/actions/ToggleMethodBreakpointAction.java +++ b/java/debugger/impl/src/com/intellij/debugger/actions/ToggleMethodBreakpointAction.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2014 JetBrains s.r.o. + * Copyright 2000-2016 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. @@ -14,10 +14,6 @@ * limitations under the License. */ -/** - * class ToggleMethodBreakpointAction - * @author Jeka - */ package com.intellij.debugger.actions; import com.intellij.debugger.DebuggerManagerEx; diff --git a/java/debugger/impl/src/com/intellij/debugger/engine/evaluation/expression/ArrayInitializerEvaluator.java b/java/debugger/impl/src/com/intellij/debugger/engine/evaluation/expression/ArrayInitializerEvaluator.java index 0fe3395bae7e..786c64c4fa8d 100644 --- a/java/debugger/impl/src/com/intellij/debugger/engine/evaluation/expression/ArrayInitializerEvaluator.java +++ b/java/debugger/impl/src/com/intellij/debugger/engine/evaluation/expression/ArrayInitializerEvaluator.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2009 JetBrains s.r.o. + * Copyright 2000-2016 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. @@ -14,17 +14,10 @@ * limitations under the License. */ -/** - * class ArrayInitializerEvaluator - * created Jun 28, 2001 - * @author Jeka - */ package com.intellij.debugger.engine.evaluation.expression; -import com.intellij.debugger.engine.evaluation.EvaluationContextImpl; import com.intellij.debugger.engine.evaluation.EvaluateException; import com.intellij.debugger.engine.evaluation.EvaluationContextImpl; -import com.intellij.debugger.engine.evaluation.EvaluateException; class ArrayInitializerEvaluator implements Evaluator{ private final Evaluator[] myValueEvaluators; diff --git a/java/debugger/impl/src/com/intellij/debugger/engine/evaluation/expression/NewArrayInstanceEvaluator.java b/java/debugger/impl/src/com/intellij/debugger/engine/evaluation/expression/NewArrayInstanceEvaluator.java index 6262165fc07d..5b7a731ca116 100644 --- a/java/debugger/impl/src/com/intellij/debugger/engine/evaluation/expression/NewArrayInstanceEvaluator.java +++ b/java/debugger/impl/src/com/intellij/debugger/engine/evaluation/expression/NewArrayInstanceEvaluator.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2015 JetBrains s.r.o. + * Copyright 2000-2016 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. @@ -14,11 +14,6 @@ * limitations under the License. */ -/** - * class NewArrayInstanceEvaluator - * created Jun 27, 2001 - * @author Jeka - */ package com.intellij.debugger.engine.evaluation.expression; import com.intellij.debugger.DebuggerBundle; diff --git a/java/debugger/impl/src/com/intellij/debugger/engine/evaluation/expression/NewClassInstanceEvaluator.java b/java/debugger/impl/src/com/intellij/debugger/engine/evaluation/expression/NewClassInstanceEvaluator.java index dd699cd7f11d..c3d501096842 100644 --- a/java/debugger/impl/src/com/intellij/debugger/engine/evaluation/expression/NewClassInstanceEvaluator.java +++ b/java/debugger/impl/src/com/intellij/debugger/engine/evaluation/expression/NewClassInstanceEvaluator.java @@ -14,11 +14,6 @@ * limitations under the License. */ -/** - * class NewArrayInstanceEvaluator - * created Jun 27, 2001 - * @author Jeka - */ package com.intellij.debugger.engine.evaluation.expression; import com.intellij.debugger.DebuggerBundle; diff --git a/java/debugger/impl/src/com/intellij/debugger/jdi/Bytecodes.java b/java/debugger/impl/src/com/intellij/debugger/jdi/Bytecodes.java index 9f82d74a37dd..d6d86c12d32b 100644 --- a/java/debugger/impl/src/com/intellij/debugger/jdi/Bytecodes.java +++ b/java/debugger/impl/src/com/intellij/debugger/jdi/Bytecodes.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2015 JetBrains s.r.o. + * Copyright 2000-2016 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. @@ -226,8 +226,8 @@ class Bytecodes { */ static final int BSM = 33; - /** - * Computes the instruction types of JVM opcodes. + /* + Computes the instruction types of JVM opcodes. */ static { int i; diff --git a/java/debugger/impl/src/com/intellij/debugger/settings/CompoundRendererConfigurable.java b/java/debugger/impl/src/com/intellij/debugger/settings/CompoundRendererConfigurable.java index 0b3adea0fb82..7b6968358269 100644 --- a/java/debugger/impl/src/com/intellij/debugger/settings/CompoundRendererConfigurable.java +++ b/java/debugger/impl/src/com/intellij/debugger/settings/CompoundRendererConfigurable.java @@ -225,9 +225,9 @@ class CompoundRendererConfigurable extends JPanel { final MyTableModel tableModel = new MyTableModel(); myTable = new JBTable(tableModel); myListChildrenEditor = new XDebuggerExpressionEditor(myProject, editorsProvider, "NamedChildrenConfigurable", null, XExpressionImpl.EMPTY_EXPRESSION, false, false, false); + JComponent editorComponent = myListChildrenEditor.getComponent(); - final TableColumn exprColumn = myTable.getColumnModel().getColumn(EXPRESSION_TABLE_COLUMN); - exprColumn.setCellEditor(new AbstractTableCellEditor() { + AbstractTableCellEditor editor = new AbstractTableCellEditor() { @Override public Object getCellEditorValue() { return TextWithImportsImpl.fromXExpression(myListChildrenEditor.getExpression()); @@ -236,9 +236,16 @@ class CompoundRendererConfigurable extends JPanel { @Override public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column) { myListChildrenEditor.setExpression(TextWithImportsImpl.toXExpression((TextWithImports)value)); - return myListChildrenEditor.getComponent(); + return editorComponent; } - }); + }; + editorComponent.registerKeyboardAction(e -> editor.stopCellEditing(), KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0), + JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT); + editorComponent.registerKeyboardAction(e -> editor.cancelCellEditing(), KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0), + JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT); + + TableColumn exprColumn = myTable.getColumnModel().getColumn(EXPRESSION_TABLE_COLUMN); + exprColumn.setCellEditor(editor); exprColumn.setCellRenderer(new DefaultTableCellRenderer() { @NotNull @Override diff --git a/java/debugger/impl/src/com/intellij/debugger/ui/breakpoints/FieldBreakpointPropertiesPanel.java b/java/debugger/impl/src/com/intellij/debugger/ui/breakpoints/FieldBreakpointPropertiesPanel.java index 41f5417799b6..b81d81c688fe 100644 --- a/java/debugger/impl/src/com/intellij/debugger/ui/breakpoints/FieldBreakpointPropertiesPanel.java +++ b/java/debugger/impl/src/com/intellij/debugger/ui/breakpoints/FieldBreakpointPropertiesPanel.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2009 JetBrains s.r.o. + * Copyright 2000-2016 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. @@ -14,10 +14,6 @@ * limitations under the License. */ -/** - * class FieldBreakpointPropertiesPanel - * @author Jeka - */ package com.intellij.debugger.ui.breakpoints; import com.intellij.debugger.DebuggerBundle; diff --git a/java/debugger/impl/src/com/intellij/debugger/ui/breakpoints/FilteredRequestorImpl.java b/java/debugger/impl/src/com/intellij/debugger/ui/breakpoints/FilteredRequestorImpl.java index 4e25cf4ac7b1..349396284cea 100644 --- a/java/debugger/impl/src/com/intellij/debugger/ui/breakpoints/FilteredRequestorImpl.java +++ b/java/debugger/impl/src/com/intellij/debugger/ui/breakpoints/FilteredRequestorImpl.java @@ -14,10 +14,6 @@ * limitations under the License. */ -/** - * class FilteredRequestorImpl - * @author Jeka - */ package com.intellij.debugger.ui.breakpoints; import com.intellij.debugger.InstanceFilter; diff --git a/java/debugger/impl/src/com/intellij/debugger/ui/breakpoints/MethodBreakpointPropertiesPanel.java b/java/debugger/impl/src/com/intellij/debugger/ui/breakpoints/MethodBreakpointPropertiesPanel.java index c9026d152e99..289d9d20a94e 100644 --- a/java/debugger/impl/src/com/intellij/debugger/ui/breakpoints/MethodBreakpointPropertiesPanel.java +++ b/java/debugger/impl/src/com/intellij/debugger/ui/breakpoints/MethodBreakpointPropertiesPanel.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2009 JetBrains s.r.o. + * Copyright 2000-2016 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. @@ -14,10 +14,6 @@ * limitations under the License. */ -/** - * class MethodBreakpointPropertiesPanel - * @author Jeka - */ package com.intellij.debugger.ui.breakpoints; import com.intellij.debugger.DebuggerBundle; diff --git a/java/idea-ui/src/com/intellij/ide/util/newProjectWizard/SourceRootFinder.java b/java/idea-ui/src/com/intellij/ide/util/newProjectWizard/SourceRootFinder.java index c0a340ebe0ea..c1bbd5adc9dc 100644 --- a/java/idea-ui/src/com/intellij/ide/util/newProjectWizard/SourceRootFinder.java +++ b/java/idea-ui/src/com/intellij/ide/util/newProjectWizard/SourceRootFinder.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2010 JetBrains s.r.o. + * Copyright 2000-2016 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. @@ -21,10 +21,6 @@ import com.intellij.openapi.util.Pair; import java.io.File; import java.util.List; -/** - * @author Maxim.Medvedev - */ - /** * @deprecated use {@link com.intellij.ide.util.projectWizard.importSources.JavaSourceRootDetector} instead */ diff --git a/java/java-analysis-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/CastMethodArgumentFix.java b/java/java-analysis-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/CastMethodArgumentFix.java index 0bdc0a5f1c03..2e6971a3ea9c 100644 --- a/java/java-analysis-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/CastMethodArgumentFix.java +++ b/java/java-analysis-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/CastMethodArgumentFix.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2009 JetBrains s.r.o. + * Copyright 2000-2016 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. @@ -14,13 +14,6 @@ * limitations under the License. */ -/** - * Created by IntelliJ IDEA. - * User: cdr - * Date: Nov 13, 2002 - * Time: 3:26:50 PM - * To change this template use Options | File Templates. - */ package com.intellij.codeInsight.daemon.impl.quickfix; import com.intellij.codeInsight.daemon.QuickFixBundle; diff --git a/java/java-analysis-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/ConstructorParametersFixer.java b/java/java-analysis-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/ConstructorParametersFixer.java index 28acb28257a7..327c54e59180 100644 --- a/java/java-analysis-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/ConstructorParametersFixer.java +++ b/java/java-analysis-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/ConstructorParametersFixer.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2009 JetBrains s.r.o. + * Copyright 2000-2016 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. @@ -14,20 +14,20 @@ * limitations under the License. */ -/** - * Propose to cast one argument to corresponding type - * in the constructor invocation - * E.g. - * - * User: cdr - * Date: Nov 13, 2002 +/* + Propose to cast one argument to corresponding type + in the constructor invocation + E.g. + + User: cdr + Date: Nov 13, 2002 */ package com.intellij.codeInsight.daemon.impl.quickfix; import com.intellij.codeInsight.daemon.impl.HighlightInfo; +import com.intellij.openapi.util.TextRange; import com.intellij.psi.*; import com.intellij.psi.infos.CandidateInfo; -import com.intellij.openapi.util.TextRange; import org.jetbrains.annotations.NotNull; public class ConstructorParametersFixer { diff --git a/java/java-analysis-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/QualifySuperArgumentFix.java b/java/java-analysis-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/QualifySuperArgumentFix.java index 0a3048f23273..6219d0e12fe3 100644 --- a/java/java-analysis-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/QualifySuperArgumentFix.java +++ b/java/java-analysis-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/QualifySuperArgumentFix.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2013 JetBrains s.r.o. + * Copyright 2000-2016 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. @@ -14,28 +14,14 @@ * limitations under the License. */ -/** - * Created by IntelliJ IDEA. - * User: cdr - * Date: Nov 13, 2002 - * Time: 3:26:50 PM - * To change this template use Options | File Templates. - */ package com.intellij.codeInsight.daemon.impl.quickfix; import com.intellij.codeInsight.daemon.impl.HighlightInfo; -import com.intellij.openapi.util.TextRange; import com.intellij.psi.*; -import com.intellij.psi.infos.CandidateInfo; import com.intellij.psi.util.PsiTreeUtil; -import com.intellij.psi.util.PsiUtil; -import com.intellij.psi.util.TypeConversionUtil; import com.intellij.refactoring.util.RefactoringChangeUtil; import org.jetbrains.annotations.NotNull; -import java.util.HashSet; -import java.util.Set; - public class QualifySuperArgumentFix extends QualifyThisOrSuperArgumentFix { public QualifySuperArgumentFix(@NotNull PsiExpression expression, @NotNull PsiClass psiClass) { super(expression, psiClass); diff --git a/java/java-analysis-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/QualifyThisArgumentFix.java b/java/java-analysis-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/QualifyThisArgumentFix.java index c5bba7888154..0375eb834407 100644 --- a/java/java-analysis-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/QualifyThisArgumentFix.java +++ b/java/java-analysis-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/QualifyThisArgumentFix.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2014 JetBrains s.r.o. + * Copyright 2000-2016 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. @@ -14,13 +14,6 @@ * limitations under the License. */ -/** - * Created by IntelliJ IDEA. - * User: cdr - * Date: Nov 13, 2002 - * Time: 3:26:50 PM - * To change this template use Options | File Templates. - */ package com.intellij.codeInsight.daemon.impl.quickfix; import com.intellij.codeInsight.daemon.impl.HighlightInfo; diff --git a/java/java-analysis-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/QualifyThisOrSuperArgumentFix.java b/java/java-analysis-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/QualifyThisOrSuperArgumentFix.java index 2ea59ccadb91..9f3cae83b5e2 100644 --- a/java/java-analysis-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/QualifyThisOrSuperArgumentFix.java +++ b/java/java-analysis-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/QualifyThisOrSuperArgumentFix.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2013 JetBrains s.r.o. + * Copyright 2000-2016 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. @@ -14,33 +14,19 @@ * limitations under the License. */ -/** - * Created by IntelliJ IDEA. - * User: cdr - * Date: Nov 13, 2002 - * Time: 3:26:50 PM - * To change this template use Options | File Templates. - */ package com.intellij.codeInsight.daemon.impl.quickfix; -import com.intellij.codeInsight.daemon.impl.HighlightInfo; import com.intellij.codeInsight.intention.IntentionAction; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.editor.Editor; import com.intellij.openapi.project.Project; -import com.intellij.openapi.util.TextRange; -import com.intellij.psi.*; -import com.intellij.psi.infos.CandidateInfo; -import com.intellij.psi.util.PsiTreeUtil; -import com.intellij.psi.util.PsiUtil; -import com.intellij.psi.util.TypeConversionUtil; -import com.intellij.refactoring.util.RefactoringChangeUtil; +import com.intellij.psi.PsiClass; +import com.intellij.psi.PsiExpression; +import com.intellij.psi.PsiFile; +import com.intellij.psi.PsiManager; import com.intellij.util.IncorrectOperationException; import org.jetbrains.annotations.NotNull; -import java.util.HashSet; -import java.util.Set; - public abstract class QualifyThisOrSuperArgumentFix implements IntentionAction { protected static final Logger LOG = Logger.getInstance("#" + QualifyThisOrSuperArgumentFix.class.getName()); protected final PsiExpression myExpression; diff --git a/java/java-analysis-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/SimplifyBooleanExpressionFix.java b/java/java-analysis-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/SimplifyBooleanExpressionFix.java index 96d90b24c256..914cc34cfc4d 100644 --- a/java/java-analysis-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/SimplifyBooleanExpressionFix.java +++ b/java/java-analysis-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/SimplifyBooleanExpressionFix.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2009 JetBrains s.r.o. + * Copyright 2000-2016 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. @@ -14,9 +14,6 @@ * limitations under the License. */ -/** - * @author cdr - */ package com.intellij.codeInsight.daemon.impl.quickfix; import com.intellij.codeInsight.FileModificationService; diff --git a/java/java-analysis-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/VariableArrayTypeFix.java b/java/java-analysis-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/VariableArrayTypeFix.java index 1087e2ec29ef..c4257b06cdb2 100644 --- a/java/java-analysis-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/VariableArrayTypeFix.java +++ b/java/java-analysis-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/VariableArrayTypeFix.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2009 JetBrains s.r.o. + * Copyright 2000-2016 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. @@ -160,8 +160,8 @@ public class VariableArrayTypeFix extends LocalQuickFixOnPsiElement { final PsiArrayInitializerExpression myInitializer = (PsiArrayInitializerExpression)startElement; final PsiVariable myVariable = getVariableLocal(myInitializer); if (myVariable == null) return; - /** - * only for the case when in same statement with initialization + /* + only for the case when in same statement with initialization */ final PsiNewExpression myNewExpression = getNewExpressionLocal(myInitializer); diff --git a/java/java-analysis-impl/src/com/intellij/codeInspection/AnonymousCanBeLambdaInspection.java b/java/java-analysis-impl/src/com/intellij/codeInspection/AnonymousCanBeLambdaInspection.java index 6b3afbe6d968..7c6067ca278e 100644 --- a/java/java-analysis-impl/src/com/intellij/codeInspection/AnonymousCanBeLambdaInspection.java +++ b/java/java-analysis-impl/src/com/intellij/codeInspection/AnonymousCanBeLambdaInspection.java @@ -139,6 +139,15 @@ public class AnonymousCanBeLambdaInspection extends BaseJavaBatchLocalInspection if (inferredType == null) { return true; } + + PsiType inferenceMethodReturnType = LambdaUtil.getFunctionalInterfaceReturnType(inferredType); + PsiType existingMethodReturnType = method.getReturnType(); + if (existingMethodReturnType == null || + inferenceMethodReturnType != null && + !PsiType.VOID.equals(inferenceMethodReturnType) && !TypeConversionUtil.isAssignable(existingMethodReturnType, inferenceMethodReturnType)) { + return true; + } + final ForbiddenRefsChecker checker = new ForbiddenRefsChecker(method, aClass, inferredType != PsiType.NULL ? inferredType : null); final PsiCodeBlock body = method.getBody(); LOG.assertTrue(body != null); diff --git a/java/java-analysis-impl/src/com/intellij/codeInspection/RedundantSuppressInspectionBase.java b/java/java-analysis-impl/src/com/intellij/codeInspection/RedundantSuppressInspectionBase.java index 388e66022cce..7304094495c6 100644 --- a/java/java-analysis-impl/src/com/intellij/codeInspection/RedundantSuppressInspectionBase.java +++ b/java/java-analysis-impl/src/com/intellij/codeInspection/RedundantSuppressInspectionBase.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2009 JetBrains s.r.o. + * Copyright 2000-2016 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. @@ -44,10 +44,10 @@ import java.util.*; * @author cdr */ public class RedundantSuppressInspectionBase extends GlobalInspectionTool { - private BidirectionalMap myQuickFixes = null; + private BidirectionalMap myQuickFixes; private static final Logger LOG = Logger.getInstance("#com.intellij.codeInspection.RedundantSuppressInspection"); - public boolean IGNORE_ALL = false; + public boolean IGNORE_ALL; @Override @NotNull diff --git a/java/java-analysis-impl/src/com/intellij/codeInspection/StreamApiMigrationInspection.java b/java/java-analysis-impl/src/com/intellij/codeInspection/StreamApiMigrationInspection.java index 02d49d6cab9a..e868a10530a4 100644 --- a/java/java-analysis-impl/src/com/intellij/codeInspection/StreamApiMigrationInspection.java +++ b/java/java-analysis-impl/src/com/intellij/codeInspection/StreamApiMigrationInspection.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2014 JetBrains s.r.o. + * Copyright 2000-2016 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. @@ -51,7 +51,7 @@ import java.util.List; public class StreamApiMigrationInspection extends BaseJavaBatchLocalInspectionTool { private static final Logger LOG = Logger.getInstance("#" + StreamApiMigrationInspection.class.getName()); - public boolean REPLACE_TRIVIAL_FOREACH = false; + public boolean REPLACE_TRIVIAL_FOREACH; @Nullable @Override diff --git a/java/java-analysis-impl/src/com/intellij/codeInspection/bytecodeAnalysis/Analysis.java b/java/java-analysis-impl/src/com/intellij/codeInspection/bytecodeAnalysis/Analysis.java index 90ae880310bd..f06b1bda7065 100644 --- a/java/java-analysis-impl/src/com/intellij/codeInspection/bytecodeAnalysis/Analysis.java +++ b/java/java-analysis-impl/src/com/intellij/codeInspection/bytecodeAnalysis/Analysis.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2014 JetBrains s.r.o. + * Copyright 2000-2016 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. @@ -26,9 +26,12 @@ import org.jetbrains.org.objectweb.asm.tree.analysis.AnalyzerException; import org.jetbrains.org.objectweb.asm.tree.analysis.BasicValue; import org.jetbrains.org.objectweb.asm.tree.analysis.Frame; -import java.util.*; +import java.util.ArrayList; +import java.util.List; +import java.util.Set; -import static com.intellij.codeInspection.bytecodeAnalysis.Direction.*; +import static com.intellij.codeInspection.bytecodeAnalysis.Direction.In; +import static com.intellij.codeInspection.bytecodeAnalysis.Direction.InOut; class AbstractValues { static final class ParamValue extends BasicValue { @@ -213,7 +216,7 @@ abstract class Analysis { final protected List[] computed; final Key aKey; - Res earlyResult = null; + Res earlyResult; protected Analysis(RichControlFlow richControlFlow, Direction direction, boolean stable) { this.richControlFlow = richControlFlow; diff --git a/java/java-analysis-impl/src/com/intellij/codeInspection/bytecodeAnalysis/Contracts.java b/java/java-analysis-impl/src/com/intellij/codeInspection/bytecodeAnalysis/Contracts.java index 9d71d4218939..08a529c5a098 100644 --- a/java/java-analysis-impl/src/com/intellij/codeInspection/bytecodeAnalysis/Contracts.java +++ b/java/java-analysis-impl/src/com/intellij/codeInspection/bytecodeAnalysis/Contracts.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2014 JetBrains s.r.o. + * Copyright 2000-2016 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. @@ -34,8 +34,9 @@ import java.util.List; import java.util.Set; import static com.intellij.codeInspection.bytecodeAnalysis.AbstractValues.*; +import static com.intellij.codeInspection.bytecodeAnalysis.Direction.InOut; +import static com.intellij.codeInspection.bytecodeAnalysis.Direction.Out; import static org.jetbrains.org.objectweb.asm.Opcodes.*; -import static com.intellij.codeInspection.bytecodeAnalysis.Direction.*; class InOutAnalysis extends Analysis { @@ -47,8 +48,8 @@ class InOutAnalysis extends Analysis { private final Value inValue; private final int generalizeShift; private Result internalResult; - private int id = 0; - private int pendingTop = 0; + private int id; + private int pendingTop; protected InOutAnalysis(RichControlFlow richControlFlow, Direction direction, boolean[] resultOrigins, boolean stable, State[] pending) { super(richControlFlow, direction, stable); @@ -273,7 +274,7 @@ class InOutInterpreter extends BasicInterpreter { final boolean[] resultOrigins; final boolean nullAnalysis; - boolean deReferenced = false; + boolean deReferenced; InOutInterpreter(Direction direction, InsnList insns, boolean[] resultOrigins) { this.direction = direction; diff --git a/java/java-analysis-impl/src/com/intellij/codeInspection/bytecodeAnalysis/NullableMethodAnalysis.java b/java/java-analysis-impl/src/com/intellij/codeInspection/bytecodeAnalysis/NullableMethodAnalysis.java index 2e2924c044ed..b865a9a4af34 100644 --- a/java/java-analysis-impl/src/com/intellij/codeInspection/bytecodeAnalysis/NullableMethodAnalysis.java +++ b/java/java-analysis-impl/src/com/intellij/codeInspection/bytecodeAnalysis/NullableMethodAnalysis.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2014 JetBrains s.r.o. + * Copyright 2000-2016 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. @@ -211,12 +211,12 @@ class NullableMethodInterpreter extends BasicInterpreter implements InterpreterE private final int[] originsMapping; final Key[] keys; - Constraint constraint = null; - int delta = 0; - int nullsDelta = 0; + Constraint constraint; + int delta; + int nullsDelta; int notNullInsn = -1; - int notNullCall = 0; - int notNullNull = 0; + int notNullCall; + int notNullNull; NullableMethodInterpreter(InsnList insns, boolean[] origins, int[] originsMapping) { this.insns = insns; diff --git a/java/java-analysis-impl/src/com/intellij/codeInspection/bytecodeAnalysis/Parameters.java b/java/java-analysis-impl/src/com/intellij/codeInspection/bytecodeAnalysis/Parameters.java index 52106534d8a7..ad52d2f8a7bb 100644 --- a/java/java-analysis-impl/src/com/intellij/codeInspection/bytecodeAnalysis/Parameters.java +++ b/java/java-analysis-impl/src/com/intellij/codeInspection/bytecodeAnalysis/Parameters.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2014 JetBrains s.r.o. + * Copyright 2000-2016 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. @@ -34,9 +34,9 @@ import java.util.List; import java.util.Set; import static com.intellij.codeInspection.bytecodeAnalysis.AbstractValues.*; +import static com.intellij.codeInspection.bytecodeAnalysis.Direction.In; import static com.intellij.codeInspection.bytecodeAnalysis.PResults.*; import static org.jetbrains.org.objectweb.asm.Opcodes.*; -import static com.intellij.codeInspection.bytecodeAnalysis.Direction.*; abstract class PResults { // SoP = sum of products @@ -211,9 +211,9 @@ class NonNullInAnalysis extends Analysis { } } - private int id = 0; - private Frame nextFrame = null; - private PResult subResult = null; + private int id; + private Frame nextFrame; + private PResult subResult; @NotNull protected Equation analyze() throws AnalyzerException { @@ -383,7 +383,7 @@ class NonNullInAnalysis extends Analysis { } - private int pendingTop = 0; + private int pendingTop; private void pendingPush(PendingAction action) throws AnalyzerException { if (pendingTop >= STEPS_LIMIT) { @@ -437,11 +437,11 @@ class NullableInAnalysis extends Analysis { } } - private int id = 0; - private Frame nextFrame = null; + private int id; + private Frame nextFrame; private PResult myResult = Identity; private PResult subResult = Identity; - private boolean top = false; + private boolean top; @NotNull protected Equation analyze() throws AnalyzerException { @@ -573,7 +573,7 @@ class NullableInAnalysis extends Analysis { } - private int pendingTop = 0; + private int pendingTop; private void pendingPush(State state) throws AnalyzerException { if (pendingTop >= STEPS_LIMIT) { @@ -602,7 +602,7 @@ class NullableInAnalysis extends Analysis { } abstract class NullityInterpreter extends BasicInterpreter { - boolean top = false; + boolean top; final boolean nullableAnalysis; final int nullityMask; private PResult subResult = Identity; diff --git a/java/java-analysis-impl/src/com/intellij/codeInspection/bytecodeAnalysis/asm/LeakingParameters.java b/java/java-analysis-impl/src/com/intellij/codeInspection/bytecodeAnalysis/asm/LeakingParameters.java index 42ee796d4bcf..6b7ba379f769 100644 --- a/java/java-analysis-impl/src/com/intellij/codeInspection/bytecodeAnalysis/asm/LeakingParameters.java +++ b/java/java-analysis-impl/src/com/intellij/codeInspection/bytecodeAnalysis/asm/LeakingParameters.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2014 JetBrains s.r.o. + * Copyright 2000-2016 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. @@ -299,8 +299,8 @@ class ParametersUsage extends Interpreter { class IParametersUsage extends Interpreter { static final IParamsValue val1 = new IParamsValue(0, 1); static final IParamsValue val2 = new IParamsValue(0, 2); - int leaking = 0; - int nullableLeaking = 0; + int leaking; + int nullableLeaking; int called = -1; final int rangeStart; final int rangeEnd; diff --git a/java/java-analysis-impl/src/com/intellij/codeInspection/canBeFinal/CanBeFinalInspection.java b/java/java-analysis-impl/src/com/intellij/codeInspection/canBeFinal/CanBeFinalInspection.java index 3582ce1a293c..9ca3844e0987 100644 --- a/java/java-analysis-impl/src/com/intellij/codeInspection/canBeFinal/CanBeFinalInspection.java +++ b/java/java-analysis-impl/src/com/intellij/codeInspection/canBeFinal/CanBeFinalInspection.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2014 JetBrains s.r.o. + * Copyright 2000-2016 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. @@ -47,8 +47,8 @@ import java.awt.*; public class CanBeFinalInspection extends GlobalJavaBatchInspectionTool { private static final Logger LOG = Logger.getInstance("#com.intellij.codeInspection.canBeFinal.CanBeFinalInspection"); - public boolean REPORT_CLASSES = false; - public boolean REPORT_METHODS = false; + public boolean REPORT_CLASSES; + public boolean REPORT_METHODS; public boolean REPORT_FIELDS = true; public static final String DISPLAY_NAME = InspectionsBundle.message("inspection.can.be.final.display.name"); @NonNls public static final String SHORT_NAME = "CanBeFinal"; diff --git a/java/java-analysis-impl/src/com/intellij/codeInspection/dataFlow/ContractInference.java b/java/java-analysis-impl/src/com/intellij/codeInspection/dataFlow/ContractInference.java index 4fdc7f5842c0..b05b41ce7211 100644 --- a/java/java-analysis-impl/src/com/intellij/codeInspection/dataFlow/ContractInference.java +++ b/java/java-analysis-impl/src/com/intellij/codeInspection/dataFlow/ContractInference.java @@ -19,8 +19,6 @@ import com.intellij.codeInsight.NullableNotNullManager; import com.intellij.codeInspection.dataFlow.MethodContract.ValueConstraint; import com.intellij.codeInspection.dataFlow.instructions.MethodCallInstruction; import com.intellij.openapi.diagnostic.Logger; -import com.intellij.openapi.util.Computable; -import com.intellij.openapi.util.Condition; import com.intellij.openapi.util.RecursionManager; import com.intellij.psi.*; import com.intellij.psi.tree.IElementType; @@ -28,8 +26,6 @@ import com.intellij.psi.util.CachedValueProvider; import com.intellij.psi.util.CachedValuesManager; import com.intellij.psi.util.PsiModificationTracker; import com.intellij.psi.util.PsiUtil; -import com.intellij.util.Function; -import com.intellij.util.NullableFunction; import com.intellij.util.containers.ContainerUtil; import com.siyeh.ig.psiutils.SideEffectChecker; import org.jetbrains.annotations.NotNull; @@ -52,19 +48,11 @@ public class ContractInference { return Collections.emptyList(); } - return CachedValuesManager.getCachedValue(method, new CachedValueProvider>() { - @Nullable - @Override - public Result> compute() { - List result = RecursionManager.doPreventingRecursion(method, true, new Computable>() { - @Override - public List compute() { - return new ContractInferenceInterpreter(method).inferContracts(); - } - }); - if (result == null) result = Collections.emptyList(); - return Result.create(result, method, PsiModificationTracker.JAVA_STRUCTURE_MODIFICATION_COUNT); - } + return CachedValuesManager.getCachedValue(method, () -> { + List result = RecursionManager.doPreventingRecursion(method, true, () -> + new ContractInferenceInterpreter(method).inferContracts()); + if (result == null) result = Collections.emptyList(); + return CachedValueProvider.Result.create(result, method, PsiModificationTracker.JAVA_STRUCTURE_MODIFICATION_COUNT); }); } } @@ -91,14 +79,11 @@ class ContractInferenceInterpreter { if (referenceTypeReturned) { contracts = boxReturnValues(contracts); } - List compatible = ContainerUtil.filter(contracts, new Condition() { - @Override - public boolean value(MethodContract contract) { - if (notNull && contract.returnValue == NOT_NULL_VALUE) { - return false; - } - return InferenceFromSourceUtil.isReturnTypeCompatible(returnType, contract.returnValue); + List compatible = ContainerUtil.filter(contracts, contract -> { + if (notNull && contract.returnValue == NOT_NULL_VALUE) { + return false; } + return InferenceFromSourceUtil.isReturnTypeCompatible(returnType, contract.returnValue); }); if (compatible.size() > ContractInference.MAX_CONTRACT_COUNT) { LOG.debug("Too many contracts for " + PsiUtil.getMemberQualifiedName(myMethod) + ", shrinking the list"); @@ -109,14 +94,11 @@ class ContractInferenceInterpreter { @NotNull private static List boxReturnValues(List contracts) { - return ContainerUtil.mapNotNull(contracts, new Function() { - @Override - public MethodContract fun(MethodContract contract) { - if (contract.returnValue == FALSE_VALUE || contract.returnValue == TRUE_VALUE) { - return new MethodContract(contract.arguments, NOT_NULL_VALUE); - } - return contract; + return ContainerUtil.mapNotNull(contracts, contract -> { + if (contract.returnValue == FALSE_VALUE || contract.returnValue == TRUE_VALUE) { + return new MethodContract(contract.arguments, NOT_NULL_VALUE); } + return contract; }); } @@ -168,42 +150,38 @@ class ContractInferenceInterpreter { final boolean varArgCall = MethodCallInstruction.isVarArgCall(targetMethod, result.getSubstitutor(), arguments, parameters); final boolean notNull = NullableNotNullManager.isNotNull(targetMethod); - List fromDelegate = ContainerUtil.mapNotNull(ControlFlowAnalyzer.getMethodContracts(targetMethod), new NullableFunction() { - @Nullable - @Override - public MethodContract fun(MethodContract delegateContract) { - ValueConstraint[] answer = myEmptyConstraints; - for (int i = 0; i < delegateContract.arguments.length; i++) { - if (i >= arguments.length) return null; - ValueConstraint argConstraint = delegateContract.arguments[i]; - if (argConstraint != ANY_VALUE) { - if (varArgCall && i >= parameters.length - 1) { - if (argConstraint == NULL_VALUE) { - return null; - } - break; + List fromDelegate = ContainerUtil.mapNotNull(ControlFlowAnalyzer.getMethodContracts(targetMethod), delegateContract -> { + ValueConstraint[] answer = myEmptyConstraints; + for (int i = 0; i < delegateContract.arguments.length; i++) { + if (i >= arguments.length) return null; + ValueConstraint argConstraint = delegateContract.arguments[i]; + if (argConstraint != ANY_VALUE) { + if (varArgCall && i >= parameters.length - 1) { + if (argConstraint == NULL_VALUE) { + return null; } + break; + } - int paramIndex = resolveParameter(arguments[i]); - if (paramIndex < 0) { - if (argConstraint != getLiteralConstraint(arguments[i])) { - return null; - } + int paramIndex = resolveParameter(arguments[i]); + if (paramIndex < 0) { + if (argConstraint != getLiteralConstraint(arguments[i])) { + return null; } - else { - answer = withConstraint(answer, paramIndex, argConstraint); - if (answer == null) { - return null; - } + } + else { + answer = withConstraint(answer, paramIndex, argConstraint); + if (answer == null) { + return null; } } } - ValueConstraint returnValue = negated ? negateConstraint(delegateContract.returnValue) : delegateContract.returnValue; - if (notNull && returnValue != THROW_EXCEPTION) { - returnValue = NOT_NULL_VALUE; - } - return answer == null ? null : new MethodContract(answer, returnValue); } + ValueConstraint returnValue = negated ? negateConstraint(delegateContract.returnValue) : delegateContract.returnValue; + if (notNull && returnValue != THROW_EXCEPTION) { + returnValue = NOT_NULL_VALUE; + } + return answer == null ? null : new MethodContract(answer, returnValue); }); if (notNull) { return ContainerUtil.concat(fromDelegate, Collections.singletonList(new MethodContract(myEmptyConstraints, NOT_NULL_VALUE))); @@ -230,8 +208,8 @@ class ContractInferenceInterpreter { if (expr instanceof PsiConditionalExpression) { List conditionResults = visitExpression(states, ((PsiConditionalExpression)expr).getCondition()); return ContainerUtil.concat( - visitExpression(antecedentsOf(filterReturning(conditionResults, TRUE_VALUE)), ((PsiConditionalExpression)expr).getThenExpression()), - visitExpression(antecedentsOf(filterReturning(conditionResults, FALSE_VALUE)), ((PsiConditionalExpression)expr).getElseExpression())); + visitExpression(antecedentsReturning(conditionResults, TRUE_VALUE), ((PsiConditionalExpression)expr).getThenExpression()), + visitExpression(antecedentsReturning(conditionResults, FALSE_VALUE), ((PsiConditionalExpression)expr).getElseExpression())); } @@ -255,14 +233,7 @@ class ContractInferenceInterpreter { if (expr instanceof PsiInstanceOfExpression) { final int parameter = resolveParameter(((PsiInstanceOfExpression)expr).getOperand()); if (parameter >= 0) { - return ContainerUtil.mapNotNull(states, new Function() { - @Override - public MethodContract fun(ValueConstraint[] state) { - ValueConstraint paramConstraint = NULL_VALUE; - ValueConstraint returnValue = FALSE_VALUE; - return contractWithConstraint(state, parameter, paramConstraint, returnValue); - } - }); + return ContainerUtil.mapNotNull(states, state -> contractWithConstraint(state, parameter, NULL_VALUE, FALSE_VALUE)); } } @@ -344,14 +315,8 @@ class ContractInferenceInterpreter { return myMethod.getParameterList().getParameters()[parameter]; } - private static List toContracts(List states, - final ValueConstraint constraint) { - return ContainerUtil.map(states, new Function() { - @Override - public MethodContract fun(ValueConstraint[] state) { - return new MethodContract(state, constraint); - } - }); + private static List toContracts(List states, ValueConstraint constraint) { + return ContainerUtil.map(states, state -> new MethodContract(state, constraint)); } private List visitLogicalOperation(PsiExpression[] operands, boolean conjunction, List states) { @@ -359,29 +324,15 @@ class ContractInferenceInterpreter { List finalStates = ContainerUtil.newArrayList(); for (PsiExpression operand : operands) { List opResults = visitExpression(states, operand); - finalStates.addAll(filterReturning(opResults, breakValue)); - states = antecedentsOf(filterReturning(opResults, negateConstraint(breakValue))); + finalStates.addAll(ContainerUtil.filter(opResults, contract -> contract.returnValue == breakValue)); + states = antecedentsReturning(opResults, negateConstraint(breakValue)); } finalStates.addAll(toContracts(states, negateConstraint(breakValue))); return finalStates; } - private static List antecedentsOf(List values) { - return ContainerUtil.map(values, new Function() { - @Override - public ValueConstraint[] fun(MethodContract contract) { - return contract.arguments; - } - }); - } - - private static List filterReturning(List values, final ValueConstraint result) { - return ContainerUtil.filter(values, new Condition() { - @Override - public boolean value(MethodContract contract) { - return contract.returnValue == result; - } - }); + private static List antecedentsReturning(List values, ValueConstraint result) { + return ContainerUtil.mapNotNull(values, contract -> contract.returnValue == result ? contract.arguments : null); } @NotNull @@ -396,10 +347,10 @@ class ContractInferenceInterpreter { PsiStatement thenBranch = ((PsiIfStatement)statement).getThenBranch(); if (thenBranch != null) { - result.addAll(visitStatements(antecedentsOf(filterReturning(conditionResults, TRUE_VALUE)), thenBranch)); + result.addAll(visitStatements(antecedentsReturning(conditionResults, TRUE_VALUE), thenBranch)); } - List falseStates = antecedentsOf(filterReturning(conditionResults, FALSE_VALUE)); + List falseStates = antecedentsReturning(conditionResults, FALSE_VALUE); PsiStatement elseBranch = ((PsiIfStatement)statement).getElseBranch(); if (elseBranch != null) { result.addAll(visitStatements(falseStates, elseBranch)); @@ -416,7 +367,7 @@ class ContractInferenceInterpreter { } else if (statement instanceof PsiAssertStatement) { List conditionResults = visitExpression(states, ((PsiAssertStatement)statement).getAssertCondition()); - result.addAll(toContracts(antecedentsOf(filterReturning(conditionResults, FALSE_VALUE)), THROW_EXCEPTION)); + result.addAll(toContracts(antecedentsReturning(conditionResults, FALSE_VALUE), THROW_EXCEPTION)); } else if (statement instanceof PsiDeclarationStatement && !mayHaveSideEffects((PsiDeclarationStatement)statement)) { continue; diff --git a/java/java-analysis-impl/src/com/intellij/codeInspection/dataFlow/DataFlowInspectionBase.java b/java/java-analysis-impl/src/com/intellij/codeInspection/dataFlow/DataFlowInspectionBase.java index add2fbeced8d..231fbebfbc53 100644 --- a/java/java-analysis-impl/src/com/intellij/codeInspection/dataFlow/DataFlowInspectionBase.java +++ b/java/java-analysis-impl/src/com/intellij/codeInspection/dataFlow/DataFlowInspectionBase.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2012 JetBrains s.r.o. + * Copyright 2000-2016 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. @@ -63,10 +63,10 @@ import java.util.*; public class DataFlowInspectionBase extends BaseJavaBatchLocalInspectionTool { private static final Logger LOG = Logger.getInstance("#com.intellij.codeInspection.dataFlow.DataFlowInspection"); @NonNls private static final String SHORT_NAME = "ConstantConditions"; - public boolean SUGGEST_NULLABLE_ANNOTATIONS = false; - public boolean DONT_REPORT_TRUE_ASSERT_STATEMENTS = false; - public boolean TREAT_UNKNOWN_MEMBERS_AS_NULLABLE = false; - public boolean IGNORE_ASSERT_STATEMENTS = false; + public boolean SUGGEST_NULLABLE_ANNOTATIONS; + public boolean DONT_REPORT_TRUE_ASSERT_STATEMENTS; + public boolean TREAT_UNKNOWN_MEMBERS_AS_NULLABLE; + public boolean IGNORE_ASSERT_STATEMENTS; public boolean REPORT_CONSTANT_REFERENCE_VALUES = true; @Override diff --git a/java/java-analysis-impl/src/com/intellij/codeInspection/dataFlow/NullityInference.java b/java/java-analysis-impl/src/com/intellij/codeInspection/dataFlow/NullityInference.java index d7f265808af1..e27fd76421f1 100644 --- a/java/java-analysis-impl/src/com/intellij/codeInspection/dataFlow/NullityInference.java +++ b/java/java-analysis-impl/src/com/intellij/codeInspection/dataFlow/NullityInference.java @@ -16,7 +16,6 @@ package com.intellij.codeInspection.dataFlow; import com.intellij.codeInsight.NullableNotNullManager; -import com.intellij.openapi.util.Computable; import com.intellij.openapi.util.RecursionManager; import com.intellij.psi.*; import com.intellij.psi.util.CachedValueProvider; @@ -24,7 +23,6 @@ import com.intellij.psi.util.CachedValuesManager; import com.intellij.psi.util.PsiModificationTracker; import com.intellij.util.containers.ContainerUtil; import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; import java.util.Set; import java.util.concurrent.atomic.AtomicBoolean; @@ -44,19 +42,10 @@ public class NullityInference { return Nullness.UNKNOWN; } - return CachedValuesManager.getCachedValue(method, new CachedValueProvider() { - @Nullable - @Override - public Result compute() { - Nullness result = RecursionManager.doPreventingRecursion(method, true, new Computable() { - @Override - public Nullness compute() { - return doInferNullity(method); - } - }); - if (result == null) result = Nullness.UNKNOWN; - return Result.create(result, method, PsiModificationTracker.JAVA_STRUCTURE_MODIFICATION_COUNT); - } + return CachedValuesManager.getCachedValue(method, () -> { + Nullness result = RecursionManager.doPreventingRecursion(method, true, () -> doInferNullity(method)); + if (result == null) result = Nullness.UNKNOWN; + return CachedValueProvider.Result.create(result, method, PsiModificationTracker.JAVA_STRUCTURE_MODIFICATION_COUNT); }); } diff --git a/java/java-analysis-impl/src/com/intellij/codeInspection/dataFlow/PurityInference.java b/java/java-analysis-impl/src/com/intellij/codeInspection/dataFlow/PurityInference.java index 38c921825469..c62feff2f812 100644 --- a/java/java-analysis-impl/src/com/intellij/codeInspection/dataFlow/PurityInference.java +++ b/java/java-analysis-impl/src/com/intellij/codeInspection/dataFlow/PurityInference.java @@ -15,7 +15,6 @@ */ package com.intellij.codeInspection.dataFlow; -import com.intellij.openapi.util.Computable; import com.intellij.openapi.util.RecursionManager; import com.intellij.openapi.util.Ref; import com.intellij.psi.*; @@ -25,7 +24,6 @@ import com.intellij.psi.util.CachedValuesManager; import com.intellij.psi.util.PropertyUtil; import com.intellij.util.containers.ContainerUtil; import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; import java.util.List; @@ -43,18 +41,9 @@ public class PurityInference { return false; } - return CachedValuesManager.getCachedValue(method, new CachedValueProvider() { - @Nullable - @Override - public Result compute() { - boolean pure = RecursionManager.doPreventingRecursion(method, true, new Computable() { - @Override - public Boolean compute() { - return doInferPurity(method); - } - }) == Boolean.TRUE; - return Result.create(pure, method); - } + return CachedValuesManager.getCachedValue(method, () -> { + boolean pure = RecursionManager.doPreventingRecursion(method, true, () -> doInferPurity(method)) == Boolean.TRUE; + return CachedValueProvider.Result.create(pure, method); }); } diff --git a/java/java-analysis-impl/src/com/intellij/codeInspection/deadCode/UnusedDeclarationInspectionBase.java b/java/java-analysis-impl/src/com/intellij/codeInspection/deadCode/UnusedDeclarationInspectionBase.java index c253cb159aa8..47fb7a64bca7 100644 --- a/java/java-analysis-impl/src/com/intellij/codeInspection/deadCode/UnusedDeclarationInspectionBase.java +++ b/java/java-analysis-impl/src/com/intellij/codeInspection/deadCode/UnusedDeclarationInspectionBase.java @@ -77,7 +77,7 @@ public class UnusedDeclarationInspectionBase extends GlobalInspectionTool { final List myExtensions = ContainerUtil.createLockFreeCopyOnWriteList(); final UnusedSymbolLocalInspectionBase myLocalInspectionBase = createUnusedSymbolLocalInspection(); - private Set myProcessedSuspicious = null; + private Set myProcessedSuspicious; private int myPhase; private GlobalInspectionContext myContext; private final boolean myEnabledInEditor; diff --git a/java/java-analysis-impl/src/com/intellij/codeInspection/defUse/DefUseInspectionBase.java b/java/java-analysis-impl/src/com/intellij/codeInspection/defUse/DefUseInspectionBase.java index f3880bfef990..d7ef822d828f 100644 --- a/java/java-analysis-impl/src/com/intellij/codeInspection/defUse/DefUseInspectionBase.java +++ b/java/java-analysis-impl/src/com/intellij/codeInspection/defUse/DefUseInspectionBase.java @@ -34,7 +34,7 @@ import java.util.*; import java.util.List; public class DefUseInspectionBase extends BaseJavaBatchLocalInspectionTool { - public boolean REPORT_PREFIX_EXPRESSIONS = false; + public boolean REPORT_PREFIX_EXPRESSIONS; public boolean REPORT_POSTFIX_EXPRESSIONS = true; public boolean REPORT_REDUNDANT_INITIALIZER = true; diff --git a/java/java-analysis-impl/src/com/intellij/codeInspection/deprecation/DeprecationInspection.java b/java/java-analysis-impl/src/com/intellij/codeInspection/deprecation/DeprecationInspection.java index b02c02657532..081053a6ed53 100644 --- a/java/java-analysis-impl/src/com/intellij/codeInspection/deprecation/DeprecationInspection.java +++ b/java/java-analysis-impl/src/com/intellij/codeInspection/deprecation/DeprecationInspection.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2012 JetBrains s.r.o. + * Copyright 2000-2016 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. @@ -44,7 +44,7 @@ public class DeprecationInspection extends BaseJavaBatchLocalInspectionTool { public static final String DISPLAY_NAME = DeprecationUtil.DEPRECATION_DISPLAY_NAME; public static final String IGNORE_METHODS_OF_DEPRECATED_NAME = "IGNORE_METHODS_OF_DEPRECATED"; - public boolean IGNORE_INSIDE_DEPRECATED = false; + public boolean IGNORE_INSIDE_DEPRECATED; public boolean IGNORE_ABSTRACT_DEPRECATED_OVERRIDES = true; public boolean IGNORE_IMPORT_STATEMENTS = true; public boolean IGNORE_METHODS_OF_DEPRECATED = true; diff --git a/java/java-analysis-impl/src/com/intellij/codeInspection/duplicateThrows/DuplicateThrowsInspection.java b/java/java-analysis-impl/src/com/intellij/codeInspection/duplicateThrows/DuplicateThrowsInspection.java index c49057015244..5a8665a534c8 100644 --- a/java/java-analysis-impl/src/com/intellij/codeInspection/duplicateThrows/DuplicateThrowsInspection.java +++ b/java/java-analysis-impl/src/com/intellij/codeInspection/duplicateThrows/DuplicateThrowsInspection.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2012 JetBrains s.r.o. + * Copyright 2000-2016 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. @@ -26,7 +26,7 @@ import javax.swing.*; public class DuplicateThrowsInspection extends BaseJavaBatchLocalInspectionTool implements CleanupLocalInspectionTool { @SuppressWarnings("PublicField") - public boolean ignoreSubclassing = false; + public boolean ignoreSubclassing; @Override @NotNull diff --git a/java/java-analysis-impl/src/com/intellij/codeInspection/ex/EntryPointsManagerBase.java b/java/java-analysis-impl/src/com/intellij/codeInspection/ex/EntryPointsManagerBase.java index ab23d803aa57..1a5e464551eb 100644 --- a/java/java-analysis-impl/src/com/intellij/codeInspection/ex/EntryPointsManagerBase.java +++ b/java/java-analysis-impl/src/com/intellij/codeInspection/ex/EntryPointsManagerBase.java @@ -77,7 +77,7 @@ public abstract class EntryPointsManagerBase extends EntryPointsManager implemen @NonNls private static final String VERSION_ATTR = "version"; @NonNls private static final String ENTRY_POINT_ATTR = "entry_point"; private boolean myAddNonJavaEntries = true; - private boolean myResolved = false; + private boolean myResolved; protected final Project myProject; private long myLastModificationCount = -1; diff --git a/java/java-analysis-impl/src/com/intellij/codeInspection/inheritance/search/InheritorsStatisticalDataSearch.java b/java/java-analysis-impl/src/com/intellij/codeInspection/inheritance/search/InheritorsStatisticalDataSearch.java index 4266b66cb6ed..c28ccc2d6096 100644 --- a/java/java-analysis-impl/src/com/intellij/codeInspection/inheritance/search/InheritorsStatisticalDataSearch.java +++ b/java/java-analysis-impl/src/com/intellij/codeInspection/inheritance/search/InheritorsStatisticalDataSearch.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2014 JetBrains s.r.o. + * Copyright 2000-2016 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. @@ -118,7 +118,7 @@ public class InheritorsStatisticalDataSearch { myAllNotAnonymousInheritors = new HashSet(); } - private int myAnonymousInheritorsCount = 0; + private int myAnonymousInheritorsCount; private Set getAllNotAnonymousInheritors() { return myAllNotAnonymousInheritors; diff --git a/java/java-analysis-impl/src/com/intellij/codeInspection/java15api/Java15APIUsageInspectionBase.java b/java/java-analysis-impl/src/com/intellij/codeInspection/java15api/Java15APIUsageInspectionBase.java index ab764a1f518e..a95ad064e8bf 100644 --- a/java/java-analysis-impl/src/com/intellij/codeInspection/java15api/Java15APIUsageInspectionBase.java +++ b/java/java-analysis-impl/src/com/intellij/codeInspection/java15api/Java15APIUsageInspectionBase.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2015 JetBrains s.r.o. + * Copyright 2000-2016 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. @@ -98,7 +98,7 @@ public class Java15APIUsageInspectionBase extends BaseJavaBatchLocalInspectionTo ourDefaultMethods.add("java.util.Iterator#remove()"); } - protected LanguageLevel myEffectiveLanguageLevel = null; + protected LanguageLevel myEffectiveLanguageLevel; @Nullable private static Set getForbiddenApi(@NotNull LanguageLevel languageLevel) { diff --git a/java/java-analysis-impl/src/com/intellij/codeInspection/javaDoc/JavaDocLocalInspectionBase.java b/java/java-analysis-impl/src/com/intellij/codeInspection/javaDoc/JavaDocLocalInspectionBase.java index b263fc278ffe..04167ce144a4 100644 --- a/java/java-analysis-impl/src/com/intellij/codeInspection/javaDoc/JavaDocLocalInspectionBase.java +++ b/java/java-analysis-impl/src/com/intellij/codeInspection/javaDoc/JavaDocLocalInspectionBase.java @@ -78,17 +78,17 @@ public class JavaDocLocalInspectionBase extends BaseJavaBatchLocalInspectionTool public Options INNER_CLASS_OPTIONS = new Options("none", ""); public Options METHOD_OPTIONS = new Options("none", "@return@param@throws or @exception"); public Options FIELD_OPTIONS = new Options("none", ""); - public boolean IGNORE_DEPRECATED = false; + public boolean IGNORE_DEPRECATED; public boolean IGNORE_JAVADOC_PERIOD = true; @SuppressWarnings("unused") @Deprecated - public boolean IGNORE_DUPLICATED_THROWS = false; - public boolean IGNORE_POINT_TO_ITSELF = false; + public boolean IGNORE_DUPLICATED_THROWS; + public boolean IGNORE_POINT_TO_ITSELF; public String myAdditionalJavadocTags = ""; private boolean myIgnoreDuplicatedThrows = true; - private boolean myIgnoreEmptyDescriptions = false; - private boolean myIgnoreSimpleAccessors = false; + private boolean myIgnoreEmptyDescriptions; + private boolean myIgnoreSimpleAccessors; public void setPackageOption(String modifier, String tags) { PACKAGE_OPTIONS.ACCESS_JAVADOC_REQUIRED_FOR = modifier; @@ -451,7 +451,7 @@ public class JavaDocLocalInspectionBase extends BaseJavaBatchLocalInspectionTool private class ProblemHolderImpl implements JavadocHighlightUtil.ProblemHolder { private final InspectionManager myManager; private final boolean myOnTheFly; - private List myProblems = null; + private List myProblems; private ProblemHolderImpl(InspectionManager manager, boolean onTheFly) { myManager = manager; diff --git a/java/java-analysis-impl/src/com/intellij/codeInspection/nullable/NullableStuffInspectionBase.java b/java/java-analysis-impl/src/com/intellij/codeInspection/nullable/NullableStuffInspectionBase.java index 229979ca347d..44a28e2c7062 100644 --- a/java/java-analysis-impl/src/com/intellij/codeInspection/nullable/NullableStuffInspectionBase.java +++ b/java/java-analysis-impl/src/com/intellij/codeInspection/nullable/NullableStuffInspectionBase.java @@ -52,9 +52,9 @@ public class NullableStuffInspectionBase extends BaseJavaBatchLocalInspectionToo @SuppressWarnings({"WeakerAccess"}) public boolean REPORT_NOTNULL_PARAMETER_OVERRIDES_NULLABLE = true; @Deprecated @SuppressWarnings({"WeakerAccess"}) public boolean REPORT_NOT_ANNOTATED_PARAMETER_OVERRIDES_NOTNULL = true; @SuppressWarnings({"WeakerAccess"}) public boolean REPORT_NOT_ANNOTATED_GETTER = true; - @SuppressWarnings({"WeakerAccess"}) public boolean IGNORE_EXTERNAL_SUPER_NOTNULL = false; + @SuppressWarnings({"WeakerAccess"}) public boolean IGNORE_EXTERNAL_SUPER_NOTNULL; @SuppressWarnings({"WeakerAccess"}) public boolean REQUIRE_NOTNULL_FIELDS_INITIALIZED = true; - @SuppressWarnings({"WeakerAccess"}) public boolean REPORT_NOTNULL_PARAMETERS_OVERRIDES_NOT_ANNOTATED = false; + @SuppressWarnings({"WeakerAccess"}) public boolean REPORT_NOTNULL_PARAMETERS_OVERRIDES_NOT_ANNOTATED; @Deprecated @SuppressWarnings({"WeakerAccess"}) public boolean REPORT_NOT_ANNOTATED_SETTER_PARAMETER = true; @Deprecated @SuppressWarnings({"WeakerAccess"}) public boolean REPORT_ANNOTATION_NOT_PROPAGATED_TO_OVERRIDERS = true; // remains for test @SuppressWarnings({"WeakerAccess"}) public boolean REPORT_NULLS_PASSED_TO_NON_ANNOTATED_METHOD = true; diff --git a/java/java-analysis-impl/src/com/intellij/codeInspection/redundantCast/RedundantCastInspection.java b/java/java-analysis-impl/src/com/intellij/codeInspection/redundantCast/RedundantCastInspection.java index 930485558c20..2e4e80599c1b 100644 --- a/java/java-analysis-impl/src/com/intellij/codeInspection/redundantCast/RedundantCastInspection.java +++ b/java/java-analysis-impl/src/com/intellij/codeInspection/redundantCast/RedundantCastInspection.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2013 JetBrains s.r.o. + * Copyright 2000-2016 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. @@ -46,8 +46,8 @@ public class RedundantCastInspection extends GenericsInspectionToolBase { private static final String DISPLAY_NAME = InspectionsBundle.message("inspection.redundant.cast.display.name"); @NonNls private static final String SHORT_NAME = "RedundantCast"; - public boolean IGNORE_ANNOTATED_METHODS = false; - public boolean IGNORE_SUSPICIOUS_METHOD_CALLS = false; + public boolean IGNORE_ANNOTATED_METHODS; + public boolean IGNORE_SUSPICIOUS_METHOD_CALLS; public RedundantCastInspection() { diff --git a/java/java-analysis-impl/src/com/intellij/codeInspection/uncheckedWarnings/UncheckedWarningLocalInspectionBase.java b/java/java-analysis-impl/src/com/intellij/codeInspection/uncheckedWarnings/UncheckedWarningLocalInspectionBase.java index accdc0b2b17b..b938eef5f260 100644 --- a/java/java-analysis-impl/src/com/intellij/codeInspection/uncheckedWarnings/UncheckedWarningLocalInspectionBase.java +++ b/java/java-analysis-impl/src/com/intellij/codeInspection/uncheckedWarnings/UncheckedWarningLocalInspectionBase.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2013 JetBrains s.r.o. + * Copyright 2000-2016 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. @@ -50,11 +50,11 @@ public class UncheckedWarningLocalInspectionBase extends BaseJavaBatchLocalInspe public static final String DISPLAY_NAME = InspectionsBundle.message("unchecked.warning"); @NonNls private static final String ID = "unchecked"; private static final Logger LOG = Logger.getInstance("#" + UncheckedWarningLocalInspectionBase.class); - public boolean IGNORE_UNCHECKED_ASSIGNMENT = false; - public boolean IGNORE_UNCHECKED_GENERICS_ARRAY_CREATION = false; - public boolean IGNORE_UNCHECKED_CALL = false; - public boolean IGNORE_UNCHECKED_CAST = false; - public boolean IGNORE_UNCHECKED_OVERRIDING = false; + public boolean IGNORE_UNCHECKED_ASSIGNMENT; + public boolean IGNORE_UNCHECKED_GENERICS_ARRAY_CREATION; + public boolean IGNORE_UNCHECKED_CALL; + public boolean IGNORE_UNCHECKED_CAST; + public boolean IGNORE_UNCHECKED_OVERRIDING; protected static JCheckBox createSetting(final String cbText, final boolean option, diff --git a/java/java-analysis-impl/src/com/intellij/codeInspection/visibility/VisibilityInspection.java b/java/java-analysis-impl/src/com/intellij/codeInspection/visibility/VisibilityInspection.java index e4d3b33a5cfc..6fb30d7070d5 100644 --- a/java/java-analysis-impl/src/com/intellij/codeInspection/visibility/VisibilityInspection.java +++ b/java/java-analysis-impl/src/com/intellij/codeInspection/visibility/VisibilityInspection.java @@ -59,7 +59,7 @@ public class VisibilityInspection extends GlobalJavaBatchInspectionTool { private static final Logger LOG = Logger.getInstance("#com.intellij.codeInspection.visibility.VisibilityInspection"); public boolean SUGGEST_PACKAGE_LOCAL_FOR_MEMBERS = true; public boolean SUGGEST_PACKAGE_LOCAL_FOR_TOP_CLASSES = true; - public boolean SUGGEST_PRIVATE_FOR_INNERS = false; + public boolean SUGGEST_PRIVATE_FOR_INNERS; private static final String DISPLAY_NAME = InspectionsBundle.message("inspection.visibility.display.name"); @NonNls public static final String SHORT_NAME = "WeakerAccess"; private static final String CAN_BE_PRIVATE = InspectionsBundle.message("inspection.visibility.compose.suggestion", VisibilityUtil.toPresentableText(PsiModifier.PRIVATE)); diff --git a/java/java-analysis-impl/src/com/intellij/find/findUsages/JavaClassFindUsagesOptions.java b/java/java-analysis-impl/src/com/intellij/find/findUsages/JavaClassFindUsagesOptions.java index 4339d36ffb38..a36824cebe36 100644 --- a/java/java-analysis-impl/src/com/intellij/find/findUsages/JavaClassFindUsagesOptions.java +++ b/java/java-analysis-impl/src/com/intellij/find/findUsages/JavaClassFindUsagesOptions.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2014 JetBrains s.r.o. + * Copyright 2000-2016 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. @@ -26,13 +26,13 @@ import java.util.LinkedHashSet; * @author peter */ public class JavaClassFindUsagesOptions extends JavaFindUsagesOptions { - public boolean isMethodsUsages = false; - public boolean isFieldsUsages = false; - public boolean isDerivedClasses = false; - public boolean isImplementingClasses = false; - public boolean isDerivedInterfaces = false; + public boolean isMethodsUsages; + public boolean isFieldsUsages; + public boolean isDerivedClasses; + public boolean isImplementingClasses; + public boolean isDerivedInterfaces; public boolean isCheckDeepInheritance = true; - public boolean isIncludeInherited = false; + public boolean isIncludeInherited; public JavaClassFindUsagesOptions(@NotNull Project project) { super(project); diff --git a/java/java-analysis-impl/src/com/intellij/find/findUsages/JavaFindUsagesOptions.java b/java/java-analysis-impl/src/com/intellij/find/findUsages/JavaFindUsagesOptions.java index 60b650ce293a..a990879fafff 100644 --- a/java/java-analysis-impl/src/com/intellij/find/findUsages/JavaFindUsagesOptions.java +++ b/java/java-analysis-impl/src/com/intellij/find/findUsages/JavaFindUsagesOptions.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2014 JetBrains s.r.o. + * Copyright 2000-2016 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. @@ -27,7 +27,7 @@ import java.util.LinkedHashSet; * @author peter */ public abstract class JavaFindUsagesOptions extends FindUsagesOptions { - public boolean isSkipImportStatements = false; + public boolean isSkipImportStatements; public JavaFindUsagesOptions(@NotNull Project project) { super(project); diff --git a/java/java-analysis-impl/src/com/intellij/find/findUsages/JavaMethodFindUsagesOptions.java b/java/java-analysis-impl/src/com/intellij/find/findUsages/JavaMethodFindUsagesOptions.java index ab39b82d109f..87970138d70a 100644 --- a/java/java-analysis-impl/src/com/intellij/find/findUsages/JavaMethodFindUsagesOptions.java +++ b/java/java-analysis-impl/src/com/intellij/find/findUsages/JavaMethodFindUsagesOptions.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2014 JetBrains s.r.o. + * Copyright 2000-2016 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. @@ -26,11 +26,11 @@ import java.util.LinkedHashSet; * @author peter */ public class JavaMethodFindUsagesOptions extends JavaFindUsagesOptions { - public boolean isOverridingMethods = false; - public boolean isImplementingMethods = false; + public boolean isOverridingMethods; + public boolean isImplementingMethods; public boolean isCheckDeepInheritance = true; - public boolean isIncludeInherited = false; - public boolean isIncludeOverloadUsages = false; + public boolean isIncludeInherited; + public boolean isIncludeOverloadUsages; public JavaMethodFindUsagesOptions(@NotNull Project project) { super(project); diff --git a/java/java-analysis-impl/src/com/intellij/find/findUsages/JavaPackageFindUsagesOptions.java b/java/java-analysis-impl/src/com/intellij/find/findUsages/JavaPackageFindUsagesOptions.java index 93cc0db69e9e..081284123e7d 100644 --- a/java/java-analysis-impl/src/com/intellij/find/findUsages/JavaPackageFindUsagesOptions.java +++ b/java/java-analysis-impl/src/com/intellij/find/findUsages/JavaPackageFindUsagesOptions.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2014 JetBrains s.r.o. + * Copyright 2000-2016 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. @@ -26,9 +26,9 @@ import java.util.LinkedHashSet; * @author peter */ public class JavaPackageFindUsagesOptions extends JavaFindUsagesOptions { - public boolean isClassesUsages = false; + public boolean isClassesUsages; public boolean isIncludeSubpackages = true; - public boolean isSkipPackageStatements = false; + public boolean isSkipPackageStatements; public JavaPackageFindUsagesOptions(@NotNull Project project) { super(project); diff --git a/java/java-analysis-impl/src/com/intellij/refactoring/extractMethod/InputVariables.java b/java/java-analysis-impl/src/com/intellij/refactoring/extractMethod/InputVariables.java index ad9897ae8c31..ccab96611fcf 100644 --- a/java/java-analysis-impl/src/com/intellij/refactoring/extractMethod/InputVariables.java +++ b/java/java-analysis-impl/src/com/intellij/refactoring/extractMethod/InputVariables.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2009 JetBrains s.r.o. + * Copyright 2000-2016 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. @@ -48,8 +48,8 @@ public class InputVariables { private ParametersFolder myFolding; private boolean myFoldingAvailable; - private Set myUsedInstanceFields = null; - private boolean myPassFields = false; + private Set myUsedInstanceFields; + private boolean myPassFields; public InputVariables(final List inputVariables, Project project, diff --git a/java/java-analysis-impl/src/com/intellij/refactoring/extractMethod/ParametersFolder.java b/java/java-analysis-impl/src/com/intellij/refactoring/extractMethod/ParametersFolder.java index b7e0e48f8c4b..3cf591b9d34a 100644 --- a/java/java-analysis-impl/src/com/intellij/refactoring/extractMethod/ParametersFolder.java +++ b/java/java-analysis-impl/src/com/intellij/refactoring/extractMethod/ParametersFolder.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2009 JetBrains s.r.o. + * Copyright 2000-2016 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. @@ -44,7 +44,7 @@ public class ParametersFolder { private final Set myUsedNames = new HashSet(); private final Set myDeleted = new HashSet(); - private boolean myFoldingSelectedByDefault = false; + private boolean myFoldingSelectedByDefault; public void clear() { diff --git a/java/java-analysis-impl/src/com/intellij/refactoring/util/duplicates/DuplicatesFinder.java b/java/java-analysis-impl/src/com/intellij/refactoring/util/duplicates/DuplicatesFinder.java index c34982debacf..99d7bdeb25fa 100644 --- a/java/java-analysis-impl/src/com/intellij/refactoring/util/duplicates/DuplicatesFinder.java +++ b/java/java-analysis-impl/src/com/intellij/refactoring/util/duplicates/DuplicatesFinder.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2015 JetBrains s.r.o. + * Copyright 2000-2016 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. @@ -46,7 +46,7 @@ public class DuplicatesFinder { private final InputVariables myParameters; private final List myOutputParameters; private final List myPatternAsList; - private boolean myMultipleExitPoints = false; + private boolean myMultipleExitPoints; @Nullable private final ReturnValue myReturnValue; public DuplicatesFinder(PsiElement[] pattern, diff --git a/java/java-analysis-impl/src/com/intellij/refactoring/util/duplicates/Match.java b/java/java-analysis-impl/src/com/intellij/refactoring/util/duplicates/Match.java index 10a3238ae7b6..5d3cb6f9f802 100644 --- a/java/java-analysis-impl/src/com/intellij/refactoring/util/duplicates/Match.java +++ b/java/java-analysis-impl/src/com/intellij/refactoring/util/duplicates/Match.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2009 JetBrains s.r.o. + * Copyright 2000-2016 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. @@ -51,8 +51,8 @@ public final class Match { private final Map> myParameterValues = new HashMap>(); private final Map> myParameterOccurrences = new HashMap>(); private final Map myDeclarationCorrespondence = new HashMap(); - private ReturnValue myReturnValue = null; - private Ref myInstanceExpression = null; + private ReturnValue myReturnValue; + private Ref myInstanceExpression; final Map myChangedParams = new HashMap(); private final boolean myIgnoreParameterTypes; diff --git a/java/java-analysis-impl/src/org/jetbrains/java/generate/config/Config.java b/java/java-analysis-impl/src/org/jetbrains/java/generate/config/Config.java index 95b93d9f9028..a10e0d59fdba 100644 --- a/java/java-analysis-impl/src/org/jetbrains/java/generate/config/Config.java +++ b/java/java-analysis-impl/src/org/jetbrains/java/generate/config/Config.java @@ -21,24 +21,24 @@ package org.jetbrains.java.generate.config; */ public class Config { - public boolean useFullyQualifiedName = false; + public boolean useFullyQualifiedName; public InsertWhere insertNewMethodOption = InsertWhere.AT_CARET; public DuplicationPolicy whenDuplicatesOption = DuplicationPolicy.ASK; public boolean filterConstantField = true; - public boolean filterEnumField = false; - public boolean filterTransientModifier = false; + public boolean filterEnumField; + public boolean filterTransientModifier; public boolean filterStaticModifier = true; - public String filterFieldName = null; - public String filterMethodName = null; - public String filterMethodType = null; - public String filterFieldType = null; + public String filterFieldName; + public String filterMethodName; + public String filterMethodType; + public String filterFieldType; public boolean filterLoggers = true; - public boolean addImplementSerializable = false; - public boolean enableMethods = false; + public boolean addImplementSerializable; + public boolean enableMethods; public boolean jumpToMethod = true; // jump cursor to toString method - public int sortElements = 0; // 0 = none, 1 = asc, 2 = desc + public int sortElements; // 0 = none, 1 = asc, 2 = desc - private FilterPattern myPattern = null; + private FilterPattern myPattern; public boolean isUseFullyQualifiedName() { return useFullyQualifiedName; diff --git a/java/java-analysis-impl/src/org/jetbrains/java/generate/config/FilterPattern.java b/java/java-analysis-impl/src/org/jetbrains/java/generate/config/FilterPattern.java index e56ac4f3d0ee..c91c6abba820 100644 --- a/java/java-analysis-impl/src/org/jetbrains/java/generate/config/FilterPattern.java +++ b/java/java-analysis-impl/src/org/jetbrains/java/generate/config/FilterPattern.java @@ -51,10 +51,10 @@ public class FilterPattern { private boolean transientModifier; private boolean enumField; private boolean loggers; - private Pattern methodNamePattern = null; - private Pattern methodTypePattern = null; - private Pattern fieldNamePattern = null; - private Pattern fieldTypePattern = null; + private Pattern methodNamePattern; + private Pattern methodTypePattern; + private Pattern fieldNamePattern; + private Pattern fieldTypePattern; public boolean fieldMatches(PsiField field) { if (isConstantField() && PsiAdapter.isConstantField(field)) { diff --git a/java/java-analysis-impl/src/org/jetbrains/java/generate/inspection/ClassHasNoToStringMethodInspection.java b/java/java-analysis-impl/src/org/jetbrains/java/generate/inspection/ClassHasNoToStringMethodInspection.java index a5359d5a1392..3100c9fca2bb 100644 --- a/java/java-analysis-impl/src/org/jetbrains/java/generate/inspection/ClassHasNoToStringMethodInspection.java +++ b/java/java-analysis-impl/src/org/jetbrains/java/generate/inspection/ClassHasNoToStringMethodInspection.java @@ -53,13 +53,13 @@ public class ClassHasNoToStringMethodInspection extends AbstractToStringInspecti /** User options for excluded deprecated classes */ public boolean excludeDeprecated = true; // must be public for JDOMSerialization /** User options for excluded enum classes */ - public boolean excludeEnum = false; // must be public for JDOMSerialization + public boolean excludeEnum; // must be public for JDOMSerialization /** User options for excluded abstract classes */ - public boolean excludeAbstract = false; // must be public for JDOMSerialization + public boolean excludeAbstract; // must be public for JDOMSerialization - public boolean excludeTestCode = false; + public boolean excludeTestCode; - public boolean excludeInnerClasses = false; + public boolean excludeInnerClasses; public ClassHasNoToStringMethodInspection() { try { diff --git a/java/java-impl/src/com/intellij/codeEditor/printing/HyperlinksToClassesOption.java b/java/java-impl/src/com/intellij/codeEditor/printing/HyperlinksToClassesOption.java index 3326e97fe2f6..7a22d4754c94 100644 --- a/java/java-impl/src/com/intellij/codeEditor/printing/HyperlinksToClassesOption.java +++ b/java/java-impl/src/com/intellij/codeEditor/printing/HyperlinksToClassesOption.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2009 JetBrains s.r.o. + * Copyright 2000-2016 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. @@ -34,7 +34,7 @@ import java.util.TreeMap; public class HyperlinksToClassesOption extends PrintOption { private JCheckBox myCbGenerateHyperlinksToClasses; - private boolean isGenerateHyperlinksToClasses = false; + private boolean isGenerateHyperlinksToClasses; @Nullable public TreeMap collectReferences(PsiFile psiFile, Map filesMap) { diff --git a/java/java-impl/src/com/intellij/codeInsight/completion/AllClassesGetter.java b/java/java-impl/src/com/intellij/codeInsight/completion/AllClassesGetter.java index 2a87f9fc8e29..99247cfd287f 100644 --- a/java/java-impl/src/com/intellij/codeInsight/completion/AllClassesGetter.java +++ b/java/java-impl/src/com/intellij/codeInsight/completion/AllClassesGetter.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2009 JetBrains s.r.o. + * Copyright 2000-2016 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. @@ -154,7 +154,7 @@ public class AllClassesGetter { int limit = Registry.intValue("ide.completion.variant.limit"); Processor processor = new Processor() { - int count = 0; + int count; final Set qNames = new THashSet(); final boolean pkgContext = JavaCompletionUtil.inSomePackage(context); final String packagePrefix = getPackagePrefix(context, parameters.getOffset()); diff --git a/java/java-impl/src/com/intellij/codeInsight/completion/MemberLookupHelper.java b/java/java-impl/src/com/intellij/codeInsight/completion/MemberLookupHelper.java index f665920528d2..6589f4a815e3 100644 --- a/java/java-impl/src/com/intellij/codeInsight/completion/MemberLookupHelper.java +++ b/java/java-impl/src/com/intellij/codeInsight/completion/MemberLookupHelper.java @@ -1,3 +1,18 @@ +/* + * Copyright 2000-2016 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.codeInsight.completion; import com.intellij.codeInsight.lookup.LookupElementPresentation; @@ -16,7 +31,7 @@ public class MemberLookupHelper { private final PsiMember myMember; private final boolean myMergedOverloads; @Nullable private final PsiClass myContainingClass; - private boolean myShouldImport = false; + private boolean myShouldImport; public MemberLookupHelper(List overloads, PsiClass containingClass, boolean shouldImport) { this(overloads.get(0), containingClass, shouldImport, true); diff --git a/java/java-impl/src/com/intellij/codeInsight/completion/StaticMemberProcessor.java b/java/java-impl/src/com/intellij/codeInsight/completion/StaticMemberProcessor.java index e79fe27ac5c2..5a152a7c6eaf 100644 --- a/java/java-impl/src/com/intellij/codeInsight/completion/StaticMemberProcessor.java +++ b/java/java-impl/src/com/intellij/codeInsight/completion/StaticMemberProcessor.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2014 JetBrains s.r.o. + * Copyright 2000-2016 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. @@ -30,7 +30,10 @@ import gnu.trove.THashSet; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; -import java.util.*; +import java.util.ArrayList; +import java.util.Collection; +import java.util.List; +import java.util.Set; /** * @author peter @@ -40,7 +43,7 @@ public abstract class StaticMemberProcessor { private final PsiElement myPosition; private final Project myProject; private final PsiResolveHelper myResolveHelper; - private boolean myHintShown = false; + private boolean myHintShown; private final boolean myPackagedContext; public StaticMemberProcessor(final PsiElement position) { diff --git a/java/java-impl/src/com/intellij/codeInsight/completion/scope/JavaCompletionProcessor.java b/java/java-impl/src/com/intellij/codeInsight/completion/scope/JavaCompletionProcessor.java index 152f82650739..6a681fd182d2 100644 --- a/java/java-impl/src/com/intellij/codeInsight/completion/scope/JavaCompletionProcessor.java +++ b/java/java-impl/src/com/intellij/codeInsight/completion/scope/JavaCompletionProcessor.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2014 JetBrains s.r.o. + * Copyright 2000-2016 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. @@ -50,8 +50,8 @@ import java.util.Set; public class JavaCompletionProcessor extends BaseScopeProcessor implements ElementClassHint { private final boolean myInJavaDoc; - private boolean myStatic = false; - private PsiElement myDeclarationHolder = null; + private boolean myStatic; + private PsiElement myDeclarationHolder; private final Map myResults = new LinkedHashMap<>(); private final Set mySecondRateResults = ContainerUtil.newIdentityTroveSet(); private final Set myShadowedNames = ContainerUtil.newHashSet(); @@ -60,10 +60,10 @@ public class JavaCompletionProcessor extends BaseScopeProcessor implements Eleme private final PsiElement myElement; private final PsiElement myScope; private final ElementFilter myFilter; - private boolean myMembersFlag = false; - private boolean myQualified = false; - private PsiType myQualifierType = null; - private PsiClass myQualifierClass = null; + private boolean myMembersFlag; + private boolean myQualified; + private PsiType myQualifierType; + private PsiClass myQualifierClass; private final Condition myMatcher; private final Options myOptions; private final boolean myAllowStaticWithInstanceQualifier; diff --git a/java/java-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/AddMethodQualifierFix.java b/java/java-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/AddMethodQualifierFix.java index 1c6fd53e460f..ce0ee8fefe91 100644 --- a/java/java-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/AddMethodQualifierFix.java +++ b/java/java-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/AddMethodQualifierFix.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2014 JetBrains s.r.o. + * Copyright 2000-2016 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. @@ -27,7 +27,6 @@ import com.intellij.openapi.ui.popup.util.BaseListPopupStep; import com.intellij.psi.*; import com.intellij.ui.popup.list.ListPopupImpl; import com.intellij.util.IncorrectOperationException; -import com.intellij.util.ObjectUtils; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.TestOnly; @@ -42,7 +41,7 @@ public class AddMethodQualifierFix implements IntentionAction { private static final boolean UNIT_TEST_MODE = ApplicationManager.getApplication().isUnitTestMode(); private final SmartPsiElementPointer myMethodCall; - private List myCandidates = null; + private List myCandidates; public AddMethodQualifierFix(final PsiMethodCallExpression methodCallExpression) { myMethodCall = SmartPointerManager.getInstance(methodCallExpression.getProject()).createSmartPsiElementPointer(methodCallExpression); diff --git a/java/java-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/ChangeExtendsToImplementsFix.java b/java/java-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/ChangeExtendsToImplementsFix.java index dce0d54e405b..1462dc3d2897 100644 --- a/java/java-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/ChangeExtendsToImplementsFix.java +++ b/java/java-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/ChangeExtendsToImplementsFix.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2009 JetBrains s.r.o. + * Copyright 2000-2016 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. @@ -14,9 +14,6 @@ * limitations under the License. */ -/** - * @author cdr - */ package com.intellij.codeInsight.daemon.impl.quickfix; import com.intellij.codeInsight.daemon.QuickFixBundle; diff --git a/java/java-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/ChangeMethodSignatureFromUsageFix.java b/java/java-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/ChangeMethodSignatureFromUsageFix.java index 277342155f61..40093816e2e1 100644 --- a/java/java-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/ChangeMethodSignatureFromUsageFix.java +++ b/java/java-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/ChangeMethodSignatureFromUsageFix.java @@ -125,7 +125,7 @@ public class ChangeMethodSignatureFromUsageFix implements IntentionAction/*, Hig StringBuilder result = new StringBuilder(); try { for (ParameterInfoImpl info : infos) { - PsiType type = info.createType(context, context.getManager()); + PsiType type = info.createType(context); if (type == null) return null; if (result.length() != 0) result.append(", "); result.append(type.getPresentableText()); diff --git a/java/java-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/ChangeParameterClassFix.java b/java/java-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/ChangeParameterClassFix.java index 6d414e5e4750..5e91052a46eb 100644 --- a/java/java-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/ChangeParameterClassFix.java +++ b/java/java-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/ChangeParameterClassFix.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2009 JetBrains s.r.o. + * Copyright 2000-2016 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. @@ -14,13 +14,6 @@ * limitations under the License. */ -/** - * Created by IntelliJ IDEA. - * User: cdr - * Date: Nov 13, 2002 - * Time: 3:26:50 PM - * To change this template use Options | File Templates. - */ package com.intellij.codeInsight.daemon.impl.quickfix; import com.intellij.codeInsight.CodeInsightUtil; diff --git a/java/java-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/CreateConstructorParameterFromFieldFix.java b/java/java-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/CreateConstructorParameterFromFieldFix.java index 97bb45cb531c..91732b67b6ad 100644 --- a/java/java-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/CreateConstructorParameterFromFieldFix.java +++ b/java/java-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/CreateConstructorParameterFromFieldFix.java @@ -371,7 +371,7 @@ public class CreateConstructorParameterFromFieldFix implements IntentionAction { for (int i = 0; i < newParameters.length; i++) { if (parameterInfos[i].getOldIndex() == -1) { final PsiParameter parameter = newParameters[i]; - final PsiType paramType = parameterInfos[i].getTypeWrapper().getType(parameter, parameter.getManager()); + final PsiType paramType = parameterInfos[i].getTypeWrapper().getType(parameter); if (type.isAssignableFrom(paramType)){ return parameter; } diff --git a/java/java-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/DeferFinalAssignmentFix.java b/java/java-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/DeferFinalAssignmentFix.java index dcae6c51d727..08822884965b 100644 --- a/java/java-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/DeferFinalAssignmentFix.java +++ b/java/java-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/DeferFinalAssignmentFix.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2009 JetBrains s.r.o. + * Copyright 2000-2016 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. @@ -14,13 +14,6 @@ * limitations under the License. */ -/** - * Created by IntelliJ IDEA. - * User: cdr - * Date: Nov 19, 2002 - * Time: 12:03:39 PM - * To change this template use Options | File Templates. - */ package com.intellij.codeInsight.daemon.impl.quickfix; import com.intellij.codeInsight.FileModificationService; diff --git a/java/java-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/InsertNewFix.java b/java/java-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/InsertNewFix.java index a418efb4da15..b9dc50f31d78 100644 --- a/java/java-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/InsertNewFix.java +++ b/java/java-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/InsertNewFix.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2009 JetBrains s.r.o. + * Copyright 2000-2016 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. @@ -14,9 +14,6 @@ * limitations under the License. */ -/** - * @author cdr - */ package com.intellij.codeInsight.daemon.impl.quickfix; import com.intellij.codeInsight.FileModificationService; diff --git a/java/java-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/RenameWrongRefFix.java b/java/java-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/RenameWrongRefFix.java index 82cca2862eac..c6ecd4b31013 100644 --- a/java/java-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/RenameWrongRefFix.java +++ b/java/java-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/RenameWrongRefFix.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2014 JetBrains s.r.o. + * Copyright 2000-2016 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. @@ -102,7 +102,7 @@ public class RenameWrongRefFix implements IntentionAction { class MyScopeProcessor extends BaseScopeProcessor { ArrayList myResult = new ArrayList(); boolean myFilterMethods; - boolean myFilterStatics = false; + boolean myFilterStatics; MyScopeProcessor(PsiReferenceExpression refExpression) { myFilterMethods = refExpression.getParent() instanceof PsiMethodCallExpression; diff --git a/java/java-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/SurroundWithTryCatchFix.java b/java/java-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/SurroundWithTryCatchFix.java index b0264dc22c52..5a48b1abb2c9 100644 --- a/java/java-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/SurroundWithTryCatchFix.java +++ b/java/java-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/SurroundWithTryCatchFix.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2009 JetBrains s.r.o. + * Copyright 2000-2016 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. @@ -39,7 +39,7 @@ import org.jetbrains.annotations.NotNull; public class SurroundWithTryCatchFix implements IntentionAction { private static final Logger LOG = Logger.getInstance("#com.intellij.codeInsight.daemon.impl.quickfix.SurroundWithTryCatchFix"); - private PsiElement myStatement = null; + private PsiElement myStatement; public SurroundWithTryCatchFix(@NotNull PsiElement element) { final PsiFunctionalExpression functionalExpression = PsiTreeUtil.getParentOfType(element, PsiFunctionalExpression.class, false, PsiStatement.class); diff --git a/java/java-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/SwitchStatementBranch.java b/java/java-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/SwitchStatementBranch.java index f361a95e1cf7..cc7602917cc8 100644 --- a/java/java-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/SwitchStatementBranch.java +++ b/java/java-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/SwitchStatementBranch.java @@ -30,8 +30,8 @@ class SwitchStatementBranch { new ArrayList(5); private final List m_pendingWhiteSpace = new ArrayList(2); - private boolean m_default = false; - private boolean m_hasStatements = false; + private boolean m_default; + private boolean m_hasStatements; public void addCaseValue(String labelString) { m_caseValues.add(labelString); diff --git a/java/java-impl/src/com/intellij/codeInsight/editorActions/AutoFormatTypedHandler.java b/java/java-impl/src/com/intellij/codeInsight/editorActions/AutoFormatTypedHandler.java index 0e2a3de30933..2a7c9f38283d 100644 --- a/java/java-impl/src/com/intellij/codeInsight/editorActions/AutoFormatTypedHandler.java +++ b/java/java-impl/src/com/intellij/codeInsight/editorActions/AutoFormatTypedHandler.java @@ -45,7 +45,7 @@ import org.jetbrains.annotations.TestOnly; import java.util.List; public class AutoFormatTypedHandler extends TypedActionHandlerBase { - private static boolean myIsEnabledInTests = false; + private static boolean myIsEnabledInTests; private static char[] NO_SPACE_AFTER = { '+', '-', '*', '/', '%', '&', '^', '|', '<', '>', '!', '=', ' ' diff --git a/java/java-impl/src/com/intellij/codeInsight/editorActions/moveUpDown/DeclarationMover.java b/java/java-impl/src/com/intellij/codeInsight/editorActions/moveUpDown/DeclarationMover.java index 3b56a946e281..4d2d0e5c56b4 100644 --- a/java/java-impl/src/com/intellij/codeInsight/editorActions/moveUpDown/DeclarationMover.java +++ b/java/java-impl/src/com/intellij/codeInsight/editorActions/moveUpDown/DeclarationMover.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2015 JetBrains s.r.o. + * Copyright 2000-2016 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. @@ -38,7 +38,7 @@ import java.util.List; class DeclarationMover extends LineMover { private static final Logger LOG = Logger.getInstance("#com.intellij.openapi.editor.actions.moveUpDown.DeclarationMover"); private PsiEnumConstant myEnumToInsertSemicolonAfter; - private boolean moveEnumConstant = false; + private boolean moveEnumConstant; @Override public void beforeMove(@NotNull final Editor editor, @NotNull final MoveInfo info, final boolean down) { diff --git a/java/java-impl/src/com/intellij/codeInsight/generation/GenerateDelegateHandler.java b/java/java-impl/src/com/intellij/codeInsight/generation/GenerateDelegateHandler.java index 6028ec3d564c..30071b845e9d 100644 --- a/java/java-impl/src/com/intellij/codeInsight/generation/GenerateDelegateHandler.java +++ b/java/java-impl/src/com/intellij/codeInsight/generation/GenerateDelegateHandler.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2009 JetBrains s.r.o. + * Copyright 2000-2016 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. @@ -46,7 +46,7 @@ import java.util.*; */ public class GenerateDelegateHandler implements LanguageCodeInsightActionHandler { private static final Logger LOG = Logger.getInstance("#com.intellij.codeInsight.generation.GenerateDelegateHandler"); - private boolean myToCopyJavaDoc = false; + private boolean myToCopyJavaDoc; @Override public boolean isValidFor(Editor editor, PsiFile file) { diff --git a/java/java-impl/src/com/intellij/codeInsight/generation/GenerateEqualsHandler.java b/java/java-impl/src/com/intellij/codeInsight/generation/GenerateEqualsHandler.java index b8f5a477097d..55e6aac1da51 100644 --- a/java/java-impl/src/com/intellij/codeInsight/generation/GenerateEqualsHandler.java +++ b/java/java-impl/src/com/intellij/codeInsight/generation/GenerateEqualsHandler.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2014 JetBrains s.r.o. + * Copyright 2000-2016 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. @@ -37,9 +37,9 @@ import java.util.List; */ public class GenerateEqualsHandler extends GenerateMembersHandlerBase { private static final Logger LOG = Logger.getInstance("#com.intellij.codeInsight.generation.GenerateEqualsHandler"); - private PsiField[] myEqualsFields = null; - private PsiField[] myHashCodeFields = null; - private PsiField[] myNonNullFields = null; + private PsiField[] myEqualsFields; + private PsiField[] myHashCodeFields; + private PsiField[] myNonNullFields; private static final PsiElementClassMember[] DUMMY_RESULT = new PsiElementClassMember[1]; //cannot return empty array, but this result won't be used anyway public GenerateEqualsHandler() { diff --git a/java/java-impl/src/com/intellij/codeInsight/generation/GenerateMembersHandlerBase.java b/java/java-impl/src/com/intellij/codeInsight/generation/GenerateMembersHandlerBase.java index 8e674adca489..1f9e4a55ad83 100644 --- a/java/java-impl/src/com/intellij/codeInsight/generation/GenerateMembersHandlerBase.java +++ b/java/java-impl/src/com/intellij/codeInsight/generation/GenerateMembersHandlerBase.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2015 JetBrains s.r.o. + * Copyright 2000-2016 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. @@ -53,7 +53,7 @@ public abstract class GenerateMembersHandlerBase implements CodeInsightActionHan private static final Logger LOG = Logger.getInstance("#com.intellij.codeInsight.generation.GenerateMembersHandlerBase"); private final String myChooserTitle; - protected boolean myToCopyJavaDoc = false; + protected boolean myToCopyJavaDoc; public GenerateMembersHandlerBase(String chooserTitle) { myChooserTitle = chooserTitle; diff --git a/java/java-impl/src/com/intellij/codeInsight/generation/OverrideImplementUtil.java b/java/java-impl/src/com/intellij/codeInsight/generation/OverrideImplementUtil.java index 7756b0725055..2ac11993dc07 100644 --- a/java/java-impl/src/com/intellij/codeInsight/generation/OverrideImplementUtil.java +++ b/java/java-impl/src/com/intellij/codeInsight/generation/OverrideImplementUtil.java @@ -28,10 +28,8 @@ import com.intellij.ide.fileTemplates.FileTemplateManager; import com.intellij.ide.fileTemplates.FileTemplateUtil; import com.intellij.ide.fileTemplates.JavaTemplateUtil; import com.intellij.ide.util.MemberChooser; -import com.intellij.idea.ActionsBundle; import com.intellij.lang.java.JavaLanguage; import com.intellij.openapi.actionSystem.KeyboardShortcut; -import com.intellij.openapi.actionSystem.Presentation; import com.intellij.openapi.actionSystem.Shortcut; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.application.Result; @@ -52,6 +50,7 @@ import com.intellij.openapi.module.ModuleUtilCore; import com.intellij.openapi.project.Project; import com.intellij.openapi.ui.DialogWrapper; import com.intellij.openapi.ui.Messages; +import com.intellij.openapi.util.text.StringUtil; import com.intellij.psi.*; import com.intellij.psi.codeStyle.CodeStyleManager; import com.intellij.psi.codeStyle.CodeStyleSettingsManager; @@ -184,7 +183,7 @@ public class OverrideImplementUtil extends OverrideImplementExploreUtil { boolean toCopyJavaDoc, boolean insertOverrideIfPossible, PsiMethod result) { - PsiUtil.setModifierProperty(result, PsiModifier.ABSTRACT, aClass.isInterface()); + PsiUtil.setModifierProperty(result, PsiModifier.ABSTRACT, aClass.isInterface() && method.hasModifierProperty(PsiModifier.ABSTRACT)); PsiUtil.setModifierProperty(result, PsiModifier.NATIVE, false); if (!toCopyJavaDoc){ @@ -368,7 +367,7 @@ public class OverrideImplementUtil extends OverrideImplementExploreUtil { final PsiClass targetClass, final FileTemplate template) throws IncorrectOperationException { if (targetClass.isInterface()) { - if (isImplementInterfaceInJava8Interface(targetClass)) { + if (isImplementInterfaceInJava8Interface(targetClass) || originalMethod.hasModifierProperty(PsiModifier.DEFAULT)) { PsiUtil.setModifierProperty(result, PsiModifier.DEFAULT, true); } else { @@ -424,10 +423,8 @@ public class OverrideImplementUtil extends OverrideImplementExploreUtil { if (!PsiUtil.isLanguageLevel8OrHigher(targetClass)){ return false; } - final String implementMethodsName = ActionsBundle.message("action.ImplementMethods.text"); - final Presentation presentation = new Presentation(); - presentation.setText(implementMethodsName); - return presentation.getText().equals(CommandProcessor.getInstance().getCurrentCommandName()); + String commandName = CommandProcessor.getInstance().getCurrentCommandName(); + return commandName != null && StringUtil.containsIgnoreCase(commandName, "implement"); } public static void chooseAndOverrideMethods(Project project, Editor editor, PsiClass aClass){ diff --git a/java/java-impl/src/com/intellij/codeInsight/generation/actions/GenerateSuperMethodCallHandler.java b/java/java-impl/src/com/intellij/codeInsight/generation/actions/GenerateSuperMethodCallHandler.java index 81a98e94a160..d88bb8d5e3e7 100644 --- a/java/java-impl/src/com/intellij/codeInsight/generation/actions/GenerateSuperMethodCallHandler.java +++ b/java/java-impl/src/com/intellij/codeInsight/generation/actions/GenerateSuperMethodCallHandler.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2009 JetBrains s.r.o. + * Copyright 2000-2016 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. @@ -14,19 +14,16 @@ * limitations under the License. */ -/** - * @author cdr - */ package com.intellij.codeInsight.generation.actions; import com.intellij.codeInsight.CodeInsightActionHandler; import com.intellij.codeInsight.CodeInsightUtilBase; import com.intellij.codeInsight.CodeInsightUtilCore; import com.intellij.codeInsight.generation.OverrideImplementUtil; -import com.intellij.openapi.project.Project; +import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.editor.Editor; import com.intellij.openapi.editor.ScrollType; -import com.intellij.openapi.diagnostic.Logger; +import com.intellij.openapi.project.Project; import com.intellij.psi.*; import com.intellij.psi.util.PsiTreeUtil; import com.intellij.util.IncorrectOperationException; diff --git a/java/java-impl/src/com/intellij/codeInsight/generation/surroundWith/JavaExpressionSurroundDescriptor.java b/java/java-impl/src/com/intellij/codeInsight/generation/surroundWith/JavaExpressionSurroundDescriptor.java index 43924d9199c3..691e9a36831e 100644 --- a/java/java-impl/src/com/intellij/codeInsight/generation/surroundWith/JavaExpressionSurroundDescriptor.java +++ b/java/java-impl/src/com/intellij/codeInsight/generation/surroundWith/JavaExpressionSurroundDescriptor.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2009 JetBrains s.r.o. + * Copyright 2000-2016 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. @@ -33,7 +33,7 @@ import java.util.Collections; * @author ven */ public class JavaExpressionSurroundDescriptor implements SurroundDescriptor { - private Surrounder[] mySurrounders = null; + private Surrounder[] mySurrounders; private static final Surrounder[] SURROUNDERS = { new JavaWithParenthesesSurrounder(), diff --git a/java/java-impl/src/com/intellij/codeInsight/generation/surroundWith/JavaWithTryCatchSurrounder.java b/java/java-impl/src/com/intellij/codeInsight/generation/surroundWith/JavaWithTryCatchSurrounder.java index 996d61483451..482ffd851162 100644 --- a/java/java-impl/src/com/intellij/codeInsight/generation/surroundWith/JavaWithTryCatchSurrounder.java +++ b/java/java-impl/src/com/intellij/codeInsight/generation/surroundWith/JavaWithTryCatchSurrounder.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2009 JetBrains s.r.o. + * Copyright 2000-2016 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. @@ -32,7 +32,7 @@ import java.util.Collections; import java.util.List; public class JavaWithTryCatchSurrounder extends JavaStatementsSurrounder { - protected boolean myGenerateFinally = false; + protected boolean myGenerateFinally; @Override public String getTemplateDescription() { diff --git a/java/java-impl/src/com/intellij/codeInsight/highlighting/HighlightImportedElementsHandler.java b/java/java-impl/src/com/intellij/codeInsight/highlighting/HighlightImportedElementsHandler.java index 71e301aa91f6..9ae19918b5c2 100644 --- a/java/java-impl/src/com/intellij/codeInsight/highlighting/HighlightImportedElementsHandler.java +++ b/java/java-impl/src/com/intellij/codeInsight/highlighting/HighlightImportedElementsHandler.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2013 JetBrains s.r.o. + * Copyright 2000-2016 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. @@ -40,7 +40,7 @@ public class HighlightImportedElementsHandler extends HighlightUsagesHandlerBase private final PsiElement myTarget; private final PsiImportStatementBase myImportStatement; private final boolean myImportStatic; - private Map> myClassReferenceListMap = null; + private Map> myClassReferenceListMap; public HighlightImportedElementsHandler(Editor editor, PsiFile file, PsiElement target, PsiImportStatementBase importStatement) { super(editor, file); diff --git a/java/java-impl/src/com/intellij/codeInsight/intention/impl/AddOnDemandStaticImportAction.java b/java/java-impl/src/com/intellij/codeInsight/intention/impl/AddOnDemandStaticImportAction.java index cc6687acbcb4..aa36b456f33d 100644 --- a/java/java-impl/src/com/intellij/codeInsight/intention/impl/AddOnDemandStaticImportAction.java +++ b/java/java-impl/src/com/intellij/codeInsight/intention/impl/AddOnDemandStaticImportAction.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2015 JetBrains s.r.o. + * Copyright 2000-2016 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. @@ -146,7 +146,7 @@ public class AddOnDemandStaticImportAction extends BaseElementAtCaretIntentionAc final TIntArrayList expressionToDequalifyOffsets = new TIntArrayList(); copy.accept(new JavaRecursiveElementWalkingVisitor() { - int delta = 0; + int delta; @Override public void visitReferenceElement(PsiJavaCodeReferenceElement expression) { if (isParameterizedReference(expression)) return; diff --git a/java/java-impl/src/com/intellij/codeInsight/intention/impl/DeannotateIntentionAction.java b/java/java-impl/src/com/intellij/codeInsight/intention/impl/DeannotateIntentionAction.java index 52deff695f95..60b33eb24b64 100644 --- a/java/java-impl/src/com/intellij/codeInsight/intention/impl/DeannotateIntentionAction.java +++ b/java/java-impl/src/com/intellij/codeInsight/intention/impl/DeannotateIntentionAction.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2015 JetBrains s.r.o. + * Copyright 2000-2016 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. @@ -44,7 +44,7 @@ import java.util.List; public class DeannotateIntentionAction implements IntentionAction, LowPriorityAction { private static final Logger LOG = Logger.getInstance("#" + DeannotateIntentionAction.class.getName()); - private String myAnnotationName = null; + private String myAnnotationName; @Override @NotNull diff --git a/java/java-impl/src/com/intellij/codeInsight/intention/impl/ImplementAbstractMethodAction.java b/java/java-impl/src/com/intellij/codeInsight/intention/impl/ImplementAbstractMethodAction.java index cfb64329f8bd..be518aec68ad 100644 --- a/java/java-impl/src/com/intellij/codeInsight/intention/impl/ImplementAbstractMethodAction.java +++ b/java/java-impl/src/com/intellij/codeInsight/intention/impl/ImplementAbstractMethodAction.java @@ -33,6 +33,7 @@ import com.intellij.psi.search.PsiElementProcessor; import com.intellij.psi.search.PsiElementProcessorAdapter; import com.intellij.psi.search.searches.ClassInheritorsSearch; import com.intellij.psi.util.PsiTreeUtil; +import com.intellij.psi.util.PsiUtil; import com.intellij.util.IncorrectOperationException; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; @@ -120,7 +121,7 @@ public class ImplementAbstractMethodAction extends BaseIntentionAction { public boolean execute(@NotNull PsiElement element) { if (element instanceof PsiClass) { PsiClass aClass = (PsiClass) element; - if (aClass.isInterface()) return true; + if (aClass.isInterface() && !PsiUtil.isLanguageLevel8OrHigher(aClass)) return true; final PsiMethod existingImplementation = findExistingImplementation(aClass, myMethod); if (existingImplementation != null && !existingImplementation.hasModifierProperty(PsiModifier.ABSTRACT)) { myHasExistingImplementations = true; diff --git a/java/java-impl/src/com/intellij/codeInsight/intention/impl/ImplementAbstractMethodHandler.java b/java/java-impl/src/com/intellij/codeInsight/intention/impl/ImplementAbstractMethodHandler.java index 8c2935c7a714..41b2e6cf456a 100644 --- a/java/java-impl/src/com/intellij/codeInsight/intention/impl/ImplementAbstractMethodHandler.java +++ b/java/java-impl/src/com/intellij/codeInsight/intention/impl/ImplementAbstractMethodHandler.java @@ -41,6 +41,7 @@ import com.intellij.openapi.util.Computable; import com.intellij.psi.*; import com.intellij.psi.search.searches.ClassInheritorsSearch; import com.intellij.psi.util.MethodSignatureUtil; +import com.intellij.psi.util.PsiUtil; import com.intellij.psi.util.PsiUtilCore; import com.intellij.psi.util.TypeConversionUtil; import com.intellij.ui.components.JBList; @@ -181,7 +182,7 @@ public class ImplementAbstractMethodHandler { private PsiClass[] getClassImplementations(final PsiClass psiClass) { ArrayList list = new ArrayList(); for (PsiClass inheritor : ClassInheritorsSearch.search(psiClass)) { - if (!inheritor.isInterface()) { + if (!inheritor.isInterface() || PsiUtil.isLanguageLevel8OrHigher(inheritor)) { final PsiSubstitutor classSubstitutor = TypeConversionUtil.getClassSubstitutor(psiClass, inheritor, PsiSubstitutor.EMPTY); PsiMethod method = classSubstitutor != null ? MethodSignatureUtil.findMethodBySignature(inheritor, myMethod.getSignature(classSubstitutor), true) : inheritor.findMethodBySignature(myMethod, true);; diff --git a/java/java-impl/src/com/intellij/codeInsight/intention/impl/ReplaceCastWithVariableAction.java b/java/java-impl/src/com/intellij/codeInsight/intention/impl/ReplaceCastWithVariableAction.java index 14a85ef7e348..a612a87b3312 100644 --- a/java/java-impl/src/com/intellij/codeInsight/intention/impl/ReplaceCastWithVariableAction.java +++ b/java/java-impl/src/com/intellij/codeInsight/intention/impl/ReplaceCastWithVariableAction.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2012 JetBrains s.r.o. + * Copyright 2000-2016 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. @@ -116,7 +116,7 @@ public class ReplaceCastWithVariableAction extends PsiElementBaseIntentionAction scope.accept( new JavaRecursiveElementWalkingVisitor() { - private boolean inScope = false; + private boolean inScope; @Override public void visitElement(PsiElement element) { diff --git a/java/java-impl/src/com/intellij/codeInsight/intention/impl/SimplifyBooleanExpressionAction.java b/java/java-impl/src/com/intellij/codeInsight/intention/impl/SimplifyBooleanExpressionAction.java index 3ae3ddcf7498..a977ab7202e8 100644 --- a/java/java-impl/src/com/intellij/codeInsight/intention/impl/SimplifyBooleanExpressionAction.java +++ b/java/java-impl/src/com/intellij/codeInsight/intention/impl/SimplifyBooleanExpressionAction.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2009 JetBrains s.r.o. + * Copyright 2000-2016 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. @@ -14,9 +14,6 @@ * limitations under the License. */ -/** - * @author cdr - */ package com.intellij.codeInsight.intention.impl; import com.intellij.codeInsight.FileModificationService; diff --git a/java/java-impl/src/com/intellij/codeInspection/deadCode/UnusedDeclarationPresentation.java b/java/java-impl/src/com/intellij/codeInspection/deadCode/UnusedDeclarationPresentation.java index 2627ca9417af..639004bf4586 100644 --- a/java/java-impl/src/com/intellij/codeInspection/deadCode/UnusedDeclarationPresentation.java +++ b/java/java-impl/src/com/intellij/codeInspection/deadCode/UnusedDeclarationPresentation.java @@ -29,7 +29,6 @@ import com.intellij.openapi.editor.Editor; import com.intellij.openapi.fileEditor.FileEditorManager; import com.intellij.openapi.fileEditor.OpenFileDescriptor; import com.intellij.openapi.project.Project; -import com.intellij.openapi.util.Comparing; import com.intellij.openapi.util.SystemInfo; import com.intellij.openapi.util.TextRange; import com.intellij.openapi.vcs.FileStatus; @@ -75,8 +74,6 @@ import java.util.*; public class UnusedDeclarationPresentation extends DefaultInspectionToolPresentation { private final Map> myPackageContents = Collections.synchronizedMap(new HashMap>()); - private Map> myOldPackageContents = null; - private final Set myIgnoreElements = new HashSet(); private WeakUnreferencedFilter myFilter; private DeadHTMLComposer myComposer; @@ -376,27 +373,7 @@ public class UnusedDeclarationPresentation extends DefaultInspectionToolPresenta @Override public boolean hasReportedProblems() { - final GlobalInspectionContextImpl context = getContext(); - if (!isDisposed() && context.getUIOptions().SHOW_ONLY_DIFF){ - return containsOnlyDiff(myPackageContents) || - myOldPackageContents != null && containsOnlyDiff(myOldPackageContents); - } - if (!myPackageContents.isEmpty()) return true; - return isOldProblemsIncluded() && !myOldPackageContents.isEmpty(); - } - - private boolean containsOnlyDiff(@NotNull Map> packageContents) { - for (String packageName : packageContents.keySet()) { - final Set refElements = packageContents.get(packageName); - if (refElements != null){ - for (RefEntity refElement : refElements) { - if (getElementStatus(refElement) != FileStatus.NOT_CHANGED){ - return true; - } - } - } - } - return false; + return !myPackageContents.isEmpty(); } @NotNull @@ -405,11 +382,6 @@ public class UnusedDeclarationPresentation extends DefaultInspectionToolPresenta return myPackageContents; } - @Override - public Map> getOldContent() { - return myOldPackageContents; - } - @Override public void ignoreCurrentElement(RefEntity refEntity) { if (refEntity == null) return; @@ -424,7 +396,6 @@ public class UnusedDeclarationPresentation extends DefaultInspectionToolPresenta @Override public void cleanup() { super.cleanup(); - myOldPackageContents = null; myPackageContents.clear(); myIgnoreElements.clear(); } @@ -433,7 +404,6 @@ public class UnusedDeclarationPresentation extends DefaultInspectionToolPresenta @Override public void finalCleanup() { super.finalCleanup(); - myOldPackageContents = null; } @Override @@ -450,15 +420,6 @@ public class UnusedDeclarationPresentation extends DefaultInspectionToolPresenta @NotNull @Override public FileStatus getElementStatus(final RefEntity element) { - final GlobalInspectionContextImpl context = getContext(); - if (!isDisposed() && context.getUIOptions().SHOW_DIFF_WITH_PREVIOUS_RUN){ - if (myOldPackageContents != null){ - final boolean old = RefUtil.contains(element, collectRefElements(myOldPackageContents)); - final boolean current = RefUtil.contains(element, collectRefElements(myPackageContents)); - return calcStatus(old, current); - } - return FileStatus.ADDED; - } return FileStatus.NOT_CHANGED; } @@ -468,14 +429,6 @@ public class UnusedDeclarationPresentation extends DefaultInspectionToolPresenta return myIgnoreElements; } - private static Set collectRefElements(Map> packageContents) { - Set allAvailable = new HashSet(); - for (Set elements : packageContents.values()) { - allAvailable.addAll(elements); - } - return allAvailable; - } - @Override @Nullable public IntentionAction findQuickFixes(@NotNull final CommonProblemDescriptor descriptor, final String hint) { diff --git a/java/java-impl/src/com/intellij/codeInspection/inferNullity/InferNullityAnnotationsAction.java b/java/java-impl/src/com/intellij/codeInspection/inferNullity/InferNullityAnnotationsAction.java index 1d29c7308ebc..25d1294818e9 100644 --- a/java/java-impl/src/com/intellij/codeInspection/inferNullity/InferNullityAnnotationsAction.java +++ b/java/java-impl/src/com/intellij/codeInspection/inferNullity/InferNullityAnnotationsAction.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2015 JetBrains s.r.o. + * Copyright 2000-2016 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. @@ -197,7 +197,7 @@ public class InferNullityAnnotationsAction extends BaseAnalysisAction { @Override public void run() { scope.accept(new PsiElementVisitor() { - int myFileCount = 0; + int myFileCount; @Override public void visitFile(final PsiFile file) { diff --git a/java/java-impl/src/com/intellij/codeInspection/magicConstant/MagicConstantInspection.java b/java/java-impl/src/com/intellij/codeInspection/magicConstant/MagicConstantInspection.java index e7a512889014..6b8f0d6edf85 100644 --- a/java/java-impl/src/com/intellij/codeInspection/magicConstant/MagicConstantInspection.java +++ b/java/java-impl/src/com/intellij/codeInspection/magicConstant/MagicConstantInspection.java @@ -37,6 +37,8 @@ import com.intellij.openapi.vfs.VirtualFile; import com.intellij.psi.*; import com.intellij.psi.codeStyle.JavaCodeStyleManager; import com.intellij.psi.impl.JavaConstantExpressionEvaluator; +import com.intellij.psi.impl.cache.impl.id.IdIndex; +import com.intellij.psi.impl.cache.impl.id.IdIndexEntry; import com.intellij.psi.javadoc.PsiDocComment; import com.intellij.psi.javadoc.PsiDocTag; import com.intellij.psi.search.GlobalSearchScope; @@ -46,6 +48,7 @@ import com.intellij.psi.util.*; import com.intellij.slicer.*; import com.intellij.util.Processor; import com.intellij.util.containers.ContainerUtil; +import com.intellij.util.indexing.FileBasedIndex; import gnu.trove.THashSet; import org.intellij.lang.annotations.MagicConstant; import org.jetbrains.annotations.Nls; @@ -418,6 +421,14 @@ public class MagicConstantInspection extends BaseJavaLocalInspectionTool { } private static AllowedValues parseBeanInfo(@NotNull PsiModifierListOwner owner, @NotNull PsiManager manager) { + PsiFile containingFile = owner.getContainingFile(); + if (containingFile != null) { + GlobalSearchScope sourceFile = GlobalSearchScope.fileScope((PsiFile)containingFile.getNavigationElement()); + if (FileBasedIndex.getInstance().getContainingFiles(IdIndex.NAME, new IdIndexEntry("beaninfo", true), sourceFile).isEmpty()) { + // optimisation: do not parse library sources if there are no "beaninfo" text in the file + return null; + } + } PsiMethod method = null; if (owner instanceof PsiParameter) { PsiParameter parameter = (PsiParameter)owner; diff --git a/java/java-impl/src/com/intellij/codeInspection/unusedReturnValue/UnusedReturnValue.java b/java/java-impl/src/com/intellij/codeInspection/unusedReturnValue/UnusedReturnValue.java index 2949a79562db..7a8f9d413467 100644 --- a/java/java-impl/src/com/intellij/codeInspection/unusedReturnValue/UnusedReturnValue.java +++ b/java/java-impl/src/com/intellij/codeInspection/unusedReturnValue/UnusedReturnValue.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2009 JetBrains s.r.o. + * Copyright 2000-2016 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. @@ -44,7 +44,7 @@ import java.util.List; public class UnusedReturnValue extends GlobalJavaBatchInspectionTool{ private MakeVoidQuickFix myQuickFix; - public boolean IGNORE_BUILDER_PATTERN = false; + public boolean IGNORE_BUILDER_PATTERN; @Override @Nullable diff --git a/java/java-impl/src/com/intellij/cyclicDependencies/CyclicDependenciesBuilder.java b/java/java-impl/src/com/intellij/cyclicDependencies/CyclicDependenciesBuilder.java index a38a1485c606..3539683dbacd 100644 --- a/java/java-impl/src/com/intellij/cyclicDependencies/CyclicDependenciesBuilder.java +++ b/java/java-impl/src/com/intellij/cyclicDependencies/CyclicDependenciesBuilder.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2009 JetBrains s.r.o. + * Copyright 2000-2016 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. @@ -46,7 +46,7 @@ public class CyclicDependenciesBuilder{ private final Map>> myBackwardFilesInDependentPackages = new HashMap>>(); private final Map> myPackageDependencies = new HashMap>(); private HashMap>> myCyclicDependencies = new HashMap>>(); - private int myFileCount = 0; + private int myFileCount; private final ForwardDependenciesBuilder myForwardBuilder; private String myRootNodeNameInUsageView; diff --git a/java/java-impl/src/com/intellij/cyclicDependencies/CyclicDependenciesUtil.java b/java/java-impl/src/com/intellij/cyclicDependencies/CyclicDependenciesUtil.java index f15268681cf3..79625827f7c4 100644 --- a/java/java-impl/src/com/intellij/cyclicDependencies/CyclicDependenciesUtil.java +++ b/java/java-impl/src/com/intellij/cyclicDependencies/CyclicDependenciesUtil.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2009 JetBrains s.r.o. + * Copyright 2000-2016 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. @@ -33,7 +33,7 @@ public class CyclicDependenciesUtil{ final TIntArrayList sccs = dfstBuilder.getSCCs(); final List> chunks = new ArrayList>(); sccs.forEach(new TIntProcedure() { - int myTNumber = 0; + int myTNumber; public boolean execute(int size) { Set packs = new LinkedHashSet(); for (int j = 0; j < size; j++) { diff --git a/java/java-impl/src/com/intellij/ide/projectView/impl/PackageViewPane.java b/java/java-impl/src/com/intellij/ide/projectView/impl/PackageViewPane.java index a8e29dedf295..e4967d286908 100644 --- a/java/java-impl/src/com/intellij/ide/projectView/impl/PackageViewPane.java +++ b/java/java-impl/src/com/intellij/ide/projectView/impl/PackageViewPane.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2014 JetBrains s.r.o. + * Copyright 2000-2016 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. @@ -14,9 +14,6 @@ * limitations under the License. */ -/** - * @author cdr - */ package com.intellij.ide.projectView.impl; import com.intellij.history.LocalHistory; @@ -28,7 +25,10 @@ import com.intellij.ide.SelectInTarget; import com.intellij.ide.impl.PackagesPaneSelectInTarget; import com.intellij.ide.projectView.ProjectView; import com.intellij.ide.projectView.ViewSettings; -import com.intellij.ide.projectView.impl.nodes.*; +import com.intellij.ide.projectView.impl.nodes.PackageElement; +import com.intellij.ide.projectView.impl.nodes.PackageElementNode; +import com.intellij.ide.projectView.impl.nodes.PackageUtil; +import com.intellij.ide.projectView.impl.nodes.PackageViewProjectNode; import com.intellij.ide.util.DeleteHandler; import com.intellij.ide.util.treeView.AbstractTreeBuilder; import com.intellij.ide.util.treeView.AbstractTreeNode; diff --git a/java/java-impl/src/com/intellij/ide/util/treeView/TreeViewUtil.java b/java/java-impl/src/com/intellij/ide/util/treeView/TreeViewUtil.java index 265c50e84e8e..310954c56883 100644 --- a/java/java-impl/src/com/intellij/ide/util/treeView/TreeViewUtil.java +++ b/java/java-impl/src/com/intellij/ide/util/treeView/TreeViewUtil.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2014 JetBrains s.r.o. + * Copyright 2000-2016 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. @@ -45,7 +45,7 @@ public class TreeViewUtil { final ConcurrentMap newMap = ContainerUtil.createConcurrentWeakMap(); map = ((UserDataHolderEx)project).putUserDataIfAbsent(SHOULD_ABBREV_PACK_KEY, newMap); if (map == newMap) { - ((PsiManagerEx)PsiManager.getInstance(project)).registerRunnableToRunOnChange(new Runnable() { + PsiManagerEx.getInstanceEx(project).registerRunnableToRunOnChange(new Runnable() { @Override public void run() { newMap.clear(); diff --git a/java/java-impl/src/com/intellij/internal/DupIconsFinder.java b/java/java-impl/src/com/intellij/internal/DupIconsFinder.java index 63ebcdc759de..43224cfb8e4a 100644 --- a/java/java-impl/src/com/intellij/internal/DupIconsFinder.java +++ b/java/java-impl/src/com/intellij/internal/DupIconsFinder.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2012 JetBrains s.r.o. + * Copyright 2000-2016 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. @@ -31,8 +31,8 @@ import java.util.Map; public class DupIconsFinder { private static final MultiMap hashes = new MultiMap(); - private static int totalClusters = 0; - private static int totalDups = 0; + private static int totalClusters; + private static int totalDups; public static void main(String[] args) throws Exception { File root = new File("/Users/max/images/icons"); diff --git a/java/java-impl/src/com/intellij/internal/statistic/libraryJar/LibraryJarDescriptors.java b/java/java-impl/src/com/intellij/internal/statistic/libraryJar/LibraryJarDescriptors.java index fbb64676422e..f9234abdfcd2 100644 --- a/java/java-impl/src/com/intellij/internal/statistic/libraryJar/LibraryJarDescriptors.java +++ b/java/java-impl/src/com/intellij/internal/statistic/libraryJar/LibraryJarDescriptors.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2014 JetBrains s.r.o. + * Copyright 2000-2016 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. @@ -15,10 +15,6 @@ */ package com.intellij.internal.statistic.libraryJar; -/** - * @author Ivan Chirkov - */ - import com.intellij.util.xmlb.annotations.AbstractCollection; import com.intellij.util.xmlb.annotations.Property; diff --git a/java/java-impl/src/com/intellij/internal/statistic/libraryJar/LibraryJarUsagesCollector.java b/java/java-impl/src/com/intellij/internal/statistic/libraryJar/LibraryJarUsagesCollector.java index 6884216ea597..b4ea358f66f6 100644 --- a/java/java-impl/src/com/intellij/internal/statistic/libraryJar/LibraryJarUsagesCollector.java +++ b/java/java-impl/src/com/intellij/internal/statistic/libraryJar/LibraryJarUsagesCollector.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2014 JetBrains s.r.o. + * Copyright 2000-2016 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. @@ -21,8 +21,10 @@ import com.intellij.internal.statistic.beans.GroupDescriptor; import com.intellij.internal.statistic.beans.UsageDescriptor; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.project.Project; -import com.intellij.openapi.projectRoots.JdkUtil; +import com.intellij.openapi.util.io.JarUtil; +import com.intellij.openapi.util.text.StringUtil; import com.intellij.openapi.vfs.JarFileSystem; +import com.intellij.openapi.vfs.VfsUtilCore; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.psi.JavaPsiFacade; import com.intellij.psi.PsiClass; @@ -44,33 +46,36 @@ public class LibraryJarUsagesCollector extends AbstractApplicationUsagesCollecto private static final String DIGIT_VERSION_PATTERN_PART = "(\\d+.\\d+|\\d+)"; private static final Pattern JAR_FILE_NAME_PATTERN = Pattern.compile("[\\w|\\-|\\.]+-(" + DIGIT_VERSION_PATTERN_PART + "[\\w|\\.]*)jar"); - private static final Pattern DIGIT_VERSION_PATTERN = Pattern.compile(DIGIT_VERSION_PATTERN_PART + ".*"); @NotNull @Override public Set getProjectUsages(@NotNull final Project project) throws CollectUsagesException { final LibraryJarDescriptor[] descriptors = LibraryJarStatisticsService.getInstance().getTechnologyDescriptors(); final Set result = new HashSet(descriptors.length); - ApplicationManager.getApplication().runReadAction(new Runnable() { - @Override - public void run() { - for (LibraryJarDescriptor descriptor : descriptors) { - String className = descriptor.myClass; - if (className == null) continue; - PsiClass[] psiClasses = JavaPsiFacade.getInstance(project).findClasses(className, ProjectScope.getLibrariesScope(project)); - for (PsiClass psiClass : psiClasses) { - if (psiClass == null) continue; + ApplicationManager.getApplication().runReadAction(() -> { + for (LibraryJarDescriptor descriptor : descriptors) { + String className = descriptor.myClass; + if (className == null) continue; - VirtualFile localFile = JarFileSystem.getInstance().getLocalVirtualFileFor(psiClass.getContainingFile().getVirtualFile()); - if (localFile == null) continue; + PsiClass[] psiClasses = JavaPsiFacade.getInstance(project).findClasses(className, ProjectScope.getLibrariesScope(project)); + for (PsiClass psiClass : psiClasses) { + if (psiClass == null) continue; - String version = getVersionByJarManifest(localFile); - if (version == null) version = getVersionByJarFileName(localFile.getName()); - if (version == null) continue; + VirtualFile jarFile = JarFileSystem.getInstance().getLocalVirtualFileFor(psiClass.getContainingFile().getVirtualFile()); + if (jarFile == null) continue; - result.add(new UsageDescriptor(descriptor.myName + "_" + version, 1)); + String version = getVersionByJarManifest(jarFile); + if (version == null) { + version = getVersionByJarFileName(jarFile.getName()); } + + if (version == null || + !StringUtil.containsChar(version, '.')) { + continue; + } + + result.add(new UsageDescriptor(descriptor.myName + "_" + version, 1)); } } }); @@ -79,21 +84,15 @@ public class LibraryJarUsagesCollector extends AbstractApplicationUsagesCollecto @Nullable private static String getVersionByJarManifest(@NotNull VirtualFile file) { - String version = JdkUtil.getJarMainAttribute(file, Attributes.Name.IMPLEMENTATION_VERSION); - if (version == null) return null; - - Matcher versionMatcher = DIGIT_VERSION_PATTERN.matcher(version); - if (!versionMatcher.matches()) return null; - - return versionMatcher.group(1); + return JarUtil.getJarAttribute(VfsUtilCore.virtualToIoFile(file), Attributes.Name.IMPLEMENTATION_VERSION); } @Nullable - public String getVersionByJarFileName(@NotNull String fileName) { + private static String getVersionByJarFileName(@NotNull String fileName) { Matcher fileNameMatcher = JAR_FILE_NAME_PATTERN.matcher(fileName); if (!fileNameMatcher.matches()) return null; - return fileNameMatcher.group(2); + return StringUtil.trimTrailing(fileNameMatcher.group(1), '.'); } @NotNull diff --git a/java/java-impl/src/com/intellij/javadoc/EnterInJavadocParamDescriptionHandler.java b/java/java-impl/src/com/intellij/javadoc/EnterInJavadocParamDescriptionHandler.java index efd6ecfe8f64..e4b333fde599 100644 --- a/java/java-impl/src/com/intellij/javadoc/EnterInJavadocParamDescriptionHandler.java +++ b/java/java-impl/src/com/intellij/javadoc/EnterInJavadocParamDescriptionHandler.java @@ -2,6 +2,7 @@ package com.intellij.javadoc; import com.intellij.codeInsight.CodeInsightSettings; import com.intellij.codeInsight.editorActions.enter.EnterHandlerDelegateAdapter; +import com.intellij.ide.highlighter.JavaFileType; import com.intellij.openapi.actionSystem.DataContext; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.editor.CaretModel; @@ -12,6 +13,7 @@ import com.intellij.openapi.util.Pair; import com.intellij.openapi.util.text.StringUtil; import com.intellij.psi.PsiDocumentManager; import com.intellij.psi.PsiFile; +import com.intellij.psi.PsiJavaFile; import com.intellij.psi.codeStyle.CodeStyleSettingsManager; import com.intellij.util.text.CharArrayUtil; import org.jetbrains.annotations.NotNull; @@ -28,13 +30,17 @@ public class EnterInJavadocParamDescriptionHandler extends EnterHandlerDelegateA @Override public Result postProcessEnter(@NotNull final PsiFile file, @NotNull Editor editor, @NotNull DataContext dataContext) { - if (!CodeInsightSettings.getInstance().SMART_INDENT_ON_ENTER - || !CodeStyleSettingsManager.getSettings(file.getProject()).JD_ALIGN_PARAM_COMMENTS) - { + if (!(file instanceof PsiJavaFile) + || !CodeInsightSettings.getInstance().SMART_INDENT_ON_ENTER + || !CodeStyleSettingsManager.getSettings(file.getProject()).JD_ALIGN_PARAM_COMMENTS) { return Result.Continue; } final CaretModel caretModel = editor.getCaretModel(); final int caretOffset = caretModel.getOffset(); + if (!isInJavaDoc(editor, caretOffset)) { + return Result.Continue; + } + final Pair> pair = myHelper.parse(file, editor, caretOffset); if (pair.first == null || pair.first.parameterDescriptionStartPosition == null) { @@ -67,4 +73,15 @@ public class EnterInJavadocParamDescriptionHandler extends EnterHandlerDelegateA myHelper.navigate(desiredPosition, editor, file.getProject()); return Result.Stop; } + + private static boolean isInJavaDoc(@NotNull Editor editor, int offset) { + Document document = editor.getDocument(); + CharSequence docChars = document.getCharsSequence(); + int i = CharArrayUtil.lastIndexOf(docChars, "/**", offset); + if (i >= 0) { + i = CharArrayUtil.indexOf(docChars, "*/", i); + return i > offset; + } + return false; + } } diff --git a/java/java-impl/src/com/intellij/javadoc/JavadocConfiguration.java b/java/java-impl/src/com/intellij/javadoc/JavadocConfiguration.java index 0a9415f38cc4..a7248ef1694e 100644 --- a/java/java-impl/src/com/intellij/javadoc/JavadocConfiguration.java +++ b/java/java-impl/src/com/intellij/javadoc/JavadocConfiguration.java @@ -32,15 +32,15 @@ public class JavadocConfiguration { public boolean OPTION_NAVIGATOR = true; public boolean OPTION_INDEX = true; public boolean OPTION_SEPARATE_INDEX = true; - public boolean OPTION_DOCUMENT_TAG_USE = false; - public boolean OPTION_DOCUMENT_TAG_AUTHOR = false; - public boolean OPTION_DOCUMENT_TAG_VERSION = false; + public boolean OPTION_DOCUMENT_TAG_USE; + public boolean OPTION_DOCUMENT_TAG_AUTHOR; + public boolean OPTION_DOCUMENT_TAG_VERSION; public boolean OPTION_DOCUMENT_TAG_DEPRECATED = true; public boolean OPTION_DEPRECATED_LIST = true; public String OTHER_OPTIONS = ""; public String HEAP_SIZE; public String LOCALE; public boolean OPEN_IN_BROWSER = true; - public boolean OPTION_INCLUDE_LIBS = false; - public boolean OPTION_LINK_TO_JDK_DOCS = false; + public boolean OPTION_INCLUDE_LIBS; + public boolean OPTION_LINK_TO_JDK_DOCS; } \ No newline at end of file diff --git a/java/java-impl/src/com/intellij/lang/java/JavaImportOptimizer.java b/java/java-impl/src/com/intellij/lang/java/JavaImportOptimizer.java index eddd536d19fb..7601d5dee787 100644 --- a/java/java-impl/src/com/intellij/lang/java/JavaImportOptimizer.java +++ b/java/java-impl/src/com/intellij/lang/java/JavaImportOptimizer.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2009 JetBrains s.r.o. + * Copyright 2000-2016 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. @@ -47,7 +47,7 @@ public class JavaImportOptimizer implements ImportOptimizer { if (newImportList == null) return EmptyRunnable.getInstance(); return new CollectingInfoRunnable() { - private int myImportListLengthDiff = 0; + private int myImportListLengthDiff; @Override public void run() { diff --git a/java/java-impl/src/com/intellij/packageDependencies/ui/TreeModelBuilder.java b/java/java-impl/src/com/intellij/packageDependencies/ui/TreeModelBuilder.java index 994f2dda4796..6a7f23070da2 100644 --- a/java/java-impl/src/com/intellij/packageDependencies/ui/TreeModelBuilder.java +++ b/java/java-impl/src/com/intellij/packageDependencies/ui/TreeModelBuilder.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2014 JetBrains s.r.o. + * Copyright 2000-2016 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. @@ -71,14 +71,14 @@ public class TreeModelBuilder { private final Map> myModuleNodes = new HashMap>(); private final Map> myModuleGroupNodes = new HashMap>(); private final Map> myLibraryNodes = new HashMap>(); - private int myScannedFileCount = 0; - private int myTotalFileCount = 0; - private int myMarkedFileCount = 0; - private GeneralGroupNode myAllLibsNode = null; + private int myScannedFileCount; + private int myTotalFileCount; + private int myMarkedFileCount; + private GeneralGroupNode myAllLibsNode; - private GeneralGroupNode mySourceRoot = null; - private GeneralGroupNode myTestRoot = null; - private GeneralGroupNode myLibsRoot = null; + private GeneralGroupNode mySourceRoot; + private GeneralGroupNode myTestRoot; + private GeneralGroupNode myLibsRoot; public static final String PRODUCTION_NAME = AnalysisScopeBundle.message("package.dependencies.production.node.text"); public static final String TEST_NAME = AnalysisScopeBundle.message("package.dependencies.test.node.text"); @@ -166,8 +166,8 @@ public class TreeModelBuilder { public void run() { countFiles(project); myFileIndex.iterateContent(new ContentIterator() { - PackageDependenciesNode lastParent = null; - VirtualFile dir = null; + PackageDependenciesNode lastParent; + VirtualFile dir; public boolean processFile(VirtualFile fileOrDir) { if (!fileOrDir.isDirectory()) { if (lastParent != null && !Comparing.equal(dir, fileOrDir.getParent())) { @@ -195,7 +195,7 @@ public class TreeModelBuilder { private void processFilesRecursively(@NotNull VirtualFile file) { VfsUtilCore.visitChildrenRecursively(file, new VirtualFileVisitor() { - private PackageDependenciesNode parent = null; + private PackageDependenciesNode parent; @Override public boolean visitFile(@NotNull VirtualFile file) { diff --git a/java/java-impl/src/com/intellij/psi/AbstractQualifiedReference.java b/java/java-impl/src/com/intellij/psi/AbstractQualifiedReference.java index d0d7cce6e280..60e72e4c47ed 100644 --- a/java/java-impl/src/com/intellij/psi/AbstractQualifiedReference.java +++ b/java/java-impl/src/com/intellij/psi/AbstractQualifiedReference.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2014 JetBrains s.r.o. + * Copyright 2000-2016 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. @@ -245,7 +245,7 @@ public abstract class AbstractQualifiedReference myResults = new LinkedHashSet(); @Override diff --git a/java/java-impl/src/com/intellij/psi/codeStyle/JavaCodeStyleSettings.java b/java/java-impl/src/com/intellij/psi/codeStyle/JavaCodeStyleSettings.java index 9a7268339b7e..d31f94e11175 100644 --- a/java/java-impl/src/com/intellij/psi/codeStyle/JavaCodeStyleSettings.java +++ b/java/java-impl/src/com/intellij/psi/codeStyle/JavaCodeStyleSettings.java @@ -21,19 +21,19 @@ public class JavaCodeStyleSettings extends CustomCodeStyleSettings { super("JavaCodeStyleSettings", container); } - public boolean SPACES_WITHIN_ANGLE_BRACKETS = false; + public boolean SPACES_WITHIN_ANGLE_BRACKETS; //Type arguments - public boolean SPACE_AFTER_CLOSING_ANGLE_BRACKET_IN_TYPE_ARGUMENT = false; + public boolean SPACE_AFTER_CLOSING_ANGLE_BRACKET_IN_TYPE_ARGUMENT; //Type parameters - public boolean SPACE_BEFORE_OPENING_ANGLE_BRACKET_IN_TYPE_PARAMETER = false; + public boolean SPACE_BEFORE_OPENING_ANGLE_BRACKET_IN_TYPE_PARAMETER; public boolean SPACE_AROUND_TYPE_BOUNDS_IN_TYPE_PARAMETERS = true; - public boolean DO_NOT_WRAP_AFTER_SINGLE_ANNOTATION = false; + public boolean DO_NOT_WRAP_AFTER_SINGLE_ANNOTATION; public int ANNOTATION_PARAMETER_WRAP = CommonCodeStyleSettings.DO_NOT_WRAP; - public boolean ALIGN_MULTILINE_ANNOTATION_PARAMETERS = false; + public boolean ALIGN_MULTILINE_ANNOTATION_PARAMETERS; public int BLANK_LINES_AROUND_INITIALIZER = 1; diff --git a/java/java-impl/src/com/intellij/psi/filters/types/AssignableFromFilter.java b/java/java-impl/src/com/intellij/psi/filters/types/AssignableFromFilter.java index 23309bd687c0..8cd68e40f2e2 100644 --- a/java/java-impl/src/com/intellij/psi/filters/types/AssignableFromFilter.java +++ b/java/java-impl/src/com/intellij/psi/filters/types/AssignableFromFilter.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2009 JetBrains s.r.o. + * Copyright 2000-2016 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. @@ -31,8 +31,8 @@ import org.jetbrains.annotations.Nullable; * To change this template use Options | File Templates. */ public class AssignableFromFilter implements ElementFilter{ - private PsiType myType = null; - private String myClassName = null; + private PsiType myType; + private String myClassName; public AssignableFromFilter(PsiType type){ myType = type; diff --git a/java/java-impl/src/com/intellij/psi/formatter/java/AbstractJavaBlock.java b/java/java-impl/src/com/intellij/psi/formatter/java/AbstractJavaBlock.java index eb662ce4ddd9..a4ecc6bf3c25 100644 --- a/java/java-impl/src/com/intellij/psi/formatter/java/AbstractJavaBlock.java +++ b/java/java-impl/src/com/intellij/psi/formatter/java/AbstractJavaBlock.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2015 JetBrains s.r.o. + * Copyright 2000-2016 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. @@ -58,9 +58,9 @@ public abstract class AbstractJavaBlock extends AbstractBlock implements JavaBlo private final Indent myIndent; protected Indent myChildIndent; protected Alignment myChildAlignment; - protected boolean myUseChildAttributes = false; + protected boolean myUseChildAttributes; @NotNull protected final AlignmentStrategy myAlignmentStrategy; - private boolean myIsAfterClassKeyword = false; + private boolean myIsAfterClassKeyword; protected Alignment myReservedAlignment; protected Alignment myReservedAlignment2; diff --git a/java/java-impl/src/com/intellij/psi/formatter/java/SyntheticCodeBlock.java b/java/java-impl/src/com/intellij/psi/formatter/java/SyntheticCodeBlock.java index 7cc75fd34bf5..30f1960119e3 100644 --- a/java/java-impl/src/com/intellij/psi/formatter/java/SyntheticCodeBlock.java +++ b/java/java-impl/src/com/intellij/psi/formatter/java/SyntheticCodeBlock.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2009 JetBrains s.r.o. + * Copyright 2000-2016 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. @@ -42,7 +42,7 @@ public class SyntheticCodeBlock implements Block, JavaBlock{ private final TextRange myTextRange; private ChildAttributes myChildAttributes; - private boolean myIsIncomplete = false; + private boolean myIsIncomplete; public SyntheticCodeBlock(List subBlocks, Alignment alignment, diff --git a/java/java-impl/src/com/intellij/psi/impl/cache/SmartIntToIntArrayMap.java b/java/java-impl/src/com/intellij/psi/impl/cache/SmartIntToIntArrayMap.java index 387962a8b03b..04fceda6884e 100644 --- a/java/java-impl/src/com/intellij/psi/impl/cache/SmartIntToIntArrayMap.java +++ b/java/java-impl/src/com/intellij/psi/impl/cache/SmartIntToIntArrayMap.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2009 JetBrains s.r.o. + * Copyright 2000-2016 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. @@ -25,7 +25,7 @@ import org.jetbrains.annotations.Nullable; * @author max */ public class SmartIntToIntArrayMap { - @Nullable TIntObjectHashMap myMultipleValuesMap = null; + @Nullable TIntObjectHashMap myMultipleValuesMap; TIntIntHashMap mySingleValueMap = new TIntIntHashMap(10, 0.9f); public int[] keys() { diff --git a/java/java-impl/src/com/intellij/psi/impl/migration/PsiMigrationManager.java b/java/java-impl/src/com/intellij/psi/impl/migration/PsiMigrationManager.java index 5f24dcadfb7d..7a363c9e1462 100644 --- a/java/java-impl/src/com/intellij/psi/impl/migration/PsiMigrationManager.java +++ b/java/java-impl/src/com/intellij/psi/impl/migration/PsiMigrationManager.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2011 JetBrains s.r.o. + * Copyright 2000-2016 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. @@ -62,6 +62,6 @@ public class PsiMigrationManager { myCurrentMigration = null; } - ((PsiManagerEx)PsiManager.getInstance(myProject)).beforeChange(true); + PsiManagerEx.getInstanceEx(myProject).beforeChange(true); } } diff --git a/java/java-impl/src/com/intellij/psi/impl/source/PsiCodeFragmentImpl.java b/java/java-impl/src/com/intellij/psi/impl/source/PsiCodeFragmentImpl.java index 10a30242b606..fa0c7e2fbb95 100644 --- a/java/java-impl/src/com/intellij/psi/impl/source/PsiCodeFragmentImpl.java +++ b/java/java-impl/src/com/intellij/psi/impl/source/PsiCodeFragmentImpl.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2013 JetBrains s.r.o. + * Copyright 2000-2016 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. @@ -63,7 +63,7 @@ public class PsiCodeFragmentImpl extends PsiFileImpl implements JavaCodeFragment @Nullable PsiElement context) { super(TokenType.CODE_FRAGMENT, contentElementType, - ((PsiManagerEx)PsiManager.getInstance(project)).getFileManager().createFileViewProvider( + PsiManagerEx.getInstanceEx(project).getFileManager().createFileViewProvider( new LightVirtualFile(name, FileTypeManager.getInstance().getFileTypeByFileName(name), text), isPhysical) ); myContext = context; @@ -93,7 +93,7 @@ public class PsiCodeFragmentImpl extends PsiFileImpl implements JavaCodeFragment return clone; } - private FileViewProvider myViewProvider = null; + private FileViewProvider myViewProvider; @Override @NotNull diff --git a/java/java-impl/src/com/intellij/psi/impl/source/codeStyle/javadoc/JDComment.java b/java/java-impl/src/com/intellij/psi/impl/source/codeStyle/javadoc/JDComment.java index d79c018139d5..2edbf1595e24 100644 --- a/java/java-impl/src/com/intellij/psi/impl/source/codeStyle/javadoc/JDComment.java +++ b/java/java-impl/src/com/intellij/psi/impl/source/codeStyle/javadoc/JDComment.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2013 JetBrains s.r.o. + * Copyright 2000-2016 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. @@ -21,10 +21,6 @@ import org.jetbrains.annotations.Nullable; import java.util.List; -/** - * @author max - */ - /** * @author Dmitry Skavish */ diff --git a/java/java-impl/src/com/intellij/psi/stubsHierarchy/impl/SingleClassHierarchyBuilder.java b/java/java-impl/src/com/intellij/psi/stubsHierarchy/impl/SingleClassHierarchyBuilder.java index f4e44af567c5..7127414b5962 100644 --- a/java/java-impl/src/com/intellij/psi/stubsHierarchy/impl/SingleClassHierarchyBuilder.java +++ b/java/java-impl/src/com/intellij/psi/stubsHierarchy/impl/SingleClassHierarchyBuilder.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2015 JetBrains s.r.o. + * Copyright 2000-2016 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. @@ -55,7 +55,7 @@ public class SingleClassHierarchyBuilder { private final HierarchyService myHierarchyService; protected final BitSet myProcessedSet = new BitSet(); private final ProjectFileIndex myProjectIndex; - boolean isInSourceMode = false; + boolean isInSourceMode; private UnitProcessor(Project project, HierarchyService hierarchyService) { myProject = project; diff --git a/java/java-impl/src/com/intellij/refactoring/JavaRefactoringSettings.java b/java/java-impl/src/com/intellij/refactoring/JavaRefactoringSettings.java index 2e27afaeec6c..ca10fa56307c 100644 --- a/java/java-impl/src/com/intellij/refactoring/JavaRefactoringSettings.java +++ b/java/java-impl/src/com/intellij/refactoring/JavaRefactoringSettings.java @@ -60,9 +60,9 @@ public class JavaRefactoringSettings implements PersistentStateComponent 0; + } + private static PsiClassType[] filterCheckedExceptions(PsiClassType[] exceptions) { List result = new ArrayList(); for (PsiClassType exceptionType : exceptions) { @@ -636,7 +649,7 @@ public class JavaChangeSignatureUsageProcessor implements ChangeSignatureUsagePr if (defaultValue == null && parameter.getOldIndex() == -1) { ((ParameterInfoImpl)parameter).setDefaultValue(""); if (!ApplicationManager.getApplication().isUnitTestMode()) { - final PsiType type = ((ParameterInfoImpl)parameter).getTypeWrapper().getType(element, element.getManager()); + final PsiType type = ((ParameterInfoImpl)parameter).getTypeWrapper().getType(element); final DefaultValueChooser chooser = new DefaultValueChooser(project, parameter.getName(), PsiTypesUtil.getDefaultValueOfType(type)); if (chooser.showAndGet()) { @@ -932,7 +945,7 @@ public class JavaChangeSignatureUsageProcessor implements ChangeSignatureUsagePr PsiSubstitutor... substitutor) throws IncorrectOperationException { final PsiParameterList list = changeInfo.getMethod().getParameterList(); final PsiElementFactory factory = JavaPsiFacade.getInstance(list.getProject()).getElementFactory(); - PsiType type = newParm.createType(list, list.getManager()); + PsiType type = newParm.createType(list); for (PsiSubstitutor psiSubstitutor : substitutor) { type = psiSubstitutor.substitute(type); } diff --git a/java/java-impl/src/com/intellij/refactoring/changeSignature/JavaParameterInfo.java b/java/java-impl/src/com/intellij/refactoring/changeSignature/JavaParameterInfo.java index b2dd2e8f0dbe..6e533a4ef06d 100644 --- a/java/java-impl/src/com/intellij/refactoring/changeSignature/JavaParameterInfo.java +++ b/java/java-impl/src/com/intellij/refactoring/changeSignature/JavaParameterInfo.java @@ -18,6 +18,7 @@ package com.intellij.refactoring.changeSignature; import com.intellij.psi.*; import com.intellij.refactoring.util.CanonicalTypes; import com.intellij.util.IncorrectOperationException; +import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; /** @@ -25,7 +26,12 @@ import org.jetbrains.annotations.Nullable; */ public interface JavaParameterInfo extends ParameterInfo { @Nullable - PsiType createType(PsiElement context, final PsiManager manager) throws IncorrectOperationException; + PsiType createType(@Nullable PsiElement context, final PsiManager manager) throws IncorrectOperationException; + + @Nullable + default PsiType createType(@NotNull PsiElement context) { + return createType(context, context.getManager()); + } String getTypeText(); diff --git a/java/java-impl/src/com/intellij/refactoring/changeSignature/MethodReferenceUsageInfo.java b/java/java-impl/src/com/intellij/refactoring/changeSignature/MethodReferenceUsageInfo.java index 7866f8631a31..c253b1333a16 100644 --- a/java/java-impl/src/com/intellij/refactoring/changeSignature/MethodReferenceUsageInfo.java +++ b/java/java-impl/src/com/intellij/refactoring/changeSignature/MethodReferenceUsageInfo.java @@ -47,7 +47,16 @@ class MethodReferenceUsageInfo extends UsageInfo { } public static boolean needToExpand(JavaChangeInfo changeInfo) { - return !changeInfo.isGenerateDelegate() && (changeInfo.isParameterSetOrOrderChanged() || changeInfo.isExceptionSetOrOrderChanged()); + if (!changeInfo.isGenerateDelegate()) { + if (changeInfo.isParameterSetOrOrderChanged()) { + return true; + } + else if (changeInfo.isExceptionSetOrOrderChanged()) { + return JavaChangeSignatureUsageProcessor.hasNewCheckedExceptions(changeInfo); + } + } + + return false; } @Nullable diff --git a/java/java-impl/src/com/intellij/refactoring/changeSignature/ParameterInfoImpl.java b/java/java-impl/src/com/intellij/refactoring/changeSignature/ParameterInfoImpl.java index 9bc2bba3b570..7fcfc830d6a9 100644 --- a/java/java-impl/src/com/intellij/refactoring/changeSignature/ParameterInfoImpl.java +++ b/java/java-impl/src/com/intellij/refactoring/changeSignature/ParameterInfoImpl.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2014 JetBrains s.r.o. + * Copyright 2000-2016 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. @@ -14,10 +14,6 @@ * limitations under the License. */ -/** - * created at Sep 17, 2001 - * @author Jeka - */ package com.intellij.refactoring.changeSignature; import com.intellij.openapi.diagnostic.Logger; diff --git a/java/java-impl/src/com/intellij/refactoring/extractMethod/ExtractMethodProcessor.java b/java/java-impl/src/com/intellij/refactoring/extractMethod/ExtractMethodProcessor.java index d22b60890fd2..45fd55ff4ac0 100644 --- a/java/java-impl/src/com/intellij/refactoring/extractMethod/ExtractMethodProcessor.java +++ b/java/java-impl/src/com/intellij/refactoring/extractMethod/ExtractMethodProcessor.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2014 JetBrains s.r.o. + * Copyright 2000-2016 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. @@ -128,8 +128,8 @@ public class ExtractMethodProcessor implements MatchProvider { protected PsiStatement myFirstExitStatementCopy; private PsiMethod myExtractedMethod; private PsiMethodCallExpression myMethodCall; - protected boolean myNullConditionalCheck = false; - protected boolean myNotNullConditionalCheck = false; + protected boolean myNullConditionalCheck; + protected boolean myNotNullConditionalCheck; private Nullness myNullness; public ExtractMethodProcessor(Project project, diff --git a/java/java-impl/src/com/intellij/refactoring/extractMethodObject/ExtractMethodObjectProcessor.java b/java/java-impl/src/com/intellij/refactoring/extractMethodObject/ExtractMethodObjectProcessor.java index d8fd2feb9efa..5bb01dbda9d0 100644 --- a/java/java-impl/src/com/intellij/refactoring/extractMethodObject/ExtractMethodObjectProcessor.java +++ b/java/java-impl/src/com/intellij/refactoring/extractMethodObject/ExtractMethodObjectProcessor.java @@ -81,7 +81,7 @@ public class ExtractMethodObjectProcessor extends BaseRefactoringProcessor { private PsiField[] myOutputFields; private PsiMethod myInnerMethod; - private boolean myMadeStatic = false; + private boolean myMadeStatic; private final Set myUsages = new LinkedHashSet(); private PsiClass myInnerClass; private boolean myChangeReturnType; diff --git a/java/java-impl/src/com/intellij/refactoring/extractSuperclass/ExtractSuperclassHandler.java b/java/java-impl/src/com/intellij/refactoring/extractSuperclass/ExtractSuperclassHandler.java index 31f2d25f1a0b..815f9450a8dc 100644 --- a/java/java-impl/src/com/intellij/refactoring/extractSuperclass/ExtractSuperclassHandler.java +++ b/java/java-impl/src/com/intellij/refactoring/extractSuperclass/ExtractSuperclassHandler.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2014 JetBrains s.r.o. + * Copyright 2000-2016 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. @@ -14,10 +14,6 @@ * limitations under the License. */ -/** - * created at Oct 25, 2001 - * @author Jeka - */ package com.intellij.refactoring.extractSuperclass; import com.intellij.history.LocalHistory; diff --git a/java/java-impl/src/com/intellij/refactoring/extractclass/BackpointerUsageVisitor.java b/java/java-impl/src/com/intellij/refactoring/extractclass/BackpointerUsageVisitor.java index 06178817fd40..fc4f709344c2 100644 --- a/java/java-impl/src/com/intellij/refactoring/extractclass/BackpointerUsageVisitor.java +++ b/java/java-impl/src/com/intellij/refactoring/extractclass/BackpointerUsageVisitor.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2009 JetBrains s.r.o. + * Copyright 2000-2016 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. @@ -25,7 +25,7 @@ import com.intellij.psi.*; import java.util.List; class BackpointerUsageVisitor extends JavaRecursiveElementWalkingVisitor { - private PsiMember myCause = null; + private PsiMember myCause; private final List myFields; private final List myInnerClasses; diff --git a/java/java-impl/src/com/intellij/refactoring/extractclass/ExtractClassProcessor.java b/java/java-impl/src/com/intellij/refactoring/extractclass/ExtractClassProcessor.java index 3332ce2ed234..944100216317 100644 --- a/java/java-impl/src/com/intellij/refactoring/extractclass/ExtractClassProcessor.java +++ b/java/java-impl/src/com/intellij/refactoring/extractclass/ExtractClassProcessor.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2015 JetBrains s.r.o. + * Copyright 2000-2016 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. @@ -81,7 +81,7 @@ public class ExtractClassProcessor extends FixableUsagesRefactoringProcessor { private final String newClassName; private final String delegateFieldName; private final boolean requiresBackpointer; - private boolean delegationRequired = false; + private boolean delegationRequired; private final ExtractEnumProcessor myExtractEnumProcessor; private final PsiClass myClass; private boolean extractInnerClass; diff --git a/java/java-impl/src/com/intellij/refactoring/extractclass/ExtractedClassBuilder.java b/java/java-impl/src/com/intellij/refactoring/extractclass/ExtractedClassBuilder.java index 03e7138eee23..4e42bd3cab93 100644 --- a/java/java-impl/src/com/intellij/refactoring/extractclass/ExtractedClassBuilder.java +++ b/java/java-impl/src/com/intellij/refactoring/extractclass/ExtractedClassBuilder.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2009 JetBrains s.r.o. + * Copyright 2000-2016 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. @@ -38,8 +38,8 @@ import java.util.Set; class ExtractedClassBuilder { private static final Logger LOGGER = Logger.getInstance("com.siyeh.rpp.extractclass.ExtractedClassBuilder"); - private String className = null; - private String packageName = null; + private String className; + private String packageName; private final List fields = new ArrayList(5); private final List methods = new ArrayList(5); private final List initializers = new ArrayList(5); @@ -48,9 +48,9 @@ class ExtractedClassBuilder { private final List typeParams = new ArrayList(); private final List interfaces = new ArrayList(); - private boolean requiresBackPointer = false; - private String originalClassName = null; - private String backPointerName = null; + private boolean requiresBackPointer; + private String originalClassName; + private String backPointerName; private Project myProject; private JavaCodeStyleManager myJavaCodeStyleManager; private Set myFieldsNeedingSetters; diff --git a/java/java-impl/src/com/intellij/refactoring/inline/InlineConstantFieldHandler.java b/java/java-impl/src/com/intellij/refactoring/inline/InlineConstantFieldHandler.java index ebc80a018c3e..8f6fe19b1de6 100644 --- a/java/java-impl/src/com/intellij/refactoring/inline/InlineConstantFieldHandler.java +++ b/java/java-impl/src/com/intellij/refactoring/inline/InlineConstantFieldHandler.java @@ -15,6 +15,7 @@ */ package com.intellij.refactoring.inline; +import com.intellij.codeInsight.PsiEquivalenceUtil; import com.intellij.codeInsight.TargetElementUtil; import com.intellij.lang.StdLanguages; import com.intellij.openapi.application.ApplicationManager; @@ -23,12 +24,19 @@ import com.intellij.openapi.progress.ProgressManager; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.Ref; import com.intellij.psi.*; +import com.intellij.psi.search.LocalSearchScope; import com.intellij.psi.search.ProjectScope; import com.intellij.psi.search.searches.ReferencesSearch; +import com.intellij.psi.util.PsiTreeUtil; import com.intellij.psi.util.PsiUtil; import com.intellij.refactoring.HelpID; import com.intellij.refactoring.RefactoringBundle; import com.intellij.refactoring.util.CommonRefactoringUtil; +import com.intellij.util.containers.ContainerUtil; +import org.jetbrains.annotations.Nullable; + +import java.util.ArrayList; +import java.util.List; /** * @author ven @@ -46,7 +54,7 @@ public class InlineConstantFieldHandler extends JavaInlineActionHandler { final PsiElement navigationElement = element.getNavigationElement(); final PsiField field = (PsiField)(navigationElement instanceof PsiField ? navigationElement : element); - if (!field.hasInitializer()) { + if (getInitializer(field) == null) { String message = RefactoringBundle.message("no.initializer.present.for.the.field"); CommonRefactoringUtil.showErrorHint(project, editor, message, REFACTORING_NAME, HelpID.INLINE_FIELD); return; @@ -66,23 +74,15 @@ public class InlineConstantFieldHandler extends JavaInlineActionHandler { if (!field.hasModifierProperty(PsiModifier.FINAL)) { final Ref hasWriteUsages = new Ref(false); - if (!ProgressManager.getInstance().runProcessWithProgressSynchronously(new Runnable() { - @Override - public void run() { - ApplicationManager.getApplication().runReadAction(new Runnable() { - @Override - public void run() { - for (PsiReference reference : ReferencesSearch.search(field)) { - final PsiElement referenceElement = reference.getElement(); - if (!(referenceElement instanceof PsiExpression && PsiUtil.isAccessedForReading((PsiExpression)referenceElement))) { - hasWriteUsages.set(true); - break; - } - } - } - }); + if (!ProgressManager.getInstance().runProcessWithProgressSynchronously(() -> ApplicationManager.getApplication().runReadAction(() -> { + for (PsiReference reference : ReferencesSearch.search(field)) { + final PsiElement referenceElement = reference.getElement(); + if (!(referenceElement instanceof PsiExpression) || PsiUtil.isAccessedForWriting((PsiExpression)referenceElement)) { + hasWriteUsages.set(true); + break; + } } - }, "Check if inline is possible...", true, project)) { + }), "Check if Inline Is Possible...", true, project)) { return; } if (hasWriteUsages.get()) { @@ -105,4 +105,40 @@ public class InlineConstantFieldHandler extends JavaInlineActionHandler { InlineFieldDialog dialog = new InlineFieldDialog(project, field, refExpression); dialog.show(); } + + @Nullable + protected static PsiExpression getInitializer(PsiField field) { + if (field.hasInitializer()) { + return field.getInitializer(); + } + + if (field.hasModifierProperty(PsiModifier.FINAL)) { + PsiClass containingClass = field.getContainingClass(); + if (containingClass != null) { + PsiMethod[] constructors = containingClass.getConstructors(); + final List result = new ArrayList<>(); + for (PsiReference reference : ReferencesSearch.search(field, new LocalSearchScope(constructors))) { + final PsiElement element = reference.getElement(); + if (element instanceof PsiReferenceExpression && PsiUtil.isOnAssignmentLeftHand((PsiExpression)element)) { + PsiAssignmentExpression assignmentExpression = PsiTreeUtil.getParentOfType(element, PsiAssignmentExpression.class); + if (assignmentExpression != null) { + ContainerUtil.addIfNotNull(assignmentExpression.getRExpression(), result); + } + } + } + + if (result.isEmpty()) return null; + + PsiExpression first = result.get(0); + for (PsiExpression expr : result) { + if (!PsiEquivalenceUtil.areElementsEquivalent(expr, first)) { + return null; + } + } + return first; + } + } + + return null; + } } diff --git a/java/java-impl/src/com/intellij/refactoring/inline/InlineConstantFieldProcessor.java b/java/java-impl/src/com/intellij/refactoring/inline/InlineConstantFieldProcessor.java index bbab285e2333..ec722d291feb 100644 --- a/java/java-impl/src/com/intellij/refactoring/inline/InlineConstantFieldProcessor.java +++ b/java/java-impl/src/com/intellij/refactoring/inline/InlineConstantFieldProcessor.java @@ -137,7 +137,7 @@ public class InlineConstantFieldProcessor extends BaseRefactoringProcessor { @Override protected void performRefactoring(@NotNull UsageInfo[] usages) { - PsiExpression initializer = myField.getInitializer(); + PsiExpression initializer = InlineConstantFieldHandler.getInitializer(myField); LOG.assertTrue(initializer != null); initializer = normalize ((PsiExpression)initializer.copy()); @@ -190,13 +190,23 @@ public class InlineConstantFieldProcessor extends BaseRefactoringProcessor { if (myField.isWritable()) { myField.normalizeDeclaration(); } + + if (isAccessedForWriting(expr)) { + PsiAssignmentExpression assignmentExpression = PsiTreeUtil.getParentOfType(expr, PsiAssignmentExpression.class); + if (assignmentExpression != null) { + assignmentExpression.delete(); + } + return; + } + if (expr instanceof PsiReferenceExpression) { PsiExpression qExpression = ((PsiReferenceExpression)expr).getQualifierExpression(); if (qExpression != null) { PsiReferenceExpression referenceExpression = null; if (initializer1 instanceof PsiReferenceExpression) { referenceExpression = (PsiReferenceExpression)initializer1; - } else if (initializer1 instanceof PsiMethodCallExpression) { + } + else if (initializer1 instanceof PsiMethodCallExpression) { referenceExpression = ((PsiMethodCallExpression)initializer1).getMethodExpression(); } if (referenceExpression != null && @@ -242,7 +252,7 @@ public class InlineConstantFieldProcessor extends BaseRefactoringProcessor { MultiMap conflicts = new MultiMap(); ReferencedElementsCollector collector = new ReferencedElementsCollector(); - PsiExpression initializer = myField.getInitializer(); + PsiExpression initializer = InlineConstantFieldHandler.getInitializer(myField); LOG.assertTrue(initializer != null); initializer.accept(collector); HashSet referencedWithVisibility = collector.myReferencedMembers; @@ -250,7 +260,7 @@ public class InlineConstantFieldProcessor extends BaseRefactoringProcessor { PsiResolveHelper resolveHelper = JavaPsiFacade.getInstance(myField.getProject()).getResolveHelper(); for (UsageInfo info : usagesIn) { PsiElement element = info.getElement(); - if (element instanceof PsiExpression && isAccessedForWriting((PsiExpression)element)) { + if (element instanceof PsiExpression && (!myField.hasModifierProperty(PsiModifier.FINAL) || myInlineThisOnly) && isAccessedForWriting((PsiExpression)element)) { String message = RefactoringBundle.message("0.is.used.for.writing.in.1", RefactoringUIUtil.getDescription(myField, true), RefactoringUIUtil.getDescription(ConflictsUtil.getContainer(element), true)); conflicts.putValue(element, message); diff --git a/java/java-impl/src/com/intellij/refactoring/inline/InlineMethodProcessor.java b/java/java-impl/src/com/intellij/refactoring/inline/InlineMethodProcessor.java index c006b85ad128..596aa32d15dd 100644 --- a/java/java-impl/src/com/intellij/refactoring/inline/InlineMethodProcessor.java +++ b/java/java-impl/src/com/intellij/refactoring/inline/InlineMethodProcessor.java @@ -137,7 +137,7 @@ public class InlineMethodProcessor extends BaseRefactoringProcessor { usages.add(new UsageInfo(reference.getElement())); } - OverridingMethodsSearch.search(myMethod).forEach(method -> { + OverridingMethodsSearch.search(myMethod, false).forEach(method -> { if (AnnotationUtil.isAnnotated(method, Override.class.getName(), false)) { usages.add(new UsageInfo(method)); } @@ -363,8 +363,8 @@ public class InlineMethodProcessor extends BaseRefactoringProcessor { private static Map> getInaccessible(HashSet referencedElements, UsageInfo[] usages, PsiElement elementToInline) { - Map> result = new HashMap>(); - + final Map> result = new HashMap>(); + final PsiResolveHelper resolveHelper = JavaPsiFacade.getInstance(elementToInline.getProject()).getResolveHelper(); for (UsageInfo usage : usages) { final PsiElement usageElement = usage.getElement(); if (usageElement == null) continue; @@ -379,7 +379,10 @@ public class InlineMethodProcessor extends BaseRefactoringProcessor { if (PsiTreeUtil.isAncestor(elementToInline, member, false)) continue; if (elementToInline instanceof PsiClass && InheritanceUtil.isInheritorOrSelf((PsiClass)elementToInline, member.getContainingClass(), true)) continue; - if (!PsiUtil.isAccessible(usage.getProject(), member, usageElement, null)) { + PsiElement resolveScope = usageElement instanceof PsiReferenceExpression + ? ((PsiReferenceExpression)usageElement).advancedResolve(false).getCurrentFileResolveScope() + : null; + if (!resolveHelper.isAccessible(member, member.getModifierList(), usageElement, null, resolveScope)) { inaccessibleReferenced.add(member); } } diff --git a/java/java-impl/src/com/intellij/refactoring/inline/ReferencedElementsCollector.java b/java/java-impl/src/com/intellij/refactoring/inline/ReferencedElementsCollector.java index 0372f065c0cb..0f8ce87c5d04 100644 --- a/java/java-impl/src/com/intellij/refactoring/inline/ReferencedElementsCollector.java +++ b/java/java-impl/src/com/intellij/refactoring/inline/ReferencedElementsCollector.java @@ -35,6 +35,7 @@ public class ReferencedElementsCollector extends JavaRecursiveElementVisitor { if (psiElement instanceof PsiMember) { checkAddMember((PsiMember)psiElement); } + super.visitReferenceElement(reference); } protected void checkAddMember(@NotNull final PsiMember member) { diff --git a/java/java-impl/src/com/intellij/refactoring/introduceField/BaseExpressionToFieldHandler.java b/java/java-impl/src/com/intellij/refactoring/introduceField/BaseExpressionToFieldHandler.java index fce4add34e0f..018e61ae48c6 100644 --- a/java/java-impl/src/com/intellij/refactoring/introduceField/BaseExpressionToFieldHandler.java +++ b/java/java-impl/src/com/intellij/refactoring/introduceField/BaseExpressionToFieldHandler.java @@ -713,7 +713,7 @@ public abstract class BaseExpressionToFieldHandler extends IntroduceHandlerBase } final SmartTypePointer type = SmartTypePointerManager.getInstance(myProject).createSmartTypePointer(myType); - initializer = IntroduceVariableBase.replaceExplicitWithDiamondWhenApplicable(initializer, myType); + initializer = IntroduceVariableBase.simplifyVariableInitializer(initializer, myType); final PsiMethod enclosingConstructor = getEnclosingConstructor(myParentClass, myAnchorElement); PsiClass destClass = mySettings.getDestinationClass() == null ? myParentClass : mySettings.getDestinationClass(); diff --git a/java/java-impl/src/com/intellij/refactoring/introduceField/IntroduceConstantHandler.java b/java/java-impl/src/com/intellij/refactoring/introduceField/IntroduceConstantHandler.java index d084cb0ce339..aa2f8bd60c04 100644 --- a/java/java-impl/src/com/intellij/refactoring/introduceField/IntroduceConstantHandler.java +++ b/java/java-impl/src/com/intellij/refactoring/introduceField/IntroduceConstantHandler.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2014 JetBrains s.r.o. + * Copyright 2000-2016 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. @@ -228,7 +228,7 @@ public class IntroduceConstantHandler extends BaseExpressionToFieldHandler { } private static class IsStaticFinalInitializerExpression extends ClassMemberReferencesVisitor { - private PsiElement myElementReference = null; + private PsiElement myElementReference; private final PsiExpression myInitializer; public IsStaticFinalInitializerExpression(PsiClass aClass, PsiExpression initializer) { diff --git a/java/java-impl/src/com/intellij/refactoring/introduceParameter/EnclosingMethodSelectionDialog.java b/java/java-impl/src/com/intellij/refactoring/introduceParameter/EnclosingMethodSelectionDialog.java index 346b1571f690..3c92436fd9eb 100644 --- a/java/java-impl/src/com/intellij/refactoring/introduceParameter/EnclosingMethodSelectionDialog.java +++ b/java/java-impl/src/com/intellij/refactoring/introduceParameter/EnclosingMethodSelectionDialog.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2009 JetBrains s.r.o. + * Copyright 2000-2016 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. @@ -29,7 +29,6 @@ import com.intellij.openapi.ui.DialogWrapper; import com.intellij.psi.PsiMethod; import com.intellij.refactoring.RefactoringBundle; import com.intellij.refactoring.ui.MethodCellRenderer; -import com.intellij.ui.IdeBorderFactory; import com.intellij.ui.ScrollPaneFactory; import com.intellij.ui.components.JBList; import org.jetbrains.annotations.NotNull; @@ -41,7 +40,7 @@ import java.util.List; public class EnclosingMethodSelectionDialog extends DialogWrapper { private final List myEnclosingMethods; - private JList myEnclosingMethodsList = null; + private JList myEnclosingMethodsList; private final JCheckBox myCbReplaceInstanceOf = new JCheckBox(RefactoringBundle.message("use.interface.superclass.in.instanceof")); private static final String REFACTORING_NAME = RefactoringBundle.message("introduce.parameter.title"); diff --git a/java/java-impl/src/com/intellij/refactoring/introduceParameter/InplaceIntroduceParameterUI.java b/java/java-impl/src/com/intellij/refactoring/introduceParameter/InplaceIntroduceParameterUI.java index 1dd601d63801..ec5e04232ee2 100644 --- a/java/java-impl/src/com/intellij/refactoring/introduceParameter/InplaceIntroduceParameterUI.java +++ b/java/java-impl/src/com/intellij/refactoring/introduceParameter/InplaceIntroduceParameterUI.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2012 JetBrains s.r.o. + * Copyright 2000-2016 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. @@ -15,10 +15,12 @@ */ package com.intellij.refactoring.introduceParameter; -import com.intellij.ui.ListCellRendererWrapper; import com.intellij.openapi.project.Project; import com.intellij.openapi.ui.LabeledComponent; -import com.intellij.psi.*; +import com.intellij.psi.PsiExpression; +import com.intellij.psi.PsiLocalVariable; +import com.intellij.psi.PsiMethod; +import com.intellij.psi.PsiParameter; import com.intellij.psi.codeStyle.CodeStyleSettingsManager; import com.intellij.psi.util.PsiUtil; import com.intellij.refactoring.IntroduceParameterRefactoring; @@ -27,6 +29,7 @@ import com.intellij.refactoring.RefactoringBundle; import com.intellij.refactoring.introduce.inplace.KeyboardComboSwitcher; import com.intellij.refactoring.ui.TypeSelectorManager; import com.intellij.ui.IdeBorderFactory; +import com.intellij.ui.ListCellRendererWrapper; import com.intellij.util.ui.UIUtil; import gnu.trove.TIntArrayList; @@ -40,7 +43,7 @@ import java.awt.event.ItemListener; */ public abstract class InplaceIntroduceParameterUI extends IntroduceParameterSettingsUI { private JComboBox myReplaceFieldsCb; - private boolean myHasWriteAccess = false; + private boolean myHasWriteAccess; private final Project myProject; private final TypeSelectorManager myTypeSelectorManager; private final PsiExpression[] myOccurrences; diff --git a/java/java-impl/src/com/intellij/refactoring/introduceParameter/IntroduceParameterDialog.java b/java/java-impl/src/com/intellij/refactoring/introduceParameter/IntroduceParameterDialog.java index 51af3a7b7cf3..9850709ba39a 100644 --- a/java/java-impl/src/com/intellij/refactoring/introduceParameter/IntroduceParameterDialog.java +++ b/java/java-impl/src/com/intellij/refactoring/introduceParameter/IntroduceParameterDialog.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2009 JetBrains s.r.o. + * Copyright 2000-2016 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. @@ -60,7 +60,7 @@ public class IntroduceParameterDialog extends RefactoringDialog { private final boolean myMustBeFinal; private final PsiExpression myExpression; private final PsiLocalVariable myLocalVar; - protected JCheckBox myCbDeclareFinal = null; + protected JCheckBox myCbDeclareFinal; protected JCheckBox myCbCollapseToLambda; // private JComponent myParameterNameField = null; @@ -73,7 +73,7 @@ public class IntroduceParameterDialog extends RefactoringDialog { private NameSuggestionsField.DataChanged myParameterNameChangedListener; private final IntroduceParameterSettingsPanel myPanel; - private boolean myHasWriteAccess = false; + private boolean myHasWriteAccess; IntroduceParameterDialog(@NotNull Project project, @NotNull List classMembersList, diff --git a/java/java-impl/src/com/intellij/refactoring/introduceParameter/IntroduceParameterProcessor.java b/java/java-impl/src/com/intellij/refactoring/introduceParameter/IntroduceParameterProcessor.java index 8951fa5d86e2..6b2d3fa95559 100644 --- a/java/java-impl/src/com/intellij/refactoring/introduceParameter/IntroduceParameterProcessor.java +++ b/java/java-impl/src/com/intellij/refactoring/introduceParameter/IntroduceParameterProcessor.java @@ -304,7 +304,7 @@ public class IntroduceParameterProcessor extends BaseRefactoringProcessor implem } public static class AnySupers extends JavaRecursiveElementWalkingVisitor { - private boolean myResult = false; + private boolean myResult; @Override public void visitSuperExpression(PsiSuperExpression expression) { myResult = true; } @@ -319,7 +319,7 @@ public class IntroduceParameterProcessor extends BaseRefactoringProcessor implem } public class AnySameNameVariables extends JavaRecursiveElementWalkingVisitor { - private Pair conflict = null; + private Pair conflict; public Pair getConflict() { return conflict; diff --git a/java/java-impl/src/com/intellij/refactoring/introduceParameter/IntroduceParameterSettingsUI.java b/java/java-impl/src/com/intellij/refactoring/introduceParameter/IntroduceParameterSettingsUI.java index af4c559bbc80..3daccf8cfd94 100644 --- a/java/java-impl/src/com/intellij/refactoring/introduceParameter/IntroduceParameterSettingsUI.java +++ b/java/java-impl/src/com/intellij/refactoring/introduceParameter/IntroduceParameterSettingsUI.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2011 JetBrains s.r.o. + * Copyright 2000-2016 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. @@ -43,18 +43,18 @@ public abstract class IntroduceParameterSettingsUI { protected final boolean myIsInvokedOnDeclaration; protected final boolean myHasInitializer; - protected StateRestoringCheckBox myCbDeleteLocalVariable = null; - protected StateRestoringCheckBox myCbUseInitializer = null; - protected JRadioButton myReplaceFieldsWithGettersNoneRadio = null; - protected JRadioButton myReplaceFieldsWithGettersInaccessibleRadio = null; - protected JRadioButton myReplaceFieldsWithGettersAllRadio = null; + protected StateRestoringCheckBox myCbDeleteLocalVariable; + protected StateRestoringCheckBox myCbUseInitializer; + protected JRadioButton myReplaceFieldsWithGettersNoneRadio; + protected JRadioButton myReplaceFieldsWithGettersInaccessibleRadio; + protected JRadioButton myReplaceFieldsWithGettersAllRadio; protected final ButtonGroup myReplaceFieldsWithGettersButtonGroup = new ButtonGroup(); protected final PsiParameter[] myParametersToRemove; protected final boolean[] myParametersToRemoveChecked; protected final boolean myIsLocalVariable; - protected JCheckBox myCbReplaceAllOccurences = null; - protected JCheckBox myCbGenerateDelegate = null; + protected JCheckBox myCbReplaceAllOccurences; + protected JCheckBox myCbGenerateDelegate; public IntroduceParameterSettingsUI(PsiLocalVariable onLocalVariable, PsiExpression onExpression, 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 2fb56af33023..f1b352733fe4 100644 --- a/java/java-impl/src/com/intellij/refactoring/introduceVariable/IntroduceVariableBase.java +++ b/java/java-impl/src/com/intellij/refactoring/introduceVariable/IntroduceVariableBase.java @@ -881,13 +881,7 @@ public abstract class IntroduceVariableBase extends IntroduceHandlerBase { PsiExpression initializer = RefactoringUtil.unparenthesizeExpression(expr1); final SmartTypePointer selectedType = SmartTypePointerManager.getInstance(project).createSmartTypePointer( settings.getSelectedType()); - if (expr1 instanceof PsiNewExpression) { - final PsiNewExpression newExpression = (PsiNewExpression)expr1; - if (newExpression.getArrayInitializer() != null) { - initializer = newExpression.getArrayInitializer(); - } - initializer = replaceExplicitWithDiamondWhenApplicable(initializer, selectedType.getType()); - } + initializer = simplifyVariableInitializer(initializer, selectedType.getType()); PsiDeclarationStatement declaration = JavaPsiFacade.getInstance(project).getElementFactory() .createVariableDeclarationStatement(settings.getEnteredName(), selectedType.getType(), initializer, container); @@ -991,20 +985,32 @@ public abstract class IntroduceVariableBase extends IntroduceHandlerBase { return false; } - public static PsiExpression replaceExplicitWithDiamondWhenApplicable(final PsiExpression initializer, - final PsiType expectedType) { - if (initializer instanceof PsiNewExpression) { + public static PsiExpression simplifyVariableInitializer(final PsiExpression initializer, + final PsiType expectedType) { + + if (initializer instanceof PsiTypeCastExpression) { + PsiTypeElement castType = ((PsiTypeCastExpression)initializer).getCastType(); + if (castType != null && TypeConversionUtil.isAssignable(expectedType, castType.getType())) { + return ((PsiTypeCastExpression)initializer).getOperand(); + } + } + else if (initializer instanceof PsiNewExpression) { final PsiNewExpression newExpression = (PsiNewExpression)initializer; - final PsiExpression tryToDetectDiamondNewExpr = ((PsiVariable)JavaPsiFacade.getElementFactory(initializer.getProject()) - .createVariableDeclarationStatement("x", expectedType, initializer, initializer).getDeclaredElements()[0]) - .getInitializer(); - if (tryToDetectDiamondNewExpr instanceof PsiNewExpression && - PsiDiamondTypeUtil.canCollapseToDiamond((PsiNewExpression)tryToDetectDiamondNewExpr, - (PsiNewExpression)tryToDetectDiamondNewExpr, - expectedType)) { - final PsiElement paramList = PsiDiamondTypeUtil - .replaceExplicitWithDiamond(newExpression.getClassOrAnonymousClassReference().getParameterList()); - return PsiTreeUtil.getParentOfType(paramList, PsiNewExpression.class); + if (newExpression.getArrayInitializer() != null) { + return newExpression.getArrayInitializer(); + } + else { + final PsiExpression tryToDetectDiamondNewExpr = ((PsiVariable)JavaPsiFacade.getElementFactory(initializer.getProject()) + .createVariableDeclarationStatement("x", expectedType, initializer, initializer).getDeclaredElements()[0]) + .getInitializer(); + if (tryToDetectDiamondNewExpr instanceof PsiNewExpression && + PsiDiamondTypeUtil.canCollapseToDiamond((PsiNewExpression)tryToDetectDiamondNewExpr, + (PsiNewExpression)tryToDetectDiamondNewExpr, + expectedType)) { + final PsiElement paramList = PsiDiamondTypeUtil + .replaceExplicitWithDiamond(newExpression.getClassOrAnonymousClassReference().getParameterList()); + return PsiTreeUtil.getParentOfType(paramList, PsiNewExpression.class); + } } } return initializer; diff --git a/java/java-impl/src/com/intellij/refactoring/introduceVariable/IntroduceVariableDialog.java b/java/java-impl/src/com/intellij/refactoring/introduceVariable/IntroduceVariableDialog.java index 9523408a3a49..2175489557dd 100644 --- a/java/java-impl/src/com/intellij/refactoring/introduceVariable/IntroduceVariableDialog.java +++ b/java/java-impl/src/com/intellij/refactoring/introduceVariable/IntroduceVariableDialog.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2011 JetBrains s.r.o. + * Copyright 2000-2016 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. @@ -18,7 +18,6 @@ package com.intellij.refactoring.introduceVariable; import com.intellij.openapi.help.HelpManager; import com.intellij.openapi.project.Project; import com.intellij.openapi.ui.DialogWrapper; -import com.intellij.psi.JavaPsiFacade; import com.intellij.psi.PsiExpression; import com.intellij.psi.PsiNameHelper; import com.intellij.psi.PsiType; @@ -48,7 +47,7 @@ class IntroduceVariableDialog extends DialogWrapper implements IntroduceVariable private NameSuggestionsField myNameField; private JCheckBox myCbReplaceAll; - private StateRestoringCheckBox myCbReplaceWrite = null; + private StateRestoringCheckBox myCbReplaceWrite; private JCheckBox myCbFinal; private boolean myCbFinalState; private TypeSelector myTypeSelector; diff --git a/java/java-impl/src/com/intellij/refactoring/introduceVariable/IntroduceVariableSettings.java b/java/java-impl/src/com/intellij/refactoring/introduceVariable/IntroduceVariableSettings.java index d6042f399162..a6d564198ec9 100644 --- a/java/java-impl/src/com/intellij/refactoring/introduceVariable/IntroduceVariableSettings.java +++ b/java/java-impl/src/com/intellij/refactoring/introduceVariable/IntroduceVariableSettings.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2009 JetBrains s.r.o. + * Copyright 2000-2016 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. @@ -14,13 +14,6 @@ * limitations under the License. */ -/** - * Created by IntelliJ IDEA. - * User: dsl - * Date: Nov 15, 2002 - * Time: 4:12:48 PM - * To change this template use Options | File Templates. - */ package com.intellij.refactoring.introduceVariable; import com.intellij.psi.PsiType; diff --git a/java/java-impl/src/com/intellij/refactoring/introduceparameterobject/JavaIntroduceParameterObjectClassDescriptor.java b/java/java-impl/src/com/intellij/refactoring/introduceparameterobject/JavaIntroduceParameterObjectClassDescriptor.java index ef2387ea2f8f..069aa33ab90d 100644 --- a/java/java-impl/src/com/intellij/refactoring/introduceparameterobject/JavaIntroduceParameterObjectClassDescriptor.java +++ b/java/java-impl/src/com/intellij/refactoring/introduceparameterobject/JavaIntroduceParameterObjectClassDescriptor.java @@ -16,6 +16,7 @@ package com.intellij.refactoring.introduceparameterobject; import com.intellij.codeInsight.generation.GenerateMembersUtil; +import com.intellij.codeInsight.highlighting.ReadWriteAccessDetector; import com.intellij.ide.highlighter.JavaFileType; import com.intellij.ide.util.PackageUtil; import com.intellij.openapi.diagnostic.Logger; @@ -31,7 +32,6 @@ import com.intellij.psi.util.TypeConversionUtil; import com.intellij.refactoring.MoveDestination; import com.intellij.refactoring.changeSignature.ParameterInfoImpl; import com.intellij.refactoring.introduceParameterObject.IntroduceParameterObjectClassDescriptor; -import com.intellij.refactoring.introduceParameterObject.IntroduceParameterObjectDelegate; import com.intellij.util.IncorrectOperationException; import com.intellij.util.containers.HashMap; import org.jetbrains.annotations.NonNls; @@ -48,8 +48,6 @@ public class JavaIntroduceParameterObjectClassDescriptor extends IntroduceParame private final Map myExistingClassProperties = new HashMap<>(); private final MoveDestination myMoveDestination; - private PsiMethod myExistingClassCompatibleConstructor; - public JavaIntroduceParameterObjectClassDescriptor(String className, String packageName, MoveDestination moveDestination, @@ -76,7 +74,7 @@ public class JavaIntroduceParameterObjectClassDescriptor extends IntroduceParame } }; for (ParameterInfoImpl parameterInfo : paramsToMerge) { - parameterInfo.getTypeWrapper().getType(method, method.getManager()).accept(typeParametersVisitor); + parameterInfo.getTypeWrapper().getType(method).accept(typeParametersVisitor); } } @@ -110,27 +108,12 @@ public class JavaIntroduceParameterObjectClassDescriptor extends IntroduceParame return text; } - public PsiMethod getExistingClassCompatibleConstructor() { - return myExistingClassCompatibleConstructor; - } - - public void setExistingClassCompatibleConstructor(PsiMethod existingClassCompatibleConstructor) { - myExistingClassCompatibleConstructor = existingClassCompatibleConstructor; - } @Override public PsiClass getExistingClass() { return (PsiClass)super.getExistingClass(); } - @Override - public void setExistingClass(PsiElement existingClass) { - super.setExistingClass(existingClass); - if (isUseExistingClass()) { - setExistingClassCompatibleConstructor(existingClassIsCompatible((PsiClass)existingClass)); - } - } - public String getGetter(ParameterInfoImpl param) { final ParameterBean bean = getBean(param); return bean != null ? bean.getGetter() : null; @@ -142,14 +125,14 @@ public class JavaIntroduceParameterObjectClassDescriptor extends IntroduceParame } @Override - public String getSetterName(ParameterInfoImpl parameterInfo, PsiElement context) { + public String getSetterName(ParameterInfoImpl parameterInfo, @NotNull PsiElement context) { final ParameterBean bean = getBean(parameterInfo); @NonNls String setter = bean != null ? bean.getSetter() : null; if (setter == null) { setter = bean != null && bean.getField() != null ? GenerateMembersUtil.suggestSetterName(bean.getField()) : GenerateMembersUtil - .suggestSetterName(parameterInfo.getName(), parameterInfo.getTypeWrapper().getType(context, context.getManager()), + .suggestSetterName(parameterInfo.getName(), parameterInfo.getTypeWrapper().getType(context), context.getProject()); } @@ -157,24 +140,25 @@ public class JavaIntroduceParameterObjectClassDescriptor extends IntroduceParame } @Override - public String getGetterName(ParameterInfoImpl paramInfo, PsiElement context) { + public String getGetterName(ParameterInfoImpl paramInfo, @NotNull PsiElement context) { final ParameterBean bean = getBean(paramInfo); @NonNls String getter = bean != null ? bean.getGetter() : null; if (getter == null) { getter = bean != null && bean.getField() != null ? GenerateMembersUtil.suggestGetterName(bean.getField()) : GenerateMembersUtil - .suggestGetterName(paramInfo.getName(), paramInfo.getTypeWrapper().getType(context, context.getManager()), + .suggestGetterName(paramInfo.getName(), paramInfo.getTypeWrapper().getType(context), context.getProject()); } return getter; } @Override - public void initExistingClass(PsiMethod method) { + public PsiMethod findCompatibleConstructorInExistingClass(PsiMethod method) { final JavaPsiFacade psiFacade = JavaPsiFacade.getInstance(method.getProject()); final String qualifiedName = StringUtil.getQualifiedName(getPackageName(), getClassName()); final PsiClass existingClass = psiFacade.findClass(qualifiedName, method.getResolveScope()); setExistingClass(existingClass); + return findCompatibleConstructor(existingClass); } @Nullable @@ -188,25 +172,25 @@ public class JavaIntroduceParameterObjectClassDescriptor extends IntroduceParame } @Nullable - private PsiMethod existingClassIsCompatible(@NotNull PsiClass aClass) { + private PsiMethod findCompatibleConstructor(@NotNull PsiClass aClass) { ParameterInfoImpl[] paramsToMerge = getParamsToMerge(); if (paramsToMerge.length == 1) { final ParameterInfoImpl parameterInfo = paramsToMerge[0]; - final PsiType paramType = parameterInfo.getTypeWrapper().getType(aClass, aClass.getManager()); + final PsiType paramType = parameterInfo.getTypeWrapper().getType(aClass); if (TypeConversionUtil.isPrimitiveWrapper(aClass.getQualifiedName())) { ParameterBean bean = new ParameterBean(); bean.setField(aClass.findFieldByName("value", false)); bean.setGetter(paramType.getCanonicalText() + "Value"); myExistingClassProperties.put(parameterInfo, bean); for (PsiMethod constructor : aClass.getConstructors()) { - if (constructorIsCompatible(constructor, new ParameterInfoImpl[]{parameterInfo}, aClass)) return constructor; + if (isConstructorCompatible(constructor, new ParameterInfoImpl[]{parameterInfo}, aClass)) return constructor; } } } final PsiMethod[] constructors = aClass.getConstructors(); PsiMethod compatibleConstructor = null; for (PsiMethod constructor : constructors) { - if (constructorIsCompatible(constructor, paramsToMerge, aClass)) { + if (isConstructorCompatible(constructor, paramsToMerge, aClass)) { compatibleConstructor = constructor; break; } @@ -246,7 +230,7 @@ public class JavaIntroduceParameterObjectClassDescriptor extends IntroduceParame return compatibleConstructor; } - private boolean constructorIsCompatible(PsiMethod constructor, ParameterInfoImpl[] paramsToMerge, PsiElement context) { + private boolean isConstructorCompatible(PsiMethod constructor, ParameterInfoImpl[] paramsToMerge, PsiElement context) { final PsiParameterList parameterList = constructor.getParameterList(); final PsiParameter[] constructorParams = parameterList.getParameters(); return areTypesCompatible(paramsToMerge, constructorParams, context); @@ -257,8 +241,7 @@ public class JavaIntroduceParameterObjectClassDescriptor extends IntroduceParame return false; } for (int i = 0; i < actual.length; i++) { - if (!TypeConversionUtil.isAssignable(actual[i].getType(), - getParameterInfo(i).getTypeWrapper().getType(context, context.getManager()))) { + if (!TypeConversionUtil.isAssignable(actual[i].getType(), getParameterInfo(i).getTypeWrapper().getType(context))) { return false; } } @@ -272,7 +255,7 @@ public class JavaIntroduceParameterObjectClassDescriptor extends IntroduceParame } @Override - public PsiClass createClass(PsiMethod method, IntroduceParameterObjectDelegate.Accessor[] accessors) { + public PsiClass createClass(PsiMethod method, ReadWriteAccessDetector.Access[] accessors) { if (isUseExistingClass()) { return getExistingClass(); } @@ -287,10 +270,10 @@ public class JavaIntroduceParameterObjectClassDescriptor extends IntroduceParame final ParameterInfoImpl[] parameterInfos = getParamsToMerge(); for (int i = 0; i < parameterInfos.length; i++) { PsiParameter parameter = parameters[parameterInfos[i].getOldIndex()]; - final boolean setterRequired = accessors[i] == IntroduceParameterObjectDelegate.Accessor.Setter; + final boolean setterRequired = accessors[i] == ReadWriteAccessDetector.Access.Write; final String newName = parameterInfos[i].getName(); beanClassBuilder - .addField(parameter, newName, parameterInfos[i].getTypeWrapper().getType(method, method.getManager()), setterRequired); + .addField(parameter, newName, parameterInfos[i].getTypeWrapper().getType(method), setterRequired); } final String classString = beanClassBuilder.buildBeanClass(); @@ -341,7 +324,7 @@ public class JavaIntroduceParameterObjectClassDescriptor extends IntroduceParame private final PsiParameter param; - private PsiField fieldAssigned = null; + private PsiField fieldAssigned; ParamAssignmentFinder(PsiParameter param) { this.param = param; diff --git a/java/java-impl/src/com/intellij/refactoring/introduceparameterobject/JavaIntroduceParameterObjectDelegate.java b/java/java-impl/src/com/intellij/refactoring/introduceparameterobject/JavaIntroduceParameterObjectDelegate.java index 09ce3b828eaf..064a6c0092f6 100644 --- a/java/java-impl/src/com/intellij/refactoring/introduceparameterobject/JavaIntroduceParameterObjectDelegate.java +++ b/java/java-impl/src/com/intellij/refactoring/introduceparameterobject/JavaIntroduceParameterObjectDelegate.java @@ -15,6 +15,7 @@ */ package com.intellij.refactoring.introduceparameterobject; +import com.intellij.codeInsight.highlighting.ReadWriteAccessDetector; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.text.StringUtil; import com.intellij.openapi.vfs.VirtualFile; @@ -36,7 +37,6 @@ import com.intellij.refactoring.introduceParameterObject.IntroduceParameterObjec import com.intellij.refactoring.introduceparameterobject.usageInfo.*; import com.intellij.refactoring.util.CanonicalTypes; import com.intellij.refactoring.util.FixableUsageInfo; -import com.intellij.refactoring.util.RefactoringUtil; import com.intellij.usageView.UsageInfo; import com.intellij.util.IncorrectOperationException; import com.intellij.util.VisibilityUtil; @@ -182,47 +182,51 @@ public class JavaIntroduceParameterObjectDelegate } @Override - public Accessor collectInternalUsages(Collection usages, - PsiMethod overridingMethod, - IntroduceParameterObjectClassDescriptor classDescriptor, - P1 parameterInfo, - String mergedParamName) { + public ReadWriteAccessDetector.Access collectInternalUsages(Collection usages, + PsiMethod overridingMethod, + IntroduceParameterObjectClassDescriptor classDescriptor, + P1 parameterInfo, + String mergedParamName) { final LocalSearchScope localSearchScope = new LocalSearchScope(overridingMethod); final PsiParameter[] params = overridingMethod.getParameterList().getParameters(); final PsiParameter parameter = params[parameterInfo.getOldIndex()]; + final ReadWriteAccessDetector detector = ReadWriteAccessDetector.findDetector(parameter); + assert detector != null; final String setter = classDescriptor.getSetterName(parameterInfo, overridingMethod); final String getter = classDescriptor.getGetterName(parameterInfo, overridingMethod); - final Accessor[] accessor = new Accessor[]{null}; + final ReadWriteAccessDetector.Access[] accessor = new ReadWriteAccessDetector.Access[]{null}; ReferencesSearch.search(parameter, localSearchScope).forEach(reference -> { - final PsiElement refElement = reference.getElement(); - if (refElement instanceof PsiReferenceExpression) { - final PsiReferenceExpression paramUsage = (PsiReferenceExpression)refElement; - if (RefactoringUtil.isPlusPlusOrMinusMinus(paramUsage.getParent())) { - accessor[0] = Accessor.Setter; - usages.add(new ReplaceParameterIncrementDecrement(paramUsage, mergedParamName, setter, getter)); - } - else if (RefactoringUtil.isAssignmentLHS(paramUsage)) { - accessor[0] = Accessor.Setter; - usages.add(new ReplaceParameterAssignmentWithCall(paramUsage, mergedParamName, setter, getter)); - } - else { - if (accessor[0] == null) { - accessor[0] = Accessor.Getter; - } - usages.add(new ReplaceParameterReferenceWithCall(paramUsage, mergedParamName, getter)); - } - } - return true; - } + final PsiElement refElement = reference.getElement(); + if (refElement instanceof PsiReferenceExpression) { + final PsiReferenceExpression paramUsage = (PsiReferenceExpression)refElement; + final ReadWriteAccessDetector.Access access = detector.getExpressionAccess(refElement); + if (access == ReadWriteAccessDetector.Access.Read) { + usages.add(new ReplaceParameterReferenceWithCall(paramUsage, mergedParamName, getter)); + if (accessor[0] == null) { + accessor[0] = ReadWriteAccessDetector.Access.Read; + } + } + else { + if (access == ReadWriteAccessDetector.Access.ReadWrite) { + usages.add(new ReplaceParameterIncrementDecrement(paramUsage, mergedParamName, setter, getter)); + } + else { + usages.add(new ReplaceParameterAssignmentWithCall(paramUsage, mergedParamName, setter, getter)); + } + accessor[0] = ReadWriteAccessDetector.Access.Write; + } + } + return true; + } ); return accessor[0]; } @Override - public void collectAccessibilityUsages(Collection usages, - PsiMethod method, - JavaIntroduceParameterObjectClassDescriptor descriptor, - Accessor[] accessors) { + public void collectUsagesToGenerateMissedFieldAccessors(Collection usages, + PsiMethod method, + JavaIntroduceParameterObjectClassDescriptor descriptor, + ReadWriteAccessDetector.Access[] accessors) { final ParameterInfoImpl[] parameterInfos = descriptor.getParamsToMerge(); final PsiClass existingClass = descriptor.getExistingClass(); final boolean useExisting = descriptor.isGenerateAccessors() || !(descriptor.isUseExistingClass() && existingClass != null); @@ -230,7 +234,7 @@ public class JavaIntroduceParameterObjectDelegate final PsiParameter[] psiParameters = method.getParameterList().getParameters(); for (int i = 0; i < parameterInfos.length; i++) { int oldParamIdx = parameterInfos[i].getOldIndex(); - final IntroduceParameterObjectDelegate.Accessor accessor = accessors[i]; + final ReadWriteAccessDetector.Access accessor = accessors[i]; if (accessor != null) { final ParameterInfoImpl parameterInfo = parameterInfos[i]; final PsiParameter parameter = psiParameters[oldParamIdx]; @@ -240,20 +244,27 @@ public class JavaIntroduceParameterObjectDelegate usages.add(new AppendAccessorsUsageInfo(parameter, existingClass, useExisting, parameterInfo, true, field)); } - if (accessor == IntroduceParameterObjectDelegate.Accessor.Setter && descriptor.getSetter(parameterInfo) == null) { + if (accessor == ReadWriteAccessDetector.Access.Write && descriptor.getSetter(parameterInfo) == null) { usages.add(new AppendAccessorsUsageInfo(parameter, existingClass, useExisting, parameterInfo, false, field)); } } } + } + @Override + public void collectAdditionalFixes(Collection usages, + final PsiMethod method, + final JavaIntroduceParameterObjectClassDescriptor descriptor) { + + if (method.getDocComment() != null) { + usages.add(new ConstructorJavadocUsageInfo(method, descriptor)); + } final String newVisibility = descriptor.getNewVisibility(); if (newVisibility != null) { - usages.add(new BeanClassVisibilityUsageInfo(existingClass, usages.toArray(UsageInfo.EMPTY_ARRAY), newVisibility, descriptor)); + usages.add(new BeanClassVisibilityUsageInfo(descriptor.getExistingClass(), usages.toArray(UsageInfo.EMPTY_ARRAY), newVisibility, descriptor)); } - usages.add(new ConstructorJavadocUsageInfo(method, descriptor)); - if (!descriptor.isUseExistingClass()) { usages.add(new FixableUsageInfo(method) { @Override diff --git a/java/java-impl/src/com/intellij/refactoring/introduceparameterobject/ParameterObjectBuilder.java b/java/java-impl/src/com/intellij/refactoring/introduceparameterobject/ParameterObjectBuilder.java index ac91a848aae8..13510f2de268 100644 --- a/java/java-impl/src/com/intellij/refactoring/introduceparameterobject/ParameterObjectBuilder.java +++ b/java/java-impl/src/com/intellij/refactoring/introduceparameterobject/ParameterObjectBuilder.java @@ -30,8 +30,8 @@ import java.util.Iterator; import java.util.List; class ParameterObjectBuilder { - private String className = null; - private String packageName = null; + private String className; + private String packageName; private final List fields = new ArrayList(5); private final List typeParams = new ArrayList(); private Project myProject; diff --git a/java/java-impl/src/com/intellij/refactoring/memberPullUp/JavaPullUpHelper.java b/java/java-impl/src/com/intellij/refactoring/memberPullUp/JavaPullUpHelper.java index d2524b4a03a3..b660567f2c55 100644 --- a/java/java-impl/src/com/intellij/refactoring/memberPullUp/JavaPullUpHelper.java +++ b/java/java-impl/src/com/intellij/refactoring/memberPullUp/JavaPullUpHelper.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2015 JetBrains s.r.o. + * Copyright 2000-2016 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. @@ -60,7 +60,7 @@ public class JavaPullUpHelper implements PullUpHelper { private final PsiClass myTargetSuperClass; private final boolean myIsTargetInterface; private final DocCommentPolicy myJavaDocPolicy; - private Set myMembersAfterMove = null; + private Set myMembersAfterMove; private final Set myMembersToMove; private final Project myProject; diff --git a/java/java-impl/src/com/intellij/refactoring/memberPullUp/PullUpProcessor.java b/java/java-impl/src/com/intellij/refactoring/memberPullUp/PullUpProcessor.java index 770dd19073aa..cc4faae65b6f 100644 --- a/java/java-impl/src/com/intellij/refactoring/memberPullUp/PullUpProcessor.java +++ b/java/java-impl/src/com/intellij/refactoring/memberPullUp/PullUpProcessor.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2015 JetBrains s.r.o. + * Copyright 2000-2016 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. @@ -66,8 +66,8 @@ public class PullUpProcessor extends BaseRefactoringProcessor implements PullUpD private final PsiClass myTargetSuperClass; private final MemberInfo[] myMembersToMove; private final DocCommentPolicy myJavaDocPolicy; - private Set myMembersAfterMove = null; - private Set myMovedMembers = null; + private Set myMembersAfterMove; + private Set myMovedMembers; private final Map> myProcessors = ContainerUtil.newHashMap(); public PullUpProcessor(PsiClass sourceClass, PsiClass targetSuperClass, MemberInfo[] membersToMove, DocCommentPolicy javaDocPolicy) { diff --git a/java/java-impl/src/com/intellij/refactoring/memberPushDown/JavaPushDownDelegate.java b/java/java-impl/src/com/intellij/refactoring/memberPushDown/JavaPushDownDelegate.java index a2a76dfc7d73..c344f6df60a1 100644 --- a/java/java-impl/src/com/intellij/refactoring/memberPushDown/JavaPushDownDelegate.java +++ b/java/java-impl/src/com/intellij/refactoring/memberPushDown/JavaPushDownDelegate.java @@ -45,6 +45,7 @@ import com.intellij.util.IncorrectOperationException; import com.intellij.util.containers.HashSet; import com.intellij.util.containers.MultiMap; import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; import java.util.*; @@ -90,11 +91,21 @@ public class JavaPushDownDelegate extends PushDownDelegate pushDownData, - MultiMap conflicts) { + MultiMap conflicts, + NewSubClassData subClassData) { List toMove = pushDownData.getMembersToMove(); - new PushDownConflicts((PsiClass)pushDownData.getSourceClass(), toMove.toArray(new MemberInfo[0]), conflicts).checkTargetClassConflicts(targetClass, targetClass); + PsiElement context = targetClass; + if (context == null) { + assert subClassData != null; + Object newClassContext = subClassData.getContext(); + if (newClassContext instanceof PsiElement) { + context = (PsiElement)newClassContext; + } + } + new PushDownConflicts((PsiClass)pushDownData.getSourceClass(), toMove.toArray(new MemberInfo[0]), conflicts) + .checkTargetClassConflicts(targetClass, context); } @Override diff --git a/java/java-impl/src/com/intellij/refactoring/migration/MigrationMapSet.java b/java/java-impl/src/com/intellij/refactoring/migration/MigrationMapSet.java index 4c1a640a0e92..1bcc190b45de 100644 --- a/java/java-impl/src/com/intellij/refactoring/migration/MigrationMapSet.java +++ b/java/java-impl/src/com/intellij/refactoring/migration/MigrationMapSet.java @@ -1,6 +1,6 @@ /* - * Copyright 2000-2015 JetBrains s.r.o. + * Copyright 2000-2016 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. @@ -40,7 +40,7 @@ import java.util.Iterator; public class MigrationMapSet { private static final Logger LOG = Logger.getInstance("#com.intellij.refactoring.migration.MigrationMapSet"); - private ArrayList myMaps = null; + private ArrayList myMaps; @NonNls private static final String MIGRATION_MAP = "migrationMap"; @NonNls private static final String ENTRY = "entry"; @NonNls private static final String NAME = "name"; diff --git a/java/java-impl/src/com/intellij/refactoring/migration/MigrationUsagesViewDescriptor.java b/java/java-impl/src/com/intellij/refactoring/migration/MigrationUsagesViewDescriptor.java index 6a6f1d816e45..7e71544ac881 100644 --- a/java/java-impl/src/com/intellij/refactoring/migration/MigrationUsagesViewDescriptor.java +++ b/java/java-impl/src/com/intellij/refactoring/migration/MigrationUsagesViewDescriptor.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2009 JetBrains s.r.o. + * Copyright 2000-2016 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. @@ -14,16 +14,12 @@ * limitations under the License. */ -/** - * created at Nov 24, 2001 - * @author Jeka - */ package com.intellij.refactoring.migration; import com.intellij.psi.PsiElement; import com.intellij.refactoring.RefactoringBundle; -import com.intellij.usageView.UsageViewDescriptor; import com.intellij.usageView.UsageViewBundle; +import com.intellij.usageView.UsageViewDescriptor; import org.jetbrains.annotations.NotNull; class MigrationUsagesViewDescriptor implements UsageViewDescriptor { diff --git a/java/java-impl/src/com/intellij/refactoring/move/moveClassesOrPackages/AutocreatingSingleSourceRootMoveDestination.java b/java/java-impl/src/com/intellij/refactoring/move/moveClassesOrPackages/AutocreatingSingleSourceRootMoveDestination.java index ce19d6bacaa5..2ad63ce6195f 100644 --- a/java/java-impl/src/com/intellij/refactoring/move/moveClassesOrPackages/AutocreatingSingleSourceRootMoveDestination.java +++ b/java/java-impl/src/com/intellij/refactoring/move/moveClassesOrPackages/AutocreatingSingleSourceRootMoveDestination.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2009 JetBrains s.r.o. + * Copyright 2000-2016 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. @@ -97,7 +97,7 @@ public class AutocreatingSingleSourceRootMoveDestination extends AutocreatingMov return true; } - PsiDirectory myTargetDirectory = null; + PsiDirectory myTargetDirectory; private PsiDirectory getDirectory() throws IncorrectOperationException { if (myTargetDirectory == null) { myTargetDirectory = RefactoringUtil.createPackageDirectoryInSourceRoot(myPackage, mySourceRoot); diff --git a/java/java-impl/src/com/intellij/refactoring/move/moveClassesOrPackages/MoveClassesOrPackagesImpl.java b/java/java-impl/src/com/intellij/refactoring/move/moveClassesOrPackages/MoveClassesOrPackagesImpl.java index 380cfa3596a4..b4fc0a915bb1 100644 --- a/java/java-impl/src/com/intellij/refactoring/move/moveClassesOrPackages/MoveClassesOrPackagesImpl.java +++ b/java/java-impl/src/com/intellij/refactoring/move/moveClassesOrPackages/MoveClassesOrPackagesImpl.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2014 JetBrains s.r.o. + * Copyright 2000-2016 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. @@ -14,10 +14,6 @@ * limitations under the License. */ -/** - * created at Nov 27, 2001 - * @author Jeka - */ package com.intellij.refactoring.move.moveClassesOrPackages; import com.intellij.history.LocalHistory; diff --git a/java/java-impl/src/com/intellij/refactoring/move/moveInner/MoveInnerDialog.java b/java/java-impl/src/com/intellij/refactoring/move/moveInner/MoveInnerDialog.java index 305c32752abd..1e41e7188ba3 100644 --- a/java/java-impl/src/com/intellij/refactoring/move/moveInner/MoveInnerDialog.java +++ b/java/java-impl/src/com/intellij/refactoring/move/moveInner/MoveInnerDialog.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2012 JetBrains s.r.o. + * Copyright 2000-2016 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. @@ -14,10 +14,6 @@ * limitations under the License. */ -/** - * created at Sep 24, 2001 - * @author Jeka - */ package com.intellij.refactoring.move.moveInner; import com.intellij.openapi.application.ApplicationManager; diff --git a/java/java-impl/src/com/intellij/refactoring/move/moveInner/MoveInnerImpl.java b/java/java-impl/src/com/intellij/refactoring/move/moveInner/MoveInnerImpl.java index 9b8fc36fbd7f..3eb40a600c9e 100644 --- a/java/java-impl/src/com/intellij/refactoring/move/moveInner/MoveInnerImpl.java +++ b/java/java-impl/src/com/intellij/refactoring/move/moveInner/MoveInnerImpl.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2014 JetBrains s.r.o. + * Copyright 2000-2016 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. @@ -14,10 +14,6 @@ * limitations under the License. */ -/** - * created at Nov 12, 2001 - * @author Jeka - */ package com.intellij.refactoring.move.moveInner; import com.intellij.ide.util.PackageChooserDialog; diff --git a/java/java-impl/src/com/intellij/refactoring/move/moveInner/MoveInnerViewDescriptor.java b/java/java-impl/src/com/intellij/refactoring/move/moveInner/MoveInnerViewDescriptor.java index 04e2400467aa..e90ef34878c0 100644 --- a/java/java-impl/src/com/intellij/refactoring/move/moveInner/MoveInnerViewDescriptor.java +++ b/java/java-impl/src/com/intellij/refactoring/move/moveInner/MoveInnerViewDescriptor.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2009 JetBrains s.r.o. + * Copyright 2000-2016 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. @@ -14,10 +14,6 @@ * limitations under the License. */ -/** - * created at Sep 11, 2001 - * @author Jeka - */ package com.intellij.refactoring.move.moveInner; import com.intellij.psi.PsiClass; diff --git a/java/java-impl/src/com/intellij/refactoring/move/moveMembers/MoveMembersDialog.java b/java/java-impl/src/com/intellij/refactoring/move/moveMembers/MoveMembersDialog.java index f5eb13ce7376..261a907a6606 100644 --- a/java/java-impl/src/com/intellij/refactoring/move/moveMembers/MoveMembersDialog.java +++ b/java/java-impl/src/com/intellij/refactoring/move/moveMembers/MoveMembersDialog.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2013 JetBrains s.r.o. + * Copyright 2000-2016 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. @@ -15,7 +15,10 @@ */ package com.intellij.refactoring.move.moveMembers; -import com.intellij.ide.util.*; +import com.intellij.ide.util.ClassFilter; +import com.intellij.ide.util.PackageUtil; +import com.intellij.ide.util.TreeClassChooser; +import com.intellij.ide.util.TreeClassChooserFactory; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.command.CommandProcessor; import com.intellij.openapi.editor.event.DocumentAdapter; @@ -39,7 +42,6 @@ import com.intellij.refactoring.move.MoveDialogBase; import com.intellij.refactoring.ui.JavaVisibilityPanel; import com.intellij.refactoring.ui.MemberSelectionPanel; import com.intellij.refactoring.ui.MemberSelectionTable; -import com.intellij.refactoring.ui.RefactoringDialog; import com.intellij.refactoring.util.CommonRefactoringUtil; import com.intellij.refactoring.util.classMembers.MemberInfo; import com.intellij.refactoring.util.classMembers.UsesAndInterfacesDependencyMemberInfoModel; @@ -407,7 +409,7 @@ public class MoveMembersDialog extends MoveDialogBase implements MoveMembersOpti } private class MyMemberInfoModel extends UsesAndInterfacesDependencyMemberInfoModel { - PsiClass myTargetClass = null; + PsiClass myTargetClass; public MyMemberInfoModel() { super(mySourceClass, null, false, DEFAULT_CONTAINMENT_VERIFIER); } diff --git a/java/java-impl/src/com/intellij/refactoring/move/moveMembers/MoveMembersImpl.java b/java/java-impl/src/com/intellij/refactoring/move/moveMembers/MoveMembersImpl.java index 07b76fd13fb9..4c783a4f7fff 100644 --- a/java/java-impl/src/com/intellij/refactoring/move/moveMembers/MoveMembersImpl.java +++ b/java/java-impl/src/com/intellij/refactoring/move/moveMembers/MoveMembersImpl.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2009 JetBrains s.r.o. + * Copyright 2000-2016 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. @@ -14,10 +14,6 @@ * limitations under the License. */ -/** - * created at Nov 21, 2001 - * @author Jeka - */ package com.intellij.refactoring.move.moveMembers; import com.intellij.openapi.project.Project; diff --git a/java/java-impl/src/com/intellij/refactoring/psi/ArrayIterator.java b/java/java-impl/src/com/intellij/refactoring/psi/ArrayIterator.java index 1fd8875f475f..3d492299baf6 100644 --- a/java/java-impl/src/com/intellij/refactoring/psi/ArrayIterator.java +++ b/java/java-impl/src/com/intellij/refactoring/psi/ArrayIterator.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2009 JetBrains s.r.o. + * Copyright 2000-2016 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. @@ -20,7 +20,7 @@ import java.util.NoSuchElementException; class ArrayIterator implements Iterator{ private final T[] contents; - private int currentIndex = 0; + private int currentIndex; private final Object lock = new Object(); ArrayIterator(T[] contents){ diff --git a/java/java-impl/src/com/intellij/refactoring/rename/naming/AutomaticUsageRenamer.java b/java/java-impl/src/com/intellij/refactoring/rename/naming/AutomaticUsageRenamer.java index ce258c3cd013..009230acd93b 100644 --- a/java/java-impl/src/com/intellij/refactoring/rename/naming/AutomaticUsageRenamer.java +++ b/java/java-impl/src/com/intellij/refactoring/rename/naming/AutomaticUsageRenamer.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2009 JetBrains s.r.o. + * Copyright 2000-2016 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. @@ -88,10 +88,10 @@ public abstract class AutomaticUsageRenamer { return myElements; } - @Nullable /** * Element source, path. For example, package. Taken into account while sorting. */ + @Nullable public String getSourceName(T element) { return null; } diff --git a/java/java-impl/src/com/intellij/refactoring/turnRefsToSuper/TurnRefsToSuperDialog.java b/java/java-impl/src/com/intellij/refactoring/turnRefsToSuper/TurnRefsToSuperDialog.java index e1946746fae1..b3afdb12ab7f 100644 --- a/java/java-impl/src/com/intellij/refactoring/turnRefsToSuper/TurnRefsToSuperDialog.java +++ b/java/java-impl/src/com/intellij/refactoring/turnRefsToSuper/TurnRefsToSuperDialog.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2011 JetBrains s.r.o. + * Copyright 2000-2016 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. @@ -42,7 +42,7 @@ public class TurnRefsToSuperDialog extends RefactoringDialog { @NotNull private final PsiClass mySubClass; private final List mySuperClasses; - private JList mySuperClassesList = null; + private JList mySuperClassesList; private final JCheckBox myCbReplaceInstanceOf = new JCheckBox(); TurnRefsToSuperDialog(Project project, @NotNull PsiClass subClass, List superClasses) { diff --git a/java/java-impl/src/com/intellij/refactoring/turnRefsToSuper/TurnRefsToSuperHandler.java b/java/java-impl/src/com/intellij/refactoring/turnRefsToSuper/TurnRefsToSuperHandler.java index 1d546d6280d8..d1678668e745 100644 --- a/java/java-impl/src/com/intellij/refactoring/turnRefsToSuper/TurnRefsToSuperHandler.java +++ b/java/java-impl/src/com/intellij/refactoring/turnRefsToSuper/TurnRefsToSuperHandler.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2009 JetBrains s.r.o. + * Copyright 2000-2016 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. @@ -14,15 +14,10 @@ * limitations under the License. */ -/** - * created at Oct 25, 2001 - * @author Jeka - */ package com.intellij.refactoring.turnRefsToSuper; import com.intellij.openapi.actionSystem.CommonDataKeys; import com.intellij.openapi.actionSystem.DataContext; -import com.intellij.openapi.actionSystem.PlatformDataKeys; import com.intellij.openapi.editor.Editor; import com.intellij.openapi.editor.ScrollType; import com.intellij.openapi.project.Project; diff --git a/java/java-impl/src/com/intellij/refactoring/typeCook/deductive/PsiTypeVariableFactory.java b/java/java-impl/src/com/intellij/refactoring/typeCook/deductive/PsiTypeVariableFactory.java index 95535071b50e..a09e0ec1fa19 100644 --- a/java/java-impl/src/com/intellij/refactoring/typeCook/deductive/PsiTypeVariableFactory.java +++ b/java/java-impl/src/com/intellij/refactoring/typeCook/deductive/PsiTypeVariableFactory.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2014 JetBrains s.r.o. + * Copyright 2000-2016 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. @@ -27,7 +27,7 @@ import java.util.*; * @author db */ public class PsiTypeVariableFactory { - private int myCurrent = 0; + private int myCurrent; private final List> myClusters = new LinkedList>(); private final Map> myVarCluster = new HashMap>(); diff --git a/java/java-impl/src/com/intellij/refactoring/typeCook/deductive/resolver/BindingFactory.java b/java/java-impl/src/com/intellij/refactoring/typeCook/deductive/resolver/BindingFactory.java index 14b9a1715050..3e0083e58467 100644 --- a/java/java-impl/src/com/intellij/refactoring/typeCook/deductive/resolver/BindingFactory.java +++ b/java/java-impl/src/com/intellij/refactoring/typeCook/deductive/resolver/BindingFactory.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2014 JetBrains s.r.o. + * Copyright 2000-2016 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. @@ -481,7 +481,7 @@ public class BindingFactory { if (type != null) { class Verifier extends PsiExtendedTypeVisitor { - boolean myFlag = false; + boolean myFlag; @Override public Void visitTypeVariable(final PsiTypeVariable var) { if (var.getIndex() == index) { @@ -565,7 +565,7 @@ public class BindingFactory { public int getWidth() { class MyProcecure implements TObjectProcedure { - int width = 0; + int width; public boolean execute(PsiType type) { if (substitute(type) != null) width++; return true; diff --git a/java/java-impl/src/com/intellij/refactoring/typeCook/deductive/resolver/ResolverTree.java b/java/java-impl/src/com/intellij/refactoring/typeCook/deductive/resolver/ResolverTree.java index a58e0561c449..00ec0fd5cc4b 100644 --- a/java/java-impl/src/com/intellij/refactoring/typeCook/deductive/resolver/ResolverTree.java +++ b/java/java-impl/src/com/intellij/refactoring/typeCook/deductive/resolver/ResolverTree.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2014 JetBrains s.r.o. + * Copyright 2000-2016 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. @@ -50,7 +50,7 @@ public class ResolverTree { private final Project myProject; private final TObjectIntHashMap myBindingDegree; //How many times this type variable is bound in the system private final Settings mySettings; - private boolean mySolutionFound = false; + private boolean mySolutionFound; private Set myConstraints; @@ -244,7 +244,7 @@ public class ResolverTree { final Map index = new HashMap(); sccs.forEach(new TIntProcedure() { - int myTNumber = 0; + int myTNumber; @Override public boolean execute(int size) { diff --git a/java/java-impl/src/com/intellij/refactoring/typeMigration/TypeMigrationLabeler.java b/java/java-impl/src/com/intellij/refactoring/typeMigration/TypeMigrationLabeler.java index 7d00278f324d..f93cfcb0e6bc 100644 --- a/java/java-impl/src/com/intellij/refactoring/typeMigration/TypeMigrationLabeler.java +++ b/java/java-impl/src/com/intellij/refactoring/typeMigration/TypeMigrationLabeler.java @@ -77,7 +77,7 @@ public class TypeMigrationLabeler { private final LinkedHashMap myNewExpressionTypeChange; private final LinkedHashMap myClassTypeArgumentsChange; - private TypeMigrationUsageInfo[] myMigratedUsages = null; + private TypeMigrationUsageInfo[] myMigratedUsages; private TypeMigrationUsageInfo myCurrentRoot; private final Map>> myRootsTree = diff --git a/java/java-impl/src/com/intellij/refactoring/ui/YesNoPreviewUsagesDialog.java b/java/java-impl/src/com/intellij/refactoring/ui/YesNoPreviewUsagesDialog.java index 7f82cda4a051..5603e277ce36 100644 --- a/java/java-impl/src/com/intellij/refactoring/ui/YesNoPreviewUsagesDialog.java +++ b/java/java-impl/src/com/intellij/refactoring/ui/YesNoPreviewUsagesDialog.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2009 JetBrains s.r.o. + * Copyright 2000-2016 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. @@ -14,17 +14,13 @@ * limitations under the License. */ -/** - * created at Oct 8, 2001 - * @author Jeka - */ package com.intellij.refactoring.ui; import com.intellij.openapi.help.HelpManager; import com.intellij.openapi.project.Project; import com.intellij.openapi.ui.DialogWrapper; -import com.intellij.openapi.ui.MultiLineLabelUI; import com.intellij.openapi.ui.Messages; +import com.intellij.openapi.ui.MultiLineLabelUI; import com.intellij.refactoring.RefactoringBundle; import org.jetbrains.annotations.NotNull; diff --git a/java/java-impl/src/com/intellij/refactoring/util/ConflictsUtil.java b/java/java-impl/src/com/intellij/refactoring/util/ConflictsUtil.java index 19d1eb9bfa08..f475a46a64ec 100644 --- a/java/java-impl/src/com/intellij/refactoring/util/ConflictsUtil.java +++ b/java/java-impl/src/com/intellij/refactoring/util/ConflictsUtil.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2009 JetBrains s.r.o. + * Copyright 2000-2016 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. @@ -14,10 +14,6 @@ * limitations under the License. */ -/** - * created at Oct 8, 2001 - * @author Jeka - */ package com.intellij.refactoring.util; import com.intellij.lang.findUsages.DescriptiveNameUtil; 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 d37425b05967..0b1f79652c2a 100644 --- a/java/java-impl/src/com/intellij/refactoring/util/RefactoringUtil.java +++ b/java/java-impl/src/com/intellij/refactoring/util/RefactoringUtil.java @@ -330,7 +330,7 @@ public class RefactoringUtil { } public static PsiMethod getEnclosingMethod(PsiElement element) { - final PsiElement container = PsiTreeUtil.getParentOfType(element, PsiMethod.class, PsiClass.class); + final PsiElement container = PsiTreeUtil.getParentOfType(element, PsiMethod.class, PsiClass.class, PsiLambdaExpression.class); return container instanceof PsiMethod ? (PsiMethod)container : null; } diff --git a/java/java-impl/src/com/intellij/refactoring/util/classMembers/ElementNeedsThis.java b/java/java-impl/src/com/intellij/refactoring/util/classMembers/ElementNeedsThis.java index 8bcacc8333e9..3f3c7e7479c4 100644 --- a/java/java-impl/src/com/intellij/refactoring/util/classMembers/ElementNeedsThis.java +++ b/java/java-impl/src/com/intellij/refactoring/util/classMembers/ElementNeedsThis.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2009 JetBrains s.r.o. + * Copyright 2000-2016 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. @@ -22,7 +22,7 @@ import com.intellij.psi.util.PsiUtil; * @author dsl */ public class ElementNeedsThis extends ClassThisReferencesVisitor { - private boolean myResult = false; + private boolean myResult; private final PsiElement myMember; public ElementNeedsThis(PsiClass aClass, PsiElement member) { diff --git a/java/java-impl/src/com/intellij/refactoring/util/classMembers/InterfaceMemberDependencyGraph.java b/java/java-impl/src/com/intellij/refactoring/util/classMembers/InterfaceMemberDependencyGraph.java index d04b5b7d3c98..741a29b66226 100644 --- a/java/java-impl/src/com/intellij/refactoring/util/classMembers/InterfaceMemberDependencyGraph.java +++ b/java/java-impl/src/com/intellij/refactoring/util/classMembers/InterfaceMemberDependencyGraph.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2013 JetBrains s.r.o. + * Copyright 2000-2016 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. @@ -26,7 +26,7 @@ import java.util.Iterator; import java.util.Set; public class InterfaceMemberDependencyGraph> implements MemberDependencyGraph { - protected HashSet myInterfaceDependencies = null; + protected HashSet myInterfaceDependencies; protected HashMap> myMembersToInterfacesMap = new HashMap>(); protected HashSet myImplementedInterfaces; protected HashMap> myMethodsFromInterfaces; diff --git a/java/java-impl/src/com/intellij/refactoring/util/classRefs/ClassReferenceScanner.java b/java/java-impl/src/com/intellij/refactoring/util/classRefs/ClassReferenceScanner.java index 2ee99941aebc..faa9cdc1910d 100644 --- a/java/java-impl/src/com/intellij/refactoring/util/classRefs/ClassReferenceScanner.java +++ b/java/java-impl/src/com/intellij/refactoring/util/classRefs/ClassReferenceScanner.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2009 JetBrains s.r.o. + * Copyright 2000-2016 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. @@ -22,7 +22,7 @@ import com.intellij.psi.*; */ public abstract class ClassReferenceScanner { protected PsiClass myClass; - private PsiReference[] myReferences = null; + private PsiReference[] myReferences; public abstract PsiReference[] findReferences(); diff --git a/java/java-impl/src/com/intellij/refactoring/util/duplicates/MethodDuplicatesHandler.java b/java/java-impl/src/com/intellij/refactoring/util/duplicates/MethodDuplicatesHandler.java index a6d97af3d961..88c54b97c43e 100644 --- a/java/java-impl/src/com/intellij/refactoring/util/duplicates/MethodDuplicatesHandler.java +++ b/java/java-impl/src/com/intellij/refactoring/util/duplicates/MethodDuplicatesHandler.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2014 JetBrains s.r.o. + * Copyright 2000-2016 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. @@ -161,7 +161,7 @@ public class MethodDuplicatesHandler implements RefactoringActionHandler, Contex } scope.accept(new PsiRecursiveElementVisitor() { - private int myFileCount = 0; + private int myFileCount; @Override public void visitFile(final PsiFile file) { if (progressIndicator != null){ if (progressIndicator.isCanceled()) return; diff --git a/java/java-impl/src/com/intellij/refactoring/util/occurrences/BaseOccurrenceManager.java b/java/java-impl/src/com/intellij/refactoring/util/occurrences/BaseOccurrenceManager.java index 4113e2cd6ca1..dd61924b09ce 100644 --- a/java/java-impl/src/com/intellij/refactoring/util/occurrences/BaseOccurrenceManager.java +++ b/java/java-impl/src/com/intellij/refactoring/util/occurrences/BaseOccurrenceManager.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2009 JetBrains s.r.o. + * Copyright 2000-2016 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. @@ -28,8 +28,8 @@ import java.util.ArrayList; * @author dsl */ public abstract class BaseOccurrenceManager implements OccurrenceManager { - private PsiExpression[] myOccurrences = null; - private PsiElement myAnchorStatement = null; + private PsiExpression[] myOccurrences; + private PsiElement myAnchorStatement; protected final OccurrenceFilter myFilter; public BaseOccurrenceManager(OccurrenceFilter filter) { diff --git a/java/java-impl/src/com/intellij/refactoring/wrapreturnvalue/ReturnValueBeanBuilder.java b/java/java-impl/src/com/intellij/refactoring/wrapreturnvalue/ReturnValueBeanBuilder.java index 965083e8ddc0..b880c8402e6a 100644 --- a/java/java-impl/src/com/intellij/refactoring/wrapreturnvalue/ReturnValueBeanBuilder.java +++ b/java/java-impl/src/com/intellij/refactoring/wrapreturnvalue/ReturnValueBeanBuilder.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2014 JetBrains s.r.o. + * Copyright 2000-2016 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. @@ -29,10 +29,10 @@ import java.util.List; class ReturnValueBeanBuilder { private final List myTypeParams = new ArrayList(); - private String myClassName = null; - private String myPackageName = null; - private Project myProject = null; - private PsiType myValueType = null; + private String myClassName; + private String myPackageName; + private Project myProject; + private PsiType myValueType; private boolean myStatic; public void setClassName(String className) { diff --git a/java/java-impl/src/com/intellij/slicer/SliceNullnessAnalyzer.java b/java/java-impl/src/com/intellij/slicer/SliceNullnessAnalyzer.java index 8aed8cd985b4..487fbe0987c3 100644 --- a/java/java-impl/src/com/intellij/slicer/SliceNullnessAnalyzer.java +++ b/java/java-impl/src/com/intellij/slicer/SliceNullnessAnalyzer.java @@ -29,8 +29,6 @@ import com.intellij.openapi.util.Computable; import com.intellij.openapi.util.Ref; import com.intellij.psi.*; import com.intellij.psi.util.PsiUtil; -import com.intellij.util.NullableFunction; -import com.intellij.util.PairProcessor; import com.intellij.util.WalkingState; import com.intellij.util.containers.ContainerUtil; import com.intellij.util.containers.FactoryMap; @@ -42,7 +40,7 @@ import java.util.*; /** * User: cdr */ -public class SliceNullnessAnalyzer { +class SliceNullnessAnalyzer { private static void groupByNullness(NullAnalysisResult result, SliceRootNode oldRoot, final Map map) { SliceRootNode root = createNewTree(result, oldRoot, map); @@ -51,13 +49,13 @@ public class SliceNullnessAnalyzer { } @NotNull - public static SliceRootNode createNewTree(NullAnalysisResult result, SliceRootNode oldRoot, final Map map) { + static SliceRootNode createNewTree(NullAnalysisResult result, SliceRootNode oldRoot, final Map map) { SliceRootNode root = oldRoot.copy(); assert oldRoot.myCachedChildren.size() == 1; SliceNode oldRootStart = oldRoot.myCachedChildren.get(0); root.setChanged(); root.targetEqualUsages.clear(); - root.myCachedChildren = new ArrayList(); + root.myCachedChildren = new ArrayList<>(); createValueRootNode(result, oldRoot, map, root, oldRootStart, "Null Values", NullAnalysisResult.NULLS); createValueRootNode(result, oldRoot, map, root, oldRootStart, "NotNull Values", NullAnalysisResult.NOT_NULLS); @@ -80,37 +78,31 @@ public class SliceNullnessAnalyzer { SliceLeafValueClassNode valueRoot = new SliceLeafValueClassNode(root.getProject(), root, nodeName); root.myCachedChildren.add(valueRoot); - Set uniqueValues = new THashSet(groupedByValue, SliceLeafAnalyzer.LEAF_ELEMENT_EQUALITY); + Set uniqueValues = new THashSet<>(groupedByValue, SliceLeafAnalyzer.LEAF_ELEMENT_EQUALITY); for (final PsiElement expression : uniqueValues) { - SliceNode newRoot = SliceLeafAnalyzer.filterTree(oldRootStart, new NullableFunction() { - @Override - public SliceNode fun(SliceNode oldNode) { - if (oldNode.getDuplicate() != null) { - return null; - } - - for (PsiElement nullSuspect : group(oldNode, map, group)) { - if (PsiEquivalenceUtil.areElementsEquivalent(nullSuspect, expression)) { - return oldNode.copy(); - } - } + SliceNode newRoot = SliceLeafAnalyzer.filterTree(oldRootStart, oldNode -> { + if (oldNode.getDuplicate() != null) { return null; } - },new PairProcessor>() { - @Override - public boolean process(SliceNode node, List children) { - if (!children.isEmpty()) return true; - PsiElement element = node.getValue().getElement(); - if (element == null) return false; - return PsiEquivalenceUtil.areElementsEquivalent(element, expression); // leaf can be there only if it's filtering expression + + for (PsiElement nullSuspect : group(oldNode, map, group)) { + if (PsiEquivalenceUtil.areElementsEquivalent(nullSuspect, expression)) { + return oldNode.copy(); + } } + return null; + }, (node, children) -> { + if (!children.isEmpty()) return true; + PsiElement element = node.getValue().getElement(); + if (element == null) return false; + return PsiEquivalenceUtil.areElementsEquivalent(element, expression); // leaf can be there only if it's filtering expression }); valueRoot.myCachedChildren.add(new SliceLeafValueRootNode(root.getProject(), expression, valueRoot, Collections.singletonList(newRoot), oldRoot.getValue().params)); } } - public static void startAnalyzeNullness(@NotNull AbstractTreeStructure treeStructure, @NotNull Runnable finish) { + static void startAnalyzeNullness(@NotNull AbstractTreeStructure treeStructure, @NotNull Runnable finish) { final SliceRootNode root = (SliceRootNode)treeStructure.getRootElement(); final Ref leafExpressions = Ref.create(null); final Map map = createMap(); @@ -151,7 +143,7 @@ public class SliceNullnessAnalyzer { @Override protected Map createMap() { - return ContainerUtil.newIdentityTroveMap(); + return ContainerUtil.newIdentityTroveMap(); } }; } @@ -164,9 +156,9 @@ public class SliceNullnessAnalyzer { } @NotNull - public static NullAnalysisResult calcNullableLeaves(@NotNull final SliceNode root, - @NotNull AbstractTreeStructure treeStructure, - @NotNull final Map map) { + static NullAnalysisResult calcNullableLeaves(@NotNull final SliceNode root, + @NotNull AbstractTreeStructure treeStructure, + @NotNull final Map map) { final SliceLeafAnalyzer.SliceNodeGuide guide = new SliceLeafAnalyzer.SliceNodeGuide(treeStructure); WalkingState walkingState = new WalkingState(guide) { @Override @@ -279,10 +271,10 @@ public class SliceNullnessAnalyzer { } static class NullAnalysisResult { - public static int NULLS = 0; - public static int NOT_NULLS = 1; - public static int UNKNOWNS = 2; - public final Collection[] groupedByValue = new Collection[] {new THashSet(),new THashSet(),new THashSet()}; + static final int NULLS = 0; + static final int NOT_NULLS = 1; + static final int UNKNOWNS = 2; + final Collection[] groupedByValue = new Collection[] {new THashSet(),new THashSet(),new THashSet()}; public void clear() { for (Collection elements : groupedByValue) { diff --git a/java/java-impl/src/com/intellij/unscramble/ThreadState.java b/java/java-impl/src/com/intellij/unscramble/ThreadState.java index d4952446a3fb..2c47f96b72f5 100644 --- a/java/java-impl/src/com/intellij/unscramble/ThreadState.java +++ b/java/java-impl/src/com/intellij/unscramble/ThreadState.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2010 JetBrains s.r.o. + * Copyright 2000-2016 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. @@ -35,7 +35,7 @@ public class ThreadState { private String myJavaThreadState; private String myThreadStateDetail; private String myExtraState; - private boolean isDaemon = false; + private boolean isDaemon; private final Set myThreadsWaitingForMyLock = new HashSet(); private final Set myDeadlockedThreads = new HashSet(); diff --git a/java/java-impl/src/com/intellij/unscramble/UnscrambleListener.java b/java/java-impl/src/com/intellij/unscramble/UnscrambleListener.java index f0e279528494..8b2cfbc15aee 100644 --- a/java/java-impl/src/com/intellij/unscramble/UnscrambleListener.java +++ b/java/java-impl/src/com/intellij/unscramble/UnscrambleListener.java @@ -15,67 +15,28 @@ */ package com.intellij.unscramble; -import com.intellij.Patches; -import com.intellij.openapi.application.ApplicationActivationListener; +import com.intellij.openapi.application.ClipboardAnalyzeListener; import com.intellij.openapi.project.DumbService; import com.intellij.openapi.project.Project; -import com.intellij.openapi.util.SystemInfo; import com.intellij.openapi.util.text.StringUtil; -import com.intellij.openapi.wm.IdeFrame; -import com.intellij.util.Alarm; +import org.jetbrains.annotations.NotNull; import java.util.regex.Pattern; /** * @author Konstantin Bulenkov */ -public class UnscrambleListener extends ApplicationActivationListener.Adapter { - private static final int MAX_STACKTRACE_SIZE = 100 * 1024; - private String stacktrace = null; - - @Override - public void applicationActivated(final IdeFrame ideFrame) { - final Runnable processClipboard = new Runnable() { - @Override - public void run() { - final String clipboard = AnalyzeStacktraceUtil.getTextInClipboard(); - if (clipboard != null && clipboard.length() < MAX_STACKTRACE_SIZE && !clipboard.equals(stacktrace)) { - stacktrace = clipboard; - final Project project = ideFrame.getProject(); - if (project != null && isStacktrace(stacktrace)) { - final UnscrambleDialog dialog = new UnscrambleDialog(project); - dialog.createNormalizeTextAction().actionPerformed(null); - if (!DumbService.isDumb(project)) { - dialog.doOKAction(); - } - } - } - } - }; - - if (Patches.SLOW_GETTING_CLIPBOARD_CONTENTS) { - //IDEA's clipboard is synchronized with the system clipboard on frame activation so we need to postpone clipboard processing - new Alarm().addRequest(processClipboard, 300); - } - else { - processClipboard.run(); - } - } - - @Override - public void applicationDeactivated(IdeFrame ideFrame) { - if (SystemInfo.isMac) return; - - stacktrace = AnalyzeStacktraceUtil.getTextInClipboard(); - } +public class UnscrambleListener extends ClipboardAnalyzeListener { private static final Pattern STACKTRACE_LINE = - Pattern.compile("[\t]*at [[_a-zA-Z0-9]+\\.]+[_a-zA-Z$0-9]+\\.[a-zA-Z0-9_]+\\([A-Za-z0-9_]+\\.java:[\\d]+\\)+[ [~]*\\[[a-zA-Z0-9\\.\\:/]\\]]*"); + Pattern.compile( + "[\t]*at [[_a-zA-Z0-9]+\\.]+[_a-zA-Z$0-9]+\\.[a-zA-Z0-9_]+\\([A-Za-z0-9_]+\\.java:[\\d]+\\)+[ [~]*\\[[a-zA-Z0-9\\.\\:/]\\]]*"); - public static boolean isStacktrace(String stacktrace) { - stacktrace = UnscrambleDialog.normalizeText(stacktrace); + @Override + public boolean canHandle(@NotNull String value) { + value = UnscrambleDialog.normalizeText(value); int linesCount = 0; - for (String line : stacktrace.split("\n")) { + for (String line : value.split("\n")) { line = line.trim(); if (line.length() == 0) continue; line = StringUtil.trimEnd(line, "\r"); @@ -89,4 +50,13 @@ public class UnscrambleListener extends ApplicationActivationListener.Adapter { } return false; } + + @Override + protected void handle(@NotNull Project project, @NotNull String value) { + final UnscrambleDialog dialog = new UnscrambleDialog(project); + dialog.createNormalizeTextAction().actionPerformed(null); + if (!DumbService.isDumb(project)) { + dialog.doOKAction(); + } + } } diff --git a/java/java-indexing-api/src/com/intellij/psi/search/searches/ClassInheritorsSearch.java b/java/java-indexing-api/src/com/intellij/psi/search/searches/ClassInheritorsSearch.java index 2c1e34be09d0..c36240502f21 100644 --- a/java/java-indexing-api/src/com/intellij/psi/search/searches/ClassInheritorsSearch.java +++ b/java/java-indexing-api/src/com/intellij/psi/search/searches/ClassInheritorsSearch.java @@ -147,11 +147,11 @@ public class ClassInheritorsSearch extends ExtensibleQueryFactory ApplicationManager.getApplication().runReadAction((Computable>)() -> SmartPointerManager.getInstance(psiClass.getProject()).createSmartPsiElementPointer(psiClass))); } - @NotNull - @Deprecated //todo to be removed in IDEA 17 /** * @deprecated use {@link #search(PsiClass, SearchScope, boolean)} instead */ + @NotNull + @Deprecated //todo to be removed in IDEA 17 public static Query search(@NotNull final PsiClass aClass, @NotNull SearchScope scope, final boolean checkDeep, final boolean checkInheritance) { return search(aClass, scope, checkDeep, checkInheritance, true); } diff --git a/java/java-indexing-impl/src/com/intellij/codeInsight/ReadableExternalAnnotationsManager.java b/java/java-indexing-impl/src/com/intellij/codeInsight/ReadableExternalAnnotationsManager.java index 4dd8e62e78a8..c4682cfbbdc9 100644 --- a/java/java-indexing-impl/src/com/intellij/codeInsight/ReadableExternalAnnotationsManager.java +++ b/java/java-indexing-impl/src/com/intellij/codeInsight/ReadableExternalAnnotationsManager.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2012 JetBrains s.r.o. + * Copyright 2000-2016 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. @@ -27,7 +27,7 @@ import org.jetbrains.annotations.Nullable; import java.util.*; public class ReadableExternalAnnotationsManager extends BaseExternalAnnotationsManager { - @Nullable private Set myAnnotationsRoots = null; + @Nullable private Set myAnnotationsRoots; public ReadableExternalAnnotationsManager(PsiManager psiManager) { super(psiManager); diff --git a/java/java-indexing-impl/src/com/intellij/psi/impl/file/impl/JavaFileManagerImpl.java b/java/java-indexing-impl/src/com/intellij/psi/impl/file/impl/JavaFileManagerImpl.java index cbed3d6cb1fb..bf7f9e42e17b 100644 --- a/java/java-indexing-impl/src/com/intellij/psi/impl/file/impl/JavaFileManagerImpl.java +++ b/java/java-indexing-impl/src/com/intellij/psi/impl/file/impl/JavaFileManagerImpl.java @@ -49,7 +49,7 @@ public class JavaFileManagerImpl implements JavaFileManager, Disposable { private final PackageIndex myPackageIndex; public JavaFileManagerImpl(Project project) { - myManager = (PsiManagerEx)PsiManager.getInstance(project); + myManager = PsiManagerEx.getInstanceEx(project); myPackageIndex = PackageIndex.getInstance(myManager.getProject()); project.getMessageBus().connect().subscribe(ProjectTopics.PROJECT_ROOTS, new ModuleRootAdapter() { @Override diff --git a/java/java-indexing-impl/src/com/intellij/psi/impl/search/AllClassesSearchExecutor.java b/java/java-indexing-impl/src/com/intellij/psi/impl/search/AllClassesSearchExecutor.java index 067db93f8551..d90a814afe57 100644 --- a/java/java-indexing-impl/src/com/intellij/psi/impl/search/AllClassesSearchExecutor.java +++ b/java/java-indexing-impl/src/com/intellij/psi/impl/search/AllClassesSearchExecutor.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2009 JetBrains s.r.o. + * Copyright 2000-2016 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. @@ -104,7 +104,7 @@ public class AllClassesSearchExecutor implements QueryExecutor() { - int i = 0; + int i; @Override public boolean process(String s) { diff --git a/java/java-indexing-impl/src/com/intellij/psi/impl/search/JavaClassInheritorsSearcher.java b/java/java-indexing-impl/src/com/intellij/psi/impl/search/JavaClassInheritorsSearcher.java index 1fe2402d1c77..41b84266a684 100644 --- a/java/java-indexing-impl/src/com/intellij/psi/impl/search/JavaClassInheritorsSearcher.java +++ b/java/java-indexing-impl/src/com/intellij/psi/impl/search/JavaClassInheritorsSearcher.java @@ -40,7 +40,9 @@ import org.jetbrains.annotations.NotNull; import java.util.Collection; import java.util.Iterator; +import java.util.List; import java.util.concurrent.ConcurrentMap; +import java.util.stream.Collectors; public class JavaClassInheritorsSearcher extends QueryExecutorBase { @Override @@ -193,7 +195,7 @@ public class JavaClassInheritorsSearcher extends QueryExecutorBase subClasses = new HashSetQueue<>(); + private final HashSetQueue subClasses = new HashSetQueue<>(); private final Object lock = new Object(); private final GlobalSearchScope projectScope; private final Semaphore currentlyProcessingClasses = new Semaphore(); @@ -210,7 +212,7 @@ public class JavaClassInheritorsSearcher extends QueryExecutorBase iterator() { return new Iterator() { - private final Iterator subClassIterator = subClasses.iterator(); + private final Iterator subClassIterator = subClasses.iterator(); @Override public boolean hasNext() { @@ -227,24 +229,26 @@ public class JavaClassInheritorsSearcher extends QueryExecutorBase)() -> (PsiClass)next.retrieve()); } }; } - private Iterator candidatesToFindSubclassesIterator; // guarded by lock + private Iterator candidatesToFindSubclassesIterator; // guarded by lock private void findNextSubclasses() { while (true) { ProgressManager.checkCanceled(); - PsiClass candidate; + PsiAnchor next; synchronized (lock) { if (candidatesToFindSubclassesIterator == null) { candidatesToFindSubclassesIterator = subClasses.iterator(); - candidate = myBaseClass; + next = null; } else { if (!candidatesToFindSubclassesIterator.hasNext()) { @@ -252,21 +256,25 @@ public class JavaClassInheritorsSearcher extends QueryExecutorBase foundSubClasses = DirectClassInheritorsSearch.search(candidate, projectScope).findAll(); - synchronized (lock) { - added = subClasses.addAll(foundSubClasses); - } + added = ApplicationManager.getApplication().runReadAction((Computable)()-> { + List pointers = foundSubClasses.stream().map(PsiAnchor::create).collect(Collectors.toList()); + synchronized (lock) { + return subClasses.addAll(pointers); + } + }); } } finally { diff --git a/java/java-psi-api/src/com/intellij/codeInsight/ClassUtil.java b/java/java-psi-api/src/com/intellij/codeInsight/ClassUtil.java index ed21bf290b09..90cc4b9759e9 100644 --- a/java/java-psi-api/src/com/intellij/codeInsight/ClassUtil.java +++ b/java/java-psi-api/src/com/intellij/codeInsight/ClassUtil.java @@ -14,9 +14,6 @@ * limitations under the License. */ -/** - * @author Alexey - */ package com.intellij.codeInsight; import com.intellij.psi.*; diff --git a/java/java-psi-api/src/com/intellij/ide/util/JavaAnonymousClassesHelper.java b/java/java-psi-api/src/com/intellij/ide/util/JavaAnonymousClassesHelper.java index ae6b362792ad..a11fb2f2feb9 100644 --- a/java/java-psi-api/src/com/intellij/ide/util/JavaAnonymousClassesHelper.java +++ b/java/java-psi-api/src/com/intellij/ide/util/JavaAnonymousClassesHelper.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2012 JetBrains s.r.o. + * Copyright 2000-2016 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. @@ -50,7 +50,7 @@ public class JavaAnonymousClassesHelper { public CachedValueProvider.Result> compute(final PsiClass upper) { final Map map = new THashMap(); upper.accept(new JavaRecursiveElementWalkingVisitor() { - int index = 0; + int index; @Override public void visitAnonymousClass(PsiAnonymousClass aClass) { diff --git a/java/java-psi-api/src/com/intellij/psi/PsiDiamondType.java b/java/java-psi-api/src/com/intellij/psi/PsiDiamondType.java index 8b92ec95a3ae..4789f5c2ecf7 100644 --- a/java/java-psi-api/src/com/intellij/psi/PsiDiamondType.java +++ b/java/java-psi-api/src/com/intellij/psi/PsiDiamondType.java @@ -179,4 +179,6 @@ public abstract class PsiDiamondType extends PsiType { } return null; } + + public abstract JavaResolveResult getStaticFactory(); } diff --git a/java/java-psi-api/src/com/intellij/psi/infos/MethodCandidateInfo.java b/java/java-psi-api/src/com/intellij/psi/infos/MethodCandidateInfo.java index 911d30607498..72c5468c2177 100644 --- a/java/java-psi-api/src/com/intellij/psi/infos/MethodCandidateInfo.java +++ b/java/java-psi-api/src/com/intellij/psi/infos/MethodCandidateInfo.java @@ -497,7 +497,15 @@ public class MethodCandidateInfo extends CandidateInfo{ return clearErrorMessageInSubexpressions(((PsiConditionalExpression)expression).getElseExpression()); } else if (expression instanceof PsiCallExpression) { - final JavaResolveResult result = ((PsiCallExpression)expression).resolveMethodGenerics(); + final JavaResolveResult result; + if (expression instanceof PsiNewExpression) { + PsiDiamondType diamondType = PsiDiamondType.getDiamondType((PsiNewExpression)expression); + result = diamondType != null ? diamondType.getStaticFactory() + : ((PsiCallExpression)expression).resolveMethodGenerics(); + } + else { + result = ((PsiCallExpression)expression).resolveMethodGenerics(); + } if (result instanceof MethodCandidateInfo) { final String message = ((MethodCandidateInfo)result).getInferenceErrorMessage(); ((MethodCandidateInfo)result).setInferenceError(null); diff --git a/java/java-psi-api/src/com/intellij/psi/util/ClassUtil.java b/java/java-psi-api/src/com/intellij/psi/util/ClassUtil.java index 9e005ffd2eef..98085e944c5b 100644 --- a/java/java-psi-api/src/com/intellij/psi/util/ClassUtil.java +++ b/java/java-psi-api/src/com/intellij/psi/util/ClassUtil.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2015 JetBrains s.r.o. + * Copyright 2000-2016 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. @@ -112,7 +112,7 @@ public class ClassUtil { final String name = prefix.length() < indexName.length() ? indexName.substring(prefix.length()) : null; final PsiClass[] result = new PsiClass[1]; containingClass.accept(new JavaRecursiveElementVisitor() { - private int myCurrentIdx = 0; + private int myCurrentIdx; @Override public void visitElement(PsiElement element) { diff --git a/java/java-psi-impl/src/com/intellij/codeInsight/javadoc/JavaDocUtil.java b/java/java-psi-impl/src/com/intellij/codeInsight/javadoc/JavaDocUtil.java index a93db9929de7..f8f5a3d122d5 100644 --- a/java/java-psi-impl/src/com/intellij/codeInsight/javadoc/JavaDocUtil.java +++ b/java/java-psi-impl/src/com/intellij/codeInsight/javadoc/JavaDocUtil.java @@ -71,6 +71,9 @@ public class JavaDocUtil { @Nullable public static PsiElement findReferenceTarget(PsiManager manager, String refText, PsiElement context, boolean useNavigationElement) { LOG.assertTrue(context == null || context.isValid()); + if (context != null) { + context = context.getNavigationElement(); + } int poundIndex = refText.indexOf('#'); final JavaPsiFacade facade = JavaPsiFacade.getInstance(manager.getProject()); @@ -268,7 +271,7 @@ public class JavaDocUtil { final PsiManager manager = aClass.getManager(); return manager.areElementsEquivalent(aClass, JavaPsiFacade.getInstance(manager.getProject()).getResolveHelper().resolveReferencedClass(shortName, context)) ? shortName - : qName; + : StringUtil.trimStart(qName, "java.lang."); } public static String getLabelText(Project project, PsiManager manager, String refText, PsiElement context) { diff --git a/java/java-psi-impl/src/com/intellij/psi/PsiDiamondTypeImpl.java b/java/java-psi-impl/src/com/intellij/psi/PsiDiamondTypeImpl.java index c197f1cec0c4..551677ec794b 100644 --- a/java/java-psi-impl/src/com/intellij/psi/PsiDiamondTypeImpl.java +++ b/java/java-psi-impl/src/com/intellij/psi/PsiDiamondTypeImpl.java @@ -22,7 +22,6 @@ import com.intellij.openapi.projectRoots.JavaSdkVersion; import com.intellij.openapi.projectRoots.JavaVersionService; import com.intellij.openapi.util.Comparing; import com.intellij.openapi.util.Computable; -import com.intellij.openapi.util.Ref; import com.intellij.openapi.util.text.StringUtil; import com.intellij.psi.codeStyle.JavaCodeStyleManager; import com.intellij.psi.impl.source.resolve.graphInference.InferenceSession; @@ -104,8 +103,7 @@ public class PsiDiamondTypeImpl extends PsiDiamondType { @Override public DiamondInferenceResult resolveInferredTypes() { - PsiElement typeElementWithDiamondTypeArgument = myTypeElement.getParent(); - final PsiNewExpression newExpression = PsiTreeUtil.getParentOfType(typeElementWithDiamondTypeArgument, PsiNewExpression.class, true, PsiTypeElement.class); + final PsiNewExpression newExpression = getNewExpression(); if (newExpression == null) { return PsiDiamondTypeImpl.DiamondInferenceResult.NULL_RESULT; } @@ -113,6 +111,17 @@ public class PsiDiamondTypeImpl extends PsiDiamondType { return resolveInferredTypes(newExpression); } + private PsiNewExpression getNewExpression() { + PsiElement typeElementWithDiamondTypeArgument = myTypeElement.getParent(); + return PsiTreeUtil.getParentOfType(typeElementWithDiamondTypeArgument, PsiNewExpression.class, true, PsiTypeElement.class); + } + + @Override + public JavaResolveResult getStaticFactory() { + final PsiNewExpression newExpression = getNewExpression(); + return newExpression != null ? getStaticFactory(newExpression, newExpression) : null; + } + public static DiamondInferenceResult resolveInferredTypes(PsiNewExpression newExpression) { return resolveInferredTypes(newExpression, newExpression); } @@ -145,41 +154,38 @@ public class PsiDiamondTypeImpl extends PsiDiamondType { return inferenceResult; } + private static JavaResolveResult getStaticFactory(final PsiNewExpression newExpression, final PsiElement context) { + return context == newExpression + ? CachedValuesManager.getCachedValue(newExpression, new CachedValueProvider() { + @Nullable + @Override + public Result compute() { + return new Result(getStaticFactoryCandidateInfo(newExpression, newExpression), + PsiModificationTracker.MODIFICATION_COUNT); + } + }) + : getStaticFactoryCandidateInfo(newExpression, context); + } + public static DiamondInferenceResult resolveInferredTypesNoCheck(final PsiNewExpression newExpression, final PsiElement context) { - final Ref staticFactoryRef = new Ref(); + final JavaResolveResult staticFactoryCandidateInfo = getStaticFactory(newExpression, context); + if (staticFactoryCandidateInfo == null) { + return DiamondInferenceResult.NULL_RESULT; + } final PsiSubstitutor inferredSubstitutor = ourDiamondGuard.doPreventingRecursion(context, false, new Computable() { @Override public PsiSubstitutor compute() { - final JavaResolveResult staticFactoryCandidateInfo = - context == newExpression - ? CachedValuesManager.getCachedValue(newExpression, new CachedValueProvider() { - @Nullable - @Override - public Result compute() { - return new Result(getStaticFactoryCandidateInfo(newExpression, newExpression), PsiModificationTracker.MODIFICATION_COUNT); - } - }) - : getStaticFactoryCandidateInfo(newExpression, context); - staticFactoryRef.set(staticFactoryCandidateInfo); - if (staticFactoryCandidateInfo != null) { - PsiSubstitutor substitutor = staticFactoryCandidateInfo.getSubstitutor(); - return staticFactoryCandidateInfo instanceof MethodCandidateInfo && ((MethodCandidateInfo)staticFactoryCandidateInfo).getInferenceErrorMessage() != null - ? null : substitutor; - } - return null; + PsiSubstitutor substitutor = staticFactoryCandidateInfo.getSubstitutor(); + return staticFactoryCandidateInfo instanceof MethodCandidateInfo && + ((MethodCandidateInfo)staticFactoryCandidateInfo).getInferenceErrorMessage() != null + ? null : substitutor; } }); if (inferredSubstitutor == null) { return DiamondInferenceResult.NULL_RESULT; } - final JavaResolveResult staticFactoryInfo = staticFactoryRef.get(); - if (staticFactoryInfo == null) { - LOG.error(inferredSubstitutor); - return DiamondInferenceResult.NULL_RESULT; - } - - if (!(staticFactoryInfo instanceof MethodCandidateInfo)) { + if (!(staticFactoryCandidateInfo instanceof MethodCandidateInfo)) { return DiamondInferenceResult.UNRESOLVED_CONSTRUCTOR; } @@ -189,7 +195,7 @@ public class PsiDiamondTypeImpl extends PsiDiamondType { return DiamondInferenceResult.RAW_RESULT; } - final PsiMethod staticFactory = ((MethodCandidateInfo)staticFactoryInfo).getElement(); + final PsiMethod staticFactory = ((MethodCandidateInfo)staticFactoryCandidateInfo).getElement(); final PsiTypeParameter[] parameters = staticFactory.getTypeParameters(); final PsiElement staticFactoryContext = staticFactory.getContext(); final PsiClass psiClass = PsiTreeUtil.getContextOfType(staticFactoryContext, PsiClass.class, false); @@ -223,31 +229,37 @@ public class PsiDiamondTypeImpl extends PsiDiamondType { return result; } - private static JavaResolveResult getStaticFactoryCandidateInfo(PsiNewExpression newExpression, - PsiElement context) { - final PsiExpressionList argumentList = newExpression.getArgumentList(); - if (argumentList == null) { - //token expected diagnostic is provided by parser - return null; - } + private static JavaResolveResult getStaticFactoryCandidateInfo(final PsiNewExpression newExpression, + final PsiElement context) { + return ourDiamondGuard.doPreventingRecursion(context, false, new Computable() { + @Override + public JavaResolveResult compute() { - final JavaMethodsConflictResolver resolver = new JavaMethodsConflictResolver(argumentList, PsiUtil.getLanguageLevel(newExpression)); - final JavaResolveResult[] result = collectStaticFactories(newExpression, resolver); - final PsiMethod staticFactory = result != null && result.length == 1 ? (PsiMethod)result[0].getElement() : null; - if (staticFactory == null) { - //additional diagnostics: inference fails due to unresolved constructor - return JavaResolveResult.EMPTY; - } + final PsiExpressionList argumentList = newExpression.getArgumentList(); + if (argumentList == null) { + //token expected diagnostic is provided by parser + return null; + } - final MethodCandidateInfo staticFactoryCandidateInfo = createMethodCandidate(staticFactory, context, false, argumentList); - if (!staticFactory.isVarArgs()) { - return staticFactoryCandidateInfo; - } + final JavaMethodsConflictResolver resolver = new JavaMethodsConflictResolver(argumentList, PsiUtil.getLanguageLevel(newExpression)); + final JavaResolveResult[] result = collectStaticFactories(newExpression, resolver); + final PsiMethod staticFactory = result != null && result.length == 1 ? (PsiMethod)result[0].getElement() : null; + if (staticFactory == null) { + //additional diagnostics: inference fails due to unresolved constructor + return JavaResolveResult.EMPTY; + } - final ArrayList conflicts = new ArrayList(); - conflicts.add(staticFactoryCandidateInfo); - conflicts.add(createMethodCandidate(staticFactory, context, true, argumentList)); - return resolver.resolveConflict(conflicts); + final MethodCandidateInfo staticFactoryCandidateInfo = createMethodCandidate(staticFactory, context, false, argumentList); + if (!staticFactory.isVarArgs()) { + return staticFactoryCandidateInfo; + } + + final ArrayList conflicts = new ArrayList(); + conflicts.add(staticFactoryCandidateInfo); + conflicts.add(createMethodCandidate(staticFactory, context, true, argumentList)); + return resolver.resolveConflict(conflicts); + } + }); } @Nullable diff --git a/java/java-psi-impl/src/com/intellij/psi/impl/JavaPsiFacadeEx.java b/java/java-psi-impl/src/com/intellij/psi/impl/JavaPsiFacadeEx.java index 3501a5c15064..92435f9efb24 100644 --- a/java/java-psi-impl/src/com/intellij/psi/impl/JavaPsiFacadeEx.java +++ b/java/java-psi-impl/src/com/intellij/psi/impl/JavaPsiFacadeEx.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2012 JetBrains s.r.o. + * Copyright 2000-2016 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. @@ -19,9 +19,7 @@ */ package com.intellij.psi.impl; -import com.intellij.openapi.Disposable; import com.intellij.openapi.project.Project; -import com.intellij.openapi.vfs.VirtualFileFilter; import com.intellij.psi.JavaPsiFacade; import com.intellij.psi.PsiClass; import com.intellij.psi.search.GlobalSearchScope; @@ -40,7 +38,4 @@ public abstract class JavaPsiFacadeEx extends JavaPsiFacade { public PsiClass findClass(@NotNull String qualifiedName) { return findClass(qualifiedName, GlobalSearchScope.allScope(getProject())); } - - @TestOnly - public abstract void setAssertOnFileLoadingFilter(@NotNull VirtualFileFilter filter, Disposable parentDisposable); } \ No newline at end of file diff --git a/java/java-psi-impl/src/com/intellij/psi/impl/JavaPsiFacadeImpl.java b/java/java-psi-impl/src/com/intellij/psi/impl/JavaPsiFacadeImpl.java index 678662e8bf2a..567efbc9955b 100644 --- a/java/java-psi-impl/src/com/intellij/psi/impl/JavaPsiFacadeImpl.java +++ b/java/java-psi-impl/src/com/intellij/psi/impl/JavaPsiFacadeImpl.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2015 JetBrains s.r.o. + * Copyright 2000-2016 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. @@ -15,7 +15,6 @@ */ package com.intellij.psi.impl; -import com.intellij.openapi.Disposable; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.progress.ProgressIndicatorProvider; import com.intellij.openapi.project.DumbService; @@ -24,7 +23,6 @@ import com.intellij.openapi.util.Comparing; import com.intellij.openapi.util.Condition; import com.intellij.openapi.util.Conditions; import com.intellij.openapi.util.text.StringUtil; -import com.intellij.openapi.vfs.VirtualFileFilter; import com.intellij.psi.*; import com.intellij.psi.impl.file.impl.JavaFileManager; import com.intellij.psi.impl.source.DummyHolderFactory; @@ -412,12 +410,6 @@ public class JavaPsiFacadeImpl extends JavaPsiFacadeEx { return PsiElementFactory.SERVICE.getInstance(myProject); } - @TestOnly - @Override - public void setAssertOnFileLoadingFilter(@NotNull final VirtualFileFilter filter, Disposable parentDisposable) { - ((PsiManagerImpl)PsiManager.getInstance(myProject)).setAssertOnFileLoadingFilter(filter, parentDisposable); - } - @TestOnly public void clearFindersCache() { myElementFinders = null; diff --git a/java/java-psi-impl/src/com/intellij/refactoring/util/CanonicalTypes.java b/java/java-psi-impl/src/com/intellij/refactoring/util/CanonicalTypes.java index 99c1dad3c89c..503a290cb3f5 100644 --- a/java/java-psi-impl/src/com/intellij/refactoring/util/CanonicalTypes.java +++ b/java/java-psi-impl/src/com/intellij/refactoring/util/CanonicalTypes.java @@ -37,7 +37,11 @@ public class CanonicalTypes { public abstract static class Type { @NotNull - public abstract PsiType getType(PsiElement context, PsiManager manager) throws IncorrectOperationException; + public abstract PsiType getType(@Nullable PsiElement context, PsiManager manager) throws IncorrectOperationException; + + public PsiType getType(@NotNull PsiElement context) { + return getType(context, context.getManager()); + } @NonNls public abstract String getTypeText(); diff --git a/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/lambda/changeSignature/AddExceptionToCatchInOneLineLambda.java b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/lambda/changeSignature/AddExceptionToCatchInOneLineLambda.java new file mode 100644 index 000000000000..e57bc71c8aef --- /dev/null +++ b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/lambda/changeSignature/AddExceptionToCatchInOneLineLambda.java @@ -0,0 +1,19 @@ +import java.util.function.Consumer; + +class Action { + public void acting(String s) { + System.out.println(s); + } +} + + +class Client { + public static void consumer(String val, Consumer func) { + func.accept(val); + } + + public static void main(String[] args) { + Action a = new Action(); + consumer("hello", (s) -> a.acting(s)); + } +} \ No newline at end of file diff --git a/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/lambda/changeSignature/AddExceptionToCatchInOneLineLambda_after.java b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/lambda/changeSignature/AddExceptionToCatchInOneLineLambda_after.java new file mode 100644 index 000000000000..b24227706e22 --- /dev/null +++ b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/lambda/changeSignature/AddExceptionToCatchInOneLineLambda_after.java @@ -0,0 +1,26 @@ +import java.io.IOException; +import java.util.function.Consumer; + +class Action { + public void acting(String s) throws IOException { + System.out.println(s); + } +} + + +class Client { + public static void consumer(String val, Consumer func) { + func.accept(val); + } + + public static void main(String[] args) { + Action a = new Action(); + consumer("hello", (s) -> { + try { + a.acting(s); + } catch (IOException e) { + e.printStackTrace(); + } + }); + } +} \ No newline at end of file diff --git a/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/lambda/changeSignature/AddUncheckedExceptionInMethodRef.java b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/lambda/changeSignature/AddUncheckedExceptionInMethodRef.java new file mode 100644 index 000000000000..767fa85ac3ba --- /dev/null +++ b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/lambda/changeSignature/AddUncheckedExceptionInMethodRef.java @@ -0,0 +1,19 @@ +import java.util.function.Consumer; + +class Action { + public void acting(String s) { + System.out.println(s); + } +} + + +class Client { + public static void consumer(String val, Consumer func) { + func.accept(val); + } + + public static void main(String[] args) { + Action a = new Action(); + consumer("hello", a::acting); + } +} \ No newline at end of file diff --git a/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/lambda/changeSignature/AddUncheckedExceptionInMethodRef_after.java b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/lambda/changeSignature/AddUncheckedExceptionInMethodRef_after.java new file mode 100644 index 000000000000..4283d8bf6324 --- /dev/null +++ b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/lambda/changeSignature/AddUncheckedExceptionInMethodRef_after.java @@ -0,0 +1,19 @@ +import java.util.function.Consumer; + +class Action { + public void acting(String s) throws NullPointerException { + System.out.println(s); + } +} + + +class Client { + public static void consumer(String val, Consumer func) { + func.accept(val); + } + + public static void main(String[] args) { + Action a = new Action(); + consumer("hello", a::acting); + } +} \ No newline at end of file diff --git a/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/lambda/expressions/ObjectOverloadsWithDiamondsOverMultipleConstructors.java b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/lambda/expressions/ObjectOverloadsWithDiamondsOverMultipleConstructors.java new file mode 100644 index 000000000000..adba0318dcb1 --- /dev/null +++ b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/lambda/expressions/ObjectOverloadsWithDiamondsOverMultipleConstructors.java @@ -0,0 +1,14 @@ + +import java.util.Collection; + +class Test { + + void m(StringBuilder builder){ + builder.append(new Foo<>((Collection)null)); + } + + static class Foo { + public Foo(Collection c) {} + public Foo(Foo t) {} + } +} \ No newline at end of file diff --git a/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/lambda/redundantCast/RejectReturnTypeChange.java b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/lambda/redundantCast/RejectReturnTypeChange.java new file mode 100644 index 000000000000..33cd6c83ad76 --- /dev/null +++ b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/lambda/redundantCast/RejectReturnTypeChange.java @@ -0,0 +1,26 @@ + +import java.util.*; +import java.util.function.Function; + +import static java.util.Collections.emptyList; + +class Ambiguous { + public void setRoots(List roots) {} + + public static List concat(Iterable> list) { + return new ArrayList(); + } + + public static List concat(List> lists) { + return new ArrayList(); + } + + public static List map(Collection iterable, Function mapping) { + return emptyList(); + } + + public void anonymousToLambda(HashSet modules) { + setRoots(Ambiguous.concat(Ambiguous.map(modules, (Function>) s -> null))); + } + +} diff --git a/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/quickFix/anonymous2lambda/beforeCodeBlockLambda.java b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/quickFix/anonymous2lambda/beforeCodeBlockLambda.java index e5bc06d3404f..55bac74f26cf 100644 --- a/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/quickFix/anonymous2lambda/beforeCodeBlockLambda.java +++ b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/quickFix/anonymous2lambda/beforeCodeBlockLambda.java @@ -1,4 +1,4 @@ -// "Replace with lambda" "true" +// "Replace with lambda" "false" class A { { bar(new ThrowableComputable() { diff --git a/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/quickFix/anonymous2lambda/beforeFormalTypes.java b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/quickFix/anonymous2lambda/beforeFormalTypes.java index 5b3a5fc6b563..3b7d467776cd 100644 --- a/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/quickFix/anonymous2lambda/beforeFormalTypes.java +++ b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/quickFix/anonymous2lambda/beforeFormalTypes.java @@ -1,4 +1,4 @@ -// "Replace with lambda" "true" +// "Replace with lambda" "false" import java.util.*; class Test2 { diff --git a/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/quickFix/anonymous2lambda/beforeNestedOverloads.java b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/quickFix/anonymous2lambda/beforeNestedOverloads.java new file mode 100644 index 000000000000..fa8131729bea --- /dev/null +++ b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/quickFix/anonymous2lambda/beforeNestedOverloads.java @@ -0,0 +1,33 @@ +// "Replace with lambda" "false" + +import java.util.*; +import java.util.function.Function; + +import static java.util.Collections.emptyList; + +class Ambiguous { + public void setRoots(List roots) {} + + public static List concat(Iterable> list) { + return new ArrayList(); + } + + public static List concat(List> lists) { + return new ArrayList(); + } + + public static List map(Collection iterable, Function mapping) { + return emptyList(); + } + + public void anonymousToLambda(HashSet modules) { + setRoots(Ambiguous.concat(Ambiguous.map(modules, new Function>() { + @Override + public List apply(String s) { + return null; + } + }) + )); + } + +} \ No newline at end of file diff --git a/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/quickFix/implementAbstractMethod/afterInterfaceDefault.java b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/quickFix/implementAbstractMethod/afterInterfaceDefault.java new file mode 100644 index 000000000000..ea30bee75645 --- /dev/null +++ b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/quickFix/implementAbstractMethod/afterInterfaceDefault.java @@ -0,0 +1,11 @@ +// "Override method 'm'" "true" +interface A { + default void m(){} +} + +interface B extends A { + @Override + default void m() { + + } +} \ No newline at end of file diff --git a/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/quickFix/implementAbstractMethod/beforeInterfaceDefault.java b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/quickFix/implementAbstractMethod/beforeInterfaceDefault.java new file mode 100644 index 000000000000..aaf2a950a64e --- /dev/null +++ b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/quickFix/implementAbstractMethod/beforeInterfaceDefault.java @@ -0,0 +1,6 @@ +// "Override method 'm'" "true" +interface A { + default void m(){} +} + +interface B extends A {} \ No newline at end of file diff --git a/java/java-tests/testData/codeInsight/javadocIG/documentationForJdkClassWhenExternalDocIsNotAvailable.html b/java/java-tests/testData/codeInsight/javadocIG/documentationForJdkClassWhenExternalDocIsNotAvailable.html index f601876a818d..e98e383bb3c7 100644 --- a/java/java-tests/testData/codeInsight/javadocIG/documentationForJdkClassWhenExternalDocIsNotAvailable.html +++ b/java/java-tests/testData/codeInsight/javadocIG/documentationForJdkClassWhenExternalDocIsNotAvailable.html @@ -1,6 +1,6 @@ java.lang
public final class String
-extends java.lang.Object
-implements java.io.Serializable, java.lang.Comparable<String>, java.lang.CharSequence
+extends Object +implements java.io.Serializable, Comparable<String>, CharSequence The String class represents character strings. All string literals in Java programs, such as "abc", are implemented as instances of this class. diff --git a/java/java-tests/testData/codeInsight/javadocIG/documentationForJdkClassWithReferencesToClassesFromJavaLang.html b/java/java-tests/testData/codeInsight/javadocIG/documentationForJdkClassWithReferencesToClassesFromJavaLang.html new file mode 100644 index 000000000000..88e173d53941 --- /dev/null +++ b/java/java-tests/testData/codeInsight/javadocIG/documentationForJdkClassWithReferencesToClassesFromJavaLang.html @@ -0,0 +1,8 @@ + java.util.List
public abstract boolean contains(Object o)
+ + Returns true if this list contains the specified element. + More formally, returns true if and only if this list contains + at least one element e such that + (o==null ? e==null : o.equals(e)). + +
Overrides:
contains in interface Collection
Parameters:
o - element whose presence in this list is to be tested.
Returns:
true if this list contains the specified element.
Throws:
ClassCastException - if the type of the specified element is incompatible with this list (optional).
NullPointerException - if the specified element is null and this list does not support null elements (optional).
\ No newline at end of file diff --git a/java/java-tests/testData/codeInsight/javadocIG/documentationForJdkClassWithReferencesToClassesFromJavaLang.java b/java/java-tests/testData/codeInsight/javadocIG/documentationForJdkClassWithReferencesToClassesFromJavaLang.java new file mode 100644 index 000000000000..47d9f53041d4 --- /dev/null +++ b/java/java-tests/testData/codeInsight/javadocIG/documentationForJdkClassWithReferencesToClassesFromJavaLang.java @@ -0,0 +1,6 @@ +class C { + { + java.util.List l = null; + l.contains(null); + } +} \ No newline at end of file diff --git a/java/java-tests/testData/inspection/magic/withLibrary/expected.xml b/java/java-tests/testData/inspection/magic/withLibrary/expected.xml new file mode 100644 index 000000000000..33405f685a37 --- /dev/null +++ b/java/java-tests/testData/inspection/magic/withLibrary/expected.xml @@ -0,0 +1,9 @@ + + + + X.java + 23 + Magic Constant + Should be one of: WindowConstants.DO_NOTHING_ON_CLOSE, WindowConstants.HIDE_ON_CLOSE, WindowConstants.DISPOSE_ON_CLOSE, WindowConstants.EXIT_ON_CLOSE + + diff --git a/platform/platform-impl/src/com/intellij/openapi/diff/impl/highlighting/TornLineParams.java b/java/java-tests/testData/inspection/magic/withLibrary/src/X.java similarity index 62% rename from platform/platform-impl/src/com/intellij/openapi/diff/impl/highlighting/TornLineParams.java rename to java/java-tests/testData/inspection/magic/withLibrary/src/X.java index 50966c7bc5aa..6ebaa13e932e 100644 --- a/platform/platform-impl/src/com/intellij/openapi/diff/impl/highlighting/TornLineParams.java +++ b/java/java-tests/testData/inspection/magic/withLibrary/src/X.java @@ -13,15 +13,17 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.intellij.openapi.diff.impl.highlighting; +import org.intellij.lang.annotations.MagicConstant; -/** - * Created by IntelliJ IDEA. - * User: Irina.Chernushina - * Date: 10/13/11 - * Time: 1:57 PM - */ -public class TornLineParams { - public static final int ourDark = 3; - public static final int ourLight = 2; +import java.awt.*; +import javax.swing.*; + +public class X { + void f(JFrame frame) { + frame.setDefaultCloseOperation(2); // there is beanInfo in in JFrame.java, have to parse (but added to exceptions, so ok) + } + + void f(Frame frame) { + frame.setState(2); // no beanInfo in Frame.java, no need to parse + } } diff --git a/java/java-tests/testData/refactoring/inlineConstantField/FinalInitializedInConstructor.java b/java/java-tests/testData/refactoring/inlineConstantField/FinalInitializedInConstructor.java new file mode 100644 index 000000000000..e6a688ee7334 --- /dev/null +++ b/java/java-tests/testData/refactoring/inlineConstantField/FinalInitializedInConstructor.java @@ -0,0 +1,15 @@ +class Test { + private final int i; + + public Test() { + this.i = 0; + } + + public Test(String s) { + this.i = 0; + } + + void foo() { + System.out.println(i); + } +} \ No newline at end of file diff --git a/java/java-tests/testData/refactoring/inlineConstantField/FinalInitializedInConstructor.java.after b/java/java-tests/testData/refactoring/inlineConstantField/FinalInitializedInConstructor.java.after new file mode 100644 index 000000000000..3e5d3b37d9fd --- /dev/null +++ b/java/java-tests/testData/refactoring/inlineConstantField/FinalInitializedInConstructor.java.after @@ -0,0 +1,12 @@ +class Test { + + public Test() { + } + + public Test(String s) { + } + + void foo() { + System.out.println(0); + } +} \ No newline at end of file diff --git a/java/java-tests/testData/refactoring/inlineConstantField/MultipleInitializers.java b/java/java-tests/testData/refactoring/inlineConstantField/MultipleInitializers.java new file mode 100644 index 000000000000..b24c9e0cb217 --- /dev/null +++ b/java/java-tests/testData/refactoring/inlineConstantField/MultipleInitializers.java @@ -0,0 +1,15 @@ +class Test { + private final int i; + + public Test() { + this.i = 0; + } + + public Test(String s) { + this.i = s.length(); + } + + void foo() { + System.out.println(i); + } +} \ No newline at end of file diff --git a/java/java-tests/testData/refactoring/inlineMethod/DeleteOverrideAnnotations.java b/java/java-tests/testData/refactoring/inlineMethod/DeleteOverrideAnnotations.java index 47b425b4a6f0..dd1e04e6d905 100644 --- a/java/java-tests/testData/refactoring/inlineMethod/DeleteOverrideAnnotations.java +++ b/java/java-tests/testData/refactoring/inlineMethod/DeleteOverrideAnnotations.java @@ -9,4 +9,9 @@ class B extends A { void err() { super.foo(); } +} + +class C extends B { + @Override + void foo() {} } \ No newline at end of file diff --git a/java/java-tests/testData/refactoring/inlineMethod/DeleteOverrideAnnotations.java.after b/java/java-tests/testData/refactoring/inlineMethod/DeleteOverrideAnnotations.java.after index ef93f313b810..eac5af8b33db 100644 --- a/java/java-tests/testData/refactoring/inlineMethod/DeleteOverrideAnnotations.java.after +++ b/java/java-tests/testData/refactoring/inlineMethod/DeleteOverrideAnnotations.java.after @@ -6,4 +6,9 @@ class B extends A { void err() { } +} + +class C extends B { + @Override + void foo() {} } \ No newline at end of file diff --git a/java/java-tests/testData/refactoring/inlineMethod/InaccessibleFieldInSuperClass.java b/java/java-tests/testData/refactoring/inlineMethod/InaccessibleFieldInSuperClass.java new file mode 100644 index 000000000000..999b632ec6bd --- /dev/null +++ b/java/java-tests/testData/refactoring/inlineMethod/InaccessibleFieldInSuperClass.java @@ -0,0 +1,13 @@ +class A { + private Integer i = 0; + + void foo() { + i.toString(); + } +} + +class B extends A { + void bar() { + foo(); + } +} \ No newline at end of file diff --git a/java/java-tests/testData/refactoring/inlineMethod/PrivateFieldInSuperClassInSameFile.java b/java/java-tests/testData/refactoring/inlineMethod/PrivateFieldInSuperClassInSameFile.java new file mode 100644 index 000000000000..7c06e74c205d --- /dev/null +++ b/java/java-tests/testData/refactoring/inlineMethod/PrivateFieldInSuperClassInSameFile.java @@ -0,0 +1,15 @@ +class Test { + class A { + private Integer i = 0; + + void foo() { + i.toString(); + } + } + + class B extends A { + void bar(A a) { + a.foo(); + } + } +} \ No newline at end of file diff --git a/java/java-tests/testData/refactoring/inlineMethod/PrivateFieldInSuperClassInSameFile.java.after b/java/java-tests/testData/refactoring/inlineMethod/PrivateFieldInSuperClassInSameFile.java.after new file mode 100644 index 000000000000..1cf60987e1d2 --- /dev/null +++ b/java/java-tests/testData/refactoring/inlineMethod/PrivateFieldInSuperClassInSameFile.java.after @@ -0,0 +1,12 @@ +class Test { + class A { + private Integer i = 0; + + } + + class B extends A { + void bar(A a) { + a.i.toString(); + } + } +} \ No newline at end of file diff --git a/java/java-tests/testData/refactoring/introduceConstant/ArrayFromVarargs_after.java b/java/java-tests/testData/refactoring/introduceConstant/ArrayFromVarargs_after.java index 3e28acac4964..931572a4ae72 100644 --- a/java/java-tests/testData/refactoring/introduceConstant/ArrayFromVarargs_after.java +++ b/java/java-tests/testData/refactoring/introduceConstant/ArrayFromVarargs_after.java @@ -2,7 +2,7 @@ class B1 { public B1(int i, String... s) {} } class A1 extends B1 { - public static final String[] xxx = new String[]{"a", "b"}; + public static final String[] xxx = {"a", "b"}; A1() { super(1, xxx); diff --git a/java/java-tests/testData/refactoring/introduceVariable/ParenthizedOccurence1.after.java b/java/java-tests/testData/refactoring/introduceVariable/ParenthizedOccurence1.after.java index b58aaf72e530..7adb962b4cdb 100644 --- a/java/java-tests/testData/refactoring/introduceVariable/ParenthizedOccurence1.after.java +++ b/java/java-tests/testData/refactoring/introduceVariable/ParenthizedOccurence1.after.java @@ -1,5 +1,5 @@ public class Introduce { void foo(String str) { - final String s = (String) str; + final String s = str; } } \ No newline at end of file diff --git a/java/java-tests/testSrc/com/intellij/codeInsight/daemon/lambda/ChangeSignatureTouchLambdaTest.java b/java/java-tests/testSrc/com/intellij/codeInsight/daemon/lambda/ChangeSignatureTouchLambdaTest.java index 720cfdbbb31b..cdfb5a39a4e1 100644 --- a/java/java-tests/testSrc/com/intellij/codeInsight/daemon/lambda/ChangeSignatureTouchLambdaTest.java +++ b/java/java-tests/testSrc/com/intellij/codeInsight/daemon/lambda/ChangeSignatureTouchLambdaTest.java @@ -15,10 +15,12 @@ */ package com.intellij.codeInsight.daemon.lambda; +import com.intellij.openapi.projectRoots.Sdk; import com.intellij.psi.PsiType; import com.intellij.refactoring.ChangeSignatureBaseTest; import com.intellij.refactoring.changeSignature.ParameterInfoImpl; import com.intellij.refactoring.changeSignature.ThrownExceptionInfo; +import com.intellij.testFramework.IdeaTestUtil; public class ChangeSignatureTouchLambdaTest extends ChangeSignatureBaseTest { @@ -38,8 +40,21 @@ public class ChangeSignatureTouchLambdaTest extends ChangeSignatureBaseTest { doTest(null, null, null, new ParameterInfoImpl[] {new ParameterInfoImpl(-1, "b", PsiType.BOOLEAN, "false")}, new ThrownExceptionInfo[0], true); } + public void testAddExceptionToCatchInOneLineLambda() throws Exception { + doTest(null, null, new String[] {"java.io.IOException"}, false); + } + + public void testAddUncheckedExceptionInMethodRef() throws Exception { + doTest(null, null, new String[] {"java.lang.NullPointerException"}, false); + } + @Override protected String getRelativePath() { return "/codeInsight/daemonCodeAnalyzer/lambda/changeSignature/"; } + + @Override + protected Sdk getProjectJDK() { + return IdeaTestUtil.getMockJdk18(); + } } diff --git a/java/java-tests/testSrc/com/intellij/codeInsight/daemon/lambda/Java8ExpressionsCheckTest.java b/java/java-tests/testSrc/com/intellij/codeInsight/daemon/lambda/Java8ExpressionsCheckTest.java index 2dd5c03a7553..0bf7155a2e65 100644 --- a/java/java-tests/testSrc/com/intellij/codeInsight/daemon/lambda/Java8ExpressionsCheckTest.java +++ b/java/java-tests/testSrc/com/intellij/codeInsight/daemon/lambda/Java8ExpressionsCheckTest.java @@ -79,6 +79,10 @@ public class Java8ExpressionsCheckTest extends LightDaemonAnalyzerTestCase { doTestAllMethodCallExpressions(); } + public void testObjectOverloadsWithDiamondsOverMultipleConstructors() throws Exception { + doTestAllMethodCallExpressions(); + } + public void testNonCachingFolding() throws Exception { final String filePath = BASE_PATH + "/" + getTestName(false) + ".java"; configureByFile(filePath); @@ -149,11 +153,19 @@ public class Java8ExpressionsCheckTest extends LightDaemonAnalyzerTestCase { assertNotNull("Failed inference for: " + expression.getText(), expression.getType()); } - final Collection parameterLists = PsiTreeUtil.findChildrenOfType(getFile(), PsiReferenceParameterList.class); - for (PsiReferenceParameterList list : parameterLists) { + final Collection parameterLists = PsiTreeUtil.findChildrenOfType(getFile(), PsiNewExpression.class); + for (PsiNewExpression newExpression : parameterLists) { getPsiManager().dropResolveCaches(); - final PsiType[] arguments = list.getTypeArguments(); - assertNotNull("Failed inference for: " + list.getParent().getText(), arguments); + final PsiType[] arguments = newExpression.getTypeArguments(); + String failMessage = "Failed inference for: " + newExpression.getParent().getText(); + assertNotNull(failMessage, arguments); + PsiDiamondType diamondType = PsiDiamondType.getDiamondType(newExpression); + if (diamondType != null) { + JavaResolveResult staticFactory = diamondType.getStaticFactory(); + assertNotNull(staticFactory); + assertTrue(staticFactory instanceof MethodCandidateInfo); + assertNull(failMessage, ((MethodCandidateInfo)staticFactory).getInferenceErrorMessage()); + } } } diff --git a/java/java-tests/testSrc/com/intellij/codeInsight/daemon/lambda/LambdaRedundantCastTest.java b/java/java-tests/testSrc/com/intellij/codeInsight/daemon/lambda/LambdaRedundantCastTest.java index c8eefc0511fd..bb6a9c97548d 100644 --- a/java/java-tests/testSrc/com/intellij/codeInsight/daemon/lambda/LambdaRedundantCastTest.java +++ b/java/java-tests/testSrc/com/intellij/codeInsight/daemon/lambda/LambdaRedundantCastTest.java @@ -81,6 +81,10 @@ public class LambdaRedundantCastTest extends LightDaemonAnalyzerTestCase { public void testInvalidResolveWithoutCast() { doTest();} + public void testRejectReturnTypeChange() throws Exception { + doTest(); + } + private void doTest() { doTest(BASE_PATH + "/" + getTestName(false) + ".java", true, false); } diff --git a/java/java-tests/testSrc/com/intellij/codeInsight/intention/CopyAbstractMethodImplementationTest.java b/java/java-tests/testSrc/com/intellij/codeInsight/intention/CopyAbstractMethodImplementationTest.java index b00f9ad44e87..1366316f3ee8 100644 --- a/java/java-tests/testSrc/com/intellij/codeInsight/intention/CopyAbstractMethodImplementationTest.java +++ b/java/java-tests/testSrc/com/intellij/codeInsight/intention/CopyAbstractMethodImplementationTest.java @@ -1,6 +1,7 @@ package com.intellij.codeInsight.intention; import com.intellij.codeInsight.daemon.LightIntentionActionTestCase; +import com.intellij.pom.java.LanguageLevel; import com.intellij.psi.codeStyle.CodeStyleSettings; import com.intellij.psi.codeStyle.CodeStyleSettingsManager; @@ -30,4 +31,9 @@ public class CopyAbstractMethodImplementationTest extends LightIntentionActionTe public void test() throws Exception { doAllTests(); } + + @Override + protected LanguageLevel getLanguageLevel() { + return LanguageLevel.JDK_1_6; + } } diff --git a/java/java-tests/testSrc/com/intellij/codeInsight/intention/ImplementAbstractMethodActionTest.java b/java/java-tests/testSrc/com/intellij/codeInsight/intention/ImplementAbstractMethodActionTest.java new file mode 100644 index 000000000000..471f743e35e6 --- /dev/null +++ b/java/java-tests/testSrc/com/intellij/codeInsight/intention/ImplementAbstractMethodActionTest.java @@ -0,0 +1,30 @@ +/* + * Copyright 2000-2016 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.codeInsight.intention; + +import com.intellij.codeInsight.daemon.LightIntentionActionTestCase; + +public class ImplementAbstractMethodActionTest extends LightIntentionActionTestCase { + @Override + protected String getBasePath() { + return "/codeInsight/daemonCodeAnalyzer/quickFix/implementAbstractMethod"; + } + + public void test() throws Exception { + doAllTests(); + } + +} diff --git a/java/java-tests/testSrc/com/intellij/codeInsight/javadoc/JavaDocInfoGeneratorTest.java b/java/java-tests/testSrc/com/intellij/codeInsight/javadoc/JavaDocInfoGeneratorTest.java index 39e0a7267b92..3f2247e108e9 100644 --- a/java/java-tests/testSrc/com/intellij/codeInsight/javadoc/JavaDocInfoGeneratorTest.java +++ b/java/java-tests/testSrc/com/intellij/codeInsight/javadoc/JavaDocInfoGeneratorTest.java @@ -45,6 +45,8 @@ import java.util.List; * @author yole */ public class JavaDocInfoGeneratorTest extends CodeInsightTestCase { + private static final String TEST_DATA_FOLDER = "/codeInsight/javadocIG/"; + private boolean myUseJava8Sdk; public void testSimpleField() throws Exception { @@ -194,7 +196,7 @@ public class JavaDocInfoGeneratorTest extends CodeInsightTestCase { } private static String exampleHtmlFileText(String name) throws IOException { - final File htmlPath = new File(JavaTestUtil.getJavaTestDataPath() + "/codeInsight/javadocIG/" + name + ".html"); + final File htmlPath = new File(JavaTestUtil.getJavaTestDataPath() + TEST_DATA_FOLDER + name + ".html"); return StringUtil.convertLineSeparators(FileUtil.loadFile(htmlPath).trim()); } @@ -234,7 +236,7 @@ public class JavaDocInfoGeneratorTest extends CodeInsightTestCase { } private PsiClass getTestClass() throws Exception{ - configureByFile("/codeInsight/javadocIG/" + getTestName(true) + ".java"); + configureByFile(); return ((PsiJavaFile)myFile).getClasses() [0]; } @@ -249,7 +251,7 @@ public class JavaDocInfoGeneratorTest extends CodeInsightTestCase { } public void testPackageInfo() throws Exception { - final String path = JavaTestUtil.getJavaTestDataPath() + "/codeInsight/javadocIG/"; + final String path = JavaTestUtil.getJavaTestDataPath() + TEST_DATA_FOLDER; final String packageInfo = path + getTestName(true); PsiTestUtil.createTestProjectStructure(myProject, myModule, path, myFilesToDelete); final String info = JavaDocInfoGeneratorFactory.create(getProject(), JavaPsiFacade.getInstance(getProject()).findPackage(getTestName(true))).generateDocInfo(null); @@ -267,7 +269,7 @@ public class JavaDocInfoGeneratorTest extends CodeInsightTestCase { } private void doTestPackageInfo(String caretPositionedAt) throws Exception { - final String rootPath = getTestDataPath() + "/codeInsight/javadocIG/"; + final String rootPath = getTestDataPath() + TEST_DATA_FOLDER; VirtualFile root = PsiTestUtil.createTestProjectStructure(myProject, myModule, rootPath, myFilesToDelete); VirtualFile piFile = root.findFileByRelativePath(getTestName(true) + "/package-info.java"); assertNotNull(piFile); @@ -279,7 +281,7 @@ public class JavaDocInfoGeneratorTest extends CodeInsightTestCase { } public void testInheritedParameter() throws Exception { - configureByFile("/codeInsight/javadocIG/" + getTestName(true) + ".java"); + configureByFile(); PsiClass outerClass = ((PsiJavaFile) myFile).getClasses()[0]; PsiClass innerClass = outerClass.findInnerClassByName("Impl", false); assertNotNull(innerClass); @@ -289,7 +291,7 @@ public class JavaDocInfoGeneratorTest extends CodeInsightTestCase { public void testHtmlLink() throws Exception { PsiTestUtil.createTestProjectStructure(myProject, myModule, - getTestDataPath() + "/codeInsight/javadocIG/htmlLinkProject", myFilesToDelete); + getTestDataPath() + TEST_DATA_FOLDER + "htmlLinkProject", myFilesToDelete); verifyJavadocFor("htmlLink"); verifyJavadocFor("pack.htmlLinkDeep"); } @@ -312,7 +314,7 @@ public class JavaDocInfoGeneratorTest extends CodeInsightTestCase { public void testHtmlLinkToPackageInfo() throws Exception { PsiTestUtil.createTestProjectStructure(myProject, myModule, - getTestDataPath() + "/codeInsight/javadocIG/htmlLinkToPackageInfo", myFilesToDelete); + getTestDataPath() + TEST_DATA_FOLDER + "htmlLinkToPackageInfo", myFilesToDelete); verifyJavadocFor("pack.A"); } @@ -327,14 +329,14 @@ public class JavaDocInfoGeneratorTest extends CodeInsightTestCase { } public void testMatchingParameterNameFromParent() throws Exception { - configureByFile("/codeInsight/javadocIG/" + getTestName(true) + ".java"); + configureByFile(); PsiClass psiClass = ((PsiJavaFile)myFile).getClasses()[1]; PsiMethod method = psiClass.getMethods()[0]; verifyJavaDoc(method); } public void testMatchingTypeParameterNameFromParent() throws Exception { - configureByFile("/codeInsight/javadocIG/" + getTestName(true) + ".java"); + configureByFile(); PsiClass psiClass = ((PsiJavaFile)myFile).getClasses()[1]; PsiMethod method = psiClass.getMethods()[0]; verifyJavaDoc(method); @@ -345,7 +347,22 @@ public class JavaDocInfoGeneratorTest extends CodeInsightTestCase { assertNotNull(aClass); verifyJavaDoc(aClass, Collections.singletonList("dummyUrl")); } - + + public void testDocumentationForJdkClassWithReferencesToClassesFromJavaLang() throws Exception { + doTestAtCaret(); + } + + private void doTestAtCaret() throws Exception { + configureByFile(); + String docInfo = JavaExternalDocumentationTest.getDocumentationText(myFile, myEditor.getCaretModel().getOffset()); + assertNotNull(docInfo); + assertEquals(exampleHtmlFileText(getTestName(true)), replaceEnvironmentDependentContent(docInfo)); + } + + private void configureByFile() throws Exception { + configureByFile(TEST_DATA_FOLDER + getTestName(true) + ".java"); + } + public void testLibraryPackageDocumentation() throws Exception { final VirtualFile libClasses = JavaExternalDocumentationTest.getJarFile("library.jar"); final VirtualFile libSources = JavaExternalDocumentationTest.getJarFile("library-src.jar"); diff --git a/java/java-tests/testSrc/com/intellij/codeInspection/MagicConstantInspectionTest.java b/java/java-tests/testSrc/com/intellij/codeInspection/MagicConstantInspectionTest.java index 3d309cecc51f..7cf6062df848 100644 --- a/java/java-tests/testSrc/com/intellij/codeInspection/MagicConstantInspectionTest.java +++ b/java/java-tests/testSrc/com/intellij/codeInspection/MagicConstantInspectionTest.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2011 JetBrains s.r.o. + * Copyright 2000-2016 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. @@ -28,15 +28,38 @@ import com.intellij.JavaTestUtil; import com.intellij.codeInspection.ex.LocalInspectionToolWrapper; import com.intellij.codeInspection.magicConstant.MagicConstantInspection; import com.intellij.openapi.projectRoots.Sdk; +import com.intellij.openapi.vfs.LocalFileSystem; +import com.intellij.openapi.vfs.VfsUtilCore; +import com.intellij.openapi.vfs.VirtualFile; +import com.intellij.openapi.vfs.VirtualFileVisitor; +import com.intellij.psi.JavaPsiFacade; +import com.intellij.psi.PsiClass; +import com.intellij.psi.impl.PsiManagerEx; +import com.intellij.psi.impl.source.PsiClassImpl; +import com.intellij.psi.search.GlobalSearchScope; +import com.intellij.testFramework.FileTreeAccessFilter; import com.intellij.testFramework.InspectionTestCase; import com.intellij.testFramework.PsiTestUtil; +import org.jetbrains.annotations.NotNull; + +import java.io.File; public class MagicConstantInspectionTest extends InspectionTestCase { + + private FileTreeAccessFilter myFilter; + @Override protected String getTestDataPath() { return JavaTestUtil.getJavaTestDataPath() + "/inspection"; } + @Override + protected void setUp() throws Exception { + super.setUp(); + myFilter = new FileTreeAccessFilter(); + PsiManagerEx.getInstanceEx(getProject()).setAssertOnFileLoadingFilter(myFilter, myTestRootDisposable); + } + @Override protected Sdk getTestProjectSdk() { return PsiTestUtil.addJdkAnnotations(super.getTestProjectSdk()); @@ -46,5 +69,27 @@ public class MagicConstantInspectionTest extends InspectionTestCase { doTest("magic/" + getTestName(true), new LocalInspectionToolWrapper(new MagicConstantInspection()), "jdk 1.7"); } + @Override + protected void setupRootModel(@NotNull String testDir, @NotNull VirtualFile[] sourceDir, String sdkName) { + super.setupRootModel(testDir, sourceDir, sdkName); + VirtualFile projectDir = LocalFileSystem.getInstance().refreshAndFindFileByIoFile(new File(testDir)); + // allow to load AST for all files to highlight + VfsUtilCore.visitChildrenRecursively(projectDir, new VirtualFileVisitor() { + @Override + public boolean visitFile(@NotNull VirtualFile v) { + myFilter.allowTreeAccessForFile(v); + return super.visitFile(v); + } + }); + // and JFrame + PsiClass cls = JavaPsiFacade.getInstance(getProject()).findClass("javax.swing.JFrame", GlobalSearchScope.allScope(getProject())); + PsiClass aClass = (PsiClass)cls.getNavigationElement(); + assertTrue(aClass instanceof PsiClassImpl); // must to have sources + + myFilter.allowTreeAccessForFile(aClass.getContainingFile().getVirtualFile()); + } + public void testSimple() throws Exception { doTest(); } + // test that the optimisation for not loading AST works + public void testWithLibrary() throws Exception { doTest(); } } diff --git a/java/java-tests/testSrc/com/intellij/codeInspection/NullableStuffInspectionAncientTest.java b/java/java-tests/testSrc/com/intellij/codeInspection/NullableStuffInspectionAncientTest.java index e1e7a3b13bc5..79c36144385b 100644 --- a/java/java-tests/testSrc/com/intellij/codeInspection/NullableStuffInspectionAncientTest.java +++ b/java/java-tests/testSrc/com/intellij/codeInspection/NullableStuffInspectionAncientTest.java @@ -1,3 +1,19 @@ +/* + * Copyright 2000-2016 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. + */ + /* * Created by IntelliJ IDEA. * User: Alexey @@ -17,6 +33,7 @@ import com.intellij.openapi.roots.OrderRootType; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.testFramework.InspectionTestCase; import com.intellij.testFramework.PsiTestUtil; +import org.jetbrains.annotations.NotNull; public class NullableStuffInspectionAncientTest extends InspectionTestCase { private final NullableStuffInspection myInspection = new NullableStuffInspection(); @@ -38,7 +55,7 @@ public class NullableStuffInspectionAncientTest extends InspectionTestCase { } @Override - protected void setupRootModel(String testDir, VirtualFile[] sourceDir, String sdkName) { + protected void setupRootModel(@NotNull String testDir, @NotNull VirtualFile[] sourceDir, String sdkName) { super.setupRootModel(testDir, sourceDir, sdkName); Sdk sdk = ModuleRootManager.getInstance(myModule).getSdk(); removeAnnotationsJar(sdk); diff --git a/java/java-tests/testSrc/com/intellij/codeInspection/TestOnlyInspectionTest.java b/java/java-tests/testSrc/com/intellij/codeInspection/TestOnlyInspectionTest.java index 1a116d820520..ec5179738ba8 100644 --- a/java/java-tests/testSrc/com/intellij/codeInspection/TestOnlyInspectionTest.java +++ b/java/java-tests/testSrc/com/intellij/codeInspection/TestOnlyInspectionTest.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2015 JetBrains s.r.o. + * Copyright 2000-2016 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. @@ -26,7 +26,7 @@ import org.jetbrains.annotations.NotNull; public class TestOnlyInspectionTest extends InspectionTestCase { @Override - protected void setupRootModel(String testDir, VirtualFile[] sourceDir, String jdkName) { + protected void setupRootModel(@NotNull String testDir, @NotNull VirtualFile[] sourceDir, String jdkName) { super.setupRootModel(testDir, sourceDir, jdkName); VirtualFile projectDir = LocalFileSystem.getInstance().findFileByPath(testDir); assertNotNull(projectDir); diff --git a/java/java-tests/testSrc/com/intellij/codeInspection/UnknownGuardInspectionTest.java b/java/java-tests/testSrc/com/intellij/codeInspection/UnknownGuardInspectionTest.java index 5d6a46115e00..56201807523e 100644 --- a/java/java-tests/testSrc/com/intellij/codeInspection/UnknownGuardInspectionTest.java +++ b/java/java-tests/testSrc/com/intellij/codeInspection/UnknownGuardInspectionTest.java @@ -14,9 +14,9 @@ * limitations under the License. */ -/** - * (c) 2016 Silent Forest AB - * created: 18 March 2016 +/* + (c) 2016 Silent Forest AB + created: 18 March 2016 */ package com.intellij.codeInspection; diff --git a/java/java-tests/testSrc/com/intellij/codeInspection/UnusedLibraryInspectionTest.java b/java/java-tests/testSrc/com/intellij/codeInspection/UnusedLibraryInspectionTest.java index a06593a2f9cd..c64ceee52e53 100644 --- a/java/java-tests/testSrc/com/intellij/codeInspection/UnusedLibraryInspectionTest.java +++ b/java/java-tests/testSrc/com/intellij/codeInspection/UnusedLibraryInspectionTest.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2014 JetBrains s.r.o. + * Copyright 2000-2016 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. @@ -26,17 +26,9 @@ package com.intellij.codeInspection; import com.intellij.JavaTestUtil; import com.intellij.analysis.AnalysisScope; -import com.intellij.codeInspection.ex.LocalInspectionToolWrapper; -import com.intellij.codeInspection.magicConstant.MagicConstantInspection; import com.intellij.codeInspection.unusedLibraries.UnusedLibrariesInspection; -import com.intellij.openapi.projectRoots.Sdk; -import com.intellij.openapi.projectRoots.SdkModificator; -import com.intellij.openapi.roots.AnnotationOrderRootType; -import com.intellij.openapi.util.io.FileUtil; -import com.intellij.openapi.vfs.LocalFileSystem; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.testFramework.InspectionTestCase; -import com.intellij.testFramework.PlatformTestUtil; import com.intellij.testFramework.PsiTestUtil; import org.jetbrains.annotations.NotNull; @@ -47,7 +39,7 @@ public class UnusedLibraryInspectionTest extends InspectionTestCase { } @Override - protected void setupRootModel(String testDir, VirtualFile[] sourceDir, String sdkName) { + protected void setupRootModel(@NotNull String testDir, @NotNull VirtualFile[] sourceDir, String sdkName) { super.setupRootModel(testDir, sourceDir, sdkName); PsiTestUtil.addLibrary(getModule(), "JUnit", getTestDataPath(), "/junit.jar"); } diff --git a/java/java-tests/testSrc/com/intellij/psi/ModifyAnnotationsTest.java b/java/java-tests/testSrc/com/intellij/psi/ModifyAnnotationsTest.java index e4f8b59403ab..a2fbbf3e65df 100644 --- a/java/java-tests/testSrc/com/intellij/psi/ModifyAnnotationsTest.java +++ b/java/java-tests/testSrc/com/intellij/psi/ModifyAnnotationsTest.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2013 JetBrains s.r.o. + * Copyright 2000-2016 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. @@ -19,6 +19,7 @@ import com.intellij.JavaTestUtil; import com.intellij.openapi.command.CommandProcessor; import com.intellij.openapi.command.WriteCommandAction; import com.intellij.openapi.vfs.VirtualFileFilter; +import com.intellij.psi.impl.PsiManagerEx; import com.intellij.psi.search.GlobalSearchScope; import com.intellij.testFramework.IdeaTestUtil; import com.intellij.testFramework.PsiTestCase; @@ -40,7 +41,7 @@ public class ModifyAnnotationsTest extends PsiTestCase { public void testReplaceAnnotation() throws Exception { //be sure not to load tree - getJavaFacade().setAssertOnFileLoadingFilter(VirtualFileFilter.ALL, myTestRootDisposable); + PsiManagerEx.getInstanceEx(getProject()).setAssertOnFileLoadingFilter(VirtualFileFilter.ALL, myTestRootDisposable); PsiClass aClass = myJavaFacade.findClass("Test", GlobalSearchScope.allScope(myProject)); assertNotNull(aClass); final PsiAnnotation[] annotations = aClass.getModifierList().getAnnotations(); @@ -48,7 +49,7 @@ public class ModifyAnnotationsTest extends PsiTestCase { assertEquals("A", annotations[0].getNameReferenceElement().getReferenceName()); final PsiAnnotation newAnnotation = myJavaFacade.getElementFactory().createAnnotationFromText("@B", null); //here the tree is going to be loaded - getJavaFacade().setAssertOnFileLoadingFilter(VirtualFileFilter.NONE, myTestRootDisposable); + PsiManagerEx.getInstanceEx(getProject()).setAssertOnFileLoadingFilter(VirtualFileFilter.NONE, myTestRootDisposable); CommandProcessor.getInstance().executeCommand(myProject, new Runnable() { @Override public void run() { diff --git a/java/java-tests/testSrc/com/intellij/psi/PsiModificationTrackerTest.java b/java/java-tests/testSrc/com/intellij/psi/PsiModificationTrackerTest.java index 6d1d9e3f9043..0eb5e71d0f59 100644 --- a/java/java-tests/testSrc/com/intellij/psi/PsiModificationTrackerTest.java +++ b/java/java-tests/testSrc/com/intellij/psi/PsiModificationTrackerTest.java @@ -247,7 +247,7 @@ public class PsiModificationTrackerTest extends CodeInsightTestCase { // gc softly-referenced file and AST PlatformTestUtil.tryGcSoftlyReachableObjects(); - final PsiManagerEx psiManager = (PsiManagerEx)PsiManager.getInstance(getProject()); + final PsiManagerEx psiManager = PsiManagerEx.getInstanceEx(getProject()); assertNull(psiManager.getFileManager().getCachedPsiFile(file)); assertFalse(count1 == tracker.getJavaStructureModificationCount()); @@ -257,7 +257,7 @@ public class PsiModificationTrackerTest extends CodeInsightTestCase { public void testClassShouldNotDisappearWithoutEvents_NoDocument() throws IOException { PsiModificationTracker tracker = PsiManager.getInstance(getProject()).getModificationTracker(); - final PsiManagerEx psiManager = (PsiManagerEx)PsiManager.getInstance(getProject()); + final PsiManagerEx psiManager = PsiManagerEx.getInstanceEx(getProject()); final VirtualFile file = addFileToProject("Foo.java", "class Foo {}").getVirtualFile(); assertNotNull(JavaPsiFacade.getInstance(getProject()).findClass("Foo", GlobalSearchScope.allScope(getProject()))); @@ -279,7 +279,7 @@ public class PsiModificationTrackerTest extends CodeInsightTestCase { PsiModificationTracker tracker = PsiManager.getInstance(getProject()).getModificationTracker(); long count0 = tracker.getJavaStructureModificationCount(); - final PsiManagerEx psiManager = (PsiManagerEx)PsiManager.getInstance(getProject()); + final PsiManagerEx psiManager = PsiManagerEx.getInstanceEx(getProject()); VirtualFile parentDir = createChildDirectory(getProject().getBaseDir(), "tmp"); assertNull(((FileManagerImpl)psiManager.getFileManager()).getCachedDirectory(parentDir)); @@ -296,7 +296,7 @@ public class PsiModificationTrackerTest extends CodeInsightTestCase { PsiModificationTracker tracker = PsiManager.getInstance(getProject()).getModificationTracker(); long count0 = tracker.getJavaStructureModificationCount(); - final PsiManagerEx psiManager = (PsiManagerEx)PsiManager.getInstance(getProject()); + final PsiManagerEx psiManager = PsiManagerEx.getInstanceEx(getProject()); VirtualFile parentDir = LocalFileSystem.getInstance().refreshAndFindFileByIoFile(createTempDirectory()); assertNull(((FileManagerImpl)psiManager.getFileManager()).getCachedDirectory(parentDir)); @@ -310,7 +310,7 @@ public class PsiModificationTrackerTest extends CodeInsightTestCase { public void testClassShouldNotDisappearWithoutEvents_VirtualFileDeleted() throws IOException { PsiModificationTracker tracker = PsiManager.getInstance(getProject()).getModificationTracker(); - final PsiManagerEx psiManager = (PsiManagerEx)PsiManager.getInstance(getProject()); + final PsiManagerEx psiManager = PsiManagerEx.getInstanceEx(getProject()); final VirtualFile file = addFileToProject("Foo.java", "class Foo {}").getVirtualFile(); assertNotNull(JavaPsiFacade.getInstance(getProject()).findClass("Foo", GlobalSearchScope.allScope(getProject()))); @@ -328,7 +328,7 @@ public class PsiModificationTrackerTest extends CodeInsightTestCase { public void testClassShouldNotDisappearWithoutEvents_ParentVirtualDirectoryDeleted() throws Exception { PsiModificationTracker tracker = PsiManager.getInstance(getProject()).getModificationTracker(); - final PsiManagerEx psiManager = (PsiManagerEx)PsiManager.getInstance(getProject()); + final PsiManagerEx psiManager = PsiManagerEx.getInstanceEx(getProject()); final VirtualFile file = addFileToProject("foo/Foo.java", "package foo; class Foo {}").getVirtualFile(); assertNotNull(JavaPsiFacade.getInstance(getProject()).findClass("foo.Foo", GlobalSearchScope.allScope(getProject()))); @@ -347,7 +347,7 @@ public class PsiModificationTrackerTest extends CodeInsightTestCase { public void testVirtualFileRename_WithPsi() throws IOException { PsiModificationTracker tracker = PsiManager.getInstance(getProject()).getModificationTracker(); - final PsiManagerEx psiManager = (PsiManagerEx)PsiManager.getInstance(getProject()); + final PsiManagerEx psiManager = PsiManagerEx.getInstanceEx(getProject()); GlobalSearchScope scope = GlobalSearchScope.allScope(getProject()); final VirtualFile file = addFileToProject("foo/Foo.java", "package foo; class Foo {}").getVirtualFile(); diff --git a/java/java-tests/testSrc/com/intellij/psi/Src15RepositoryUseTest.java b/java/java-tests/testSrc/com/intellij/psi/Src15RepositoryUseTest.java index be6000658221..7a1577548608 100644 --- a/java/java-tests/testSrc/com/intellij/psi/Src15RepositoryUseTest.java +++ b/java/java-tests/testSrc/com/intellij/psi/Src15RepositoryUseTest.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2012 JetBrains s.r.o. + * Copyright 2000-2016 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. @@ -16,11 +16,11 @@ package com.intellij.psi; import com.intellij.openapi.application.ex.PathManagerEx; -import com.intellij.openapi.projectRoots.impl.JavaSdkImpl; import com.intellij.openapi.roots.LanguageLevelProjectExtension; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.openapi.vfs.VirtualFileFilter; import com.intellij.pom.java.LanguageLevel; +import com.intellij.psi.impl.PsiManagerEx; import com.intellij.psi.search.GlobalSearchScope; import com.intellij.psi.search.searches.AnnotatedMembersSearch; import com.intellij.psi.search.searches.AnnotatedPackagesSearch; @@ -294,7 +294,7 @@ public class Src15RepositoryUseTest extends PsiTestCase { } public void testAnnotationIndex() throws Exception { - getJavaFacade().setAssertOnFileLoadingFilter(new VirtualFileFilter() { + PsiManagerEx.getInstanceEx(getProject()).setAssertOnFileLoadingFilter(new VirtualFileFilter() { @Override public boolean accept(final VirtualFile file) { return !"package-info.java".equals(file.getName()); @@ -321,11 +321,11 @@ public class Src15RepositoryUseTest extends PsiTestCase { } private void setupLoadingFilter() { - getJavaFacade().setAssertOnFileLoadingFilter(VirtualFileFilter.ALL, myTestRootDisposable); + PsiManagerEx.getInstanceEx(getProject()).setAssertOnFileLoadingFilter(VirtualFileFilter.ALL, myTestRootDisposable); } private void tearDownLoadingFilter() { - getJavaFacade().setAssertOnFileLoadingFilter(VirtualFileFilter.NONE, myTestRootDisposable); + PsiManagerEx.getInstanceEx(getProject()).setAssertOnFileLoadingFilter(VirtualFileFilter.NONE, myTestRootDisposable); } @NotNull diff --git a/java/java-tests/testSrc/com/intellij/psi/SrcRepositoryUseTest.java b/java/java-tests/testSrc/com/intellij/psi/SrcRepositoryUseTest.java index 98740f83d35e..0627b13693ff 100644 --- a/java/java-tests/testSrc/com/intellij/psi/SrcRepositoryUseTest.java +++ b/java/java-tests/testSrc/com/intellij/psi/SrcRepositoryUseTest.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2015 JetBrains s.r.o. + * Copyright 2000-2016 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. @@ -30,6 +30,7 @@ import com.intellij.openapi.vfs.VfsUtilCore; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.openapi.vfs.VirtualFileFilter; import com.intellij.pom.java.LanguageLevel; +import com.intellij.psi.impl.PsiManagerEx; import com.intellij.psi.impl.source.PsiFileImpl; import com.intellij.psi.impl.source.tree.CompositeElement; import com.intellij.psi.search.GlobalSearchScope; @@ -584,11 +585,11 @@ public class SrcRepositoryUseTest extends PsiTestCase{ } private void teardownLoadingFilter() { - getJavaFacade().setAssertOnFileLoadingFilter(VirtualFileFilter.NONE, myTestRootDisposable); + PsiManagerEx.getInstanceEx(getProject()).setAssertOnFileLoadingFilter(VirtualFileFilter.NONE, myTestRootDisposable); } private void setupLoadingFilter() { - getJavaFacade().setAssertOnFileLoadingFilter(VirtualFileFilter.ALL, myTestRootDisposable); + PsiManagerEx.getInstanceEx(getProject()).setAssertOnFileLoadingFilter(VirtualFileFilter.ALL, myTestRootDisposable); } public void testAnonymousClass2() throws Exception { diff --git a/java/java-tests/testSrc/com/intellij/psi/search/ClassInheritorsTest.java b/java/java-tests/testSrc/com/intellij/psi/search/ClassInheritorsTest.java new file mode 100644 index 000000000000..965809599a48 --- /dev/null +++ b/java/java-tests/testSrc/com/intellij/psi/search/ClassInheritorsTest.java @@ -0,0 +1,52 @@ +/* + * Copyright 2000-2016 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.psi.search; + +import com.intellij.codeInsight.daemon.DaemonAnalyzerTestCase; +import com.intellij.openapi.projectRoots.Sdk; +import com.intellij.psi.PsiClass; +import com.intellij.psi.impl.compiled.ClsClassImpl; +import com.intellij.psi.impl.source.PsiClassImpl; +import com.intellij.psi.search.searches.ClassInheritorsSearch; +import com.intellij.psi.search.searches.DirectClassInheritorsSearch; +import com.intellij.testFramework.IdeaTestUtil; + +import java.util.Collection; +import java.util.HashSet; +import java.util.List; +import java.util.stream.Collectors; + +public class ClassInheritorsTest extends DaemonAnalyzerTestCase { + @Override + protected Sdk getTestProjectJdk() { + // there must be src.zip + return IdeaTestUtil.getMockJdk17("1.7"); + } + + public void testClsAndSourcesDoNotMixUp() { + PsiClass numberClass = getJavaFacade().findClass("java.lang.Number", GlobalSearchScope.allScope(getProject())); + assertTrue(String.valueOf(numberClass), numberClass instanceof ClsClassImpl); + PsiClass n2 = (PsiClass)numberClass.getNavigationElement(); + assertTrue(String.valueOf(n2), n2 instanceof PsiClassImpl); + Collection subClasses = DirectClassInheritorsSearch.search(n2, GlobalSearchScope.allScope(getProject())).findAll(); + List fqn = subClasses.stream().map(PsiClass::getQualifiedName).sorted().collect(Collectors.toList()); + assertEquals(fqn.toString(), fqn.size(), new HashSet<>(fqn).size()); // no dups mean no Cls/Psi mixed + + Collection allSubClasses = ClassInheritorsSearch.search(n2, GlobalSearchScope.allScope(getProject()), true).findAll(); + List allFqn = allSubClasses.stream().map(PsiClass::getQualifiedName).sorted().collect(Collectors.toList()); + assertEquals(allFqn.toString(), allFqn.size(), new HashSet<>(allFqn).size()); + } +} diff --git a/java/java-tests/testSrc/com/intellij/refactoring/MakeClassStaticTest.java b/java/java-tests/testSrc/com/intellij/refactoring/MakeClassStaticTest.java index ba225e2ab864..4ab7b6e5be34 100644 --- a/java/java-tests/testSrc/com/intellij/refactoring/MakeClassStaticTest.java +++ b/java/java-tests/testSrc/com/intellij/refactoring/MakeClassStaticTest.java @@ -1,5 +1,17 @@ -/** - * @author ven +/* + * Copyright 2000-2016 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.refactoring; diff --git a/java/java-tests/testSrc/com/intellij/refactoring/MoveClassAndFileTest.java b/java/java-tests/testSrc/com/intellij/refactoring/MoveClassAndFileTest.java index 44ec8338d5ea..dc3f426ab782 100644 --- a/java/java-tests/testSrc/com/intellij/refactoring/MoveClassAndFileTest.java +++ b/java/java-tests/testSrc/com/intellij/refactoring/MoveClassAndFileTest.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2012 JetBrains s.r.o. + * Copyright 2000-2016 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. @@ -15,11 +15,6 @@ */ package com.intellij.refactoring; -/** - * User: anna - * Date: Aug 31, 2010 - */ - import com.intellij.JavaTestUtil; import com.intellij.openapi.fileEditor.FileDocumentManager; import com.intellij.openapi.vfs.LocalFileSystem; diff --git a/java/java-tests/testSrc/com/intellij/refactoring/inline/InlineConstantFieldTest.java b/java/java-tests/testSrc/com/intellij/refactoring/inline/InlineConstantFieldTest.java index 1f8e2bad2986..d9e1cc2e3e67 100644 --- a/java/java-tests/testSrc/com/intellij/refactoring/inline/InlineConstantFieldTest.java +++ b/java/java-tests/testSrc/com/intellij/refactoring/inline/InlineConstantFieldTest.java @@ -38,15 +38,22 @@ public class InlineConstantFieldTest extends LightRefactoringTestCase { doTest(); } + public void testFinalInitializedInConstructor() throws Exception { + doTest(); + } + + public void testMultipleInitializers() throws Exception { + configureByFile("/refactoring/inlineConstantField/" + getTestName(false) + ".java"); + PsiElement element = TargetElementUtil + .findTargetElement(myEditor, TargetElementUtil.ELEMENT_NAME_ACCEPTED | TargetElementUtil.REFERENCED_ELEMENT_ACCEPTED); + assertTrue(element instanceof PsiField); + assertNull(InlineConstantFieldHandler.getInitializer((PsiField)element)); + } + private void doTest() throws Exception { String name = getTestName(false); @NonNls String fileName = "/refactoring/inlineConstantField/" + name + ".java"; configureByFile(fileName); - performAction(); - checkResultByFile(fileName + ".after"); - } - - private void performAction() { PsiElement element = TargetElementUtil .findTargetElement(myEditor, TargetElementUtil.ELEMENT_NAME_ACCEPTED | TargetElementUtil.REFERENCED_ELEMENT_ACCEPTED); final PsiReference ref = myFile.findReferenceAt(myEditor.getCaretModel().getOffset()); @@ -54,5 +61,6 @@ public class InlineConstantFieldTest extends LightRefactoringTestCase { assertTrue(element instanceof PsiField); PsiField field = (PsiField)element.getNavigationElement(); new InlineConstantFieldProcessor(field, getProject(), refExpr, element instanceof PsiCompiledElement).run(); + checkResultByFile(fileName + ".after"); } } \ No newline at end of file diff --git a/java/java-tests/testSrc/com/intellij/refactoring/inline/InlineMethodTest.java b/java/java-tests/testSrc/com/intellij/refactoring/inline/InlineMethodTest.java index ecffe8d0e407..eceece9ea85d 100644 --- a/java/java-tests/testSrc/com/intellij/refactoring/inline/InlineMethodTest.java +++ b/java/java-tests/testSrc/com/intellij/refactoring/inline/InlineMethodTest.java @@ -316,6 +316,14 @@ public class InlineMethodTest extends LightRefactoringTestCase { doTest(); } + public void testInaccessibleFieldInSuperClass() throws Exception { + doTestConflict("Field A.i that is used in inlined method is not accessible from call site(s) in method B.bar()"); + } + + public void testPrivateFieldInSuperClassInSameFile() throws Exception { + doTest(); + } + private void doTestInlineThisOnly() { @NonNls String fileName = "/refactoring/inlineMethod/" + getTestName(false) + ".java"; configureByFile(fileName); diff --git a/java/testFramework/src/com/intellij/codeInsight/daemon/DaemonAnalyzerTestCase.java b/java/testFramework/src/com/intellij/codeInsight/daemon/DaemonAnalyzerTestCase.java index bcb68177295f..d6649cdcbb11 100644 --- a/java/testFramework/src/com/intellij/codeInsight/daemon/DaemonAnalyzerTestCase.java +++ b/java/testFramework/src/com/intellij/codeInsight/daemon/DaemonAnalyzerTestCase.java @@ -59,7 +59,7 @@ import com.intellij.openapi.util.io.FileUtil; import com.intellij.openapi.vfs.*; import com.intellij.profile.codeInspection.InspectionProjectProfileManager; import com.intellij.psi.*; -import com.intellij.psi.impl.JavaPsiFacadeEx; +import com.intellij.psi.impl.PsiManagerEx; import com.intellij.psi.impl.cache.CacheManager; import com.intellij.psi.impl.search.IndexPatternBuilder; import com.intellij.psi.impl.source.resolve.reference.ReferenceProvidersRegistry; @@ -275,10 +275,7 @@ public abstract class DaemonAnalyzerTestCase extends CodeInsightTestCase { if (!DumbService.isDumb(getProject())) { CacheManager.SERVICE.getInstance(myProject).getFilesWithWord("XXX", UsageSearchContext.IN_COMMENTS, GlobalSearchScope.allScope(myProject), true); } - final JavaPsiFacadeEx facade = getJavaFacade(); - if (facade != null) { - facade.setAssertOnFileLoadingFilter(myVirtualFileFilter, myTestRootDisposable); // check repository work - } + PsiManagerEx.getInstanceEx(getProject()).setAssertOnFileLoadingFilter(myVirtualFileFilter, myTestRootDisposable); try { Collection infos = doHighlighting(); @@ -289,9 +286,7 @@ public abstract class DaemonAnalyzerTestCase extends CodeInsightTestCase { return infos; } finally { - if (facade != null) { - facade.setAssertOnFileLoadingFilter(VirtualFileFilter.NONE, myTestRootDisposable); - } + PsiManagerEx.getInstanceEx(getProject()).setAssertOnFileLoadingFilter(VirtualFileFilter.NONE, myTestRootDisposable); } } diff --git a/java/testFramework/src/com/intellij/codeInsight/daemon/LightDaemonAnalyzerTestCase.java b/java/testFramework/src/com/intellij/codeInsight/daemon/LightDaemonAnalyzerTestCase.java index b8fdd3b15109..e8a63d4eb1cb 100644 --- a/java/testFramework/src/com/intellij/codeInsight/daemon/LightDaemonAnalyzerTestCase.java +++ b/java/testFramework/src/com/intellij/codeInsight/daemon/LightDaemonAnalyzerTestCase.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2015 JetBrains s.r.o. + * Copyright 2000-2016 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. @@ -26,6 +26,7 @@ import com.intellij.openapi.editor.Editor; import com.intellij.openapi.vfs.VirtualFileFilter; import com.intellij.psi.PsiDocumentManager; import com.intellij.psi.PsiFile; +import com.intellij.psi.impl.PsiManagerEx; import com.intellij.testFramework.ExpectedHighlightingData; import com.intellij.testFramework.FileTreeAccessFilter; import com.intellij.testFramework.HighlightTestInfo; @@ -91,7 +92,7 @@ public abstract class LightDaemonAnalyzerTestCase extends LightCodeInsightTestCa } protected void doTestConfiguredFile(boolean checkWarnings, boolean checkWeakWarnings, boolean checkInfos, @Nullable String filePath) { - getJavaFacade().setAssertOnFileLoadingFilter(VirtualFileFilter.NONE, myTestRootDisposable); + PsiManagerEx.getInstanceEx(getProject()).setAssertOnFileLoadingFilter(VirtualFileFilter.NONE, myTestRootDisposable); ExpectedHighlightingData data = getExpectedHighlightingData(checkWarnings, checkWeakWarnings, checkInfos); checkHighlighting(data, composeLocalPath(filePath)); @@ -112,7 +113,7 @@ public abstract class LightDaemonAnalyzerTestCase extends LightCodeInsightTestCa PsiDocumentManager.getInstance(getProject()).commitAllDocuments(); getFile().getText(); //to load text myJavaFilesFilter.allowTreeAccessForFile(getVFile()); - getJavaFacade().setAssertOnFileLoadingFilter(myJavaFilesFilter, myTestRootDisposable); // check repository work + PsiManagerEx.getInstanceEx(getProject()).setAssertOnFileLoadingFilter(myJavaFilesFilter, myTestRootDisposable); try { Collection infos = doHighlighting(); @@ -120,7 +121,7 @@ public abstract class LightDaemonAnalyzerTestCase extends LightCodeInsightTestCa data.checkResult(infos, getEditor().getDocument().getText(), filePath); } finally { - getJavaFacade().setAssertOnFileLoadingFilter(VirtualFileFilter.NONE, myTestRootDisposable); + PsiManagerEx.getInstanceEx(getProject()).setAssertOnFileLoadingFilter(VirtualFileFilter.NONE, myTestRootDisposable); } } diff --git a/java/testFramework/src/com/intellij/testFramework/InspectionTestCase.java b/java/testFramework/src/com/intellij/testFramework/InspectionTestCase.java index 581b96838ac2..bf6fab22bd8d 100644 --- a/java/testFramework/src/com/intellij/testFramework/InspectionTestCase.java +++ b/java/testFramework/src/com/intellij/testFramework/InspectionTestCase.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2015 JetBrains s.r.o. + * Copyright 2000-2016 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. @@ -54,7 +54,7 @@ import java.io.File; * @author max * @since Apr 11, 2002 */ -@SuppressWarnings({"HardCodedStringLiteral"}) +@SuppressWarnings("HardCodedStringLiteral") public abstract class InspectionTestCase extends PsiTestCase { private static final Logger LOG = Logger.getInstance("#com.intellij.testFramework.InspectionTestCase"); private EntryPoint myUnusedCodeExtension; @@ -72,73 +72,70 @@ public abstract class InspectionTestCase extends PsiTestCase { return (InspectionManagerEx)InspectionManager.getInstance(myProject); } - public void doTest(@NonNls String folderName, LocalInspectionTool tool) { + public void doTest(@NonNls @NotNull String folderName, @NotNull LocalInspectionTool tool) { doTest(folderName, new LocalInspectionToolWrapper(tool)); } - public void doTest(@NonNls String folderName, GlobalInspectionTool tool) { + public void doTest(@NonNls @NotNull String folderName, @NotNull GlobalInspectionTool tool) { doTest(folderName, new GlobalInspectionToolWrapper(tool)); } - public void doTest(@NonNls String folderName, GlobalInspectionTool tool, boolean checkRange) { + public void doTest(@NonNls @NotNull String folderName, @NotNull GlobalInspectionTool tool, boolean checkRange) { doTest(folderName, new GlobalInspectionToolWrapper(tool), checkRange); } - public void doTest(@NonNls String folderName, GlobalInspectionTool tool, boolean checkRange, boolean runDeadCodeFirst) { + public void doTest(@NonNls @NotNull String folderName, @NotNull GlobalInspectionTool tool, boolean checkRange, boolean runDeadCodeFirst) { doTest(folderName, new GlobalInspectionToolWrapper(tool), "java 1.4", checkRange, runDeadCodeFirst); } - public void doTest(@NonNls String folderName, InspectionToolWrapper tool) { + public void doTest(@NonNls @NotNull String folderName, @NotNull InspectionToolWrapper tool) { doTest(folderName, tool, "java 1.4"); } - public void doTest(@NonNls String folderName, InspectionToolWrapper tool, final boolean checkRange) { + public void doTest(@NonNls @NotNull String folderName, @NotNull InspectionToolWrapper tool, final boolean checkRange) { doTest(folderName, tool, "java 1.4", checkRange); } - public void doTest(@NonNls String folderName, LocalInspectionTool tool, @NonNls final String jdkName) { + public void doTest(@NonNls @NotNull String folderName, @NotNull LocalInspectionTool tool, @NonNls final String jdkName) { doTest(folderName, new LocalInspectionToolWrapper(tool), jdkName); } - public void doTest(@NonNls String folderName, InspectionToolWrapper tool, @NonNls final String jdkName) { + public void doTest(@NonNls @NotNull String folderName, @NotNull InspectionToolWrapper tool, @NonNls final String jdkName) { doTest(folderName, tool, jdkName, false); } - public void doTest(@NonNls String folderName, InspectionToolWrapper tool, @NonNls final String jdkName, boolean checkRange) { + public void doTest(@NonNls @NotNull String folderName, @NotNull InspectionToolWrapper tool, @NonNls final String jdkName, boolean checkRange) { doTest(folderName, tool, jdkName, checkRange, false); } - public void doTest(@NonNls String folderName, - InspectionToolWrapper toolWrapper, + public void doTest(@NonNls @NotNull String folderName, + @NotNull InspectionToolWrapper toolWrapper, @NonNls final String jdkName, boolean checkRange, boolean runDeadCodeFirst, - InspectionToolWrapper... additional) { + @NotNull InspectionToolWrapper... additional) { final String testDir = getTestDataPath() + "/" + folderName; GlobalInspectionContextImpl context = runTool(testDir, jdkName, runDeadCodeFirst, toolWrapper, additional); InspectionTestUtil.compareToolResults(context, toolWrapper, checkRange, testDir); } - protected void runTool(@NonNls final String testDir, @NonNls final String jdkName, final InspectionToolWrapper tool) { + protected void runTool(@NonNls @NotNull String testDir, @NonNls final String jdkName, @NotNull InspectionToolWrapper tool) { runTool(testDir, jdkName, false, tool); } - protected GlobalInspectionContextImpl runTool(final String testDir, + protected GlobalInspectionContextImpl runTool(@NotNull final String testDir, final String jdkName, boolean runDeadCodeFirst, @NotNull InspectionToolWrapper toolWrapper, @NotNull InspectionToolWrapper... additional) { final VirtualFile[] sourceDir = new VirtualFile[1]; - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - try { - setupRootModel(testDir, sourceDir, jdkName); - } - catch (Exception e) { - LOG.error(e); - } + ApplicationManager.getApplication().runWriteAction(() -> { + try { + setupRootModel(testDir, sourceDir, jdkName); + } + catch (Exception e) { + LOG.error(e); } }); VirtualFile projectDir = LocalFileSystem.getInstance().refreshAndFindFileByIoFile(new File(testDir)); @@ -160,7 +157,7 @@ public abstract class InspectionTestCase extends PsiTestCase { return new AnalysisScope(psiManager.findDirectory(sourceDir)); } - protected void setupRootModel(final String testDir, final VirtualFile[] sourceDir, final String sdkName) { + protected void setupRootModel(@NotNull String testDir, @NotNull VirtualFile[] sourceDir, final String sdkName) { VirtualFile projectDir = LocalFileSystem.getInstance().refreshAndFindFileByIoFile(new File(testDir)); assertNotNull("could not find project dir " + testDir, projectDir); sourceDir[0] = projectDir.findChild("src"); diff --git a/java/testFramework/src/com/intellij/testFramework/fixtures/JavaCodeInsightFixtureTestCase.java b/java/testFramework/src/com/intellij/testFramework/fixtures/JavaCodeInsightFixtureTestCase.java index 9b27dec4aae8..a925b07075fb 100644 --- a/java/testFramework/src/com/intellij/testFramework/fixtures/JavaCodeInsightFixtureTestCase.java +++ b/java/testFramework/src/com/intellij/testFramework/fixtures/JavaCodeInsightFixtureTestCase.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2014 JetBrains s.r.o. + * Copyright 2000-2016 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. @@ -22,7 +22,6 @@ import com.intellij.openapi.roots.LanguageLevelProjectExtension; import com.intellij.pom.java.LanguageLevel; import com.intellij.psi.JavaPsiFacade; import com.intellij.psi.PsiElementFactory; -import com.intellij.psi.PsiManager; import com.intellij.psi.impl.PsiManagerEx; import com.intellij.testFramework.UsefulTestCase; import com.intellij.testFramework.builders.JavaModuleFixtureBuilder; @@ -104,7 +103,7 @@ public abstract class JavaCodeInsightFixtureTestCase extends UsefulTestCase{ } protected PsiManagerEx getPsiManager() { - return (PsiManagerEx)PsiManager.getInstance(getProject()); + return PsiManagerEx.getInstanceEx(getProject()); } public PsiElementFactory getElementFactory() { diff --git a/java/typeMigration/testData/inspections/guava/transformAndConcat3_after.java b/java/typeMigration/testData/inspections/guava/transformAndConcat3_after.java index 3cf1caf4cfe3..fec0c7a08666 100644 --- a/java/typeMigration/testData/inspections/guava/transformAndConcat3_after.java +++ b/java/typeMigration/testData/inspections/guava/transformAndConcat3_after.java @@ -1,4 +1,5 @@ import java.util.ArrayList; +import java.util.function.Function; import java.util.stream.Stream; import java.util.stream.StreamSupport; @@ -7,16 +8,19 @@ class A { ArrayList strings = new ArrayList(); Stream it = strings.stream(); - int i = (int) it.flatMap(o -> { - if ('a' > 2) { - return StreamSupport.stream(getIterable().spliterator(), false); - } else if ('c' < 123) { - ArrayList strings1 = new ArrayList<>(); - strings1.add(o); - return strings1.stream(); + int i = (int) it.flatMap((o) -> StreamSupport.stream(new Function>() { + @Override + public Iterable apply(String o) { + if ('a' > 2) { + return getIterable(); + } else if ('c' < 123) { + ArrayList strings1 = new ArrayList<>(); + strings1.add(o); + return strings1; + } + return null; } - return null; - }).count(); + }.apply(o).spliterator(), false)).count(); } diff --git a/lib/required_for_dist.txt b/lib/required_for_dist.txt index 19c275f29735..65aa9a757933 100644 --- a/lib/required_for_dist.txt +++ b/lib/required_for_dist.txt @@ -65,6 +65,7 @@ sanselan-0.98-snapshot.jar SceneBuilderKit-8.1.1.jar serviceMessages.jar snappy-in-java-0.3.1.jar +sqlite-jdbc-3.6.20.1.jar swingx-core-1.6.2.jar slf4j-api-1.7.10.jar slf4j-log4j12-1.7.10.jar diff --git a/lib/sqlite-jdbc-3.6.20.1.jar b/lib/sqlite-jdbc-3.6.20.1.jar new file mode 100644 index 000000000000..442d76b0ef95 Binary files /dev/null and b/lib/sqlite-jdbc-3.6.20.1.jar differ diff --git a/platform/analysis-api/src/com/intellij/codeInspection/InspectionManager.java b/platform/analysis-api/src/com/intellij/codeInspection/InspectionManager.java index 6dcede54c97e..6d899616a626 100644 --- a/platform/analysis-api/src/com/intellij/codeInspection/InspectionManager.java +++ b/platform/analysis-api/src/com/intellij/codeInspection/InspectionManager.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2009 JetBrains s.r.o. + * Copyright 2000-2016 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. @@ -93,42 +93,42 @@ public abstract class InspectionManager { @NotNull ProblemHighlightType highlightType, boolean onTheFly, final LocalQuickFix... fixes); + /** + * use {@link #createProblemDescriptor(PsiElement, String, boolean, LocalQuickFix[], ProblemHighlightType)} instead + */ @Deprecated @NotNull - /** - * use {@link #createProblemDescriptor(PsiElement, String, boolean, LocalQuickFix, ProblemHighlightType)} instead - */ public abstract ProblemDescriptor createProblemDescriptor(@NotNull PsiElement psiElement, @NotNull String descriptionTemplate, LocalQuickFix fix, @NotNull ProblemHighlightType highlightType); - @Deprecated - @NotNull /** * use {@link #createProblemDescriptor(PsiElement, String, boolean, LocalQuickFix[], ProblemHighlightType)} instead */ + @Deprecated + @NotNull public abstract ProblemDescriptor createProblemDescriptor(@NotNull PsiElement psiElement, @NotNull String descriptionTemplate, LocalQuickFix[] fixes, @NotNull ProblemHighlightType highlightType); - @Deprecated - @NotNull /** * use {@link #createProblemDescriptor(PsiElement, String, LocalQuickFix[], ProblemHighlightType, boolean, boolean)} instead */ + @Deprecated + @NotNull public abstract ProblemDescriptor createProblemDescriptor(@NotNull PsiElement psiElement, @NotNull String descriptionTemplate, LocalQuickFix[] fixes, @NotNull ProblemHighlightType highlightType, boolean isAfterEndOfLine); - @Deprecated - @NotNull /** * use {@link #createProblemDescriptor(PsiElement, PsiElement, String, ProblemHighlightType, boolean, LocalQuickFix...)} instead */ + @Deprecated + @NotNull public abstract ProblemDescriptor createProblemDescriptor(@NotNull PsiElement startElement, @NotNull PsiElement endElement, @NotNull String descriptionTemplate, @@ -136,22 +136,22 @@ public abstract class InspectionManager { LocalQuickFix... fixes); - @Deprecated - @NotNull /** * use {@link #createProblemDescriptor(PsiElement, TextRange, String, ProblemHighlightType, boolean, LocalQuickFix...)} instead */ + @Deprecated + @NotNull public abstract ProblemDescriptor createProblemDescriptor(@NotNull final PsiElement psiElement, final TextRange rangeInElement, @NotNull final String descriptionTemplate, @NotNull ProblemHighlightType highlightType, final LocalQuickFix... fixes); - @Deprecated - @NotNull /** * use {@link #createProblemDescriptor(PsiElement, String, boolean, ProblemHighlightType, boolean, LocalQuickFix...)} instead */ + @Deprecated + @NotNull public abstract ProblemDescriptor createProblemDescriptor(@NotNull final PsiElement psiElement, @NotNull final String descriptionTemplate, final boolean showTooltip, diff --git a/platform/analysis-api/src/com/intellij/codeInspection/ProblemHighlightType.java b/platform/analysis-api/src/com/intellij/codeInspection/ProblemHighlightType.java index ce5a07e80b54..5e25416b6b43 100644 --- a/platform/analysis-api/src/com/intellij/codeInspection/ProblemHighlightType.java +++ b/platform/analysis-api/src/com/intellij/codeInspection/ProblemHighlightType.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2009 JetBrains s.r.o. + * Copyright 2000-2016 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. @@ -33,9 +33,9 @@ public enum ProblemHighlightType { /** The same as {@link #GENERIC_ERROR_OR_WARNING} with enforced {@link com.intellij.codeHighlighting.HighlightDisplayLevel#ERROR} severity level */ GENERIC_ERROR, - @Deprecated /** Enforces {@link com.intellij.codeHighlighting.HighlightDisplayLevel#INFO} severity level * use #WEAK_WARNING instead*/ + @Deprecated INFO, /** Enforces {@link com.intellij.codeHighlighting.HighlightDisplayLevel#WEAK_WARNING} severity level */ diff --git a/platform/analysis-api/src/com/intellij/profile/Profile.java b/platform/analysis-api/src/com/intellij/profile/Profile.java index 7aa2370836b5..e9945762ebc0 100644 --- a/platform/analysis-api/src/com/intellij/profile/Profile.java +++ b/platform/analysis-api/src/com/intellij/profile/Profile.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2015 JetBrains s.r.o. + * Copyright 2000-2016 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. @@ -28,10 +28,10 @@ public interface Profile extends Comparable, Scheme { void setLocal(boolean isLocal); - @Deprecated /** * @deprecated Use !{@link #isProjectLevel()} */ + @Deprecated boolean isLocal(); boolean isProjectLevel(); diff --git a/platform/boot/src/com/intellij/lang/properties/charset/Native2AsciiCharsetDecoder.java b/platform/boot/src/com/intellij/lang/properties/charset/Native2AsciiCharsetDecoder.java index f4a2b411daf8..7da4b9cdf6b7 100644 --- a/platform/boot/src/com/intellij/lang/properties/charset/Native2AsciiCharsetDecoder.java +++ b/platform/boot/src/com/intellij/lang/properties/charset/Native2AsciiCharsetDecoder.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2015 JetBrains s.r.o. + * Copyright 2000-2016 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. @@ -16,10 +16,6 @@ package com.intellij.lang.properties.charset; -/** - * @author Alexey - */ - import java.nio.BufferUnderflowException; import java.nio.ByteBuffer; import java.nio.CharBuffer; diff --git a/platform/boot/src/com/intellij/lang/properties/charset/Native2AsciiCharsetEncoder.java b/platform/boot/src/com/intellij/lang/properties/charset/Native2AsciiCharsetEncoder.java index 115a611be09d..c07e69d0b324 100644 --- a/platform/boot/src/com/intellij/lang/properties/charset/Native2AsciiCharsetEncoder.java +++ b/platform/boot/src/com/intellij/lang/properties/charset/Native2AsciiCharsetEncoder.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2012 JetBrains s.r.o. + * Copyright 2000-2016 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. @@ -16,17 +16,13 @@ package com.intellij.lang.properties.charset; -/** - * @author Alexey - */ - +import java.nio.BufferOverflowException; +import java.nio.BufferUnderflowException; +import java.nio.ByteBuffer; +import java.nio.CharBuffer; +import java.nio.charset.Charset; import java.nio.charset.CharsetEncoder; import java.nio.charset.CoderResult; -import java.nio.charset.Charset; -import java.nio.CharBuffer; -import java.nio.ByteBuffer; -import java.nio.BufferUnderflowException; -import java.nio.BufferOverflowException; class Native2AsciiCharsetEncoder extends CharsetEncoder { diff --git a/platform/built-in-server-api/src/org/jetbrains/ide/BinaryRequestHandler.java b/platform/built-in-server-api/src/org/jetbrains/ide/BinaryRequestHandler.java index ba616c250603..ac4d54becc39 100644 --- a/platform/built-in-server-api/src/org/jetbrains/ide/BinaryRequestHandler.java +++ b/platform/built-in-server-api/src/org/jetbrains/ide/BinaryRequestHandler.java @@ -25,10 +25,10 @@ import java.util.UUID; public abstract class BinaryRequestHandler { public static final ExtensionPointName EP_NAME = ExtensionPointName.create("org.jetbrains.binaryRequestHandler"); - @NotNull /** * uuidgen on Mac OS X could be used to generate UUID */ + @NotNull public abstract UUID getId(); @NotNull diff --git a/platform/built-in-server/src/org/jetbrains/ide/RestService.java b/platform/built-in-server/src/org/jetbrains/ide/RestService.java index 2d8beb522d5a..c0938646613f 100644 --- a/platform/built-in-server/src/org/jetbrains/ide/RestService.java +++ b/platform/built-in-server/src/org/jetbrains/ide/RestService.java @@ -104,10 +104,10 @@ public abstract class RestService extends HttpRequestHandler { return false; } - @NotNull /** * Use human-readable name or UUID if it is an internal service. */ + @NotNull protected abstract String getServiceName(); protected abstract boolean isMethodSupported(@NotNull HttpMethod method); @@ -144,10 +144,10 @@ public abstract class RestService extends HttpRequestHandler { } } - @Nullable("error text or null if successful") /** * Return error or send response using {@link #sendOk(FullHttpRequest, ChannelHandlerContext)}, {@link #send(BufferExposingByteArrayOutputStream, FullHttpRequest, ChannelHandlerContext)} */ + @Nullable("error text or null if successful") public abstract String execute(@NotNull QueryStringDecoder urlDecoder, @NotNull FullHttpRequest request, @NotNull ChannelHandlerContext context) throws IOException; @NotNull diff --git a/platform/core-api/src/com/intellij/ide/util/PropertiesComponent.java b/platform/core-api/src/com/intellij/ide/util/PropertiesComponent.java index b182fa9c3215..525d42018537 100644 --- a/platform/core-api/src/com/intellij/ide/util/PropertiesComponent.java +++ b/platform/core-api/src/com/intellij/ide/util/PropertiesComponent.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2015 JetBrains s.r.o. + * Copyright 2000-2016 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. @@ -106,12 +106,12 @@ public abstract class PropertiesComponent { return ObjectUtils.notNull(getValue(name), defaultValue); } - @SuppressWarnings("unused") - @Deprecated /** * @deprecated Use {@link #getInt(String, int)} * Init was never performed and in any case is not recommended. */ + @SuppressWarnings("unused") + @Deprecated public final int getOrInitInt(@NotNull String name, int defaultValue) { return getInt(name, defaultValue); } @@ -130,10 +130,10 @@ public abstract class PropertiesComponent { } } - @Deprecated /** * @deprecated Use {@link #getValue(String, String)} */ + @Deprecated public String getOrInit(@NonNls String name, String defaultValue) { if (!isValueSet(name)) { setValue(name, defaultValue); diff --git a/platform/core-api/src/com/intellij/openapi/components/RoamingType.java b/platform/core-api/src/com/intellij/openapi/components/RoamingType.java index 6a8b81fe578e..2258b0e62140 100644 --- a/platform/core-api/src/com/intellij/openapi/components/RoamingType.java +++ b/platform/core-api/src/com/intellij/openapi/components/RoamingType.java @@ -31,15 +31,15 @@ public enum RoamingType { */ DEFAULT, - @Deprecated /** * Use {@link #DEFAULT} instead */ + @Deprecated PER_USER, - @Deprecated /** * Use {@link #PER_OS} instead */ + @Deprecated PER_PLATFORM, } diff --git a/platform/core-api/src/com/intellij/openapi/options/SchemeProcessor.java b/platform/core-api/src/com/intellij/openapi/options/SchemeProcessor.java index a4da435f2eeb..03db46183270 100644 --- a/platform/core-api/src/com/intellij/openapi/options/SchemeProcessor.java +++ b/platform/core-api/src/com/intellij/openapi/options/SchemeProcessor.java @@ -47,11 +47,11 @@ public abstract class SchemeProcessor { throw new AbstractMethodError(); } - @Nullable /** * @param duringLoad If occurred during {@link SchemesManager#loadSchemes()} call * Returns null if element is not valid. */ + @Nullable public T readScheme(@NotNull Element element, boolean duringLoad) throws Exception { return readScheme(element); } diff --git a/platform/core-api/src/com/intellij/openapi/progress/EmptyProgressIndicator.java b/platform/core-api/src/com/intellij/openapi/progress/EmptyProgressIndicator.java index 4f68f1d25f25..a5cd279b2e23 100644 --- a/platform/core-api/src/com/intellij/openapi/progress/EmptyProgressIndicator.java +++ b/platform/core-api/src/com/intellij/openapi/progress/EmptyProgressIndicator.java @@ -20,8 +20,8 @@ import com.intellij.openapi.application.ModalityState; import org.jetbrains.annotations.NotNull; public class EmptyProgressIndicator implements StandardProgressIndicator { - private volatile boolean myIsRunning = false; - private volatile boolean myIsCanceled = false; + private volatile boolean myIsRunning; + private volatile boolean myIsCanceled; @Override public void start() { diff --git a/platform/core-api/src/com/intellij/openapi/util/ActionCallback.java b/platform/core-api/src/com/intellij/openapi/util/ActionCallback.java index 85e2a57adca4..948d62495390 100644 --- a/platform/core-api/src/com/intellij/openapi/util/ActionCallback.java +++ b/platform/core-api/src/com/intellij/openapi/util/ActionCallback.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2015 JetBrains s.r.o. + * Copyright 2000-2016 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. @@ -277,12 +277,12 @@ public class ActionCallback implements Disposable { }; } - @SuppressWarnings("UnusedDeclaration") - @NotNull - @Deprecated /** * @deprecated use {@link #notifyWhenRejected(ActionCallback)} */ + @SuppressWarnings("UnusedDeclaration") + @NotNull + @Deprecated public Runnable createSetRejectedRunnable() { return new Runnable() { @Override diff --git a/platform/core-api/src/com/intellij/openapi/util/AsyncResult.java b/platform/core-api/src/com/intellij/openapi/util/AsyncResult.java index 8c7a536b541f..0ba40aab1c69 100644 --- a/platform/core-api/src/com/intellij/openapi/util/AsyncResult.java +++ b/platform/core-api/src/com/intellij/openapi/util/AsyncResult.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2015 JetBrains s.r.o. + * Copyright 2000-2016 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. @@ -65,23 +65,23 @@ public class AsyncResult extends ActionCallback { return subResult; } - @SuppressWarnings("unused") - @NotNull - @Deprecated /** * @deprecated Don't use AsyncResult - use Promise instead. */ + @SuppressWarnings("unused") + @NotNull + @Deprecated public ActionCallback subCallback(@NotNull Consumer doneHandler) { ActionCallback subCallback = new ActionCallback(); doWhenDone(new SubCallbackDoneCallback(subCallback, doneHandler)).notifyWhenRejected(subCallback); return subCallback; } - @NotNull - @Deprecated /** * @deprecated Use {@link #doWhenDone(com.intellij.util.Consumer)} (to remove in IDEA 16) */ + @NotNull + @Deprecated public AsyncResult doWhenDone(@SuppressWarnings("deprecation") @NotNull final Handler handler) { doWhenDone(new Runnable() { @Override @@ -147,28 +147,28 @@ public class AsyncResult extends ActionCallback { return this; } - @Deprecated /** * @deprecated Use {@link com.intellij.util.Consumer} (to remove in IDEA 16) */ + @Deprecated public interface Handler { void run(T t); } - @Deprecated /** * @deprecated Don't use AsyncResult - use Promise instead. */ + @Deprecated public static class Done extends AsyncResult { public Done(T value) { setDone(value); } } - @Deprecated /** * @deprecated Don't use AsyncResult - use Promise instead. */ + @Deprecated public static class Rejected extends AsyncResult { public Rejected() { setRejected(); @@ -179,21 +179,21 @@ public class AsyncResult extends ActionCallback { } } - @NotNull - @Deprecated /** * @deprecated Don't use AsyncResult - use Promise instead. */ + @NotNull + @Deprecated public static AsyncResult rejected() { //noinspection unchecked,deprecation return new Rejected(); } - @NotNull - @Deprecated /** * @deprecated Don't use AsyncResult - use Promise instead. */ + @NotNull + @Deprecated public static AsyncResult rejected(@NotNull String errorMessage) { AsyncResult result = new AsyncResult(); result.reject(errorMessage); @@ -205,11 +205,11 @@ public class AsyncResult extends ActionCallback { return new AsyncResult().setDone(result); } - @NotNull - @Deprecated /** * @deprecated Don't use AsyncResult - use Promise instead. */ + @NotNull + @Deprecated public static AsyncResult doneList() { //noinspection unchecked return done((R)Collections.emptyList()); diff --git a/platform/core-api/src/com/intellij/psi/PsiTreeChangeEvent.java b/platform/core-api/src/com/intellij/psi/PsiTreeChangeEvent.java index b3c3de7d7a66..8f5946a42bc2 100644 --- a/platform/core-api/src/com/intellij/psi/PsiTreeChangeEvent.java +++ b/platform/core-api/src/com/intellij/psi/PsiTreeChangeEvent.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2015 JetBrains s.r.o. + * Copyright 2000-2016 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. @@ -34,10 +34,10 @@ public abstract class PsiTreeChangeEvent extends EventObject { @NonNls public static final String PROP_FILE_TYPES = "propFileTypes"; - @NonNls /** * In the event with this property the {@link #getOldValue()} contains virtual file of the change */ + @NonNls public static final String PROP_UNLOADED_PSI = "propUnloadedPsi"; protected PsiElement myParent; diff --git a/platform/core-api/src/com/intellij/psi/search/PsiElementProcessor.java b/platform/core-api/src/com/intellij/psi/search/PsiElementProcessor.java index 5dd855abb694..9fc7e8c58313 100644 --- a/platform/core-api/src/com/intellij/psi/search/PsiElementProcessor.java +++ b/platform/core-api/src/com/intellij/psi/search/PsiElementProcessor.java @@ -91,7 +91,7 @@ public interface PsiElementProcessor { class CollectElementsWithLimit extends CollectElements{ private final AtomicInteger myCount = new AtomicInteger(0); - private volatile boolean myOverflow = false; + private volatile boolean myOverflow; private final int myLimit; public CollectElementsWithLimit(int limit) { @@ -119,7 +119,7 @@ public interface PsiElementProcessor { } class FindElement implements PsiElementProcessor { - private volatile T myFoundElement = null; + private volatile T myFoundElement; public boolean isFound() { return myFoundElement != null; diff --git a/platform/core-impl/src/com/intellij/extapi/psi/ASTDelegatePsiElement.java b/platform/core-impl/src/com/intellij/extapi/psi/ASTDelegatePsiElement.java index 7821c1cf9e9e..1132e0fd3d0f 100644 --- a/platform/core-impl/src/com/intellij/extapi/psi/ASTDelegatePsiElement.java +++ b/platform/core-impl/src/com/intellij/extapi/psi/ASTDelegatePsiElement.java @@ -29,7 +29,6 @@ import com.intellij.openapi.util.TextRange; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiFile; import com.intellij.psi.PsiInvalidElementAccessException; -import com.intellij.psi.PsiManager; import com.intellij.psi.impl.CheckUtil; import com.intellij.psi.impl.PsiElementBase; import com.intellij.psi.impl.PsiManagerEx; @@ -66,7 +65,7 @@ public abstract class ASTDelegatePsiElement extends PsiElementBase { public PsiManagerEx getManager() { Project project = ProjectCoreUtil.theOnlyOpenProject(); if (project != null) { - return (PsiManagerEx)PsiManager.getInstance(project); + return PsiManagerEx.getInstanceEx(project); } PsiElement parent = this; diff --git a/platform/core-impl/src/com/intellij/extapi/psi/StubBasedPsiElementBase.java b/platform/core-impl/src/com/intellij/extapi/psi/StubBasedPsiElementBase.java index 73f868cc4eeb..009e7d3e802b 100644 --- a/platform/core-impl/src/com/intellij/extapi/psi/StubBasedPsiElementBase.java +++ b/platform/core-impl/src/com/intellij/extapi/psi/StubBasedPsiElementBase.java @@ -27,7 +27,10 @@ import com.intellij.openapi.project.ProjectCoreUtil; import com.intellij.openapi.util.Key; import com.intellij.openapi.util.text.StringUtil; import com.intellij.openapi.vfs.VirtualFile; -import com.intellij.psi.*; +import com.intellij.psi.PsiElement; +import com.intellij.psi.PsiFile; +import com.intellij.psi.PsiInvalidElementAccessException; +import com.intellij.psi.PsiLock; import com.intellij.psi.impl.DebugUtil; import com.intellij.psi.impl.PsiManagerEx; import com.intellij.psi.impl.source.PsiFileImpl; @@ -282,7 +285,7 @@ public class StubBasedPsiElementBase extends ASTDelegateP public PsiManagerEx getManager() { Project project = ProjectCoreUtil.theOnlyOpenProject(); if (project != null) { - return (PsiManagerEx)PsiManager.getInstance(project); + return PsiManagerEx.getInstanceEx(project); } return (PsiManagerEx)getContainingFile().getManager(); } diff --git a/platform/core-impl/src/com/intellij/lang/impl/PsiBuilderImpl.java b/platform/core-impl/src/com/intellij/lang/impl/PsiBuilderImpl.java index 06a09d0b9d14..7c9f0874a347 100644 --- a/platform/core-impl/src/com/intellij/lang/impl/PsiBuilderImpl.java +++ b/platform/core-impl/src/com/intellij/lang/impl/PsiBuilderImpl.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2015 JetBrains s.r.o. + * Copyright 2000-2016 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. @@ -1766,8 +1766,8 @@ public class PsiBuilderImpl extends UserDataHolderBase implements PsiBuilder { boolean forceInsertion) { final int start = builder.myLexStarts[startLexemeIndex]; final int end = builder.myLexStarts[endLexemeIndex]; - /** Corresponding code for heavy tree is located in {@link com.intellij.lang.impl.PsiBuilderImpl#insertLeaves} - * and is applied only to plain lexemes */ + /* Corresponding code for heavy tree is located in {@link com.intellij.lang.impl.PsiBuilderImpl#insertLeaves} + and is applied only to plain lexemes */ if (start > end || !forceInsertion && start == end && !(type instanceof ILeafElementType)) { return; } diff --git a/platform/core-impl/src/com/intellij/openapi/vfs/impl/ZipHandler.java b/platform/core-impl/src/com/intellij/openapi/vfs/impl/ZipHandler.java index 065ad388f6c2..0363d8a1b8a3 100644 --- a/platform/core-impl/src/com/intellij/openapi/vfs/impl/ZipHandler.java +++ b/platform/core-impl/src/com/intellij/openapi/vfs/impl/ZipHandler.java @@ -36,7 +36,7 @@ import java.util.zip.ZipEntry; import java.util.zip.ZipFile; public class ZipHandler extends ArchiveHandler { - private volatile String myCanonicalPathToZip = null; + private volatile String myCanonicalPathToZip; private volatile long myFileStamp; private volatile long myFileLength; diff --git a/platform/core-impl/src/com/intellij/psi/impl/PsiManagerEx.java b/platform/core-impl/src/com/intellij/psi/impl/PsiManagerEx.java index 2c94947cd8d6..5c790ff949c7 100644 --- a/platform/core-impl/src/com/intellij/psi/impl/PsiManagerEx.java +++ b/platform/core-impl/src/com/intellij/psi/impl/PsiManagerEx.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2009 JetBrains s.r.o. + * Copyright 2000-2016 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. @@ -15,17 +15,28 @@ */ package com.intellij.psi.impl; +import com.intellij.openapi.Disposable; +import com.intellij.openapi.project.Project; import com.intellij.openapi.vfs.VirtualFile; +import com.intellij.openapi.vfs.VirtualFileFilter; import com.intellij.psi.PsiManager; import com.intellij.psi.impl.file.impl.FileManager; import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.TestOnly; /** * @author peter */ public abstract class PsiManagerEx extends PsiManager { + public static PsiManagerEx getInstanceEx(Project project) { + return (PsiManagerEx)getInstance(project); + } public abstract boolean isBatchFilesProcessingMode(); + @TestOnly + public abstract void setAssertOnFileLoadingFilter(@NotNull VirtualFileFilter filter, @NotNull Disposable parentDisposable); + + @TestOnly public abstract boolean isAssertOnFileLoading(@NotNull VirtualFile file); /** diff --git a/platform/core-impl/src/com/intellij/psi/impl/PsiManagerImpl.java b/platform/core-impl/src/com/intellij/psi/impl/PsiManagerImpl.java index 094c145df091..b681be0366fc 100644 --- a/platform/core-impl/src/com/intellij/psi/impl/PsiManagerImpl.java +++ b/platform/core-impl/src/com/intellij/psi/impl/PsiManagerImpl.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2015 JetBrains s.r.o. + * Copyright 2000-2016 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. @@ -137,6 +137,7 @@ public class PsiManagerImpl extends PsiManagerEx { return false; } + @Override @TestOnly public void setAssertOnFileLoadingFilter(@NotNull VirtualFileFilter filter, @NotNull Disposable parentDisposable) { // Find something to ensure there's no changed files waiting to be processed in repository indices. diff --git a/platform/core-impl/src/com/intellij/psi/impl/PsiToDocumentSynchronizer.java b/platform/core-impl/src/com/intellij/psi/impl/PsiToDocumentSynchronizer.java index 391df3ab683d..b6ef290704ea 100644 --- a/platform/core-impl/src/com/intellij/psi/impl/PsiToDocumentSynchronizer.java +++ b/platform/core-impl/src/com/intellij/psi/impl/PsiToDocumentSynchronizer.java @@ -46,7 +46,7 @@ public class PsiToDocumentSynchronizer extends PsiTreeChangeAdapter { private final MessageBus myBus; private final Map> myTransactionsMap = new HashMap>(); - private volatile Document mySyncDocument = null; + private volatile Document mySyncDocument; public PsiToDocumentSynchronizer(PsiDocumentManagerBase psiDocumentManager, MessageBus bus) { myPsiDocumentManager = psiDocumentManager; diff --git a/platform/core-impl/src/com/intellij/psi/impl/meta/MetaRegistry.java b/platform/core-impl/src/com/intellij/psi/impl/meta/MetaRegistry.java index 6fc82840d587..4cedf570e038 100644 --- a/platform/core-impl/src/com/intellij/psi/impl/meta/MetaRegistry.java +++ b/platform/core-impl/src/com/intellij/psi/impl/meta/MetaRegistry.java @@ -51,7 +51,7 @@ public class MetaRegistry extends MetaDataRegistrar { private static final Logger LOG = Logger.getInstance(MetaRegistry.class); private static final List ourBindings = ContainerUtil.createLockFreeCopyOnWriteList(); - private static volatile boolean ourContributorsLoaded = false; + private static volatile boolean ourContributorsLoaded; private static final Key> META_DATA_KEY = Key.create("META DATA KEY"); diff --git a/platform/core-impl/src/com/intellij/psi/impl/smartPointers/SmartPsiElementPointerImpl.java b/platform/core-impl/src/com/intellij/psi/impl/smartPointers/SmartPsiElementPointerImpl.java index 73db174d0774..91bd35f0da83 100644 --- a/platform/core-impl/src/com/intellij/psi/impl/smartPointers/SmartPsiElementPointerImpl.java +++ b/platform/core-impl/src/com/intellij/psi/impl/smartPointers/SmartPsiElementPointerImpl.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2015 JetBrains s.r.o. + * Copyright 2000-2016 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. @@ -99,7 +99,7 @@ class SmartPsiElementPointerImpl implements SmartPointerEx void cacheElement(@Nullable E element) { myElement = element == null ? null : - ((PsiManagerEx)PsiManager.getInstance(getProject())).isBatchFilesProcessingMode() ? new WeakReference(element) : + PsiManagerEx.getInstanceEx(getProject()).isBatchFilesProcessingMode() ? new WeakReference(element) : new SoftReference(element); } diff --git a/platform/core-impl/src/com/intellij/psi/impl/source/DummyHolder.java b/platform/core-impl/src/com/intellij/psi/impl/source/DummyHolder.java index 0b26946ca61e..b0414a2c2e8e 100644 --- a/platform/core-impl/src/com/intellij/psi/impl/source/DummyHolder.java +++ b/platform/core-impl/src/com/intellij/psi/impl/source/DummyHolder.java @@ -31,7 +31,7 @@ public class DummyHolder extends PsiFileImpl { private final CharTable myTable; private final Boolean myExplicitlyValid; private final Language myLanguage; - private volatile FileElement myFileElement = null; + private volatile FileElement myFileElement; @SuppressWarnings("EmptyClass") private static class DummyHolderTreeLock {} private final DummyHolderTreeLock myTreeElementLock = new DummyHolderTreeLock(); @@ -162,7 +162,7 @@ public class DummyHolder extends PsiFileImpl { return psiClone; } - private FileViewProvider myViewProvider = null; + private FileViewProvider myViewProvider; @Override @NotNull diff --git a/platform/core-impl/src/com/intellij/psi/impl/source/tree/TreeElement.java b/platform/core-impl/src/com/intellij/psi/impl/source/tree/TreeElement.java index 7fa637c3ba43..99fa8cb6fe59 100644 --- a/platform/core-impl/src/com/intellij/psi/impl/source/tree/TreeElement.java +++ b/platform/core-impl/src/com/intellij/psi/impl/source/tree/TreeElement.java @@ -23,7 +23,6 @@ import com.intellij.openapi.project.ProjectCoreUtil; import com.intellij.openapi.util.TextRange; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiLock; -import com.intellij.psi.PsiManager; import com.intellij.psi.TokenType; import com.intellij.psi.impl.DebugUtil; import com.intellij.psi.impl.ElementBase; @@ -70,7 +69,7 @@ public abstract class TreeElement extends ElementBase implements ASTNode, Clonea public PsiManagerEx getManager() { Project project = ProjectCoreUtil.theOnlyOpenProject(); if (project != null) { - return (PsiManagerEx)PsiManager.getInstance(project); + return PsiManagerEx.getInstanceEx(project); } TreeElement element; for (element = this; element.getTreeParent() != null; element = element.getTreeParent()) { diff --git a/platform/core-impl/src/com/intellij/util/CachedValueBase.java b/platform/core-impl/src/com/intellij/util/CachedValueBase.java index eae0032d5b20..548ead1529d3 100644 --- a/platform/core-impl/src/com/intellij/util/CachedValueBase.java +++ b/platform/core-impl/src/com/intellij/util/CachedValueBase.java @@ -35,7 +35,7 @@ import java.util.List; */ public abstract class CachedValueBase { private static final Logger LOG = Logger.getInstance("#com.intellij.psi.impl.CachedValueImpl"); - private volatile SoftReference> myData = null; + private volatile SoftReference> myData; private Data computeData(@Nullable CachedValueProvider.Result result) { T value = result == null ? null : result.getValue(); diff --git a/platform/core-impl/src/com/intellij/util/profiling/ResolveProfiler.java b/platform/core-impl/src/com/intellij/util/profiling/ResolveProfiler.java index fe653837c453..d23201542703 100644 --- a/platform/core-impl/src/com/intellij/util/profiling/ResolveProfiler.java +++ b/platform/core-impl/src/com/intellij/util/profiling/ResolveProfiler.java @@ -34,7 +34,7 @@ public class ResolveProfiler { private static final boolean DISABLED = true; private static final ThreadLocal threadMap = new ThreadLocal(); - private static volatile int fileCount = 0; + private static volatile int fileCount; private static class ThreadInfo { private final String myFileName; diff --git a/platform/diff-api/src/com/intellij/ide/diff/DirDiffSettings.java b/platform/diff-api/src/com/intellij/ide/diff/DirDiffSettings.java index 8e5b8506bd70..015aa07ab9ae 100644 --- a/platform/diff-api/src/com/intellij/ide/diff/DirDiffSettings.java +++ b/platform/diff-api/src/com/intellij/ide/diff/DirDiffSettings.java @@ -46,10 +46,10 @@ public class DirDiffSettings { public boolean showInFrame = true; // in dialog otherwise //Usually used to set additional compare settings - private final List extraToolbarActions = new ArrayList(); + private final List extraToolbarActions = new ArrayList<>(); //Non-standard diff tools can store additional data here to use it while building data model - public final HashMap customSettings = new HashMap(); + public final HashMap customSettings = new HashMap<>(); private String filter = ""; private Pattern filterPattern = PatternUtil.fromMask("*"); diff --git a/platform/diff-impl/src/com/intellij/diff/DiffManagerImpl.java b/platform/diff-impl/src/com/intellij/diff/DiffManagerImpl.java index f9bea70ca2dd..b5a5cac2c8fb 100644 --- a/platform/diff-impl/src/com/intellij/diff/DiffManagerImpl.java +++ b/platform/diff-impl/src/com/intellij/diff/DiffManagerImpl.java @@ -88,7 +88,7 @@ public class DiffManagerImpl extends DiffManagerEx { @NotNull @Override public List getDiffTools() { - List result = new ArrayList(); + List result = new ArrayList<>(); Collections.addAll(result, DiffTool.EP_NAME.getExtensions()); result.add(SimpleDiffTool.INSTANCE); result.add(UnifiedDiffTool.INSTANCE); @@ -100,7 +100,7 @@ public class DiffManagerImpl extends DiffManagerEx { @NotNull @Override public List getMergeTools() { - List result = new ArrayList(); + List result = new ArrayList<>(); Collections.addAll(result, MergeTool.EP_NAME.getExtensions()); result.add(TextMergeTool.INSTANCE); result.add(BinaryMergeTool.INSTANCE); diff --git a/platform/diff-impl/src/com/intellij/diff/DiffRequestFactoryImpl.java b/platform/diff-impl/src/com/intellij/diff/DiffRequestFactoryImpl.java index c1d745ef9ee8..2d1dec6b1c44 100644 --- a/platform/diff-impl/src/com/intellij/diff/DiffRequestFactoryImpl.java +++ b/platform/diff-impl/src/com/intellij/diff/DiffRequestFactoryImpl.java @@ -213,7 +213,7 @@ public class DiffRequestFactoryImpl extends DiffRequestFactory { DocumentContent outputContent = myContentFactory.create(project, outputDocument, fileType); CharSequence originalContent = outputDocument.getImmutableCharSequence(); - List contents = new ArrayList(3); + List contents = new ArrayList<>(3); for (String text : textContents) { contents.add(myContentFactory.create(text, fileType)); } @@ -258,7 +258,7 @@ public class DiffRequestFactoryImpl extends DiffRequestFactory { DocumentContent outputContent = myContentFactory.create(project, outputDocument); CharSequence originalContent = outputDocument.getImmutableCharSequence(); - List contents = new ArrayList(3); + List contents = new ArrayList<>(3); for (byte[] bytes : byteContents) { contents.add(FileAwareDocumentContent.create(project, bytes, output)); } @@ -282,7 +282,7 @@ public class DiffRequestFactoryImpl extends DiffRequestFactory { if (outputContent == null) throw new InvalidDiffRequestException("Can't process file: " + output); byte[] originalContent = output.contentsToByteArray(); - List contents = new ArrayList(3); + List contents = new ArrayList<>(3); for (byte[] bytes : byteContents) { contents.add(myContentFactory.createFromBytes(project, output, bytes)); } @@ -332,7 +332,7 @@ public class DiffRequestFactoryImpl extends DiffRequestFactory { @Nullable String title, @NotNull List contentTitles, @Nullable Consumer applyCallback) throws InvalidDiffRequestException { - List byteContents = new ArrayList(3); + List byteContents = new ArrayList<>(3); for (VirtualFile file : fileContents) { try { byteContents.add(file.contentsToByteArray()); @@ -361,8 +361,8 @@ public class DiffRequestFactoryImpl extends DiffRequestFactory { if (outputContent == null) throw new InvalidDiffRequestException("Can't process file: " + output.getPresentableUrl()); byte[] originalContent = output.contentsToByteArray(); - List contents = new ArrayList(3); - List byteContents = new ArrayList(3); + List contents = new ArrayList<>(3); + List byteContents = new ArrayList<>(3); for (VirtualFile file : fileContents) { FileContent content = myContentFactory.createFile(project, file); if (content == null) throw new InvalidDiffRequestException("Can't process file: " + file.getPresentableUrl()); diff --git a/platform/diff-impl/src/com/intellij/diff/actions/AllLinesIterator.java b/platform/diff-impl/src/com/intellij/diff/actions/AllLinesIterator.java new file mode 100644 index 000000000000..7e8cf7c369a6 --- /dev/null +++ b/platform/diff-impl/src/com/intellij/diff/actions/AllLinesIterator.java @@ -0,0 +1,56 @@ +/* + * Copyright 2000-2016 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.diff.actions; + +import com.intellij.openapi.editor.Document; +import com.intellij.openapi.util.Pair; +import org.jetbrains.annotations.NotNull; + +import java.util.Iterator; + +import static com.intellij.diff.util.DiffUtil.getLineCount; + +public class AllLinesIterator implements Iterator> { + @NotNull private final Document myDocument; + private int myLine = 0; + + public AllLinesIterator(@NotNull Document document) { + myDocument = document; + } + + @Override + public boolean hasNext() { + return myLine < getLineCount(myDocument); + } + + @Override + public Pair next() { + int offset1 = myDocument.getLineStartOffset(myLine); + int offset2 = myDocument.getLineEndOffset(myLine); + + CharSequence text = myDocument.getImmutableCharSequence().subSequence(offset1, offset2); + + Pair pair = new Pair<>(myLine, text); + myLine++; + + return pair; + } + + @Override + public void remove() { + throw new UnsupportedOperationException(); + } +} diff --git a/platform/diff-impl/src/com/intellij/diff/actions/BufferedLineIterator.java b/platform/diff-impl/src/com/intellij/diff/actions/BufferedLineIterator.java index f69ee836b6c3..56c9271d45e9 100644 --- a/platform/diff-impl/src/com/intellij/diff/actions/BufferedLineIterator.java +++ b/platform/diff-impl/src/com/intellij/diff/actions/BufferedLineIterator.java @@ -26,7 +26,7 @@ public abstract class BufferedLineIterator implements Iterator> myBuffer; public BufferedLineIterator() { - myBuffer = new LinkedList>(); + myBuffer = new LinkedList<>(); } public abstract boolean hasNextBlock(); diff --git a/platform/diff-impl/src/com/intellij/diff/actions/DocumentsSynchronizer.java b/platform/diff-impl/src/com/intellij/diff/actions/DocumentsSynchronizer.java index 1b46787ba7a6..a78772419afd 100644 --- a/platform/diff-impl/src/com/intellij/diff/actions/DocumentsSynchronizer.java +++ b/platform/diff-impl/src/com/intellij/diff/actions/DocumentsSynchronizer.java @@ -25,7 +25,6 @@ import org.jetbrains.annotations.CalledInAwt; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; -import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; abstract class DocumentsSynchronizer { @@ -51,11 +50,8 @@ abstract class DocumentsSynchronizer { } }; - private final PropertyChangeListener myROListener = new PropertyChangeListener() { - @Override - public void propertyChange(PropertyChangeEvent evt) { - if (Document.PROP_WRITABLE.equals(evt.getPropertyName())) getDocument2().setReadOnly(!getDocument1().isWritable()); - } + private final PropertyChangeListener myROListener = event -> { + if (Document.PROP_WRITABLE.equals(event.getPropertyName())) getDocument2().setReadOnly(!getDocument1().isWritable()); }; protected DocumentsSynchronizer(@Nullable Project project, @NotNull Document document1, @NotNull Document document2) { @@ -85,17 +81,10 @@ abstract class DocumentsSynchronizer { @NotNull final CharSequence newText) { try { myDuringModification = true; - CommandProcessor.getInstance().executeCommand(myProject, new Runnable() { - @Override - public void run() { - assert endOffset <= document.getTextLength(); - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - document.replaceString(startOffset, endOffset, newText); - } - }); - } + CommandProcessor.getInstance().executeCommand(myProject, () -> { + ApplicationManager.getApplication().runWriteAction(() -> { + document.replaceString(startOffset, endOffset, newText); + }); }, "Synchronize document and its fragment", document); } finally { diff --git a/platform/diff-impl/src/com/intellij/diff/actions/impl/GoToChangePopupBuilder.java b/platform/diff-impl/src/com/intellij/diff/actions/impl/GoToChangePopupBuilder.java index 5827823e6878..3a968bc46212 100644 --- a/platform/diff-impl/src/com/intellij/diff/actions/impl/GoToChangePopupBuilder.java +++ b/platform/diff-impl/src/com/intellij/diff/actions/impl/GoToChangePopupBuilder.java @@ -126,12 +126,9 @@ public class GoToChangePopupBuilder { @Override public PopupStep onChosen(final DiffRequestProducer selectedValue, boolean finalChoice) { - return doFinalStep(new Runnable() { - @Override - public void run() { - int index = myChain.getRequests().indexOf(selectedValue); - myOnSelected.consume(index); - } + return doFinalStep(() -> { + int index = myChain.getRequests().indexOf(selectedValue); + myOnSelected.consume(index); }); } } diff --git a/platform/diff-impl/src/com/intellij/diff/actions/impl/SetEditorSettingsAction.java b/platform/diff-impl/src/com/intellij/diff/actions/impl/SetEditorSettingsAction.java index a318bb6c2932..5f1bdaf6a7b9 100644 --- a/platform/diff-impl/src/com/intellij/diff/actions/impl/SetEditorSettingsAction.java +++ b/platform/diff-impl/src/com/intellij/diff/actions/impl/SetEditorSettingsAction.java @@ -15,16 +15,17 @@ */ package com.intellij.diff.actions.impl; +import com.intellij.diff.tools.util.SyncScrollSupport; import com.intellij.diff.tools.util.base.HighlightingLevel; import com.intellij.diff.tools.util.base.TextDiffSettingsHolder; import com.intellij.icons.AllIcons; import com.intellij.openapi.actionSystem.*; import com.intellij.openapi.actionSystem.ex.ActionUtil; import com.intellij.openapi.editor.Editor; +import com.intellij.openapi.editor.actions.AbstractToggleUseSoftWrapsAction; import com.intellij.openapi.editor.ex.EditorGutterComponentEx; import com.intellij.openapi.editor.impl.EditorImpl; import com.intellij.openapi.project.DumbAware; -import com.intellij.util.Function; import com.intellij.util.containers.ContainerUtil; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; @@ -35,6 +36,7 @@ import java.util.List; public class SetEditorSettingsAction extends ActionGroup implements DumbAware { @NotNull private final TextDiffSettingsHolder.TextDiffSettings myTextSettings; @NotNull private final List myEditors; + @Nullable private SyncScrollSupport.Support mySyncScrollSupport; @NotNull private final AnAction[] myActions; @@ -123,8 +125,14 @@ public class SetEditorSettingsAction extends ActionGroup implements DumbAware { @Override public void apply(@NotNull Editor editor, boolean value) { - if (editor.getSettings().isUseSoftWraps() != value) { - editor.getSettings().setUseSoftWraps(value); + if (editor.getSettings().isUseSoftWraps() == value) return; + + if (mySyncScrollSupport != null) mySyncScrollSupport.enterDisableScrollSection(); + try { + AbstractToggleUseSoftWrapsAction.toggleSoftWraps(editor, null, value); + } + finally { + if (mySyncScrollSupport != null) mySyncScrollSupport.exitDisableScrollSection(); } } @@ -142,6 +150,10 @@ public class SetEditorSettingsAction extends ActionGroup implements DumbAware { }; } + public void setSyncScrollSupport(@Nullable SyncScrollSupport.Support syncScrollSupport) { + mySyncScrollSupport = syncScrollSupport; + } + public void applyDefaults() { for (AnAction action : myActions) { ((EditorSettingAction)action).applyDefaults(myEditors); @@ -151,7 +163,7 @@ public class SetEditorSettingsAction extends ActionGroup implements DumbAware { @NotNull @Override public AnAction[] getChildren(@Nullable AnActionEvent e) { - List result = new ArrayList(); + List result = new ArrayList<>(); ContainerUtil.addAll(result, myActions); result.add(Separator.getInstance()); result.add(ActionManager.getInstance().getAction(IdeActions.GROUP_DIFF_EDITOR_GUTTER_POPUP)); @@ -194,12 +206,7 @@ public class SetEditorSettingsAction extends ActionGroup implements DumbAware { public EditorHighlightingLayerAction() { super("Highlighting Level", true); - myOptions = ContainerUtil.map(HighlightingLevel.values(), new Function() { - @Override - public AnAction fun(HighlightingLevel level) { - return new OptionAction(level); - } - }, AnAction.EMPTY_ARRAY); + myOptions = ContainerUtil.map(HighlightingLevel.values(), level -> new OptionAction(level), AnAction.EMPTY_ARRAY); } @NotNull diff --git a/platform/diff-impl/src/com/intellij/diff/applications/ApplicationStarterBase.java b/platform/diff-impl/src/com/intellij/diff/applications/ApplicationStarterBase.java index dfb5e85bd3d9..5a6fe1d2518c 100644 --- a/platform/diff-impl/src/com/intellij/diff/applications/ApplicationStarterBase.java +++ b/platform/diff-impl/src/com/intellij/diff/applications/ApplicationStarterBase.java @@ -109,7 +109,7 @@ public abstract class ApplicationStarterBase extends ApplicationStarterEx { @NotNull public static List findFiles(@NotNull List filePaths, @Nullable String currentDirectory) throws Exception { - List files = new ArrayList(); + List files = new ArrayList<>(); for (String path : filePaths) { VirtualFile virtualFile = findFile(path, currentDirectory); diff --git a/platform/diff-impl/src/com/intellij/diff/comparison/ByChar.java b/platform/diff-impl/src/com/intellij/diff/comparison/ByChar.java index 3570efb6a145..dcf45202a8a7 100644 --- a/platform/diff-impl/src/com/intellij/diff/comparison/ByChar.java +++ b/platform/diff-impl/src/com/intellij/diff/comparison/ByChar.java @@ -136,7 +136,7 @@ public class ByChar { @NotNull CharSequence text1, @NotNull CharSequence text2, @NotNull FairDiffIterable changes) { - final List ranges = new ArrayList(); + final List ranges = new ArrayList<>(); for (Range ch : changes.iterateChanges()) { int startOffset1; diff --git a/platform/diff-impl/src/com/intellij/diff/comparison/ByLine.java b/platform/diff-impl/src/com/intellij/diff/comparison/ByLine.java index f763f5042a9c..f204eafde823 100644 --- a/platform/diff-impl/src/com/intellij/diff/comparison/ByLine.java +++ b/platform/diff-impl/src/com/intellij/diff/comparison/ByLine.java @@ -28,7 +28,6 @@ import com.intellij.openapi.progress.ProgressIndicator; import com.intellij.openapi.util.Pair; import com.intellij.openapi.util.registry.Registry; import com.intellij.openapi.util.text.StringUtil; -import com.intellij.util.Function; import com.intellij.util.containers.ContainerUtil; import gnu.trove.TIntArrayList; import org.jetbrains.annotations.NotNull; @@ -293,7 +292,7 @@ public class ByLine { private static List convertIntoFragments(@NotNull List lines1, @NotNull List lines2, @NotNull FairDiffIterable changes) { - List fragments = new ArrayList(); + List fragments = new ArrayList<>(); for (Range ch : changes.iterateChanges()) { IntPair offsets1 = getOffsets(lines1, ch.start1, ch.end1); IntPair offsets2 = getOffsets(lines2, ch.start2, ch.end2); @@ -306,12 +305,7 @@ public class ByLine { @NotNull private static List convertIntoFragments(@NotNull List conflicts) { - return ContainerUtil.map(conflicts, new Function() { - @Override - public MergeLineFragment fun(MergeRange ch) { - return new MergeLineFragmentImpl(ch); - } - }); + return ContainerUtil.map(conflicts, ch -> new MergeLineFragmentImpl(ch)); } @NotNull @@ -354,7 +348,7 @@ public class ByLine { @NotNull private static Pair, TIntArrayList> getBigLines(@NotNull List lines, int threshold) { - List bigLines = new ArrayList(lines.size()); + List bigLines = new ArrayList<>(lines.size()); TIntArrayList indexes = new TIntArrayList(lines.size()); for (int i = 0; i < lines.size(); i++) { @@ -372,7 +366,7 @@ public class ByLine { @NotNull List lines2, @NotNull FairDiffIterable iterable, @NotNull ProgressIndicator indicator) { - List changes = new ArrayList(); + List changes = new ArrayList<>(); for (Range ch : iterable.iterateChanges()) { Range expanded = TrimUtil.expand(lines1, lines2, ch.start1, ch.start2, ch.end1, ch.end2); @@ -388,7 +382,7 @@ public class ByLine { @NotNull private static List getLines(@NotNull CharSequence text, @NotNull ComparisonPolicy policy) { - List lines = new ArrayList(); + List lines = new ArrayList<>(); int offset = 0; while (true) { @@ -417,7 +411,7 @@ public class ByLine { @NotNull private static List convertToIgnoreWhitespace(@NotNull List original) { - List result = new ArrayList(original.size()); + List result = new ArrayList<>(original.size()); for (Line line : original) { result.add(Line.createIgnore(line.getOriginalText(), line.getOffset1())); diff --git a/platform/diff-impl/src/com/intellij/diff/comparison/ByWord.java b/platform/diff-impl/src/com/intellij/diff/comparison/ByWord.java index c738c6cb0993..3f97de4fbe4c 100644 --- a/platform/diff-impl/src/com/intellij/diff/comparison/ByWord.java +++ b/platform/diff-impl/src/com/intellij/diff/comparison/ByWord.java @@ -28,7 +28,6 @@ import com.intellij.diff.util.Range; import com.intellij.openapi.progress.ProgressIndicator; import com.intellij.openapi.util.Couple; import com.intellij.openapi.util.text.StringUtil; -import com.intellij.util.Function; import com.intellij.util.containers.ContainerUtil; import com.intellij.util.text.MergingCharSequence; import org.jetbrains.annotations.NotNull; @@ -128,7 +127,7 @@ public class ByWord { List wordBlocks = new LineFragmentSplitter(text1, text2, words1, words2, wordChanges, indicator).run(); - List lineBlocks = new ArrayList(wordBlocks.size()); + List lineBlocks = new ArrayList<>(wordBlocks.size()); for (WordBlock block : wordBlocks) { Range offsets = block.offsets; Range words = block.words; @@ -162,12 +161,7 @@ public class ByWord { @NotNull private static List convertIntoFragments(@NotNull List conflicts) { - return ContainerUtil.map(conflicts, new Function() { - @Override - public MergeWordFragment fun(MergeRange ch) { - return new MergeWordFragmentImpl(ch); - } - }); + return ContainerUtil.map(conflicts, ch -> new MergeWordFragmentImpl(ch)); } @NotNull @@ -485,8 +479,8 @@ public class ByWord { @NotNull private static Couple> splitIterable2Side(@NotNull FairDiffIterable changes, int offset) { - final List ranges1 = new ArrayList(); - final List ranges2 = new ArrayList(); + final List ranges1 = new ArrayList<>(); + final List ranges2 = new ArrayList<>(); for (Range ch : changes.iterateUnchanged()) { if (ch.end2 <= offset) { ranges1.add(new Range(ch.start1, ch.end1, ch.start2, ch.end2)); @@ -524,7 +518,7 @@ public class ByWord { myText2 = text2; myIndicator = indicator; - myChanges = new ArrayList(); + myChanges = new ArrayList<>(); } @NotNull @@ -564,7 +558,7 @@ public class ByWord { myText3 = text3; myIndicator = indicator; - myChanges = new ArrayList(); + myChanges = new ArrayList<>(); } @NotNull @@ -607,7 +601,7 @@ public class ByWord { myText2 = text2; myIndicator = indicator; - myChanges = new ArrayList(); + myChanges = new ArrayList<>(); } @NotNull @@ -644,7 +638,7 @@ public class ByWord { myText3 = text3; myIndicator = indicator; - myChanges = new ArrayList(); + myChanges = new ArrayList<>(); } @NotNull @@ -678,7 +672,7 @@ public class ByWord { myText2 = text2; myIndicator = indicator; - myChanges = new ArrayList(); + myChanges = new ArrayList<>(); } @NotNull @@ -733,7 +727,7 @@ public class ByWord { myText3 = text3; myIndicator = indicator; - myChanges = new ArrayList(); + myChanges = new ArrayList<>(); } @NotNull @@ -823,7 +817,7 @@ public class ByWord { @NotNull public static List getInlineChunks(@NotNull final CharSequence text) { - final List chunks = new ArrayList(); + final List chunks = new ArrayList<>(); final int len = text.length(); diff --git a/platform/diff-impl/src/com/intellij/diff/comparison/ChunkOptimizer.java b/platform/diff-impl/src/com/intellij/diff/comparison/ChunkOptimizer.java index f762d86637ee..5473af0c275a 100644 --- a/platform/diff-impl/src/com/intellij/diff/comparison/ChunkOptimizer.java +++ b/platform/diff-impl/src/com/intellij/diff/comparison/ChunkOptimizer.java @@ -53,7 +53,7 @@ abstract class ChunkOptimizer { myIterable = iterable; myIndicator = indicator; - myRanges = new ArrayList(); + myRanges = new ArrayList<>(); } @NotNull diff --git a/platform/diff-impl/src/com/intellij/diff/comparison/ComparisonManagerImpl.java b/platform/diff-impl/src/com/intellij/diff/comparison/ComparisonManagerImpl.java index 53128b5c9f76..4b212f6dc01b 100644 --- a/platform/diff-impl/src/com/intellij/diff/comparison/ComparisonManagerImpl.java +++ b/platform/diff-impl/src/com/intellij/diff/comparison/ComparisonManagerImpl.java @@ -61,7 +61,7 @@ public class ComparisonManagerImpl extends ComparisonManager { @NotNull ProgressIndicator indicator) throws DiffTooBigException { List lineFragments = compareLines(text1, text2, policy, indicator); - List fineFragments = new ArrayList(lineFragments.size()); + List fineFragments = new ArrayList<>(lineFragments.size()); int tooBigChunksCount = 0; for (LineFragment fragment : lineFragments) { @@ -209,13 +209,8 @@ public class ComparisonManagerImpl extends ComparisonManager { public List squash(@NotNull List oldFragments) { if (oldFragments.isEmpty()) return oldFragments; - final List newFragments = new ArrayList(); - processAdjoining(oldFragments, new Consumer>() { - @Override - public void consume(List fragments) { - newFragments.add(doSquash(fragments)); - } - }); + final List newFragments = new ArrayList<>(); + processAdjoining(oldFragments, fragments -> newFragments.add(doSquash(fragments))); return newFragments; } @@ -228,13 +223,8 @@ public class ComparisonManagerImpl extends ComparisonManager { if (!squash && !trim) return oldFragments; if (oldFragments.isEmpty()) return oldFragments; - final List newFragments = new ArrayList(); - processAdjoining(oldFragments, new Consumer>() { - @Override - public void consume(List fragments) { - newFragments.addAll(processAdjoining(fragments, text1, text2, policy, squash, trim)); - } - }); + final List newFragments = new ArrayList<>(); + processAdjoining(oldFragments, fragments -> newFragments.addAll(processAdjoining(fragments, text1, text2, policy, squash, trim))); return newFragments; } @@ -300,7 +290,7 @@ public class ComparisonManagerImpl extends ComparisonManager { LineFragment firstFragment = oldFragments.get(0); LineFragment lastFragment = oldFragments.get(oldFragments.size() - 1); - List newInnerFragments = new ArrayList(); + List newInnerFragments = new ArrayList<>(); for (LineFragment fragment : oldFragments) { for (DiffFragment innerFragment : extractInnerFragments(fragment)) { int shift1 = fragment.getStartOffset1() - firstFragment.getStartOffset1(); diff --git a/platform/diff-impl/src/com/intellij/diff/comparison/ComparisonMergeUtil.java b/platform/diff-impl/src/com/intellij/diff/comparison/ComparisonMergeUtil.java index c5e9c358376b..cf531d50e866 100644 --- a/platform/diff-impl/src/com/intellij/diff/comparison/ComparisonMergeUtil.java +++ b/platform/diff-impl/src/com/intellij/diff/comparison/ComparisonMergeUtil.java @@ -35,8 +35,8 @@ public class ComparisonMergeUtil { FairMergeBuilder builder = new FairMergeBuilder(); - PeekIterator unchanged1 = new PeekIterator(fragments1.unchanged()); - PeekIterator unchanged2 = new PeekIterator(fragments2.unchanged()); + PeekIterator unchanged1 = new PeekIterator<>(fragments1.unchanged()); + PeekIterator unchanged2 = new PeekIterator<>(fragments2.unchanged()); while (!unchanged1.atEnd() || !unchanged2.atEnd()) { indicator.checkCanceled(); @@ -69,7 +69,7 @@ public class ComparisonMergeUtil { } private static class FairMergeBuilder { - @NotNull private final ArrayList myResult = new ArrayList(); + @NotNull private final ArrayList myResult = new ArrayList<>(); @NotNull private final EqualPair[] myPairs = new EqualPair[2]; // LEFT, RIGHT @NotNull private final int[] myProcessed = new int[]{0, 0, 0}; // LEFT, RIGHT, BASE diff --git a/platform/diff-impl/src/com/intellij/diff/comparison/LineFragmentSplitter.java b/platform/diff-impl/src/com/intellij/diff/comparison/LineFragmentSplitter.java index 4a822a3ac4a9..39dade48257c 100644 --- a/platform/diff-impl/src/com/intellij/diff/comparison/LineFragmentSplitter.java +++ b/platform/diff-impl/src/com/intellij/diff/comparison/LineFragmentSplitter.java @@ -38,7 +38,7 @@ class LineFragmentSplitter { @NotNull private final FairDiffIterable myIterable; @NotNull private final ProgressIndicator myIndicator; - @NotNull private final List myResult = new ArrayList(); + @NotNull private final List myResult = new ArrayList<>(); public LineFragmentSplitter(@NotNull CharSequence text1, @NotNull CharSequence text2, diff --git a/platform/diff-impl/src/com/intellij/diff/comparison/iterables/DiffIterableBase.java b/platform/diff-impl/src/com/intellij/diff/comparison/iterables/DiffIterableBase.java index df65b239e024..a0f882d7455a 100644 --- a/platform/diff-impl/src/com/intellij/diff/comparison/iterables/DiffIterableBase.java +++ b/platform/diff-impl/src/com/intellij/diff/comparison/iterables/DiffIterableBase.java @@ -24,23 +24,13 @@ abstract class DiffIterableBase implements DiffIterable { @NotNull @Override public Iterable iterateUnchanged() { - return new Iterable() { - @Override - public Iterator iterator() { - return unchanged(); - } - }; + return this::unchanged; } @NotNull @Override public Iterable iterateChanges() { - return new Iterable() { - @Override - public Iterator iterator() { - return changes(); - } - }; + return this::changes; } protected static abstract class MyIterator implements Iterator { diff --git a/platform/diff-impl/src/com/intellij/diff/comparison/iterables/DiffIterableUtil.java b/platform/diff-impl/src/com/intellij/diff/comparison/iterables/DiffIterableUtil.java index 5cee140c10f6..11f05ba2c5d7 100644 --- a/platform/diff-impl/src/com/intellij/diff/comparison/iterables/DiffIterableUtil.java +++ b/platform/diff-impl/src/com/intellij/diff/comparison/iterables/DiffIterableUtil.java @@ -143,7 +143,7 @@ public class DiffIterableUtil { @NotNull public static List convertIntoFragments(@NotNull DiffIterable changes) { - final List fragments = new ArrayList(); + final List fragments = new ArrayList<>(); for (Range ch : changes.iterateChanges()) { fragments.add(new DiffFragmentImpl(ch.start1, ch.end1, ch.start2, ch.end2)); } @@ -152,52 +152,47 @@ public class DiffIterableUtil { @NotNull public static Iterable> iterateAll(@NotNull final DiffIterable iterable) { - return new Iterable>() { + return () -> new Iterator>() { + @NotNull private final Iterator myChanges = iterable.changes(); + @NotNull private final Iterator myUnchanged = iterable.unchanged(); + + @Nullable private Range lastChanged = myChanges.hasNext() ? myChanges.next() : null; + @Nullable private Range lastUnchanged = myUnchanged.hasNext() ? myUnchanged.next() : null; + @Override - public Iterator> iterator() { - return new Iterator>() { - @NotNull private final Iterator myChanges = iterable.changes(); - @NotNull private final Iterator myUnchanged = iterable.unchanged(); + public boolean hasNext() { + return lastChanged != null || lastUnchanged != null; + } - @Nullable private Range lastChanged = myChanges.hasNext() ? myChanges.next() : null; - @Nullable private Range lastUnchanged = myUnchanged.hasNext() ? myUnchanged.next() : null; + @Override + public Pair next() { + boolean equals; + if (lastChanged == null) { + equals = true; + } + else if (lastUnchanged == null) { + equals = false; + } + else { + equals = lastUnchanged.start1 < lastChanged.start1 || lastUnchanged.start2 < lastChanged.start2; + } - @Override - public boolean hasNext() { - return lastChanged != null || lastUnchanged != null; - } + if (equals) { + Range range = lastUnchanged; + lastUnchanged = myUnchanged.hasNext() ? myUnchanged.next() : null; + //noinspection ConstantConditions + return Pair.create(range, true); + } + else { + Range range = lastChanged; + lastChanged = myChanges.hasNext() ? myChanges.next() : null; + return Pair.create(range, false); + } + } - @Override - public Pair next() { - boolean equals; - if (lastChanged == null) { - equals = true; - } - else if (lastUnchanged == null) { - equals = false; - } - else { - equals = lastUnchanged.start1 < lastChanged.start1 || lastUnchanged.start2 < lastChanged.start2; - } - - if (equals) { - Range range = lastUnchanged; - lastUnchanged = myUnchanged.hasNext() ? myUnchanged.next() : null; - //noinspection ConstantConditions - return Pair.create(range, true); - } - else { - Range range = lastChanged; - lastChanged = myChanges.hasNext() ? myChanges.next() : null; - return Pair.create(range, false); - } - } - - @Override - public void remove() { - throw new UnsupportedOperationException(); - } - }; + @Override + public void remove() { + throw new UnsupportedOperationException(); } }; } @@ -368,8 +363,8 @@ public class DiffIterableUtil { Range range = pair.first; boolean equals = pair.second; - List data1 = new ArrayList(); - List data2 = new ArrayList(); + List data1 = new ArrayList<>(); + List data2 = new ArrayList<>(); for (int i = range.start1; i < range.end1; i++) { data1.add(objects1.get(i)); @@ -378,7 +373,7 @@ public class DiffIterableUtil { data2.add(objects2.get(i)); } - result.add(new LineRangeData(data1, data2, equals)); + result.add(new LineRangeData<>(data1, data2, equals)); } return result; diff --git a/platform/diff-impl/src/com/intellij/diff/impl/CacheDiffRequestChainProcessor.java b/platform/diff-impl/src/com/intellij/diff/impl/CacheDiffRequestChainProcessor.java index 93b4593ae8d0..1580e555b2a5 100644 --- a/platform/diff-impl/src/com/intellij/diff/impl/CacheDiffRequestChainProcessor.java +++ b/platform/diff-impl/src/com/intellij/diff/impl/CacheDiffRequestChainProcessor.java @@ -26,7 +26,6 @@ import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.progress.ProcessCanceledException; import com.intellij.openapi.progress.ProgressIndicator; import com.intellij.openapi.project.Project; -import com.intellij.util.Consumer; import com.intellij.util.containers.ContainerUtil; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; @@ -123,13 +122,10 @@ public abstract class CacheDiffRequestChainProcessor extends CacheDiffRequestPro @NotNull private AnAction createGoToChangeAction() { - return GoToChangePopupBuilder.create(myRequestChain, new Consumer() { - @Override - public void consume(Integer index) { - if (index >= 0 && index != myRequestChain.getIndex()) { - myRequestChain.setIndex(index); - updateRequest(); - } + return GoToChangePopupBuilder.create(myRequestChain, index -> { + if (index >= 0 && index != myRequestChain.getIndex()) { + myRequestChain.setIndex(index); + updateRequest(); } }); } diff --git a/platform/diff-impl/src/com/intellij/diff/impl/CacheDiffRequestProcessor.java b/platform/diff-impl/src/com/intellij/diff/impl/CacheDiffRequestProcessor.java index 790e85a7f551..91813ca63150 100644 --- a/platform/diff-impl/src/com/intellij/diff/impl/CacheDiffRequestProcessor.java +++ b/platform/diff-impl/src/com/intellij/diff/impl/CacheDiffRequestProcessor.java @@ -32,7 +32,6 @@ import com.intellij.openapi.progress.util.ProgressWindow; import com.intellij.openapi.project.DumbAwareAction; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.UserDataHolder; -import com.intellij.util.Function; import org.jetbrains.annotations.CalledInAwt; import org.jetbrains.annotations.CalledInBackground; import org.jetbrains.annotations.NotNull; @@ -44,7 +43,7 @@ public abstract class CacheDiffRequestProcessor extends DiffRequestProcessor private static final Logger LOG = Logger.getInstance(CacheDiffRequestProcessor.class); @NotNull private final SoftHardCacheMap myRequestCache = - new SoftHardCacheMap(5, 5); + new SoftHardCacheMap<>(5, 5); @NotNull private final DiffTaskQueue myQueue = new DiffTaskQueue(); @@ -108,25 +107,15 @@ public abstract class CacheDiffRequestProcessor extends DiffRequestProcessor } myQueue.executeAndTryWait( - new Function() { - @Override - public Runnable fun(ProgressIndicator indicator) { - final DiffRequest request = doLoadRequest(requestProvider, indicator); - return new Runnable() { - @CalledInAwt - @Override - public void run() { - myRequestCache.put(requestProvider, request); - applyRequest(request, force, scrollToChangePolicy); - } - }; - } + indicator -> { + final DiffRequest request = doLoadRequest(requestProvider, indicator); + return () -> { + myRequestCache.put(requestProvider, request); + applyRequest(request, force, scrollToChangePolicy); + }; }, - new Runnable() { - @Override - public void run() { - applyRequest(new LoadingDiffRequest(getRequestName(requestProvider)), force, scrollToChangePolicy); - } + () -> { + applyRequest(new LoadingDiffRequest(getRequestName(requestProvider)), force, scrollToChangePolicy); }, ProgressWindow.DEFAULT_PROGRESS_DIALOG_POSTPONE_TIME_MILLIS ); diff --git a/platform/diff-impl/src/com/intellij/diff/impl/DiffRequestPanelImpl.java b/platform/diff-impl/src/com/intellij/diff/impl/DiffRequestPanelImpl.java index 22628a1c1c07..ebc9f4983fcf 100644 --- a/platform/diff-impl/src/com/intellij/diff/impl/DiffRequestPanelImpl.java +++ b/platform/diff-impl/src/com/intellij/diff/impl/DiffRequestPanelImpl.java @@ -51,12 +51,7 @@ public class DiffRequestPanelImpl implements DiffRequestPanel { @Override public void setRequest(@Nullable DiffRequest request) { myProcessor.setRequest(request); - UIUtil.invokeLaterIfNeeded(new Runnable() { - @Override - public void run() { - myProcessor.updateRequest(); - } - }); + UIUtil.invokeLaterIfNeeded(() -> myProcessor.updateRequest()); } @Override diff --git a/platform/diff-impl/src/com/intellij/diff/impl/DiffRequestProcessor.java b/platform/diff-impl/src/com/intellij/diff/impl/DiffRequestProcessor.java index def1fb25b190..96e28efe6421 100644 --- a/platform/diff-impl/src/com/intellij/diff/impl/DiffRequestProcessor.java +++ b/platform/diff-impl/src/com/intellij/diff/impl/DiffRequestProcessor.java @@ -51,7 +51,10 @@ import com.intellij.openapi.ui.Messages; import com.intellij.openapi.ui.popup.Balloon; import com.intellij.openapi.ui.popup.JBPopupFactory; import com.intellij.openapi.ui.popup.ListPopup; -import com.intellij.openapi.util.*; +import com.intellij.openapi.util.Disposer; +import com.intellij.openapi.util.Key; +import com.intellij.openapi.util.UserDataHolder; +import com.intellij.openapi.util.UserDataHolderBase; import com.intellij.openapi.wm.IdeFocusManager; import com.intellij.openapi.wm.ex.IdeFocusTraversalPolicy; import com.intellij.ui.HintHint; @@ -115,7 +118,7 @@ public abstract class DiffRequestProcessor implements Disposable { mySettings = DiffSettingsHolder.getInstance().getSettings(myContext.getUserData(DiffUserDataKeys.PLACE)); myAvailableTools = DiffManagerEx.getInstance().getDiffTools(); - myToolOrder = new ArrayList(getToolOrderFromSettings(myAvailableTools)); + myToolOrder = new ArrayList<>(getToolOrderFromSettings(myAvailableTools)); // UI @@ -144,12 +147,7 @@ public abstract class DiffRequestProcessor implements Disposable { myState = EmptyState.INSTANCE; myContentPanel.setContent(DiffUtil.createMessagePanel(((LoadingDiffRequest)myActiveRequest).getMessage())); - myOpenInEditorAction = new OpenInEditorAction(new Runnable() { - @Override - public void run() { - onAfterNavigate(); - } - }); + myOpenInEditorAction = new OpenInEditorAction(() -> onAfterNavigate()); } // @@ -187,7 +185,7 @@ public abstract class DiffRequestProcessor implements Disposable { @NotNull private List filterFittedTools(@NotNull List tools) { - List result = new ArrayList(); + List result = new ArrayList<>(); for (DiffTool tool : tools) { try { if (tool instanceof FrameDiffTool && tool.canShow(myContext, myActiveRequest)) { @@ -253,16 +251,12 @@ public abstract class DiffRequestProcessor implements Disposable { force = force || (myQueuedApplyRequest != null && myQueuedApplyRequest.force); myQueuedApplyRequest = new ApplyData(request, force, scrollToChangePolicy); - Runnable task = new Runnable() { - @Override - public void run() { - if (myQueuedApplyRequest == null || myDisposed) return; - doApplyRequest(myQueuedApplyRequest.request, myQueuedApplyRequest.force, myQueuedApplyRequest.scrollToChangePolicy); - myQueuedApplyRequest = null; - } - }; - IdeFocusManager.getInstance(myProject).doWhenFocusSettlesDown(task); + IdeFocusManager.getInstance(myProject).doWhenFocusSettlesDown(() -> { + if (myQueuedApplyRequest == null || myDisposed) return; + doApplyRequest(myQueuedApplyRequest.request, myQueuedApplyRequest.force, myQueuedApplyRequest.scrollToChangePolicy); + myQueuedApplyRequest = null; + }); } @CalledInAwt @@ -349,16 +343,11 @@ public abstract class DiffRequestProcessor implements Disposable { @NotNull protected List getToolOrderFromSettings(@NotNull List availableTools) { - List result = new ArrayList(); + List result = new ArrayList<>(); List savedOrder = getSettings().getDiffToolsOrder(); for (final String clazz : savedOrder) { - DiffTool tool = ContainerUtil.find(availableTools, new Condition() { - @Override - public boolean value(DiffTool tool) { - return tool.getClass().getCanonicalName().equals(clazz); - } - }); + DiffTool tool = ContainerUtil.find(availableTools, t -> t.getClass().getCanonicalName().equals(clazz)); if (tool != null) result.add(tool); } @@ -370,7 +359,7 @@ public abstract class DiffRequestProcessor implements Disposable { } protected void updateToolOrderSettings(@NotNull List toolOrder) { - List savedOrder = new ArrayList(); + List savedOrder = new ArrayList<>(); for (DiffTool tool : toolOrder) { savedOrder.add(tool.getClass().getCanonicalName()); } @@ -380,24 +369,21 @@ public abstract class DiffRequestProcessor implements Disposable { @Override public void dispose() { if (myDisposed) return; - UIUtil.invokeLaterIfNeeded(new Runnable() { - @Override - public void run() { - if (myDisposed) return; - myDisposed = true; + UIUtil.invokeLaterIfNeeded(() -> { + if (myDisposed) return; + myDisposed = true; - onDispose(); + onDispose(); - myState.destroy(); - myToolbarStatusPanel.setContent(null); - myToolbarPanel.setContent(null); - myContentPanel.setContent(null); + myState.destroy(); + myToolbarStatusPanel.setContent(null); + myToolbarPanel.setContent(null); + myContentPanel.setContent(null); - myActiveRequest.onAssigned(false); + myActiveRequest.onAssigned(false); - myState = EmptyState.INSTANCE; - myActiveRequest = NoDiffRequest.INSTANCE; - } + myState = EmptyState.INSTANCE; + myActiveRequest = NoDiffRequest.INSTANCE; }); } @@ -405,7 +391,7 @@ public abstract class DiffRequestProcessor implements Disposable { protected DefaultActionGroup collectToolbarActions(@Nullable List viewerActions) { DefaultActionGroup group = new DefaultActionGroup(); - List navigationActions = new ArrayList(); + List navigationActions = new ArrayList<>(); navigationActions.addAll(getNavigationActions()); navigationActions.add(myOpenInEditorAction); navigationActions.add(new MyChangeDiffToolAction()); @@ -432,7 +418,7 @@ public abstract class DiffRequestProcessor implements Disposable { protected DefaultActionGroup collectPopupActions(@Nullable List viewerActions) { DefaultActionGroup group = new DefaultActionGroup(); - List selectToolActions = new ArrayList(); + List selectToolActions = new ArrayList<>(); for (DiffTool tool : getAvailableFittedTools()) { if (tool == myState.getActiveTool()) continue; selectToolActions.add(new DiffToolToggleAction(tool)); @@ -1172,7 +1158,7 @@ public abstract class DiffRequestProcessor implements Disposable { FrameDiffTool.ToolbarComponents toolbarComponents1 = myViewer.init(); FrameDiffTool.ToolbarComponents toolbarComponents2 = myWrapperViewer.init(); - List toolbarActions = new ArrayList(); + List toolbarActions = new ArrayList<>(); if (toolbarComponents1.toolbarActions != null) toolbarActions.addAll(toolbarComponents1.toolbarActions); if (toolbarComponents2.toolbarActions != null) { if (!toolbarActions.isEmpty() && !toolbarComponents2.toolbarActions.isEmpty()) toolbarActions.add(Separator.getInstance()); @@ -1180,7 +1166,7 @@ public abstract class DiffRequestProcessor implements Disposable { } buildToolbar(toolbarActions); - List popupActions = new ArrayList(); + List popupActions = new ArrayList<>(); if (toolbarComponents1.popupActions != null) popupActions.addAll(toolbarComponents1.popupActions); if (toolbarComponents2.popupActions != null) { if (!popupActions.isEmpty() && !toolbarComponents2.popupActions.isEmpty()) popupActions.add(Separator.getInstance()); diff --git a/platform/diff-impl/src/com/intellij/diff/impl/DiffSettingsHolder.java b/platform/diff-impl/src/com/intellij/diff/impl/DiffSettingsHolder.java index f669f8ab4a93..233320827d5e 100644 --- a/platform/diff-impl/src/com/intellij/diff/impl/DiffSettingsHolder.java +++ b/platform/diff-impl/src/com/intellij/diff/impl/DiffSettingsHolder.java @@ -43,7 +43,7 @@ public class DiffSettingsHolder implements PersistentStateComponent DIFF_TOOLS_ORDER = new ArrayList(); + @NotNull public List DIFF_TOOLS_ORDER = new ArrayList<>(); public boolean SYNC_BINARY_EDITOR_SETTINGS = true; } @@ -114,7 +114,7 @@ public class DiffSettingsHolder implements PersistentStateComponent PLACES_MAP = new HashMap(); + public Map PLACES_MAP = new HashMap<>(); public SharedSettings SHARED_SETTINGS = new SharedSettings(); } diff --git a/platform/diff-impl/src/com/intellij/diff/impl/DiffWindowBase.java b/platform/diff-impl/src/com/intellij/diff/impl/DiffWindowBase.java index e9970e8f09f0..cb0139fc9fdc 100644 --- a/platform/diff-impl/src/com/intellij/diff/impl/DiffWindowBase.java +++ b/platform/diff-impl/src/com/intellij/diff/impl/DiffWindowBase.java @@ -21,7 +21,6 @@ import com.intellij.diff.util.DiffUtil; import com.intellij.openapi.project.Project; import com.intellij.openapi.ui.WindowWrapper; import com.intellij.openapi.ui.WindowWrapperBuilder; -import com.intellij.openapi.util.Computable; import com.intellij.openapi.util.Disposer; import com.intellij.util.ImageLoader; import org.jetbrains.annotations.NotNull; @@ -54,17 +53,11 @@ public abstract class DiffWindowBase { .setProject(myProject) .setParent(myHints.getParent()) .setDimensionServiceKey(dialogGroupKey) - .setPreferredFocusedComponent(new Computable() { - @Override - public JComponent compute() { - return myProcessor.getPreferredFocusedComponent(); - } + .setPreferredFocusedComponent(() -> { + return myProcessor.getPreferredFocusedComponent(); }) - .setOnShowCallback(new Runnable() { - @Override - public void run() { - myProcessor.updateRequest(); - } + .setOnShowCallback(() -> { + myProcessor.updateRequest(); }) .build(); myWrapper.setImage(ImageLoader.loadFromResource("/diff/Diff.png")); diff --git a/platform/diff-impl/src/com/intellij/diff/merge/BinaryMergeTool.java b/platform/diff-impl/src/com/intellij/diff/merge/BinaryMergeTool.java index 92e7457450a3..201fa506e2ae 100644 --- a/platform/diff-impl/src/com/intellij/diff/merge/BinaryMergeTool.java +++ b/platform/diff-impl/src/com/intellij/diff/merge/BinaryMergeTool.java @@ -23,7 +23,6 @@ import com.intellij.diff.requests.DiffRequest; import com.intellij.diff.requests.SimpleDiffRequest; import com.intellij.diff.tools.binary.ThreesideBinaryDiffViewer; import com.intellij.diff.tools.holders.BinaryEditorHolder; -import com.intellij.openapi.util.BooleanGetter; import com.intellij.openapi.util.Disposer; import com.intellij.util.containers.ContainerUtil; import org.jetbrains.annotations.CalledInAwt; @@ -31,7 +30,6 @@ import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.swing.*; -import java.awt.event.ActionEvent; import java.util.List; public class BinaryMergeTool implements MergeTool { @@ -111,12 +109,7 @@ public class BinaryMergeTool implements MergeTool { components.statusPanel = init.statusPanel; components.toolbarActions = init.toolbarActions; - components.closeHandler = new BooleanGetter() { - @Override - public boolean get() { - return MergeUtil.showExitWithoutApplyingChangesDialog(BinaryMergeViewer.this, myMergeRequest, myMergeContext); - } - }; + components.closeHandler = () -> MergeUtil.showExitWithoutApplyingChangesDialog(this, myMergeRequest, myMergeContext); return components; } @@ -125,18 +118,7 @@ public class BinaryMergeTool implements MergeTool { @Override public Action getResolveAction(@NotNull final MergeResult result) { if (result == MergeResult.RESOLVED) return null; - - String caption = MergeUtil.getResolveActionTitle(result, myMergeRequest, myMergeContext); - return new AbstractAction(caption) { - @Override - public void actionPerformed(ActionEvent e) { - if (result == MergeResult.CANCEL && - !MergeUtil.showExitWithoutApplyingChangesDialog(BinaryMergeViewer.this, myMergeRequest, myMergeContext)) { - return; - } - myMergeContext.finishMerge(result); - } - }; + return MergeUtil.createSimpleResolveAction(result, myMergeRequest, myMergeContext, this); } @Override diff --git a/platform/diff-impl/src/com/intellij/diff/merge/MergeRequestProcessor.java b/platform/diff-impl/src/com/intellij/diff/merge/MergeRequestProcessor.java index 680a46a6f631..b6e9fd9f03ad 100644 --- a/platform/diff-impl/src/com/intellij/diff/merge/MergeRequestProcessor.java +++ b/platform/diff-impl/src/com/intellij/diff/merge/MergeRequestProcessor.java @@ -207,17 +207,14 @@ public abstract class MergeRequestProcessor implements Disposable { @Override public void dispose() { if (myDisposed) return; - UIUtil.invokeLaterIfNeeded(new Runnable() { - @Override - public void run() { - if (myDisposed) return; - myDisposed = true; + UIUtil.invokeLaterIfNeeded(() -> { + if (myDisposed) return; + myDisposed = true; - onDispose(); + onDispose(); - destroyViewer(); - applyRequestResult(MergeResult.CANCEL); - } + destroyViewer(); + applyRequestResult(MergeResult.CANCEL); }); } diff --git a/platform/diff-impl/src/com/intellij/diff/merge/MergeUtil.java b/platform/diff-impl/src/com/intellij/diff/merge/MergeUtil.java index 709800913a47..aa706cb260e0 100644 --- a/platform/diff-impl/src/com/intellij/diff/merge/MergeUtil.java +++ b/platform/diff-impl/src/com/intellij/diff/merge/MergeUtil.java @@ -33,9 +33,27 @@ import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.swing.*; +import java.awt.event.ActionEvent; import java.util.List; public class MergeUtil { + @NotNull + public static Action createSimpleResolveAction(@NotNull MergeResult result, + @NotNull MergeRequest request, + @NotNull MergeContext context, + @NotNull MergeViewer viewer) { + String caption = getResolveActionTitle(result, request, context); + return new AbstractAction(caption) { + @Override + public void actionPerformed(ActionEvent e) { + if (result == MergeResult.CANCEL && !showExitWithoutApplyingChangesDialog(viewer, request, context)) { + return; + } + context.finishMerge(result); + } + }; + } + @NotNull public static String getResolveActionTitle(@NotNull MergeResult result, @NotNull MergeRequest request, @NotNull MergeContext context) { Function getter = DiffUtil.getUserData(request, context, DiffUserDataKeysEx.MERGE_ACTION_CAPTIONS); diff --git a/platform/diff-impl/src/com/intellij/diff/merge/TextMergeChange.java b/platform/diff-impl/src/com/intellij/diff/merge/TextMergeChange.java index ab74baa42318..ef74ced12797 100644 --- a/platform/diff-impl/src/com/intellij/diff/merge/TextMergeChange.java +++ b/platform/diff-impl/src/com/intellij/diff/merge/TextMergeChange.java @@ -47,7 +47,7 @@ public class TextMergeChange extends ThreesideDiffChangeBase { @NotNull private final TextMergeViewer myMergeViewer; @NotNull private final TextMergeViewer.MyThreesideViewer myViewer; - @NotNull private final List myOperations = new ArrayList(); + @NotNull private final List myOperations = new ArrayList<>(); @NotNull private final MergeLineFragment myFragment; @@ -325,32 +325,20 @@ public class TextMergeChange extends ThreesideDiffChangeBase { private GutterIconRenderer createApplyRenderer(@NotNull final Side side, final boolean modifier) { if (isResolved(side)) return null; Icon icon = isOnesideAppliedConflict() ? DiffUtil.getArrowDownIcon(side) : DiffUtil.getArrowIcon(side); - return createIconRenderer(DiffBundle.message("merge.dialog.apply.change.action.name"), icon, isConflict(), new Runnable() { - @Override - public void run() { - myViewer.executeMergeCommand("Accept change", Collections.singletonList(TextMergeChange.this), new Runnable() { - @Override - public void run() { - myViewer.replaceChange(TextMergeChange.this, side, modifier); - } - }); - } + return createIconRenderer(DiffBundle.message("merge.dialog.apply.change.action.name"), icon, isConflict(), () -> { + myViewer.executeMergeCommand("Accept change", Collections.singletonList(this), () -> { + myViewer.replaceChange(this, side, modifier); + }); }); } @Nullable private GutterIconRenderer createIgnoreRenderer(@NotNull final Side side, final boolean modifier) { if (isResolved(side)) return null; - return createIconRenderer(DiffBundle.message("merge.dialog.ignore.change.action.name"), AllIcons.Diff.Remove, isConflict(), new Runnable() { - @Override - public void run() { - myViewer.executeMergeCommand("Ignore change", Collections.singletonList(TextMergeChange.this), new Runnable() { - @Override - public void run() { - myViewer.ignoreChange(TextMergeChange.this, side, modifier); - } - }); - } + return createIconRenderer(DiffBundle.message("merge.dialog.ignore.change.action.name"), AllIcons.Diff.Remove, isConflict(), () -> { + myViewer.executeMergeCommand("Ignore change", Collections.singletonList(this), () -> { + myViewer.ignoreChange(this, side, modifier); + }); }); } diff --git a/platform/diff-impl/src/com/intellij/diff/merge/TextMergeViewer.java b/platform/diff-impl/src/com/intellij/diff/merge/TextMergeViewer.java index f0d75cedbefe..70399b13db58 100644 --- a/platform/diff-impl/src/com/intellij/diff/merge/TextMergeViewer.java +++ b/platform/diff-impl/src/com/intellij/diff/merge/TextMergeViewer.java @@ -55,15 +55,11 @@ import com.intellij.openapi.project.Project; import com.intellij.openapi.ui.MessageType; import com.intellij.openapi.ui.Messages; import com.intellij.openapi.ui.popup.Balloon; -import com.intellij.openapi.ui.popup.BalloonBuilder; import com.intellij.openapi.ui.popup.JBPopupFactory; -import com.intellij.openapi.util.BooleanGetter; -import com.intellij.openapi.util.Condition; import com.intellij.openapi.util.Disposer; import com.intellij.ui.HyperlinkAdapter; import com.intellij.ui.awt.RelativePoint; import com.intellij.util.Alarm; -import com.intellij.util.Function; import com.intellij.util.containers.ContainerUtil; import com.intellij.util.containers.hash.HashSet; import com.intellij.util.ui.JBUI; @@ -140,12 +136,7 @@ public class TextMergeViewer implements MergeTool.MergeViewer { components.statusPanel = init.statusPanel; components.toolbarActions = init.toolbarActions; - components.closeHandler = new BooleanGetter() { - @Override - public boolean get() { - return MergeUtil.showExitWithoutApplyingChangesDialog(TextMergeViewer.this, myMergeRequest, myMergeContext); - } - }; + components.closeHandler = () -> MergeUtil.showExitWithoutApplyingChangesDialog(this, myMergeRequest, myMergeContext); return components; } @@ -180,7 +171,7 @@ public class TextMergeViewer implements MergeTool.MergeViewer { @NotNull private final MyInnerDiffWorker myInnerDiffWorker; // all changes - both applied and unapplied ones - @NotNull private final List myAllMergeChanges = new ArrayList(); + @NotNull private final List myAllMergeChanges = new ArrayList<>(); private boolean myInitialRediffStarted; private boolean myInitialRediffFinished; @@ -189,7 +180,7 @@ public class TextMergeViewer implements MergeTool.MergeViewer { @Nullable private MergeCommandAction myCurrentMergeCommand; private int myBulkChangeUpdateDepth; - private final Set myChangesToUpdate = new HashSet(); + private final Set myChangesToUpdate = new HashSet<>(); public MyThreesideViewer(@NotNull DiffContext context, @NotNull ContentDiffRequest request) { super(context, request); @@ -221,7 +212,7 @@ public class TextMergeViewer implements MergeTool.MergeViewer { @NotNull @Override protected List createToolbarActions() { - List group = new ArrayList(); + List group = new ArrayList<>(); group.add(new MyHighlightPolicySettingAction()); group.add(new MyToggleAutoScrollAction()); @@ -243,7 +234,7 @@ public class TextMergeViewer implements MergeTool.MergeViewer { @NotNull @Override protected List createEditorPopupActions() { - List group = new ArrayList(); + List group = new ArrayList<>(); group.add(new ApplySelectedChangesAction(Side.LEFT, false)); group.add(new ApplySelectedChangesAction(Side.RIGHT, false)); @@ -262,7 +253,7 @@ public class TextMergeViewer implements MergeTool.MergeViewer { @Nullable @Override protected List createPopupActions() { - List group = new ArrayList(); + List group = new ArrayList<>(); group.add(Separator.getInstance()); group.add(new MyToggleAutoScrollAction()); @@ -309,14 +300,11 @@ public class TextMergeViewer implements MergeTool.MergeViewer { final Document baseDocument = ThreeSide.BASE.select(myMergeRequest.getContents()).getDocument(); final Document outputDocument = myMergeRequest.getOutputContent().getDocument(); - DiffUtil.executeWriteCommand(outputDocument, getProject(), "Init merge content", new Runnable() { - @Override - public void run() { - outputDocument.setText(baseDocument.getCharsSequence()); - if (myUndoManager != null) { - DocumentReference ref = DocumentReferenceManager.getInstance().create(outputDocument); - myUndoManager.nonundoableActionPerformed(ref, false); - } + DiffUtil.executeWriteCommand(outputDocument, getProject(), "Init merge content", () -> { + outputDocument.setText(baseDocument.getCharsSequence()); + if (myUndoManager != null) { + DocumentReference ref = DocumentReferenceManager.getInstance().create(outputDocument); + myUndoManager.nonundoableActionPerformed(ref, false); } }); } @@ -346,29 +334,26 @@ public class TextMergeViewer implements MergeTool.MergeViewer { // we need invokeLater() here because viewer is partially-initialized (ex: there are no toolbar or status panel) // user can see this state while we're showing progress indicator, so we want let init() to finish. - ApplicationManager.getApplication().invokeLater(new Runnable() { - @Override - public void run() { - ProgressManager.getInstance().run(new Task.Modal(getProject(), "Computing differences...", true) { - private Runnable myCallback; + ApplicationManager.getApplication().invokeLater(() -> { + ProgressManager.getInstance().run(new Task.Modal(getProject(), "Computing differences...", true) { + private Runnable myCallback; - @Override - public void run(@NotNull ProgressIndicator indicator) { - myCallback = doPerformRediff(indicator); - } + @Override + public void run(@NotNull ProgressIndicator indicator) { + myCallback = doPerformRediff(indicator); + } - @Override - public void onCancel() { - myMergeContext.finishMerge(MergeResult.CANCEL); - } + @Override + public void onCancel() { + myMergeContext.finishMerge(MergeResult.CANCEL); + } - @Override - public void onSuccess() { - if (isDisposed()) return; - myCallback.run(); - } - }); - } + @Override + public void onSuccess() { + if (isDisposed()) return; + myCallback.run(); + } + }); }); } @@ -395,43 +380,37 @@ public class TextMergeViewer implements MergeTool.MergeViewer { } catch (Throwable e) { LOG.error(e); - return new Runnable() { - @Override - public void run() { - clearDiffPresentation(); - myPanel.setErrorContent(); - } + return () -> { + clearDiffPresentation(); + myPanel.setErrorContent(); }; } } @NotNull private Runnable apply(@NotNull final List fragments) { - return new Runnable() { - @Override - public void run() { - setInitialOutputContent(); + return () -> { + setInitialOutputContent(); - clearDiffPresentation(); - resetChangeCounters(); + clearDiffPresentation(); + resetChangeCounters(); - for (int index = 0; index < fragments.size(); index++) { - MergeLineFragment fragment = fragments.get(index); - TextMergeChange change = new TextMergeChange(fragment, index, TextMergeViewer.this); - myAllMergeChanges.add(change); - onChangeAdded(change); - } - - myInitialScrollHelper.onRediff(); - - myContentPanel.repaintDividers(); - myStatusPanel.update(); - - getEditor().setViewer(false); - - myInnerDiffWorker.onSettingsChanged(); - myInitialRediffFinished = true; + for (int index = 0; index < fragments.size(); index++) { + MergeLineFragment fragment = fragments.get(index); + TextMergeChange change = new TextMergeChange(fragment, index, TextMergeViewer.this); + myAllMergeChanges.add(change); + onChangeAdded(change); } + + myInitialScrollHelper.onRediff(); + + myContentPanel.repaintDividers(); + myStatusPanel.update(); + + getEditor().setViewer(false); + + myInnerDiffWorker.onSettingsChanged(); + myInitialRediffFinished = true; }; } @@ -516,12 +495,7 @@ public class TextMergeViewer implements MergeTool.MergeViewer { if (myScheduled.isEmpty()) return; myAlarm.cancelAllRequests(); - myAlarm.addRequest(new Runnable() { - @Override - public void run() { - launchRediff(); - } - }, ProgressWindow.DEFAULT_PROGRESS_DIALOG_POSTPONE_TIME_MILLIS); + myAlarm.addRequest(this::launchRediff, ProgressWindow.DEFAULT_PROGRESS_DIALOG_POSTPONE_TIME_MILLIS); } @CalledInAwt @@ -537,19 +511,11 @@ public class TextMergeViewer implements MergeTool.MergeViewer { getEditor(ThreeSide.BASE).getDocument(), getEditor(ThreeSide.RIGHT).getDocument()}; - final List data = ContainerUtil.map(scheduled, new Function() { - @Override - public InnerChunkData fun(TextMergeChange change) { - return new InnerChunkData(change, documents); - } - }); + final List data = ContainerUtil.map(scheduled, change -> new InnerChunkData(change, documents)); final ProgressIndicator indicator = myProgress; - ApplicationManager.getApplication().executeOnPooledThread(new Runnable() { - @Override - public void run() { - performRediff(scheduled, data, indicator); - } + ApplicationManager.getApplication().executeOnPooledThread(() -> { + performRediff(scheduled, data, indicator); }); } @@ -557,27 +523,24 @@ public class TextMergeViewer implements MergeTool.MergeViewer { private void performRediff(@NotNull final List scheduled, @NotNull final List data, @NotNull final ProgressIndicator indicator) { - final List> result = new ArrayList>(data.size()); + final List> result = new ArrayList<>(data.size()); for (InnerChunkData chunkData : data) { result.add(DiffUtil.compareThreesideInner(chunkData.text, ComparisonPolicy.DEFAULT, indicator)); } - ApplicationManager.getApplication().invokeAndWait(new Runnable() { - @Override - public void run() { - if (!myEnabled || indicator.isCanceled()) return; - myProgress = null; + ApplicationManager.getApplication().invokeAndWait(() -> { + if (!myEnabled || indicator.isCanceled()) return; + myProgress = null; - for (int i = 0; i < scheduled.size(); i++) { - TextMergeChange change = scheduled.get(i); - if (myScheduled.contains(change)) continue; - change.setInnerFragments(result.get(i)); - } + for (int i = 0; i < scheduled.size(); i++) { + TextMergeChange change = scheduled.get(i); + if (myScheduled.contains(change)) continue; + change.setInnerFragments(result.get(i)); + } - myStatusPanel.setBusy(false); - if (!myScheduled.isEmpty()) { - launchRediff(); - } + myStatusPanel.setBusy(false); + if (!myScheduled.isEmpty()) { + launchRediff(); } }, ModalityState.any()); } @@ -592,6 +555,7 @@ public class TextMergeViewer implements MergeTool.MergeViewer { protected void onBeforeDocumentChange(@NotNull DocumentEvent e) { super.onBeforeDocumentChange(e); enterBulkChangeUpdateBlock(); + if (isDisposed()) return; if (myAllMergeChanges.isEmpty()) return; List documents = ContainerUtil.map(getEditors(), Editor::getDocument); @@ -679,28 +643,28 @@ public class TextMergeViewer implements MergeTool.MergeViewer { } if (getChangesCount() == 0 && getConflictsCount() == 0) { LOG.assertTrue(getFirstUnresolvedChange(true, null) == null); - ApplicationManager.getApplication().invokeLater(new Runnable() { - @Override - public void run() { - String message = "All changes have been processed.
Save changes and finish merging"; - HyperlinkListener listener = new HyperlinkAdapter() { - @Override - protected void hyperlinkActivated(HyperlinkEvent e) { - destroyChangedBlocks(); - myMergeContext.finishMerge(MergeResult.RESOLVED); - } - }; + ApplicationManager.getApplication().invokeLater(() -> { + if (isDisposed()) return; + String message = "All changes have been processed.
Save changes and finish merging"; + HyperlinkListener listener = new HyperlinkAdapter() { + @Override + protected void hyperlinkActivated(HyperlinkEvent e) { + if (isDisposed()) return; + destroyChangedBlocks(); + myMergeContext.finishMerge(MergeResult.RESOLVED); + } + }; - JComponent component = getEditor().getComponent(); - Point point = new Point(component.getWidth() / 2, JBUI.scale(5)); - Color bgColor = MessageType.INFO.getPopupBackground(); + JComponent component = getEditor().getComponent(); + Point point = new Point(component.getWidth() / 2, JBUI.scale(5)); + Color bgColor = MessageType.INFO.getPopupBackground(); - BalloonBuilder balloonBuilder = JBPopupFactory.getInstance().createHtmlTextBalloonBuilder(message, null, bgColor, listener) - .setAnimationCycle(200); - Balloon balloon = balloonBuilder.createBalloon(); - balloon.show(new RelativePoint(component, point), Balloon.Position.below); - Disposer.register(MyThreesideViewer.this, balloon); - } + Balloon balloon = JBPopupFactory.getInstance() + .createHtmlTextBalloonBuilder(message, null, bgColor, listener) + .setAnimationCycle(200) + .createBalloon(); + balloon.show(new RelativePoint(component, point), Balloon.Position.below); + Disposer.register(this, balloon); }); } } @@ -726,12 +690,7 @@ public class TextMergeViewer implements MergeTool.MergeViewer { @NotNull @Override public List getChanges() { - return ContainerUtil.filter(myAllMergeChanges, new Condition() { - @Override - public boolean value(TextMergeChange mergeChange) { - return !mergeChange.isResolved(); - } - }); + return ContainerUtil.filter(myAllMergeChanges, mergeChange -> !mergeChange.isResolved()); } @NotNull @@ -821,7 +780,7 @@ public class TextMergeViewer implements MergeTool.MergeViewer { if (myUndoManager == null) return; List affectedChanges = getAffectedChanges(); - final List states = new ArrayList(affectedChanges.size()); + final List states = new ArrayList<>(affectedChanges.size()); for (TextMergeChange change : affectedChanges) { states.add(change.storeState()); } @@ -990,7 +949,7 @@ public class TextMergeViewer implements MergeTool.MergeViewer { private List collectAffectedChanges(@Nullable List directChanges) { if (directChanges == null || directChanges.isEmpty()) return null; - List result = new ArrayList(directChanges.size()); + List result = new ArrayList<>(directChanges.size()); int directIndex = 0; int otherIndex = 0; @@ -1098,11 +1057,8 @@ public class TextMergeViewer implements MergeTool.MergeViewer { String title = e.getPresentation().getText() + " in merge"; - executeMergeCommand(title, selectedChanges.size() > 1, selectedChanges, new Runnable() { - @Override - public void run() { - apply(side, selectedChanges); - } + executeMergeCommand(title, selectedChanges.size() > 1, selectedChanges, () -> { + apply(side, selectedChanges); }); } @@ -1132,7 +1088,7 @@ public class TextMergeViewer implements MergeTool.MergeViewer { final BitSet lines = DiffUtil.getSelectedLines(getEditor(side)); List changes = getChanges(); - List affectedChanges = new ArrayList(); + List affectedChanges = new ArrayList<>(); for (TextMergeChange change : changes) { if (!isEnabled(change)) continue; int line1 = change.getStartLine(side); @@ -1287,11 +1243,8 @@ public class TextMergeViewer implements MergeTool.MergeViewer { @Override public void actionPerformed(AnActionEvent e) { - executeMergeCommand("Apply Non Conflicted Changes", true, null, new Runnable() { - @Override - public void run() { - doPerform(); - } + executeMergeCommand("Apply Non Conflicted Changes", true, null, () -> { + doPerform(); }); TextMergeChange firstConflict = getFirstUnresolvedChange(true, null); @@ -1422,7 +1375,7 @@ public class TextMergeViewer implements MergeTool.MergeViewer { public MyUndoableAction(@NotNull TextMergeViewer viewer, @NotNull List states, boolean undo) { super(viewer.getViewer().getEditor().getDocument()); - myViewerRef = new WeakReference(viewer); + myViewerRef = new WeakReference<>(viewer); myStates = states; myUndo = undo; diff --git a/platform/diff-impl/src/com/intellij/diff/requests/TextMergeRequestImpl.java b/platform/diff-impl/src/com/intellij/diff/requests/TextMergeRequestImpl.java index 0a3b245a3f7d..f01b41e31879 100644 --- a/platform/diff-impl/src/com/intellij/diff/requests/TextMergeRequestImpl.java +++ b/platform/diff-impl/src/com/intellij/diff/requests/TextMergeRequestImpl.java @@ -108,11 +108,8 @@ public class TextMergeRequestImpl extends TextMergeRequest { } if (applyContent != null) { - DiffUtil.executeWriteCommand(myOutput.getDocument(), myProject, null, new Runnable() { - @Override - public void run() { - myOutput.getDocument().setText(applyContent); - } + DiffUtil.executeWriteCommand(myOutput.getDocument(), myProject, null, () -> { + myOutput.getDocument().setText(applyContent); }); } diff --git a/platform/diff-impl/src/com/intellij/diff/requests/UnknownFileTypeDiffRequest.java b/platform/diff-impl/src/com/intellij/diff/requests/UnknownFileTypeDiffRequest.java index 0d9126633127..fe1eb3cbec23 100644 --- a/platform/diff-impl/src/com/intellij/diff/requests/UnknownFileTypeDiffRequest.java +++ b/platform/diff-impl/src/com/intellij/diff/requests/UnknownFileTypeDiffRequest.java @@ -60,12 +60,9 @@ public class UnknownFileTypeDiffRequest extends ComponentDiffRequest { label.append("Associate", SimpleTextAttributes.LINK_ATTRIBUTES, new Runnable() { @Override public void run() { - DumbService.allowStartingDumbModeInside(DumbModePermission.MAY_START_BACKGROUND, new Runnable() { - @Override - public void run() { - FileType type = FileTypeChooser.associateFileType(myFileName); - if (type != null) onSuccess(context); - } + DumbService.allowStartingDumbModeInside(DumbModePermission.MAY_START_BACKGROUND, () -> { + FileType type = FileTypeChooser.associateFileType(myFileName); + if (type != null) onSuccess(context); }); } }); diff --git a/platform/diff-impl/src/com/intellij/diff/settings/DiffSettingsPanel.java b/platform/diff-impl/src/com/intellij/diff/settings/DiffSettingsPanel.java index 4257af2a09d9..e466b7de9366 100644 --- a/platform/diff-impl/src/com/intellij/diff/settings/DiffSettingsPanel.java +++ b/platform/diff-impl/src/com/intellij/diff/settings/DiffSettingsPanel.java @@ -69,7 +69,7 @@ public class DiffSettingsPanel { setPaintLabels(true); //noinspection UseOfObsoleteCollectionType - Dictionary sliderLabels = new Hashtable(); + Dictionary sliderLabels = new Hashtable<>(); for (int i = 0; i < TextDiffSettingsHolder.CONTEXT_RANGE_MODES.length; i++) { sliderLabels.put(i, new JLabel(TextDiffSettingsHolder.CONTEXT_RANGE_MODE_LABELS[i])); } diff --git a/platform/diff-impl/src/com/intellij/diff/settings/ExternalDiffSettingsPanel.java b/platform/diff-impl/src/com/intellij/diff/settings/ExternalDiffSettingsPanel.java index dde66d742515..ffa27c9d51bf 100644 --- a/platform/diff-impl/src/com/intellij/diff/settings/ExternalDiffSettingsPanel.java +++ b/platform/diff-impl/src/com/intellij/diff/settings/ExternalDiffSettingsPanel.java @@ -24,8 +24,6 @@ import com.intellij.util.ui.UIUtil; import org.jetbrains.annotations.NotNull; import javax.swing.*; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; public class ExternalDiffSettingsPanel { private static final String DESCRIPTION_TEXT = @@ -55,18 +53,8 @@ public class ExternalDiffSettingsPanel { public ExternalDiffSettingsPanel() { myDescriptionLabel.setText(DESCRIPTION_TEXT); - myDiffEnabled.getModel().addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - updateEnabledEffect(); - } - }); - myMergeEnabled.getModel().addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - updateEnabledEffect(); - } - }); + myDiffEnabled.getModel().addActionListener(e -> updateEnabledEffect()); + myMergeEnabled.getModel().addActionListener(e -> updateEnabledEffect()); myDiffPath.addBrowseFolderListener(DiffBundle.message("select.external.diff.program.dialog.title"), null, null, FileChooserDescriptorFactory.createSingleFileNoJarsDescriptor()); diff --git a/platform/diff-impl/src/com/intellij/diff/tools/ErrorDiffTool.java b/platform/diff-impl/src/com/intellij/diff/tools/ErrorDiffTool.java index 444990f07386..398c475e6513 100644 --- a/platform/diff-impl/src/com/intellij/diff/tools/ErrorDiffTool.java +++ b/platform/diff-impl/src/com/intellij/diff/tools/ErrorDiffTool.java @@ -113,11 +113,8 @@ public class ErrorDiffTool implements FrameDiffTool { if (fileName != null && FileTypeManager.getInstance().getFileTypeByFileName(fileName) != UnknownFileType.INSTANCE) { // FileType was assigned elsewhere (ex: by other UnknownFileTypeDiffRequest). We should reload request. if (myContext instanceof DiffContextEx) { - ApplicationManager.getApplication().invokeLater(new Runnable() { - @Override - public void run() { - ((DiffContextEx)myContext).reloadDiffRequest(); - } + ApplicationManager.getApplication().invokeLater(() -> { + ((DiffContextEx)myContext).reloadDiffRequest(); }, ModalityState.current()); } } diff --git a/platform/diff-impl/src/com/intellij/diff/tools/binary/OnesideBinaryDiffViewer.java b/platform/diff-impl/src/com/intellij/diff/tools/binary/OnesideBinaryDiffViewer.java index 2023ca0bbe12..cbd0a0f10cef 100644 --- a/platform/diff-impl/src/com/intellij/diff/tools/binary/OnesideBinaryDiffViewer.java +++ b/platform/diff-impl/src/com/intellij/diff/tools/binary/OnesideBinaryDiffViewer.java @@ -61,7 +61,7 @@ public class OnesideBinaryDiffViewer extends OnesideDiffViewer createToolbarActions() { - List group = new ArrayList(); + List group = new ArrayList<>(); group.add(myTransferableStateSupport.createToggleAction()); group.addAll(super.createToolbarActions()); return group; @@ -80,12 +80,9 @@ public class OnesideBinaryDiffViewer extends OnesideDiffViewer { + clearDiffPresentation(); + if (notification != null) myPanel.addNotification(notification); }; } diff --git a/platform/diff-impl/src/com/intellij/diff/tools/binary/ThreesideBinaryDiffViewer.java b/platform/diff-impl/src/com/intellij/diff/tools/binary/ThreesideBinaryDiffViewer.java index 110787a4147a..311dfd20364d 100644 --- a/platform/diff-impl/src/com/intellij/diff/tools/binary/ThreesideBinaryDiffViewer.java +++ b/platform/diff-impl/src/com/intellij/diff/tools/binary/ThreesideBinaryDiffViewer.java @@ -54,7 +54,7 @@ public class ThreesideBinaryDiffViewer extends ThreesideDiffViewer createToolbarActions() { - List group = new ArrayList(); + List group = new ArrayList<>(); group.add(myTransferableStateSupport.createToggleAction()); group.addAll(super.createToolbarActions()); return group; diff --git a/platform/diff-impl/src/com/intellij/diff/tools/binary/TwosideBinaryDiffViewer.java b/platform/diff-impl/src/com/intellij/diff/tools/binary/TwosideBinaryDiffViewer.java index 2819e88e4399..f4808414a16a 100644 --- a/platform/diff-impl/src/com/intellij/diff/tools/binary/TwosideBinaryDiffViewer.java +++ b/platform/diff-impl/src/com/intellij/diff/tools/binary/TwosideBinaryDiffViewer.java @@ -86,7 +86,7 @@ public class TwosideBinaryDiffViewer extends TwosideDiffViewer createToolbarActions() { - List group = new ArrayList(); + List group = new ArrayList<>(); group.add(new MyAcceptSideAction(Side.LEFT)); group.add(new MyAcceptSideAction(Side.RIGHT)); @@ -157,12 +157,9 @@ public class TwosideBinaryDiffViewer extends TwosideDiffViewer { + clearDiffPresentation(); + if (notification != null) myPanel.addNotification(notification); }; } diff --git a/platform/diff-impl/src/com/intellij/diff/tools/dir/DirDiffViewer.java b/platform/diff-impl/src/com/intellij/diff/tools/dir/DirDiffViewer.java index 7e76e17f5535..b368a8e53c1f 100644 --- a/platform/diff-impl/src/com/intellij/diff/tools/dir/DirDiffViewer.java +++ b/platform/diff-impl/src/com/intellij/diff/tools/dir/DirDiffViewer.java @@ -32,7 +32,6 @@ import com.intellij.ide.highlighter.ArchiveFileType; import com.intellij.internal.statistic.UsageTrigger; import com.intellij.openapi.Disposable; import com.intellij.openapi.actionSystem.AnAction; -import com.intellij.openapi.actionSystem.DataProvider; import com.intellij.openapi.actionSystem.DefaultActionGroup; import com.intellij.openapi.actionSystem.PlatformDataKeys; import com.intellij.openapi.diff.impl.dir.DirDiffFrame; @@ -42,8 +41,6 @@ import com.intellij.openapi.diff.impl.dir.DirDiffWindow; import com.intellij.openapi.project.DefaultProjectFactory; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.Disposer; -import com.intellij.util.ArrayUtil; -import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; @@ -93,14 +90,11 @@ class DirDiffViewer implements FrameDiffTool.DiffViewer { myPanel = new JPanel(new BorderLayout()); myPanel.add(myDirDiffPanel.getPanel(), BorderLayout.CENTER); - DataManager.registerDataProvider(myPanel, new DataProvider() { - @Override - public Object getData(@NonNls String dataId) { - if (PlatformDataKeys.HELP_ID.is(dataId)) { - return "reference.dialogs.diff.folder"; - } - return myDirDiffPanel.getData(dataId); + DataManager.registerDataProvider(myPanel, dataId -> { + if (PlatformDataKeys.HELP_ID.is(dataId)) { + return "reference.dialogs.diff.folder"; } + return myDirDiffPanel.getData(dataId); }); } diff --git a/platform/diff-impl/src/com/intellij/diff/tools/external/ExternalDiffTool.java b/platform/diff-impl/src/com/intellij/diff/tools/external/ExternalDiffTool.java index 65d610d3c69a..9a7485a4b5c3 100644 --- a/platform/diff-impl/src/com/intellij/diff/tools/external/ExternalDiffTool.java +++ b/platform/diff-impl/src/com/intellij/diff/tools/external/ExternalDiffTool.java @@ -61,8 +61,8 @@ public class ExternalDiffTool { @NotNull final DiffDialogHints hints) { try { //noinspection unchecked - final Ref> requestsRef = new Ref>(); - final Ref exceptionRef = new Ref(); + final Ref> requestsRef = new Ref<>(); + final Ref exceptionRef = new Ref<>(); ProgressManager.getInstance().run(new Task.Modal(project, "Loading Requests", true) { @Override public void run(@NotNull ProgressIndicator indicator) { @@ -77,7 +77,7 @@ public class ExternalDiffTool { if (!exceptionRef.isNull()) throw exceptionRef.get(); - List showInBuiltin = new ArrayList(); + List showInBuiltin = new ArrayList<>(); for (DiffRequest request : requestsRef.get()) { if (canShow(request)) { showRequest(project, request); @@ -103,10 +103,10 @@ public class ExternalDiffTool { private static List collectRequests(@Nullable Project project, @NotNull final DiffRequestChain chain, @NotNull ProgressIndicator indicator) { - List requests = new ArrayList(); + List requests = new ArrayList<>(); UserDataHolderBase context = new UserDataHolderBase(); - List errorRequests = new ArrayList(); + List errorRequests = new ArrayList<>(); // TODO: show all changes on explicit selection List producers = Collections.singletonList(chain.getRequests().get(chain.getIndex())); diff --git a/platform/diff-impl/src/com/intellij/diff/tools/external/ExternalDiffToolUtil.java b/platform/diff-impl/src/com/intellij/diff/tools/external/ExternalDiffToolUtil.java index ef7f335aec4c..3bca380ad1e3 100644 --- a/platform/diff-impl/src/com/intellij/diff/tools/external/ExternalDiffToolUtil.java +++ b/platform/diff-impl/src/com/intellij/diff/tools/external/ExternalDiffToolUtil.java @@ -182,14 +182,14 @@ public class ExternalDiffToolUtil { assert contents.size() == 2 || contents.size() == 3; assert titles.size() == contents.size(); - List files = new ArrayList(); + List files = new ArrayList<>(); for (int i = 0; i < contents.size(); i++) { files.add(createFile(contents.get(i), titles.get(i), windowTitle)); } CommandLineTokenizer parameterTokenizer = new CommandLineTokenizer(settings.getDiffParameters(), true); - List args = new ArrayList(); + List args = new ArrayList<>(); while (parameterTokenizer.hasMoreTokens()) { String arg = parameterTokenizer.nextToken(); if ("%1".equals(arg)) { @@ -224,7 +224,7 @@ public class ExternalDiffToolUtil { throws IOException, ExecutionException { boolean success = false; OutputFile outputFile = null; - List inputFiles = new ArrayList(); + List inputFiles = new ArrayList<>(); try { DiffContent outputContent = request.getOutputContent(); List contents = request.getContents(); @@ -242,7 +242,7 @@ public class ExternalDiffToolUtil { CommandLineTokenizer parameterTokenizer = new CommandLineTokenizer(settings.getMergeParameters(), true); - List args = new ArrayList(); + List args = new ArrayList<>(); while (parameterTokenizer.hasMoreTokens()) { String arg = parameterTokenizer.nextToken(); if ("%1".equals(arg)) { @@ -269,7 +269,7 @@ public class ExternalDiffToolUtil { final Process process = commandLine.createProcess(); if (settings.isMergeTrustExitCode()) { - final Ref resultRef = new Ref(); + final Ref resultRef = new Ref<>(); ProgressManager.getInstance().run(new Task.Modal(project, "Waiting for external tool", true) { @Override @@ -388,11 +388,8 @@ public class ExternalDiffToolUtil { @Override public void apply() throws IOException { final String content = StringUtil.convertLineSeparators(FileUtil.loadFile(myLocalFile, myCharset)); - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - myDocument.setText(content); - } + ApplicationManager.getApplication().runWriteAction(() -> { + myDocument.setText(content); }); } } diff --git a/platform/diff-impl/src/com/intellij/diff/tools/fragmented/LineNumberConvertor.java b/platform/diff-impl/src/com/intellij/diff/tools/fragmented/LineNumberConvertor.java index 16df5ae84a83..c0bd49409920 100644 --- a/platform/diff-impl/src/com/intellij/diff/tools/fragmented/LineNumberConvertor.java +++ b/platform/diff-impl/src/com/intellij/diff/tools/fragmented/LineNumberConvertor.java @@ -83,22 +83,12 @@ public class LineNumberConvertor { @NotNull public TIntFunction createConvertor1() { - return new TIntFunction() { - @Override - public int execute(int value) { - return convert1(value); - } - }; + return this::convert1; } @NotNull public TIntFunction createConvertor2() { - return new TIntFunction() { - @Override - public int execute(int value) { - return convert2(value); - } - }; + return this::convert2; } private int convert(int value, @NotNull Side side, boolean fromOneside, boolean approximate) { @@ -147,11 +137,11 @@ public class LineNumberConvertor { } public static class Builder { - @NotNull private final TreeMap myFragments1 = new TreeMap(); - @NotNull private final TreeMap myFragments2 = new TreeMap(); + @NotNull private final TreeMap myFragments1 = new TreeMap<>(); + @NotNull private final TreeMap myFragments2 = new TreeMap<>(); - @NotNull private final TreeMap myInvertedFragments1 = new TreeMap(); - @NotNull private final TreeMap myInvertedFragments2 = new TreeMap(); + @NotNull private final TreeMap myInvertedFragments1 = new TreeMap<>(); + @NotNull private final TreeMap myInvertedFragments2 = new TreeMap<>(); public void put1(int start, int newStart, int length) { myFragments1.put(start, newStart); @@ -219,7 +209,7 @@ public class LineNumberConvertor { * */ private class Corrector { - private final List myChanges = new SmartList(); + private final List myChanges = new SmartList<>(); @SuppressWarnings("UnnecessaryLocalVariable") public void handleOnesideChange(int startLine, int endLine, int shift, @NotNull Side masterSide) { diff --git a/platform/diff-impl/src/com/intellij/diff/tools/fragmented/UnifiedDiffChange.java b/platform/diff-impl/src/com/intellij/diff/tools/fragmented/UnifiedDiffChange.java index c68b9454223d..7d38d7cab7e2 100644 --- a/platform/diff-impl/src/com/intellij/diff/tools/fragmented/UnifiedDiffChange.java +++ b/platform/diff-impl/src/com/intellij/diff/tools/fragmented/UnifiedDiffChange.java @@ -45,8 +45,8 @@ public class UnifiedDiffChange { @NotNull private final LineFragment myLineFragment; - @NotNull private final List myHighlighters = new ArrayList(); - @NotNull private final List myOperations = new ArrayList(); + @NotNull private final List myHighlighters = new ArrayList<>(); + @NotNull private final List myOperations = new ArrayList<>(); public UnifiedDiffChange(@NotNull UnifiedDiffViewer viewer, @NotNull ChangedBlock block) { myViewer = viewer; @@ -218,12 +218,9 @@ public class UnifiedDiffChange { final Project project = e.getProject(); final Document document = myViewer.getDocument(sourceSide.other()); - DiffUtil.executeWriteCommand(document, project, "Replace change", new Runnable() { - @Override - public void run() { - myViewer.replaceChange(UnifiedDiffChange.this, sourceSide); - myViewer.scheduleRediff(); - } + DiffUtil.executeWriteCommand(document, project, "Replace change", () -> { + myViewer.replaceChange(UnifiedDiffChange.this, sourceSide); + myViewer.scheduleRediff(); }); // applyChange() will schedule rediff, but we want to try to do it in sync // and we can't do it inside write action diff --git a/platform/diff-impl/src/com/intellij/diff/tools/fragmented/UnifiedDiffViewer.java b/platform/diff-impl/src/com/intellij/diff/tools/fragmented/UnifiedDiffViewer.java index a48e1444ef3c..b2ed4c57a1c2 100644 --- a/platform/diff-impl/src/com/intellij/diff/tools/fragmented/UnifiedDiffViewer.java +++ b/platform/diff-impl/src/com/intellij/diff/tools/fragmented/UnifiedDiffViewer.java @@ -16,6 +16,7 @@ package com.intellij.diff.tools.fragmented; import com.intellij.diff.DiffContext; +import com.intellij.diff.actions.AllLinesIterator; import com.intellij.diff.actions.BufferedLineIterator; import com.intellij.diff.actions.NavigationContextChecker; import com.intellij.diff.actions.impl.OpenInEditorWithMouseAction; @@ -56,7 +57,6 @@ import com.intellij.openapi.util.Computable; import com.intellij.openapi.util.Pair; import com.intellij.openapi.util.TextRange; import com.intellij.openapi.util.UserDataHolder; -import com.intellij.util.Function; import com.intellij.util.containers.ContainerUtil; import gnu.trove.TIntFunction; import org.jetbrains.annotations.*; @@ -64,7 +64,6 @@ import org.jetbrains.annotations.*; import javax.swing.*; import java.util.*; -import static com.intellij.diff.util.DiffUtil.getLineCount; import static com.intellij.diff.util.DiffUtil.getLinesContent; public class UnifiedDiffViewer extends ListenerDiffViewerBase { @@ -186,7 +185,7 @@ public class UnifiedDiffViewer extends ListenerDiffViewerBase { @Override @CalledInAwt public List createToolbarActions() { - List group = new ArrayList(); + List group = new ArrayList<>(); // TODO: allow to choose myMasterSide group.add(new MyIgnorePolicySettingAction()); @@ -205,7 +204,7 @@ public class UnifiedDiffViewer extends ListenerDiffViewerBase { @Override @CalledInAwt public List createPopupActions() { - List group = new ArrayList(); + List group = new ArrayList<>(); group.add(Separator.getInstance()); group.add(new MyIgnorePolicySettingAction().getPopupGroup()); @@ -222,7 +221,7 @@ public class UnifiedDiffViewer extends ListenerDiffViewerBase { @NotNull protected List createEditorPopupActions() { - List group = new ArrayList(); + List group = new ArrayList<>(); if (isEditable(Side.RIGHT, false)) { group.add(new ReplaceSelectedChangesAction(Side.LEFT, false)); @@ -306,12 +305,9 @@ public class UnifiedDiffViewer extends ListenerDiffViewerBase { return apply(editorData, builder.getBlocks(), convertor, changedLines, isContentsEqual); } catch (DiffTooBigException e) { - return new Runnable() { - @Override - public void run() { - clearDiffPresentation(); - myPanel.setTooBigContent(); - } + return () -> { + clearDiffPresentation(); + myPanel.setTooBigContent(); }; } catch (ProcessCanceledException e) { @@ -319,12 +315,9 @@ public class UnifiedDiffViewer extends ListenerDiffViewerBase { } catch (Throwable e) { LOG.error(e); - return new Runnable() { - @Override - public void run() { - clearDiffPresentation(); - myPanel.setErrorContent(); - } + return () -> { + clearDiffPresentation(); + myPanel.setErrorContent(); }; } } @@ -379,79 +372,73 @@ public class UnifiedDiffViewer extends ListenerDiffViewerBase { @NotNull final LineNumberConvertor convertor, @NotNull final List changedLines, final boolean isContentsEqual) { - return new Runnable() { - @Override - public void run() { - myFoldingModel.updateContext(myRequest, getFoldingModelSettings()); + return () -> { + myFoldingModel.updateContext(myRequest, getFoldingModelSettings()); - LineCol oldCaretPosition = LineCol.fromOffset(myDocument, myEditor.getCaretModel().getPrimaryCaret().getOffset()); - Pair oldCaretLineTwoside = transferLineFromOneside(oldCaretPosition.line); + LineCol oldCaretPosition = LineCol.fromOffset(myDocument, myEditor.getCaretModel().getPrimaryCaret().getOffset()); + Pair oldCaretLineTwoside = transferLineFromOneside(oldCaretPosition.line); - clearDiffPresentation(); + clearDiffPresentation(); - if (isContentsEqual) { - boolean equalCharsets = TextDiffViewerUtil.areEqualCharsets(getContents()); - boolean equalSeparators = TextDiffViewerUtil.areEqualLineSeparators(getContents()); - myPanel.addNotification(DiffNotifications.createEqualContents(equalCharsets, equalSeparators)); - } - - TIntFunction separatorLines = myFoldingModel.getLineNumberConvertor(); - myEditor.getGutterComponentEx().setLineNumberConvertor(mergeConverters(data.getLineConvertor1(), separatorLines), - mergeConverters(data.getLineConvertor2(), separatorLines)); - - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - myDuringOnesideDocumentModification = true; - try { - myDocument.setText(data.getText()); - } - finally { - myDuringOnesideDocumentModification = false; - } - } - }); - - if (data.getHighlighter() != null) myEditor.setHighlighter(data.getHighlighter()); - DiffUtil.setEditorCodeStyle(myProject, myEditor, data.getFileType()); - - if (data.getRangeHighlighter() != null) data.getRangeHighlighter().apply(myProject, myDocument); - - - ArrayList diffChanges = new ArrayList(blocks.size()); - for (ChangedBlock block : blocks) { - diffChanges.add(new UnifiedDiffChange(UnifiedDiffViewer.this, block)); - } - - List guarderRangeBlocks = new ArrayList(); - if (!myEditor.isViewer()) { - for (ChangedBlock block : blocks) { - LineRange range = myMasterSide.select(block.getRange2(), block.getRange1()); - TextRange textRange = DiffUtil.getLinesRange(myDocument, range.start, range.end); - if (textRange.isEmpty()) continue; - guarderRangeBlocks.add(createGuardedBlock(textRange.getStartOffset(), textRange.getEndOffset())); - } - int textLength = myDocument.getTextLength(); // there are 'fake' newline at the very end - guarderRangeBlocks.add(createGuardedBlock(textLength, textLength)); - } - - - myChangedBlockData = new ChangedBlockData(diffChanges, guarderRangeBlocks, convertor, isContentsEqual); - - - int newCaretLine = transferLineToOneside(oldCaretLineTwoside.second, - oldCaretLineTwoside.second.select(oldCaretLineTwoside.first)); - myEditor.getCaretModel().moveToOffset(LineCol.toOffset(myDocument, newCaretLine, oldCaretPosition.column)); - - myFoldingModel.install(changedLines, myRequest, getFoldingModelSettings()); - - myInitialScrollHelper.onRediff(); - - myStatusPanel.update(); - myPanel.setGoodContent(); + if (isContentsEqual) { + boolean equalCharsets = TextDiffViewerUtil.areEqualCharsets(getContents()); + boolean equalSeparators = TextDiffViewerUtil.areEqualLineSeparators(getContents()); + myPanel.addNotification(DiffNotifications.createEqualContents(equalCharsets, equalSeparators)); } + + TIntFunction separatorLines = myFoldingModel.getLineNumberConvertor(); + myEditor.getGutterComponentEx().setLineNumberConvertor(mergeConverters(data.getLineConvertor1(), separatorLines), + mergeConverters(data.getLineConvertor2(), separatorLines)); + + ApplicationManager.getApplication().runWriteAction(() -> { + myDuringOnesideDocumentModification = true; + try { + myDocument.setText(data.getText()); + } + finally { + myDuringOnesideDocumentModification = false; + } + }); + + if (data.getHighlighter() != null) myEditor.setHighlighter(data.getHighlighter()); + DiffUtil.setEditorCodeStyle(myProject, myEditor, data.getFileType()); + + if (data.getRangeHighlighter() != null) data.getRangeHighlighter().apply(myProject, myDocument); + + + ArrayList diffChanges = new ArrayList<>(blocks.size()); + for (ChangedBlock block : blocks) { + diffChanges.add(new UnifiedDiffChange(this, block)); + } + + List guarderRangeBlocks = new ArrayList<>(); + if (!myEditor.isViewer()) { + for (ChangedBlock block : blocks) { + LineRange range = myMasterSide.select(block.getRange2(), block.getRange1()); + TextRange textRange = DiffUtil.getLinesRange(myDocument, range.start, range.end); + if (textRange.isEmpty()) continue; + guarderRangeBlocks.add(createGuardedBlock(textRange.getStartOffset(), textRange.getEndOffset())); + } + int textLength = myDocument.getTextLength(); // there are 'fake' newline at the very end + guarderRangeBlocks.add(createGuardedBlock(textLength, textLength)); + } + + + myChangedBlockData = new ChangedBlockData(diffChanges, guarderRangeBlocks, convertor, isContentsEqual); + + + int newCaretLine = transferLineToOneside(oldCaretLineTwoside.second, + oldCaretLineTwoside.second.select(oldCaretLineTwoside.first)); + myEditor.getCaretModel().moveToOffset(LineCol.toOffset(myDocument, newCaretLine, oldCaretPosition.column)); + + myFoldingModel.install(changedLines, myRequest, getFoldingModelSettings()); + + myInitialScrollHelper.onRediff(); + + myStatusPanel.update(); + myPanel.setGoodContent(); }; } @@ -465,12 +452,7 @@ public class UnifiedDiffViewer extends ListenerDiffViewerBase { @Contract("!null, _ -> !null") private static TIntFunction mergeConverters(@NotNull final TIntFunction convertor, @NotNull final TIntFunction separatorLines) { - return new TIntFunction() { - @Override - public int execute(int value) { - return convertor.execute(separatorLines.execute(value)); - } - }; + return value -> convertor.execute(separatorLines.execute(value)); } /* @@ -703,13 +685,10 @@ public class UnifiedDiffViewer extends ListenerDiffViewerBase { if (isStateIsOutOfDate()) return; String title = e.getPresentation().getText() + " selected changes"; - DiffUtil.executeWriteCommand(getDocument(myModifiedSide), e.getProject(), title, new Runnable() { - @Override - public void run() { - // state is invalidated during apply(), but changes are in reverse order, so they should not conflict with each other - apply(selectedChanges); - scheduleRediff(); - } + DiffUtil.executeWriteCommand(getDocument(myModifiedSide), e.getProject(), title, () -> { + // state is invalidated during apply(), but changes are in reverse order, so they should not conflict with each other + apply(selectedChanges); + scheduleRediff(); }); } @@ -947,7 +926,7 @@ public class UnifiedDiffViewer extends ListenerDiffViewerBase { final BitSet lines = DiffUtil.getSelectedLines(myEditor); List changes = myChangedBlockData.getDiffChanges(); - List affectedChanges = new ArrayList(); + List affectedChanges = new ArrayList<>(); for (int i = changes.size() - 1; i >= 0; i--) { UnifiedDiffChange change = changes.get(i); int line1 = change.getLine1(); @@ -1113,49 +1092,12 @@ public class UnifiedDiffViewer extends ListenerDiffViewerBase { // Scroll from annotate // - private class AllLinesIterator implements Iterator> { - @NotNull private final Side mySide; - @NotNull private final Document myDocument; - private int myLine = 0; - - private AllLinesIterator(@NotNull Side side) { - mySide = side; - - myDocument = getContent(mySide).getDocument(); - } - - @Override - public boolean hasNext() { - return myLine < getLineCount(myDocument); - } - - @Override - public Pair next() { - int offset1 = myDocument.getLineStartOffset(myLine); - int offset2 = myDocument.getLineEndOffset(myLine); - - CharSequence text = myDocument.getImmutableCharSequence().subSequence(offset1, offset2); - - Pair pair = new Pair(myLine, text); - myLine++; - - return pair; - } - - @Override - public void remove() { - throw new UnsupportedOperationException(); - } - } - private class ChangedLinesIterator extends BufferedLineIterator { - @NotNull private final Side mySide; @NotNull private final List myChanges; private int myIndex = 0; - private ChangedLinesIterator(@NotNull Side side, @NotNull List changes) { - mySide = side; + private ChangedLinesIterator(@NotNull List changes) { myChanges = changes; init(); } @@ -1174,7 +1116,7 @@ public class UnifiedDiffViewer extends ListenerDiffViewerBase { LineFragment lineFragment = change.getLineFragment(); - Document document = getContent(mySide).getDocument(); + Document document = getContent2().getDocument(); CharSequence insertedText = getLinesContent(document, lineFragment.getStartLine2(), lineFragment.getEndLine2()); int lineNumber = lineFragment.getStartLine2(); @@ -1434,13 +1376,13 @@ public class UnifiedDiffViewer extends ListenerDiffViewerBase { if (myNavigationContext == null) return false; if (myChangedBlockData == null) return false; - ChangedLinesIterator changedLinesIterator = new ChangedLinesIterator(Side.RIGHT, myChangedBlockData.getDiffChanges()); + ChangedLinesIterator changedLinesIterator = new ChangedLinesIterator(myChangedBlockData.getDiffChanges()); NavigationContextChecker checker = new NavigationContextChecker(changedLinesIterator, myNavigationContext); int line = checker.contextMatchCheck(); if (line == -1) { // this will work for the case, when spaces changes are ignored, and corresponding fragments are not reported as changed // just try to find target line -> +- - AllLinesIterator allLinesIterator = new AllLinesIterator(Side.RIGHT); + AllLinesIterator allLinesIterator = new AllLinesIterator(getContent2().getDocument()); NavigationContextChecker checker2 = new NavigationContextChecker(allLinesIterator, myNavigationContext); line = checker2.contextMatchCheck(); } @@ -1459,13 +1401,9 @@ public class UnifiedDiffViewer extends ListenerDiffViewerBase { public void install(@Nullable List changedLines, @NotNull UserDataHolder context, @NotNull FoldingModelSupport.Settings settings) { - Iterator it = map(changedLines, new Function() { - @Override - public int[] fun(LineRange line) { - return new int[]{ - line.start, - line.end}; - } + Iterator it = map(changedLines, line -> new int[]{ + line.start, + line.end }); install(it, context, settings); } diff --git a/platform/diff-impl/src/com/intellij/diff/tools/fragmented/UnifiedEditorHighlighter.java b/platform/diff-impl/src/com/intellij/diff/tools/fragmented/UnifiedEditorHighlighter.java index 3099af0d0e47..4340d8c2d8fc 100644 --- a/platform/diff-impl/src/com/intellij/diff/tools/fragmented/UnifiedEditorHighlighter.java +++ b/platform/diff-impl/src/com/intellij/diff/tools/fragmented/UnifiedEditorHighlighter.java @@ -31,7 +31,6 @@ import org.jetbrains.annotations.NotNull; import java.util.ArrayList; import java.util.Collections; -import java.util.Comparator; import java.util.List; class UnifiedEditorHighlighter implements EditorHighlighter { @@ -46,7 +45,7 @@ class UnifiedEditorHighlighter implements EditorHighlighter { @NotNull List ranges, int textLength) { myDocument = document; - myPieces = new ArrayList(); + myPieces = new ArrayList<>(); init(highlighter1.createIterator(0), highlighter2.createIterator(0), ranges, textLength); } @@ -133,12 +132,7 @@ class UnifiedEditorHighlighter implements EditorHighlighter { @NotNull @Override public HighlighterIterator createIterator(int startOffset) { - int index = Collections.binarySearch(myPieces, new Element(startOffset, 0, null, null), new Comparator() { - @Override - public int compare(Element o1, Element o2) { - return o1.getStart() - o2.getStart(); - } - }); + int index = Collections.binarySearch(myPieces, new Element(startOffset, 0, null, null), (o1, o2) -> o1.getStart() - o2.getStart()); // index: (-insertion point - 1), where insertionPoint is the index of the first element greater than the key // and we need index of the first element that is less or equal (floorElement) if (index < 0) index = Math.max(-index - 2, 0); diff --git a/platform/diff-impl/src/com/intellij/diff/tools/fragmented/UnifiedEditorRangeHighlighter.java b/platform/diff-impl/src/com/intellij/diff/tools/fragmented/UnifiedEditorRangeHighlighter.java index 740027bb11c2..71376d58c5d2 100644 --- a/platform/diff-impl/src/com/intellij/diff/tools/fragmented/UnifiedEditorRangeHighlighter.java +++ b/platform/diff-impl/src/com/intellij/diff/tools/fragmented/UnifiedEditorRangeHighlighter.java @@ -25,7 +25,6 @@ import com.intellij.openapi.editor.markup.MarkupModel; import com.intellij.openapi.editor.markup.RangeHighlighter; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.TextRange; -import com.intellij.util.Processor; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; @@ -35,7 +34,7 @@ import java.util.List; class UnifiedEditorRangeHighlighter { public static final Logger LOG = UnifiedDiffViewer.LOG; - @NotNull private final List myPieces = new ArrayList(); + @NotNull private final List myPieces = new ArrayList<>(); public UnifiedEditorRangeHighlighter(@Nullable Project project, @NotNull Document document) { ApplicationManager.getApplication().assertReadAccessAllowed(); @@ -43,16 +42,13 @@ class UnifiedEditorRangeHighlighter { MarkupModelEx model = (MarkupModelEx)DocumentMarkupModel.forDocument(document, project, false); if (model == null) return; - model.processRangeHighlightersOverlappingWith(0, document.getTextLength(), new Processor() { - @Override - public boolean process(RangeHighlighterEx marker) { - int newStart = marker.getStartOffset(); - int newEnd = marker.getEndOffset(); + model.processRangeHighlightersOverlappingWith(0, document.getTextLength(), marker -> { + int newStart = marker.getStartOffset(); + int newEnd = marker.getEndOffset(); - myPieces.add(new Element(marker, newStart, newEnd)); + myPieces.add(new Element(marker, newStart, newEnd)); - return true; - } + return true; }); } @@ -85,21 +81,18 @@ class UnifiedEditorRangeHighlighter { final TextRange changed = range.getChanged(); final int changedLength = changed.getEndOffset() - changed.getStartOffset(); - model.processRangeHighlightersOverlappingWith(changed.getStartOffset(), changed.getEndOffset(), new Processor() { - @Override - public boolean process(RangeHighlighterEx marker) { - int relativeStart = Math.max(marker.getStartOffset() - changed.getStartOffset(), 0); - int relativeEnd = Math.min(marker.getEndOffset() - changed.getStartOffset(), changedLength); + model.processRangeHighlightersOverlappingWith(changed.getStartOffset(), changed.getEndOffset(), marker -> { + int relativeStart = Math.max(marker.getStartOffset() - changed.getStartOffset(), 0); + int relativeEnd = Math.min(marker.getEndOffset() - changed.getStartOffset(), changedLength); - int newStart = base.getStartOffset() + relativeStart; - int newEnd = base.getStartOffset() + relativeEnd; + int newStart = base.getStartOffset() + relativeStart; + int newEnd = base.getStartOffset() + relativeEnd; - if (newEnd - newStart <= 0) return true; + if (newEnd - newStart <= 0) return true; - myPieces.add(new Element(marker, newStart, newEnd)); + myPieces.add(new Element(marker, newStart, newEnd)); - return true; - } + return true; }); } diff --git a/platform/diff-impl/src/com/intellij/diff/tools/fragmented/UnifiedFragmentBuilder.java b/platform/diff-impl/src/com/intellij/diff/tools/fragmented/UnifiedFragmentBuilder.java index 37cac428f465..8710e8bfffe8 100644 --- a/platform/diff-impl/src/com/intellij/diff/tools/fragmented/UnifiedFragmentBuilder.java +++ b/platform/diff-impl/src/com/intellij/diff/tools/fragmented/UnifiedFragmentBuilder.java @@ -33,10 +33,10 @@ class UnifiedFragmentBuilder { @NotNull private final Side myMasterSide; @NotNull private final StringBuilder myBuilder = new StringBuilder(); - @NotNull private final List myBlocks = new ArrayList(); - @NotNull private final List myRanges = new ArrayList(); + @NotNull private final List myBlocks = new ArrayList<>(); + @NotNull private final List myRanges = new ArrayList<>(); @NotNull private final LineNumberConvertor.Builder myConvertor = new LineNumberConvertor.Builder(); - @NotNull private final List myChangedLines = new ArrayList(); + @NotNull private final List myChangedLines = new ArrayList<>(); public UnifiedFragmentBuilder(@NotNull List fragments, @NotNull Document document1, diff --git a/platform/diff-impl/src/com/intellij/diff/tools/simple/SimpleDiffChange.java b/platform/diff-impl/src/com/intellij/diff/tools/simple/SimpleDiffChange.java index dfd771c32a33..549255ce3f44 100644 --- a/platform/diff-impl/src/com/intellij/diff/tools/simple/SimpleDiffChange.java +++ b/platform/diff-impl/src/com/intellij/diff/tools/simple/SimpleDiffChange.java @@ -41,8 +41,8 @@ public class SimpleDiffChange { @NotNull private final LineFragment myFragment; @Nullable private final List myInnerFragments; - @NotNull private final List myHighlighters = new ArrayList(); - @NotNull private final List myOperations = new ArrayList(); + @NotNull private final List myHighlighters = new ArrayList<>(); + @NotNull private final List myOperations = new ArrayList<>(); private boolean myIsValid = true; private int[] myLineStartShifts = new int[2]; @@ -257,22 +257,16 @@ public class SimpleDiffChange { @Nullable private GutterIconRenderer createApplyRenderer(@NotNull final Side side) { - return createIconRenderer(side, "Accept", DiffUtil.getArrowIcon(side), new Runnable() { - @Override - public void run() { - myViewer.replaceChange(SimpleDiffChange.this, side); - } + return createIconRenderer(side, "Accept", DiffUtil.getArrowIcon(side), () -> { + myViewer.replaceChange(this, side); }); } @Nullable private GutterIconRenderer createAppendRenderer(@NotNull final Side side) { - return createIconRenderer(side, "Append", DiffUtil.getArrowDownIcon(side), new Runnable() { - @Override - public void run() { - UsageTrigger.trigger("diff.SimpleDiffChange.Append"); - myViewer.appendChange(SimpleDiffChange.this, side); - } + return createIconRenderer(side, "Append", DiffUtil.getArrowDownIcon(side), () -> { + UsageTrigger.trigger("diff.SimpleDiffChange.Append"); + myViewer.appendChange(this, side); }); } @@ -288,12 +282,7 @@ public class SimpleDiffChange { if (!myIsValid) return; final Project project = e.getProject(); final Document document = myViewer.getEditor(sourceSide.other()).getDocument(); - DiffUtil.executeWriteCommand(document, project, "Replace change", new Runnable() { - @Override - public void run() { - perform.run(); - } - }); + DiffUtil.executeWriteCommand(document, project, "Replace change", perform); } }; } diff --git a/platform/diff-impl/src/com/intellij/diff/tools/simple/SimpleDiffViewer.java b/platform/diff-impl/src/com/intellij/diff/tools/simple/SimpleDiffViewer.java index 0ef1c17f858c..98f236de8989 100644 --- a/platform/diff-impl/src/com/intellij/diff/tools/simple/SimpleDiffViewer.java +++ b/platform/diff-impl/src/com/intellij/diff/tools/simple/SimpleDiffViewer.java @@ -23,6 +23,7 @@ import com.intellij.diff.fragments.LineFragment; import com.intellij.diff.requests.ContentDiffRequest; import com.intellij.diff.requests.DiffRequest; import com.intellij.diff.tools.util.*; +import com.intellij.diff.actions.AllLinesIterator; import com.intellij.diff.tools.util.base.HighlightPolicy; import com.intellij.diff.tools.util.base.TextDiffViewerUtil; import com.intellij.diff.tools.util.side.TwosideTextDiffViewer; @@ -43,10 +44,8 @@ import com.intellij.openapi.progress.ProcessCanceledException; import com.intellij.openapi.progress.ProgressIndicator; import com.intellij.openapi.project.DumbAware; import com.intellij.openapi.util.Computable; -import com.intellij.openapi.util.Pair; import com.intellij.openapi.util.UserDataHolder; import com.intellij.openapi.util.text.StringUtil; -import com.intellij.util.Function; import com.intellij.util.containers.ContainerUtil; import org.jetbrains.annotations.*; @@ -57,7 +56,6 @@ import java.util.BitSet; import java.util.Iterator; import java.util.List; -import static com.intellij.diff.util.DiffUtil.getLineCount; import static com.intellij.util.ObjectUtils.assertNotNull; public class SimpleDiffViewer extends TwosideTextDiffViewer { @@ -67,8 +65,8 @@ public class SimpleDiffViewer extends TwosideTextDiffViewer { @NotNull private final PrevNextDifferenceIterable myPrevNextDifferenceIterable; @NotNull private final StatusPanel myStatusPanel; - @NotNull private final List myDiffChanges = new ArrayList(); - @NotNull private final List myInvalidDiffChanges = new ArrayList(); + @NotNull private final List myDiffChanges = new ArrayList<>(); + @NotNull private final List myInvalidDiffChanges = new ArrayList<>(); private boolean myIsContentsEqual; @NotNull private final MyFoldingModel myFoldingModel; @@ -109,7 +107,7 @@ public class SimpleDiffViewer extends TwosideTextDiffViewer { @NotNull @Override protected List createToolbarActions() { - List group = new ArrayList(); + List group = new ArrayList<>(); group.add(new MyIgnorePolicySettingAction()); group.add(new MyHighlightPolicySettingAction()); @@ -127,7 +125,7 @@ public class SimpleDiffViewer extends TwosideTextDiffViewer { @NotNull @Override protected List createPopupActions() { - List group = new ArrayList(); + List group = new ArrayList<>(); group.add(Separator.getInstance()); group.add(new MyIgnorePolicySettingAction().getPopupGroup()); @@ -146,7 +144,7 @@ public class SimpleDiffViewer extends TwosideTextDiffViewer { @NotNull @Override protected List createEditorPopupActions() { - List group = new ArrayList(); + List group = new ArrayList<>(); group.add(new ReplaceSelectedChangesAction(Side.LEFT, false)); group.add(new AppendSelectedChangesAction(Side.LEFT, false)); @@ -230,43 +228,37 @@ public class SimpleDiffViewer extends TwosideTextDiffViewer { @NotNull private Runnable apply(@NotNull final CompareData data) { - return new Runnable() { - @Override - public void run() { - myFoldingModel.updateContext(myRequest, getFoldingModelSettings()); - clearDiffPresentation(); + return () -> { + myFoldingModel.updateContext(myRequest, getFoldingModelSettings()); + clearDiffPresentation(); - myIsContentsEqual = data.isContentsEqual(); - if (data.isContentsEqual()) { - boolean equalCharsets = TextDiffViewerUtil.areEqualCharsets(getContents()); - boolean equalSeparators = TextDiffViewerUtil.areEqualLineSeparators(getContents()); - myPanel.addNotification(DiffNotifications.createEqualContents(equalCharsets, equalSeparators)); - } - - if (data.getFragments() != null) { - for (LineFragment fragment : data.getFragments()) { - myDiffChanges.add(new SimpleDiffChange(SimpleDiffViewer.this, fragment)); - } - } - - myFoldingModel.install(data.getFragments(), myRequest, getFoldingModelSettings()); - - myInitialScrollHelper.onRediff(); - - myContentPanel.repaintDivider(); - myStatusPanel.update(); + myIsContentsEqual = data.isContentsEqual(); + if (data.isContentsEqual()) { + boolean equalCharsets = TextDiffViewerUtil.areEqualCharsets(getContents()); + boolean equalSeparators = TextDiffViewerUtil.areEqualLineSeparators(getContents()); + myPanel.addNotification(DiffNotifications.createEqualContents(equalCharsets, equalSeparators)); } + + if (data.getFragments() != null) { + for (LineFragment fragment : data.getFragments()) { + myDiffChanges.add(new SimpleDiffChange(this, fragment)); + } + } + + myFoldingModel.install(data.getFragments(), myRequest, getFoldingModelSettings()); + + myInitialScrollHelper.onRediff(); + + myContentPanel.repaintDivider(); + myStatusPanel.update(); }; } @NotNull private Runnable applyNotification(@Nullable final JComponent notification) { - return new Runnable() { - @Override - public void run() { - clearDiffPresentation(); - if (notification != null) myPanel.addNotification(notification); - } + return () -> { + clearDiffPresentation(); + if (notification != null) myPanel.addNotification(notification); }; } @@ -325,7 +317,7 @@ public class SimpleDiffViewer extends TwosideTextDiffViewer { LineRange lineRange = DiffUtil.getAffectedLineRange(e); int shift = DiffUtil.countLinesShift(e); - List invalid = new ArrayList(); + List invalid = new ArrayList<>(); for (SimpleDiffChange change : myDiffChanges) { if (change.processChange(lineRange.start, lineRange.end, shift, side)) { invalid.add(change); @@ -360,13 +352,13 @@ public class SimpleDiffViewer extends TwosideTextDiffViewer { } protected boolean doScrollToContext(@NotNull DiffNavigationContext context) { - ChangedLinesIterator changedLinesIterator = new ChangedLinesIterator(Side.RIGHT); + ChangedLinesIterator changedLinesIterator = new ChangedLinesIterator(); NavigationContextChecker checker = new NavigationContextChecker(changedLinesIterator, context); int line = checker.contextMatchCheck(); if (line == -1) { // this will work for the case, when spaces changes are ignored, and corresponding fragments are not reported as changed // just try to find target line -> +- - AllLinesIterator allLinesIterator = new AllLinesIterator(Side.RIGHT); + AllLinesIterator allLinesIterator = new AllLinesIterator(getEditor(Side.RIGHT).getDocument()); NavigationContextChecker checker2 = new NavigationContextChecker(allLinesIterator, context); line = checker2.contextMatchCheck(); } @@ -427,7 +419,7 @@ public class SimpleDiffViewer extends TwosideTextDiffViewer { private List getSelectedChanges(@NotNull Side side) { final BitSet lines = DiffUtil.getSelectedLines(getEditor(side)); - List affectedChanges = new ArrayList(); + List affectedChanges = new ArrayList<>(); for (int i = myDiffChanges.size() - 1; i >= 0; i--) { SimpleDiffChange change = myDiffChanges.get(i); int line1 = change.getStartLine(side); @@ -551,11 +543,8 @@ public class SimpleDiffViewer extends TwosideTextDiffViewer { if (!isEditable(myModifiedSide)) return; String title = e.getPresentation().getText() + " selected changes"; - DiffUtil.executeWriteCommand(getEditor(myModifiedSide).getDocument(), e.getProject(), title, new Runnable() { - @Override - public void run() { - apply(selectedChanges); - } + DiffUtil.executeWriteCommand(getEditor(myModifiedSide).getDocument(), e.getProject(), title, () -> { + apply(selectedChanges); }); } @@ -715,47 +704,10 @@ public class SimpleDiffViewer extends TwosideTextDiffViewer { // Scroll from annotate // - private class AllLinesIterator implements Iterator> { - @NotNull private final Side mySide; - @NotNull private final Document myDocument; - private int myLine = 0; - - private AllLinesIterator(@NotNull Side side) { - mySide = side; - - myDocument = getEditor(mySide).getDocument(); - } - - @Override - public boolean hasNext() { - return myLine < getLineCount(myDocument); - } - - @Override - public Pair next() { - int offset1 = myDocument.getLineStartOffset(myLine); - int offset2 = myDocument.getLineEndOffset(myLine); - - CharSequence text = myDocument.getImmutableCharSequence().subSequence(offset1, offset2); - - Pair pair = new Pair(myLine, text); - myLine++; - - return pair; - } - - @Override - public void remove() { - throw new UnsupportedOperationException(); - } - } - private class ChangedLinesIterator extends BufferedLineIterator { - @NotNull private final Side mySide; private int myIndex = 0; - private ChangedLinesIterator(@NotNull Side side) { - mySide = side; + private ChangedLinesIterator() { init(); } @@ -769,10 +721,10 @@ public class SimpleDiffViewer extends TwosideTextDiffViewer { SimpleDiffChange change = myDiffChanges.get(myIndex); myIndex++; - int line1 = change.getStartLine(mySide); - int line2 = change.getEndLine(mySide); + int line1 = change.getStartLine(Side.RIGHT); + int line2 = change.getEndLine(Side.RIGHT); - Document document = getEditor(mySide).getDocument(); + Document document = getEditor(Side.RIGHT).getDocument(); for (int i = line1; i < line2; i++) { int offset1 = document.getLineStartOffset(i); @@ -912,15 +864,11 @@ public class SimpleDiffViewer extends TwosideTextDiffViewer { public void install(@Nullable final List fragments, @NotNull UserDataHolder context, @NotNull FoldingModelSupport.Settings settings) { - Iterator it = map(fragments, new Function() { - @Override - public int[] fun(LineFragment fragment) { - return new int[]{ - fragment.getStartLine1(), - fragment.getEndLine1(), - fragment.getStartLine2(), - fragment.getEndLine2()}; - } + Iterator it = map(fragments, fragment -> new int[]{ + fragment.getStartLine1(), + fragment.getEndLine1(), + fragment.getStartLine2(), + fragment.getEndLine2() }); install(it, context, settings); } diff --git a/platform/diff-impl/src/com/intellij/diff/tools/simple/SimpleOnesideDiffViewer.java b/platform/diff-impl/src/com/intellij/diff/tools/simple/SimpleOnesideDiffViewer.java index 4c098fe2df87..7094557ecc9b 100644 --- a/platform/diff-impl/src/com/intellij/diff/tools/simple/SimpleOnesideDiffViewer.java +++ b/platform/diff-impl/src/com/intellij/diff/tools/simple/SimpleOnesideDiffViewer.java @@ -21,6 +21,7 @@ import com.intellij.diff.contents.DocumentContent; import com.intellij.diff.requests.ContentDiffRequest; import com.intellij.diff.requests.DiffRequest; import com.intellij.diff.tools.util.DiffDataKeys; +import com.intellij.diff.actions.AllLinesIterator; import com.intellij.diff.tools.util.base.HighlightPolicy; import com.intellij.diff.tools.util.base.TextDiffViewerUtil; import com.intellij.diff.tools.util.side.OnesideTextDiffViewer; @@ -36,14 +37,12 @@ import com.intellij.openapi.editor.Document; import com.intellij.openapi.editor.LogicalPosition; import com.intellij.openapi.editor.markup.RangeHighlighter; import com.intellij.openapi.progress.ProgressIndicator; -import com.intellij.openapi.util.Pair; import org.jetbrains.annotations.CalledInAwt; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.ArrayList; -import java.util.Iterator; import java.util.List; import static com.intellij.diff.util.DiffUtil.getLineCount; @@ -53,7 +52,7 @@ public class SimpleOnesideDiffViewer extends OnesideTextDiffViewer { @NotNull private final MyInitialScrollHelper myInitialScrollHelper = new MyInitialScrollHelper(); - @NotNull private final List myHighlighters = new ArrayList(); + @NotNull private final List myHighlighters = new ArrayList<>(); public SimpleOnesideDiffViewer(@NotNull DiffContext context, @NotNull DiffRequest request) { super(context, (ContentDiffRequest)request); @@ -72,7 +71,7 @@ public class SimpleOnesideDiffViewer extends OnesideTextDiffViewer { @NotNull @Override protected List createToolbarActions() { - List group = new ArrayList(); + List group = new ArrayList<>(); group.add(new MyIgnorePolicySettingAction()); group.add(new MyHighlightPolicySettingAction()); @@ -88,7 +87,7 @@ public class SimpleOnesideDiffViewer extends OnesideTextDiffViewer { @NotNull @Override protected List createPopupActions() { - List group = new ArrayList(); + List group = new ArrayList<>(); group.add(Separator.getInstance()); group.add(new MyIgnorePolicySettingAction().getPopupGroup()); @@ -122,32 +121,27 @@ public class SimpleOnesideDiffViewer extends OnesideTextDiffViewer { @Override @NotNull protected Runnable performRediff(@NotNull final ProgressIndicator indicator) { - indicator.checkCanceled(); + return () -> { + clearDiffPresentation(); - return new Runnable() { - @Override - public void run() { - clearDiffPresentation(); + boolean shouldHighlight = getTextSettings().getHighlightPolicy() != HighlightPolicy.DO_NOT_HIGHLIGHT; + if (shouldHighlight) { + final DocumentContent content = getContent(); + final Document document = content.getDocument(); - boolean shouldHighlight = getTextSettings().getHighlightPolicy() != HighlightPolicy.DO_NOT_HIGHLIGHT; - if (shouldHighlight) { - final DocumentContent content = getContent(); - final Document document = content.getDocument(); + TextDiffType type = getSide().select(TextDiffType.DELETED, TextDiffType.INSERTED); - TextDiffType type = getSide().select(TextDiffType.DELETED, TextDiffType.INSERTED); + myHighlighters.addAll(DiffDrawUtil.createHighlighter(getEditor(), 0, getLineCount(document), type, false)); - myHighlighters.addAll(DiffDrawUtil.createHighlighter(getEditor(), 0, getLineCount(document), type, false)); + int startLine = 0; + int endLine = getLineCount(document); - int startLine = 0; - int endLine = getLineCount(document); - - if (startLine != endLine) { - myHighlighters.addAll(DiffDrawUtil.createLineMarker(getEditor(), startLine, endLine, type, false)); - } + if (startLine != endLine) { + myHighlighters.addAll(DiffDrawUtil.createLineMarker(getEditor(), startLine, endLine, type, false)); } - - myInitialScrollHelper.onRediff(); } + + myInitialScrollHelper.onRediff(); }; } @@ -173,7 +167,7 @@ public class SimpleOnesideDiffViewer extends OnesideTextDiffViewer { protected boolean doScrollToContext(@NotNull DiffNavigationContext context) { if (getSide().isLeft()) return false; - AllLinesIterator allLinesIterator = new AllLinesIterator(); + AllLinesIterator allLinesIterator = new AllLinesIterator(getEditor().getDocument()); NavigationContextChecker checker2 = new NavigationContextChecker(allLinesIterator, context); int line = checker2.contextMatchCheck(); if (line == -1) return false; @@ -227,42 +221,6 @@ public class SimpleOnesideDiffViewer extends OnesideTextDiffViewer { } } - // - // Scroll from annotate - // - - private class AllLinesIterator implements Iterator> { - @NotNull private final Document myDocument; - private int myLine = 0; - - private AllLinesIterator() { - myDocument = getEditor().getDocument(); - } - - @Override - public boolean hasNext() { - return myLine < getLineCount(myDocument); - } - - @Override - public Pair next() { - int offset1 = myDocument.getLineStartOffset(myLine); - int offset2 = myDocument.getLineEndOffset(myLine); - - CharSequence text = myDocument.getImmutableCharSequence().subSequence(offset1, offset2); - - Pair pair = new Pair(myLine, text); - myLine++; - - return pair; - } - - @Override - public void remove() { - throw new UnsupportedOperationException(); - } - } - // // Helpers // diff --git a/platform/diff-impl/src/com/intellij/diff/tools/simple/SimpleThreesideDiffViewer.java b/platform/diff-impl/src/com/intellij/diff/tools/simple/SimpleThreesideDiffViewer.java index 94b70e92ff66..f94cb6b662af 100644 --- a/platform/diff-impl/src/com/intellij/diff/tools/simple/SimpleThreesideDiffViewer.java +++ b/platform/diff-impl/src/com/intellij/diff/tools/simple/SimpleThreesideDiffViewer.java @@ -55,8 +55,8 @@ import java.util.List; public class SimpleThreesideDiffViewer extends ThreesideTextDiffViewerEx { public static final Logger LOG = Logger.getInstance(SimpleThreesideDiffViewer.class); - @NotNull private final List myDiffChanges = new ArrayList(); - @NotNull private final List myInvalidDiffChanges = new ArrayList(); + @NotNull private final List myDiffChanges = new ArrayList<>(); + @NotNull private final List myInvalidDiffChanges = new ArrayList<>(); public SimpleThreesideDiffViewer(@NotNull DiffContext context, @NotNull DiffRequest request) { super(context, (ContentDiffRequest)request); @@ -65,7 +65,7 @@ public class SimpleThreesideDiffViewer extends ThreesideTextDiffViewerEx { @NotNull @Override protected List createToolbarActions() { - List group = new ArrayList(); + List group = new ArrayList<>(); group.add(new MyIgnorePolicySettingAction()); group.add(new MyHighlightPolicySettingAction()); @@ -88,7 +88,7 @@ public class SimpleThreesideDiffViewer extends ThreesideTextDiffViewerEx { @NotNull @Override protected List createPopupActions() { - List group = new ArrayList(); + List group = new ArrayList<>(); group.add(Separator.getInstance()); group.add(new MyIgnorePolicySettingAction().getPopupGroup()); @@ -143,7 +143,7 @@ public class SimpleThreesideDiffViewer extends ThreesideTextDiffViewerEx { comparisonPolicy, indicator); if (getHighlightPolicy().isFineFragments()) { - List fineLineFragments = new ArrayList(lineFragments.size()); + List fineLineFragments = new ArrayList<>(lineFragments.size()); for (final MergeLineFragment fragment : lineFragments) { CharSequence[] chunks = ApplicationManager.getApplication().runReadAction(new Computable() { @@ -193,26 +193,23 @@ public class SimpleThreesideDiffViewer extends ThreesideTextDiffViewerEx { @NotNull private Runnable apply(@NotNull final List fragments, @NotNull final ComparisonPolicy comparisonPolicy) { - return new Runnable() { - @Override - public void run() { - myFoldingModel.updateContext(myRequest, getFoldingModelSettings()); - clearDiffPresentation(); + return () -> { + myFoldingModel.updateContext(myRequest, getFoldingModelSettings()); + clearDiffPresentation(); - resetChangeCounters(); - for (MergeLineFragment fragment : fragments) { - SimpleThreesideDiffChange change = new SimpleThreesideDiffChange(fragment, getEditors(), comparisonPolicy); - myDiffChanges.add(change); - onChangeAdded(change); - } - - myFoldingModel.install(fragments, myRequest, getFoldingModelSettings()); - - myInitialScrollHelper.onRediff(); - - myContentPanel.repaintDividers(); - myStatusPanel.update(); + resetChangeCounters(); + for (MergeLineFragment fragment : fragments) { + SimpleThreesideDiffChange change = new SimpleThreesideDiffChange(fragment, getEditors(), comparisonPolicy); + myDiffChanges.add(change); + onChangeAdded(change); } + + myFoldingModel.install(fragments, myRequest, getFoldingModelSettings()); + + myInitialScrollHelper.onRediff(); + + myContentPanel.repaintDividers(); + myStatusPanel.update(); }; } @@ -251,7 +248,7 @@ public class SimpleThreesideDiffViewer extends ThreesideTextDiffViewerEx { LineRange lineRange = DiffUtil.getAffectedLineRange(e); int shift = DiffUtil.countLinesShift(e); - List invalid = new ArrayList(); + List invalid = new ArrayList<>(); for (SimpleThreesideDiffChange change : myDiffChanges) { if (change.processChange(lineRange.start, lineRange.end, shift, side)) { invalid.add(change); diff --git a/platform/diff-impl/src/com/intellij/diff/tools/simple/ThreesideDiffChangeBase.java b/platform/diff-impl/src/com/intellij/diff/tools/simple/ThreesideDiffChangeBase.java index 6b552fa1e5b0..ea81de34a28e 100644 --- a/platform/diff-impl/src/com/intellij/diff/tools/simple/ThreesideDiffChangeBase.java +++ b/platform/diff-impl/src/com/intellij/diff/tools/simple/ThreesideDiffChangeBase.java @@ -36,8 +36,8 @@ import java.util.List; public abstract class ThreesideDiffChangeBase { @NotNull private final ConflictType myType; - @NotNull protected final List myHighlighters = new ArrayList(); - @NotNull protected final List myInnerHighlighters = new ArrayList(); + @NotNull protected final List myHighlighters = new ArrayList<>(); + @NotNull protected final List myInnerHighlighters = new ArrayList<>(); public ThreesideDiffChangeBase(@NotNull MergeLineFragment fragment, @NotNull List editors, diff --git a/platform/diff-impl/src/com/intellij/diff/tools/simple/ThreesideTextDiffViewerEx.java b/platform/diff-impl/src/com/intellij/diff/tools/simple/ThreesideTextDiffViewerEx.java index 55a7e366f68b..8a413b1b7e21 100644 --- a/platform/diff-impl/src/com/intellij/diff/tools/simple/ThreesideTextDiffViewerEx.java +++ b/platform/diff-impl/src/com/intellij/diff/tools/simple/ThreesideTextDiffViewerEx.java @@ -35,7 +35,6 @@ import com.intellij.openapi.project.DumbAwareAction; import com.intellij.openapi.util.Condition; import com.intellij.openapi.util.UserDataHolder; import com.intellij.openapi.util.text.StringUtil; -import com.intellij.util.Function; import com.intellij.util.containers.ContainerUtil; import org.jetbrains.annotations.CalledInAwt; import org.jetbrains.annotations.NonNls; @@ -118,12 +117,9 @@ public abstract class ThreesideTextDiffViewerEx extends ThreesideTextDiffViewer @NotNull protected Runnable applyNotification(@Nullable final JComponent notification) { - return new Runnable() { - @Override - public void run() { - clearDiffPresentation(); - if (notification != null) myPanel.addNotification(notification); - } + return () -> { + clearDiffPresentation(); + if (notification != null) myPanel.addNotification(notification); }; } @@ -455,17 +451,13 @@ public abstract class ThreesideTextDiffViewerEx extends ThreesideTextDiffViewer public void install(@Nullable List fragments, @NotNull UserDataHolder context, @NotNull FoldingModelSupport.Settings settings) { - Iterator it = map(fragments, new Function() { - @Override - public int[] fun(MergeLineFragment fragment) { - return new int[]{ - fragment.getStartLine(ThreeSide.LEFT), - fragment.getEndLine(ThreeSide.LEFT), - fragment.getStartLine(ThreeSide.BASE), - fragment.getEndLine(ThreeSide.BASE), - fragment.getStartLine(ThreeSide.RIGHT), - fragment.getEndLine(ThreeSide.RIGHT)}; - } + Iterator it = map(fragments, fragment -> new int[]{ + fragment.getStartLine(ThreeSide.LEFT), + fragment.getEndLine(ThreeSide.LEFT), + fragment.getStartLine(ThreeSide.BASE), + fragment.getEndLine(ThreeSide.BASE), + fragment.getStartLine(ThreeSide.RIGHT), + fragment.getEndLine(ThreeSide.RIGHT) }); install(it, context, settings); } diff --git a/platform/diff-impl/src/com/intellij/diff/tools/util/DiffNotifications.java b/platform/diff-impl/src/com/intellij/diff/tools/util/DiffNotifications.java index 8421fdce6a9d..f8979bed739f 100644 --- a/platform/diff-impl/src/com/intellij/diff/tools/util/DiffNotifications.java +++ b/platform/diff-impl/src/com/intellij/diff/tools/util/DiffNotifications.java @@ -19,6 +19,7 @@ import com.intellij.diff.comparison.DiffTooBigException; import com.intellij.diff.util.TextDiffType; import com.intellij.openapi.diff.DiffBundle; import com.intellij.ui.EditorNotificationPanel; +import com.intellij.ui.HyperlinkLabel; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; @@ -90,11 +91,8 @@ public class DiffNotifications { panel.text(text); panel.setBackgroundColor(background); if (showHideAction) { - panel.createActionLabel("Hide", new Runnable() { - public void run() { - panel.setVisible(false); - } - }).setToolTipText("Hide this notification"); + HyperlinkLabel link = panel.createActionLabel("Hide", () -> panel.setVisible(false)); + link.setToolTipText("Hide this notification"); } return panel; } diff --git a/platform/diff-impl/src/com/intellij/diff/tools/util/FoldingModelSupport.java b/platform/diff-impl/src/com/intellij/diff/tools/util/FoldingModelSupport.java index 90458b614f06..e4f4094af4c5 100644 --- a/platform/diff-impl/src/com/intellij/diff/tools/util/FoldingModelSupport.java +++ b/platform/diff-impl/src/com/intellij/diff/tools/util/FoldingModelSupport.java @@ -64,7 +64,7 @@ public class FoldingModelSupport { protected final int myCount; @NotNull protected final EditorEx[] myEditors; - @NotNull protected final List myFoldings = new ArrayList(); + @NotNull protected final List myFoldings = new ArrayList<>(); private boolean myDuringSynchronize; private final boolean[] myShouldUpdateLineNumbers; @@ -99,12 +99,9 @@ public class FoldingModelSupport { if (changedLines == null) return; if (settings.range == -1) return; - runBatchOperation(new Runnable() { - @Override - public void run() { - FoldingBuilder builder = new FoldingBuilder(context, settings); - builder.build(changedLines); - } + runBatchOperation(() -> { + FoldingBuilder builder = new FoldingBuilder(context, settings); + builder.build(changedLines); }); updateLineNumbers(true); @@ -155,7 +152,7 @@ public class FoldingModelSupport { } private void addRange(int[] starts, int[] ends) { - List result = new ArrayList(3); + List result = new ArrayList<>(3); int[] rangeStarts = new int[myCount]; int[] rangeEnds = new int[myCount]; @@ -262,13 +259,10 @@ public class FoldingModelSupport { private void destroyFoldings(final int index) { final FoldingModelEx model = myEditors[index].getFoldingModel(); - model.runBatchFoldingOperation(new Runnable() { - @Override - public void run() { - for (FoldedBlock folding : getFoldedBlocks()) { - FoldRegion region = folding.getRegion(index); - if (region != null) model.removeFoldRegion(region); - } + model.runBatchFoldingOperation(() -> { + for (FoldedBlock folding : getFoldedBlocks()) { + FoldRegion region = folding.getRegion(index); + if (region != null) model.removeFoldRegion(region); } }); } @@ -293,19 +287,16 @@ public class FoldingModelSupport { @NotNull protected TIntFunction getLineConvertor(final int index) { - return new TIntFunction() { - @Override - public int execute(int value) { - updateLineNumbers(false); - for (FoldedBlock folding : getFoldedBlocks()) { // TODO: avoid full scan - it could slowdown painting - int line = folding.getLine(index); - if (line == -1) continue; - if (line > value) break; - FoldRegion region = folding.getRegion(index); - if (line == value && region != null && !region.isExpanded()) return -1; - } - return value; + return value -> { + updateLineNumbers(false); + for (FoldedBlock folding : getFoldedBlocks()) { // TODO: avoid full scan - it could slowdown painting + int line = folding.getLine(index); + if (line == -1) continue; + if (line > value) break; + FoldRegion region = folding.getRegion(index); + if (line == value && region != null && !region.isExpanded()) return -1; } + return value; }; } @@ -332,13 +323,10 @@ public class FoldingModelSupport { for (int i = 0; i < myCount; i++) { final int index = i; final FoldingModelEx model = myEditors[index].getFoldingModel(); - model.runBatchFoldingOperation(new Runnable() { - @Override - public void run() { - for (FoldedBlock folding : getFoldedBlocks()) { - FoldRegion region = folding.getRegion(index); - if (region != null) region.setExpanded(expanded); - } + model.runBatchFoldingOperation(() -> { + for (FoldedBlock folding : getFoldedBlocks()) { + FoldRegion region = folding.getRegion(index); + if (region != null) region.setExpanded(expanded); } }); } @@ -350,7 +338,7 @@ public class FoldingModelSupport { private class MyFoldingListener implements FoldingListener { private final int myIndex; - @NotNull Set myModifiedRegions = new HashSet(); + @NotNull Set myModifiedRegions = new HashSet<>(); public MyFoldingListener(int index) { myIndex = index; @@ -370,17 +358,14 @@ public class FoldingModelSupport { for (int i = 0; i < myCount; i++) { if (i == myIndex) continue; final int pairedIndex = i; - myEditors[pairedIndex].getFoldingModel().runBatchFoldingOperation(new Runnable() { - @Override - public void run() { - for (FoldedBlock folding : getFoldedBlocks()) { - FoldRegion region = folding.getRegion(myIndex); - if (region == null || !region.isValid()) continue; - if (myModifiedRegions.contains(region)) { - FoldRegion pairedRegion = folding.getRegion(pairedIndex); - if (pairedRegion == null || !pairedRegion.isValid()) continue; - pairedRegion.setExpanded(region.isExpanded()); - } + myEditors[pairedIndex].getFoldingModel().runBatchFoldingOperation(() -> { + for (FoldedBlock folding : getFoldedBlocks()) { + FoldRegion region = folding.getRegion(myIndex); + if (region == null || !region.isValid()) continue; + if (myModifiedRegions.contains(region)) { + FoldRegion pairedRegion = folding.getRegion(pairedIndex); + if (pairedRegion == null || !pairedRegion.isValid()) continue; + pairedRegion.setExpanded(region.isExpanded()); } } }); @@ -514,7 +499,7 @@ public class FoldingModelSupport { @NotNull private List getFoldedRanges(int index, @NotNull Settings settings) { ApplicationManager.getApplication().assertReadAccessAllowed(); - List ranges = new ArrayList(); + List ranges = new ArrayList<>(); DocumentEx document = myEditors[index].getDocument(); for (FoldedBlock[] blocks : myFoldings) { @@ -581,40 +566,34 @@ public class FoldingModelSupport { @NotNull private Iterable getFoldedBlocks() { - return new Iterable() { - @NotNull + return () -> new Iterator() { + private int myGroupIndex = 0; + private int myBlockIndex = 0; + @Override - public Iterator iterator() { - return new Iterator() { - private int myGroupIndex = 0; - private int myBlockIndex = 0; + public boolean hasNext() { + return myGroupIndex < myFoldings.size(); + } - @Override - public boolean hasNext() { - return myGroupIndex < myFoldings.size(); - } + @Override + public FoldedBlock next() { + FoldedBlock[] group = myFoldings.get(myGroupIndex); + FoldedBlock folding = group[myBlockIndex]; - @Override - public FoldedBlock next() { - FoldedBlock[] group = myFoldings.get(myGroupIndex); - FoldedBlock folding = group[myBlockIndex]; + if (group.length > myBlockIndex + 1) { + myBlockIndex++; + } + else { + myGroupIndex++; + myBlockIndex = 0; + } - if (group.length > myBlockIndex + 1) { - myBlockIndex++; - } - else { - myGroupIndex++; - myBlockIndex = 0; - } + return folding; + } - return folding; - } - - @Override - public void remove() { - throw new UnsupportedOperationException(); - } - }; + @Override + public void remove() { + throw new UnsupportedOperationException(); } }; } @@ -622,7 +601,7 @@ public class FoldingModelSupport { protected class FoldedBlock { @NotNull private final FoldRegion[] myRegions; @NotNull private final int[] myLines; - @NotNull private final List myHighlighters = new ArrayList(myCount); + @NotNull private final List myHighlighters = new ArrayList<>(myCount); public FoldedBlock(@NotNull FoldRegion[] regions) { assert regions.length == myCount; @@ -670,19 +649,16 @@ public class FoldingModelSupport { @NotNull private BooleanGetter getHighlighterCondition(@NotNull final FoldedBlock[] block, final int index) { - return new BooleanGetter() { - @Override - public boolean get() { - if (!myEditors[index].getFoldingModel().isFoldingEnabled()) return false; + return () -> { + if (!myEditors[index].getFoldingModel().isFoldingEnabled()) return false; - for (FoldedBlock folding : block) { - FoldRegion region = folding.getRegion(index); - boolean visible = region != null && region.isValid() && !region.isExpanded(); - if (folding == FoldedBlock.this) return visible; - if (visible) return false; // do not paint separator, if 'parent' folding is collapsed - } - return false; + for (FoldedBlock folding : block) { + FoldRegion region = folding.getRegion(index); + boolean visible = region != null && region.isValid() && !region.isExpanded(); + if (folding == this) return visible; + if (visible) return false; // do not paint separator, if 'parent' folding is collapsed } + return false; }; } } diff --git a/platform/diff-impl/src/com/intellij/diff/tools/util/KeyboardModifierListener.java b/platform/diff-impl/src/com/intellij/diff/tools/util/KeyboardModifierListener.java index 01310a408bda..3211943ad96b 100644 --- a/platform/diff-impl/src/com/intellij/diff/tools/util/KeyboardModifierListener.java +++ b/platform/diff-impl/src/com/intellij/diff/tools/util/KeyboardModifierListener.java @@ -54,14 +54,11 @@ public class KeyboardModifierListener implements Disposable { // we can use KeyListener on Editors, but Ctrl+Click will not work with focus in other place. // ex: commit dialog with focus in commit message - IdeEventQueue.getInstance().addPostprocessor(new IdeEventQueue.EventDispatcher() { - @Override - public boolean dispatch(AWTEvent e) { - if (e instanceof KeyEvent) { - onKeyEvent((KeyEvent)e); - } - return false; + IdeEventQueue.getInstance().addPostprocessor(e -> { + if (e instanceof KeyEvent) { + onKeyEvent((KeyEvent)e); } + return false; }, disposable); myWindow = UIUtil.getWindow(component); diff --git a/platform/diff-impl/src/com/intellij/diff/tools/util/SoftHardCacheMap.java b/platform/diff-impl/src/com/intellij/diff/tools/util/SoftHardCacheMap.java index 8ded7c1e0566..edd15dbc0f1d 100644 --- a/platform/diff-impl/src/com/intellij/diff/tools/util/SoftHardCacheMap.java +++ b/platform/diff-impl/src/com/intellij/diff/tools/util/SoftHardCacheMap.java @@ -25,8 +25,8 @@ public class SoftHardCacheMap { @NotNull private final SoftValueHashMap mySoftLinkMap; public SoftHardCacheMap(final int protectedQueueSize, final int probationalQueueSize) { - mySLRUMap = new SLRUMap(protectedQueueSize, probationalQueueSize); - mySoftLinkMap = new SoftValueHashMap(); + mySLRUMap = new SLRUMap<>(protectedQueueSize, probationalQueueSize); + mySoftLinkMap = new SoftValueHashMap<>(); } @Nullable diff --git a/platform/diff-impl/src/com/intellij/diff/tools/util/SyncScrollSupport.java b/platform/diff-impl/src/com/intellij/diff/tools/util/SyncScrollSupport.java index 1bd2bcbd8b33..86a54a7cedb8 100644 --- a/platform/diff-impl/src/com/intellij/diff/tools/util/SyncScrollSupport.java +++ b/platform/diff-impl/src/com/intellij/diff/tools/util/SyncScrollSupport.java @@ -44,6 +44,12 @@ public class SyncScrollSupport { int transfer(@NotNull Side baseSide, int line); } + public interface Support { + void enterDisableScrollSection(); + + void exitDisableScrollSection(); + } + public static class TwosideSyncScrollSupport extends SyncScrollSupportBase { @NotNull private final List myEditors; @NotNull private final SyncScrollable myScrollable; @@ -212,17 +218,19 @@ public class SyncScrollSupport { // Impl // - private abstract static class SyncScrollSupportBase { + private abstract static class SyncScrollSupportBase implements Support { private int myDuringSyncScrollDepth = 0; public boolean isDuringSyncScroll() { return myDuringSyncScrollDepth > 0; } + @Override public void enterDisableScrollSection() { myDuringSyncScrollDepth++; } + @Override public void exitDisableScrollSection() { myDuringSyncScrollDepth--; assert myDuringSyncScrollDepth >= 0; @@ -261,32 +269,26 @@ public class SyncScrollSupport { doScrollHorizontally(masterEditor, 0, false); // animation will be canceled by "scroll vertically" anyway doScrollVertically(masterEditor, masterOffset, animate); - masterEditor.getScrollingModel().runActionOnScrollingFinished(new Runnable() { - @Override - public void run() { - for (ScrollHelper helper : helpers) { - helper.removeAnchor(); - } + masterEditor.getScrollingModel().runActionOnScrollingFinished(() -> { + for (ScrollHelper helper : helpers) { + helper.removeAnchor(); + } - int masterFinalOffset = masterEditor.getScrollingModel().getVisibleArea().y; - boolean animateSlaves = animate && masterFinalOffset == masterStartOffset; - for (int i = 0; i < count; i++) { - if (i == masterIndex) continue; - Editor editor = editors.get(i); + int masterFinalOffset = masterEditor.getScrollingModel().getVisibleArea().y; + boolean animateSlaves = animate && masterFinalOffset == masterStartOffset; + for (int i = 0; i < count; i++) { + if (i == masterIndex) continue; + Editor editor = editors.get(i); - int finalOffset = editor.getScrollingModel().getVisibleArea().y; - if (finalOffset != offsets[i]) { - enterDisableScrollSection(); + int finalOffset = editor.getScrollingModel().getVisibleArea().y; + if (finalOffset != offsets[i]) { + enterDisableScrollSection(); - doScrollVertically(editor, offsets[i], animateSlaves); + doScrollVertically(editor, offsets[i], animateSlaves); - editor.getScrollingModel().runActionOnScrollingFinished(new Runnable() { - @Override - public void run() { - exitDisableScrollSection(); - } - }); - } + editor.getScrollingModel().runActionOnScrollingFinished(() -> { + exitDisableScrollSection(); + }); } } }); diff --git a/platform/diff-impl/src/com/intellij/diff/tools/util/TransferableFileEditorStateSupport.java b/platform/diff-impl/src/com/intellij/diff/tools/util/TransferableFileEditorStateSupport.java index 0f413e332c0a..67413c9d77f3 100644 --- a/platform/diff-impl/src/com/intellij/diff/tools/util/TransferableFileEditorStateSupport.java +++ b/platform/diff-impl/src/com/intellij/diff/tools/util/TransferableFileEditorStateSupport.java @@ -32,7 +32,6 @@ import com.intellij.openapi.util.Condition; import com.intellij.openapi.util.Disposer; import com.intellij.openapi.util.Key; import com.intellij.ui.ToggleActionButton; -import com.intellij.util.Function; import com.intellij.util.containers.ContainerUtil; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; @@ -47,11 +46,8 @@ public class TransferableFileEditorStateSupport { @NotNull private static final Key>> TRANSFERABLE_FILE_EDITOR_STATE = Key.create("Diff.TransferableFileEditorState"); - private static final Condition IS_SUPPORTED = new Condition() { - @Override - public boolean value(BinaryEditorHolder holder) { - return getEditorState(holder.getEditor()) != null; - } + private static final Condition IS_SUPPORTED = holder -> { + return getEditorState(holder.getEditor()) != null; }; @NotNull private final DiffSettingsHolder.DiffSettings mySettings; @@ -143,12 +139,7 @@ public class TransferableFileEditorStateSupport { private boolean myDuringUpdate = false; public MySynchronizer(@NotNull List editors) { - myEditors = ContainerUtil.map(editors, new Function() { - @Override - public FileEditor fun(BinaryEditorHolder holder) { - return holder.getEditor(); - } - }); + myEditors = ContainerUtil.map(editors, holder -> holder.getEditor()); } public void install(@NotNull Disposable disposable) { diff --git a/platform/diff-impl/src/com/intellij/diff/tools/util/base/DiffPanelBase.java b/platform/diff-impl/src/com/intellij/diff/tools/util/base/DiffPanelBase.java index e0e6f22833a4..ea9628bb3d48 100644 --- a/platform/diff-impl/src/com/intellij/diff/tools/util/base/DiffPanelBase.java +++ b/platform/diff-impl/src/com/intellij/diff/tools/util/base/DiffPanelBase.java @@ -35,8 +35,8 @@ public abstract class DiffPanelBase extends JPanel implements DataProvider { @NotNull private final DataProvider myDataProvider; @NotNull protected final DiffContext myContext; - @NotNull private final List myPersistentNotifications = new ArrayList(); - @NotNull private final List myNotifications = new ArrayList(); + @NotNull private final List myPersistentNotifications = new ArrayList<>(); + @NotNull private final List myNotifications = new ArrayList<>(); @NotNull protected final JPanel myContentPanel; @NotNull protected final Wrapper myNotificationsPanel; diff --git a/platform/diff-impl/src/com/intellij/diff/tools/util/base/DiffViewerBase.java b/platform/diff-impl/src/com/intellij/diff/tools/util/base/DiffViewerBase.java index 96929ad2e752..1dd7b782a42d 100644 --- a/platform/diff-impl/src/com/intellij/diff/tools/util/base/DiffViewerBase.java +++ b/platform/diff-impl/src/com/intellij/diff/tools/util/base/DiffViewerBase.java @@ -30,7 +30,6 @@ import com.intellij.openapi.progress.util.ProgressWindow; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.Disposer; import com.intellij.util.Alarm; -import com.intellij.util.Function; import com.intellij.util.SmartList; import com.intellij.util.containers.ContainerUtil; import com.intellij.util.ui.UIUtil; @@ -43,7 +42,7 @@ import java.util.List; public abstract class DiffViewerBase implements DiffViewer, DataProvider { protected static final Logger LOG = Logger.getInstance(DiffViewerBase.class); - @NotNull private final List myListeners = new SmartList(); + @NotNull private final List myListeners = new SmartList<>(); @Nullable protected final Project myProject; @NotNull protected final DiffContext myContext; @@ -80,24 +79,19 @@ public abstract class DiffViewerBase implements DiffViewer, DataProvider { @CalledInAwt public final void dispose() { if (myDisposed) return; - - Runnable doDispose = new Runnable() { - @Override - public void run() { - if (myDisposed) return; - myDisposed = true; - - abortRediff(); - updateContextHints(); - - fireEvent(EventType.DISPOSE); - - onDispose(); - } - }; - if (!ApplicationManager.getApplication().isDispatchThread()) LOG.warn(new Throwable("dispose() not from EDT")); - UIUtil.invokeLaterIfNeeded(doDispose); + + UIUtil.invokeLaterIfNeeded(() -> { + if (myDisposed) return; + myDisposed = true; + + abortRediff(); + updateContextHints(); + + fireEvent(EventType.DISPOSE); + + onDispose(); + }); } @CalledInAwt @@ -113,12 +107,7 @@ public abstract class DiffViewerBase implements DiffViewer, DataProvider { if (isDisposed()) return; abortRediff(); - myTaskAlarm.addRequest(new Runnable() { - @Override - public void run() { - rediff(); - } - }, ProgressWindow.DEFAULT_PROGRESS_DIALOG_POSTPONE_TIME_MILLIS); + myTaskAlarm.addRequest(this::rediff, ProgressWindow.DEFAULT_PROGRESS_DIALOG_POSTPONE_TIME_MILLIS); } @CalledInAwt @@ -145,27 +134,15 @@ public abstract class DiffViewerBase implements DiffViewer, DataProvider { int waitMillis = trySync || tryRediffSynchronously() ? ProgressWindow.DEFAULT_PROGRESS_DIALOG_POSTPONE_TIME_MILLIS : 0; myTaskExecutor.executeAndTryWait( - new Function() { - @Override - public Runnable fun(final ProgressIndicator indicator) { - final Runnable callback = performRediff(indicator); - return new Runnable() { - @Override - public void run() { - callback.run(); - onAfterRediff(); - fireEvent(EventType.AFTER_REDIFF); - } - }; - } + indicator -> { + final Runnable callback = performRediff(indicator); + return () -> { + callback.run(); + onAfterRediff(); + fireEvent(EventType.AFTER_REDIFF); + }; }, - new Runnable() { - @Override - public void run() { - onSlowRediff(); - } - }, - waitMillis, forceEDT + this::onSlowRediff, waitMillis, forceEDT ); } @@ -209,13 +186,13 @@ public abstract class DiffViewerBase implements DiffViewer, DataProvider { } protected List createToolbarActions() { - List group = new ArrayList(); + List group = new ArrayList<>(); ContainerUtil.addAll(group, ((ActionGroup)ActionManager.getInstance().getAction(IdeActions.DIFF_VIEWER_TOOLBAR)).getChildren(null)); return group; } protected List createPopupActions() { - List group = new ArrayList(); + List group = new ArrayList<>(); ContainerUtil.addAll(group, ((ActionGroup)ActionManager.getInstance().getAction(IdeActions.DIFF_VIEWER_POPUP)).getChildren(null)); return group; } diff --git a/platform/diff-impl/src/com/intellij/diff/tools/util/base/HighlightingLevel.java b/platform/diff-impl/src/com/intellij/diff/tools/util/base/HighlightingLevel.java index 4d536f5a2c68..a0345b5a704f 100644 --- a/platform/diff-impl/src/com/intellij/diff/tools/util/base/HighlightingLevel.java +++ b/platform/diff-impl/src/com/intellij/diff/tools/util/base/HighlightingLevel.java @@ -25,25 +25,16 @@ import org.jetbrains.annotations.Nullable; import javax.swing.*; public enum HighlightingLevel { - INSPECTIONS("Inspections", AllIcons.Ide.HectorOn, new Condition() { - @Override - public boolean value(RangeHighlighter rangeHighlighter) { - return true; - } + INSPECTIONS("Inspections", AllIcons.Ide.HectorOn, rangeHighlighter -> { + return true; }), - ADVANCED("Syntax", AllIcons.Ide.HectorSyntax, new Condition() { - @Override - public boolean value(RangeHighlighter rangeHighlighter) { - return rangeHighlighter.getLayer() <= HighlighterLayer.ADDITIONAL_SYNTAX; - } + ADVANCED("Syntax", AllIcons.Ide.HectorSyntax, rangeHighlighter -> { + return rangeHighlighter.getLayer() <= HighlighterLayer.ADDITIONAL_SYNTAX; }), - SIMPLE("None", AllIcons.Ide.HectorOff, new Condition() { - @Override - public boolean value(RangeHighlighter rangeHighlighter) { - return rangeHighlighter.getLayer() <= HighlighterLayer.SYNTAX; - } + SIMPLE("None", AllIcons.Ide.HectorOff, rangeHighlighter -> { + return rangeHighlighter.getLayer() <= HighlighterLayer.SYNTAX; }); @NotNull private final String myText; diff --git a/platform/diff-impl/src/com/intellij/diff/tools/util/base/ListenerDiffViewerBase.java b/platform/diff-impl/src/com/intellij/diff/tools/util/base/ListenerDiffViewerBase.java index 4b9bff7c64a9..1c74e4f84a3e 100644 --- a/platform/diff-impl/src/com/intellij/diff/tools/util/base/ListenerDiffViewerBase.java +++ b/platform/diff-impl/src/com/intellij/diff/tools/util/base/ListenerDiffViewerBase.java @@ -81,7 +81,7 @@ public abstract class ListenerDiffViewerBase extends DiffViewerBase { @Nullable protected VirtualFileListener createFileListener(@NotNull ContentDiffRequest request) { - final List files = new ArrayList(0); + final List files = new ArrayList<>(0); for (DiffContent content : request.getContents()) { if (content instanceof FileContent && !(content instanceof DocumentContent)) { files.add(((FileContent)content).getFile()); @@ -131,7 +131,7 @@ public abstract class ListenerDiffViewerBase extends DiffViewerBase { @NotNull private Set getDocuments() { - Set documents = new HashSet(); + Set documents = new HashSet<>(); for (DiffContent content : myRequest.getContents()) { if (content instanceof DocumentContent) { documents.add(((DocumentContent)content).getDocument()); diff --git a/platform/diff-impl/src/com/intellij/diff/tools/util/base/TextDiffSettingsHolder.java b/platform/diff-impl/src/com/intellij/diff/tools/util/base/TextDiffSettingsHolder.java index 841cd4ba2d01..19c184ee9339 100644 --- a/platform/diff-impl/src/com/intellij/diff/tools/util/base/TextDiffSettingsHolder.java +++ b/platform/diff-impl/src/com/intellij/diff/tools/util/base/TextDiffSettingsHolder.java @@ -84,7 +84,7 @@ public class TextDiffSettingsHolder implements PersistentStateComponent getDefaultPlaceSettings() { - Map map = new TreeMap(); + Map map = new TreeMap<>(); PlaceSettings changes = new PlaceSettings(); changes.EXPAND_BY_DEFAULT = false; diff --git a/platform/diff-impl/src/com/intellij/diff/tools/util/base/TextDiffViewerUtil.java b/platform/diff-impl/src/com/intellij/diff/tools/util/base/TextDiffViewerUtil.java index e01dbfc101c0..f72f601759e5 100644 --- a/platform/diff-impl/src/com/intellij/diff/tools/util/base/TextDiffViewerUtil.java +++ b/platform/diff-impl/src/com/intellij/diff/tools/util/base/TextDiffViewerUtil.java @@ -54,7 +54,7 @@ public class TextDiffViewerUtil { @NotNull public static List createEditorPopupActions() { - List result = new ArrayList(); + List result = new ArrayList<>(); result.add(ActionManager.getInstance().getAction("CompareClipboardWithSelection")); result.add(Separator.getInstance()); diff --git a/platform/diff-impl/src/com/intellij/diff/tools/util/side/ThreesideContentPanel.java b/platform/diff-impl/src/com/intellij/diff/tools/util/side/ThreesideContentPanel.java index f3120bce4652..7ccb46b47c91 100644 --- a/platform/diff-impl/src/com/intellij/diff/tools/util/side/ThreesideContentPanel.java +++ b/platform/diff-impl/src/com/intellij/diff/tools/util/side/ThreesideContentPanel.java @@ -44,7 +44,7 @@ public class ThreesideContentPanel extends JPanel { EditorHolder baseHolder = ThreeSide.BASE.select(holders); myBaseEditor = baseHolder instanceof TextEditorHolder ? ((TextEditorHolder)baseHolder).getEditor() : null; - ArrayList components = new ArrayList(3); + ArrayList components = new ArrayList<>(3); for (int i = 0; i < 3; i++) { components.add(new HolderPanel(holders.get(i), titleComponents.get(i))); } diff --git a/platform/diff-impl/src/com/intellij/diff/tools/util/side/ThreesideDiffViewer.java b/platform/diff-impl/src/com/intellij/diff/tools/util/side/ThreesideDiffViewer.java index 404246c2dc97..44e1319252e6 100644 --- a/platform/diff-impl/src/com/intellij/diff/tools/util/side/ThreesideDiffViewer.java +++ b/platform/diff-impl/src/com/intellij/diff/tools/util/side/ThreesideDiffViewer.java @@ -97,7 +97,7 @@ public abstract class ThreesideDiffViewer extends Listen protected List createEditorHolders(@NotNull EditorHolderFactory factory) { List contents = myRequest.getContents(); - List holders = new ArrayList(3); + List holders = new ArrayList<>(3); for (int i = 0; i < 3; i++) { DiffContent content = contents.get(i); holders.add(factory.create(content, myContext)); diff --git a/platform/diff-impl/src/com/intellij/diff/tools/util/side/ThreesideTextDiffViewer.java b/platform/diff-impl/src/com/intellij/diff/tools/util/side/ThreesideTextDiffViewer.java index bfe02792a800..39a6cb31718e 100644 --- a/platform/diff-impl/src/com/intellij/diff/tools/util/side/ThreesideTextDiffViewer.java +++ b/platform/diff-impl/src/com/intellij/diff/tools/util/side/ThreesideTextDiffViewer.java @@ -42,7 +42,6 @@ import com.intellij.openapi.editor.ex.EditorEx; import com.intellij.openapi.editor.ex.EditorMarkupModel; import com.intellij.openapi.fileEditor.OpenFileDescriptor; import com.intellij.openapi.util.Pair; -import com.intellij.util.Function; import com.intellij.util.containers.ContainerUtil; import org.jetbrains.annotations.CalledInAwt; import org.jetbrains.annotations.NonNls; @@ -139,6 +138,7 @@ public abstract class ThreesideTextDiffViewer extends ThreesideDiffViewer getEditors() { if (myEditors == null) { - myEditors = ContainerUtil.map(getEditorHolders(), new Function() { - @Override - public EditorEx fun(TextEditorHolder holder) { - return holder.getEditor(); - } - }); + myEditors = ContainerUtil.map(getEditorHolders(), holder -> holder.getEditor()); } return myEditors; } diff --git a/platform/diff-impl/src/com/intellij/diff/tools/util/side/TwosideDiffViewer.java b/platform/diff-impl/src/com/intellij/diff/tools/util/side/TwosideDiffViewer.java index 85db70b7e657..26e80c570daf 100644 --- a/platform/diff-impl/src/com/intellij/diff/tools/util/side/TwosideDiffViewer.java +++ b/platform/diff-impl/src/com/intellij/diff/tools/util/side/TwosideDiffViewer.java @@ -94,7 +94,7 @@ public abstract class TwosideDiffViewer extends Listener protected List createEditorHolders(@NotNull EditorHolderFactory factory) { List contents = myRequest.getContents(); - List holders = new ArrayList(2); + List holders = new ArrayList<>(2); for (int i = 0; i < 2; i++) { DiffContent content = contents.get(i); holders.add(factory.create(content, myContext)); diff --git a/platform/diff-impl/src/com/intellij/diff/tools/util/side/TwosideTextDiffViewer.java b/platform/diff-impl/src/com/intellij/diff/tools/util/side/TwosideTextDiffViewer.java index a9d77d95a86b..0c9774909434 100644 --- a/platform/diff-impl/src/com/intellij/diff/tools/util/side/TwosideTextDiffViewer.java +++ b/platform/diff-impl/src/com/intellij/diff/tools/util/side/TwosideTextDiffViewer.java @@ -44,7 +44,6 @@ import com.intellij.openapi.editor.event.VisibleAreaEvent; import com.intellij.openapi.editor.event.VisibleAreaListener; import com.intellij.openapi.editor.ex.EditorEx; import com.intellij.openapi.fileEditor.OpenFileDescriptor; -import com.intellij.util.Function; import com.intellij.util.containers.ContainerUtil; import org.jetbrains.annotations.CalledInAwt; import org.jetbrains.annotations.NonNls; @@ -164,6 +163,7 @@ public abstract class TwosideTextDiffViewer extends TwosideDiffViewer getEditors() { if (myEditors == null) { - myEditors = ContainerUtil.map(getEditorHolders(), new Function() { - @Override - public EditorEx fun(TextEditorHolder holder) { - return holder.getEditor(); - } - }); + myEditors = ContainerUtil.map(getEditorHolders(), holder -> holder.getEditor()); } return myEditors; } @@ -326,7 +321,7 @@ public abstract class TwosideTextDiffViewer extends TwosideDiffViewer createVisiblePolygons(@NotNull Editor editor1, @NotNull Editor editor2, @NotNull DividerPaintable paintable) { - final List polygons = new ArrayList(); + final List polygons = new ArrayList<>(); final Transformation[] transformations = new Transformation[]{getTransformation(editor1), getTransformation(editor2)}; @@ -125,7 +125,7 @@ public class DiffDividerDrawUtil { public static List createVisibleSeparators(@NotNull Editor editor1, @NotNull Editor editor2, @NotNull DividerSeparatorPaintable paintable) { - final List separators = new ArrayList(); + final List separators = new ArrayList<>(); final Transformation[] transformations = new Transformation[]{getTransformation(editor1), getTransformation(editor2)}; @@ -137,15 +137,12 @@ public class DiffDividerDrawUtil { final EditorColorsScheme scheme = editor1.getColorsScheme(); - paintable.process(new DividerSeparatorPaintable.Handler() { - @Override - public boolean process(int line1, int line2) { - if (leftInterval.start > line1 + 1 && rightInterval.start > line2 + 1) return true; - if (leftInterval.end < line1 && rightInterval.end < line2) return false; + paintable.process((line1, line2) -> { + if (leftInterval.start > line1 + 1 && rightInterval.start > line2 + 1) return true; + if (leftInterval.end < line1 && rightInterval.end < line2) return false; - separators.add(createSeparator(transformations, line1, line2, height1, height2, scheme)); - return true; - } + separators.add(createSeparator(transformations, line1, line2, height1, height2, scheme)); + return true; }); return separators; @@ -153,16 +150,13 @@ public class DiffDividerDrawUtil { @NotNull private static Transformation getTransformation(@NotNull final Editor editor) { - return new Transformation() { - @Override - public int transform(int line) { - int yOffset = editor.logicalPositionToXY(new LogicalPosition(line, 0)).y; + return (line) -> { + int yOffset = editor.logicalPositionToXY(new LogicalPosition(line, 0)).y; - final JComponent header = editor.getHeaderComponent(); - int headerOffset = header == null ? 0 : header.getHeight(); + final JComponent header = editor.getHeaderComponent(); + int headerOffset = header == null ? 0 : header.getHeight(); - return yOffset - editor.getScrollingModel().getVerticalScrollOffset() + headerOffset; - } + return yOffset - editor.getScrollingModel().getVerticalScrollOffset() + headerOffset; }; } diff --git a/platform/diff-impl/src/com/intellij/diff/util/DiffUtil.java b/platform/diff-impl/src/com/intellij/diff/util/DiffUtil.java index aba0d70fc09d..4180e08119be 100644 --- a/platform/diff-impl/src/com/intellij/diff/util/DiffUtil.java +++ b/platform/diff-impl/src/com/intellij/diff/util/DiffUtil.java @@ -83,7 +83,6 @@ import com.intellij.ui.JBColor; import com.intellij.ui.ScreenUtil; import com.intellij.ui.components.JBLabel; import com.intellij.util.DocumentUtil; -import com.intellij.util.Function; import com.intellij.util.LineSeparator; import com.intellij.util.containers.ContainerUtil; import com.intellij.util.ui.JBInsets; @@ -110,6 +109,10 @@ public class DiffUtil { // Editor // + public static boolean isDiffEditor(@NotNull Editor editor) { + return editor.getUserData(DiffManagerImpl.EDITOR_IS_DIFF_KEY) != null; + } + @Nullable public static EditorHighlighter initEditorHighlighter(@Nullable Project project, @NotNull DocumentContent content, @@ -369,7 +372,7 @@ public class DiffUtil { return Collections.nCopies(titles.size(), null); } - List components = new ArrayList(titles.size()); + List components = new ArrayList<>(titles.size()); for (int i = 0; i < contents.size(); i++) { JComponent title = createTitle(StringUtil.notNullize(titles.get(i))); title = createTitleWithNotifications(title, contents.get(i)); @@ -387,7 +390,7 @@ public class DiffUtil { boolean equalCharsets = TextDiffViewerUtil.areEqualCharsets(contents); boolean equalSeparators = TextDiffViewerUtil.areEqualLineSeparators(contents); - List result = new ArrayList(contents.size()); + List result = new ArrayList<>(contents.size()); if (equalCharsets && equalSeparators && !ContainerUtil.exists(titles, Condition.NOT_NULL)) { return Collections.nCopies(titles.size(), null); @@ -408,7 +411,7 @@ public class DiffUtil { List notifications = getCustomNotifications(content); if (notifications.isEmpty()) return title; - List components = new ArrayList(); + List components = new ArrayList<>(); if (title != null) components.add(title); components.addAll(notifications); return createStackedComponents(components, TITLE_GAP); @@ -500,7 +503,7 @@ public class DiffUtil { @NotNull public static List createSyncHeightComponents(@NotNull final List components) { if (!ContainerUtil.exists(components, Condition.NOT_NULL)) return components; - List result = new ArrayList(); + List result = new ArrayList<>(); for (int i = 0; i < components.size(); i++) { result.add(new SyncHeightComponent(components, i)); } @@ -601,12 +604,7 @@ public class DiffUtil { List wordConflicts = ByWord.compare(chunk1, chunk2, comparisonPolicy, indicator); - return ContainerUtil.map(wordConflicts, new Function() { - @Override - public MergeWordFragment fun(DiffFragment fragment) { - return new MyWordFragment(side1, side2, fragment); - } - }); + return ContainerUtil.map(wordConflicts, fragment -> new MyWordFragment(side1, side2, fragment)); } private static boolean isChunksEquals(@Nullable CharSequence chunk1, @@ -783,7 +781,7 @@ public class DiffUtil { startLine, endLine, document.getLineCount())); } - List result = new ArrayList(); + List result = new ArrayList<>(); for (int i = startLine; i < endLine; i++) { int start = document.getLineStartOffset(i); int end = document.getLineEndOffset(i); @@ -939,26 +937,15 @@ public class DiffUtil { return; } - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - CommandProcessor.getInstance().executeCommand(myProject, new Runnable() { - @Override - public void run() { - if (myUnderBulkUpdate) { - DocumentUtil.executeInBulk(myDocument, true, new Runnable() { - @Override - public void run() { - execute(); - } - }); - } - else { - execute(); - } - } - }, myCommandName, myCommandGroupId, myConfirmationPolicy, myDocument); - } + ApplicationManager.getApplication().runWriteAction(() -> { + CommandProcessor.getInstance().executeCommand(myProject, () -> { + if (myUnderBulkUpdate) { + DocumentUtil.executeInBulk(myDocument, true, this::execute); + } + else { + execute(); + } + }, myCommandName, myCommandGroupId, myConfirmationPolicy, myDocument); }); } @@ -1180,7 +1167,7 @@ public class DiffUtil { public static List filterSuppressedTools(@NotNull List tools) { if (tools.size() < 2) return tools; - final List> suppressedTools = new ArrayList>(); + final List> suppressedTools = new ArrayList<>(); for (T tool : tools) { try { if (tool instanceof SuppressiveDiffTool) suppressedTools.addAll(((SuppressiveDiffTool)tool).getSuppressedTools()); @@ -1192,13 +1179,7 @@ public class DiffUtil { if (suppressedTools.isEmpty()) return tools; - List filteredTools = ContainerUtil.filter(tools, new Condition() { - @Override - public boolean value(T tool) { - return !suppressedTools.contains(tool.getClass()); - } - }); - + List filteredTools = ContainerUtil.filter(tools, tool -> !suppressedTools.contains(tool.getClass())); return filteredTools.isEmpty() ? tools : filteredTools; } diff --git a/platform/diff-impl/src/com/intellij/diff/util/TextDiffTypeFactory.java b/platform/diff-impl/src/com/intellij/diff/util/TextDiffTypeFactory.java index 27ed81431e22..047f18b0c063 100644 --- a/platform/diff-impl/src/com/intellij/diff/util/TextDiffTypeFactory.java +++ b/platform/diff-impl/src/com/intellij/diff/util/TextDiffTypeFactory.java @@ -42,7 +42,7 @@ public class TextDiffTypeFactory { new TextDiffTypeImpl(DiffColors.DIFF_CONFLICT, DiffBundle.message("diff.type.conflict.name")); private static final TextDiffTypeFactory ourInstance = new TextDiffTypeFactory(); - private final List myTypes = new ArrayList(); + private final List myTypes = new ArrayList<>(); private TextDiffTypeFactory() { ContainerUtil.addAll(myTypes, INSERTED, DELETED, MODIFIED, CONFLICT); diff --git a/platform/diff-impl/src/com/intellij/openapi/diff/impl/dir/DTree.java b/platform/diff-impl/src/com/intellij/openapi/diff/impl/dir/DTree.java index c7094b860025..3325ca54a1ce 100644 --- a/platform/diff-impl/src/com/intellij/openapi/diff/impl/dir/DTree.java +++ b/platform/diff-impl/src/com/intellij/openapi/diff/impl/dir/DTree.java @@ -69,7 +69,7 @@ public class DTree { public Collection getChildren() { init(); if (myChildrenList == null) { - myChildrenList = new SortedList(COMPARATOR); + myChildrenList = new SortedList<>(COMPARATOR); myChildrenList.addAll(myChildren.values()); } return myChildrenList; @@ -114,7 +114,7 @@ public class DTree { private void init() { if (myChildren == null) { - myChildren = new HashMap(); + myChildren = new HashMap<>(); } } diff --git a/platform/diff-impl/src/com/intellij/openapi/diff/impl/dir/DirDiffPanel.java b/platform/diff-impl/src/com/intellij/openapi/diff/impl/dir/DirDiffPanel.java index 4098f36425ea..61681ca9be00 100644 --- a/platform/diff-impl/src/com/intellij/openapi/diff/impl/dir/DirDiffPanel.java +++ b/platform/diff-impl/src/com/intellij/openapi/diff/impl/dir/DirDiffPanel.java @@ -539,7 +539,7 @@ public class DirDiffPanel implements Disposable, DataProvider { private OpenFileDescriptor[] getOpenFileDescriptorsArray() { Project project = myModel.getProject(); List elements = myModel.getSelectedElements(); - List descriptors = new ArrayList(); + List descriptors = new ArrayList<>(); for (DirDiffElementImpl element : elements) { DiffElement source = element.getSource(); DiffElement target = element.getTarget(); diff --git a/platform/diff-impl/src/com/intellij/openapi/diff/impl/dir/DirDiffTableModel.java b/platform/diff-impl/src/com/intellij/openapi/diff/impl/dir/DirDiffTableModel.java index d4588e9d2b3e..d64ae486280e 100644 --- a/platform/diff-impl/src/com/intellij/openapi/diff/impl/dir/DirDiffTableModel.java +++ b/platform/diff-impl/src/com/intellij/openapi/diff/impl/dir/DirDiffTableModel.java @@ -73,11 +73,11 @@ public class DirDiffTableModel extends AbstractTableModel implements DirDiffMode private DiffElement mySrc; private DiffElement myTrg; private DTree myTree; - private final List myElements = new ArrayList(); + private final List myElements = new ArrayList<>(); private final AtomicBoolean myUpdating = new AtomicBoolean(false); private JBTable myTable; public String DECORATOR = "DIFF_TABLE_DECORATOR"; - public final AtomicReference text = new AtomicReference(prepareText("")); + public final AtomicReference text = new AtomicReference<>(prepareText("")); private Updater myUpdater; private List myListeners = ContainerUtil.createLockFreeCopyOnWriteList(); private TableSelectionConfig mySelectionConfig; @@ -282,7 +282,7 @@ public class DirDiffTableModel extends AbstractTableModel implements DirDiffMode myTree.setTarget(myTrg); myTree.update(mySettings); - ArrayList elements = new ArrayList(); + ArrayList elements = new ArrayList<>(); fillElements(myTree, elements); myElements.clear(); myElements.addAll(elements); @@ -333,7 +333,7 @@ public class DirDiffTableModel extends AbstractTableModel implements DirDiffMode public void run() { if (myDisposed) return; myTree.updateVisibility(mySettings); - final ArrayList elements = new ArrayList(); + final ArrayList elements = new ArrayList<>(); fillElements(myTree, elements); final Runnable uiThread = new Runnable() { public void run() { @@ -512,7 +512,7 @@ public class DirDiffTableModel extends AbstractTableModel implements DirDiffMode public List getSelectedElements() { final int[] rows = myTable.getSelectedRows(); - final ArrayList elements = new ArrayList(); + final ArrayList elements = new ArrayList<>(); for (int row : rows) { final DirDiffElementImpl element = getElementAt(row); if (element == null || element.isSeparator()) continue; @@ -604,8 +604,8 @@ public class DirDiffTableModel extends AbstractTableModel implements DirDiffMode final String path = element.getParentNode().getPath(); if (source instanceof BackgroundOperatingDiffElement) { - final Ref errorMessage = new Ref(); - final Ref diff = new Ref(); + final Ref errorMessage = new Ref<>(); + final Ref diff = new Ref<>(); Runnable onFinish = new Runnable() { @Override public void run() { @@ -662,8 +662,8 @@ public class DirDiffTableModel extends AbstractTableModel implements DirDiffMode final String path = element.getParentNode().getPath(); if (target instanceof BackgroundOperatingDiffElement) { - final Ref errorMessage = new Ref(); - final Ref diff = new Ref(); + final Ref errorMessage = new Ref<>(); + final Ref diff = new Ref<>(); Runnable onFinish = new Runnable() { @Override public void run() { @@ -744,7 +744,7 @@ public class DirDiffTableModel extends AbstractTableModel implements DirDiffMode final DiffElement target = element.getTarget(); LOG.assertTrue(source == null || target == null); if (source instanceof BackgroundOperatingDiffElement || target instanceof BackgroundOperatingDiffElement) { - final Ref errorMessage = new Ref(); + final Ref errorMessage = new Ref<>(); Runnable onFinish = new Runnable() { @Override public void run() { @@ -805,7 +805,7 @@ public class DirDiffTableModel extends AbstractTableModel implements DirDiffMode } public void synchronizeAll() { - List elements = new ArrayList(myElements); + List elements = new ArrayList<>(myElements); if (!checkCanDelete(elements)) { return; } diff --git a/platform/diff-impl/src/com/intellij/openapi/diff/impl/dir/actions/ChangeCompareModeGroup.java b/platform/diff-impl/src/com/intellij/openapi/diff/impl/dir/actions/ChangeCompareModeGroup.java index fe97eec6079f..5d27a03b2fb5 100644 --- a/platform/diff-impl/src/com/intellij/openapi/diff/impl/dir/actions/ChangeCompareModeGroup.java +++ b/platform/diff-impl/src/com/intellij/openapi/diff/impl/dir/actions/ChangeCompareModeGroup.java @@ -38,7 +38,7 @@ public class ChangeCompareModeGroup extends ComboBoxAction implements ShortcutPr public ChangeCompareModeGroup(DirDiffTableModel model) { mySettings = model.getSettings(); getTemplatePresentation().setText(mySettings.compareMode.getPresentableName(mySettings)); - final ArrayList actions = new ArrayList(); + final ArrayList actions = new ArrayList<>(); if (model.getSettings().showCompareModes) { for (DirDiffSettings.CompareMode mode : DirDiffSettings.CompareMode.values()) { actions.add(new ChangeCompareModeAction(model, mode)); diff --git a/platform/diff-impl/src/com/intellij/openapi/diff/impl/dir/actions/DirDiffToolbarActions.java b/platform/diff-impl/src/com/intellij/openapi/diff/impl/dir/actions/DirDiffToolbarActions.java index e845e939c0d2..f170b83a8e40 100644 --- a/platform/diff-impl/src/com/intellij/openapi/diff/impl/dir/actions/DirDiffToolbarActions.java +++ b/platform/diff-impl/src/com/intellij/openapi/diff/impl/dir/actions/DirDiffToolbarActions.java @@ -34,7 +34,7 @@ public class DirDiffToolbarActions extends ActionGroup { public DirDiffToolbarActions(DirDiffTableModel model, JComponent panel) { super("Directory Diff Actions", false); - final List actions = new ArrayList(Arrays.asList( + final List actions = new ArrayList<>(Arrays.asList( new RefreshDirDiffAction(model), Separator.getInstance(), new EnableLeft(model), diff --git a/platform/dvcs-impl/src/com/intellij/dvcs/push/ui/PushLog.java b/platform/dvcs-impl/src/com/intellij/dvcs/push/ui/PushLog.java index 369b7b144573..973bfaf3a2f8 100644 --- a/platform/dvcs-impl/src/com/intellij/dvcs/push/ui/PushLog.java +++ b/platform/dvcs-impl/src/com/intellij/dvcs/push/ui/PushLog.java @@ -222,7 +222,7 @@ public class PushLog extends JPanel implements DataProvider { PopupHandler.installPopupHandler(myTree, VcsLogActionPlaces.POPUP_ACTION_GROUP, CONTEXT_MENU); myChangesBrowser = - new ChangesBrowser(project, null, Collections.emptyList(), null, false, true, null, ChangesBrowser.MyUseCase.LOCAL_CHANGES, + new ChangesBrowser(project, null, Collections.emptyList(), null, false, false, null, ChangesBrowser.MyUseCase.LOCAL_CHANGES, null); myChangesBrowser.getDiffAction().registerCustomShortcutSet(myChangesBrowser.getDiffAction().getShortcutSet(), myTree); final EditSourceForDialogAction editSourceAction = new EditSourceForDialogAction(myChangesBrowser); diff --git a/platform/editor-ui-api/src/com/intellij/ide/ui/UISettingsListener.java b/platform/editor-ui-api/src/com/intellij/ide/ui/UISettingsListener.java index 1dcce2c076a3..56738a1e0286 100644 --- a/platform/editor-ui-api/src/com/intellij/ide/ui/UISettingsListener.java +++ b/platform/editor-ui-api/src/com/intellij/ide/ui/UISettingsListener.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2013 JetBrains s.r.o. + * Copyright 2000-2016 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. @@ -14,9 +14,6 @@ * limitations under the License. */ -/** - * @author Vladimir Kondratyev - */ package com.intellij.ide.ui; import com.intellij.util.messages.Topic; diff --git a/platform/editor-ui-ex/src/com/intellij/openapi/editor/colors/impl/AbstractColorsScheme.java b/platform/editor-ui-ex/src/com/intellij/openapi/editor/colors/impl/AbstractColorsScheme.java index f2922966eba2..47fa8fc58e24 100644 --- a/platform/editor-ui-ex/src/com/intellij/openapi/editor/colors/impl/AbstractColorsScheme.java +++ b/platform/editor-ui-ex/src/com/intellij/openapi/editor/colors/impl/AbstractColorsScheme.java @@ -14,14 +14,12 @@ * limitations under the License. */ -/** - * @author Yura Cangea - */ package com.intellij.openapi.editor.colors.impl; import com.intellij.application.options.EditorFontsConstants; import com.intellij.ide.ui.ColorBlindness; import com.intellij.ide.ui.UISettings; +import com.intellij.openapi.application.ex.ApplicationInfoEx; import com.intellij.openapi.editor.HighlighterColors; import com.intellij.openapi.editor.colors.*; import com.intellij.openapi.editor.colors.ex.DefaultColorSchemesManager; @@ -31,6 +29,7 @@ import com.intellij.openapi.options.FontSize; import com.intellij.openapi.util.Comparing; import com.intellij.openapi.util.Couple; import com.intellij.openapi.util.WriteExternalException; +import com.intellij.util.PlatformUtils; import com.intellij.util.containers.ContainerUtilRt; import com.intellij.util.containers.HashMap; import com.intellij.util.ui.JBUI; @@ -41,6 +40,7 @@ import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.awt.*; +import java.text.SimpleDateFormat; import java.util.*; import java.util.List; @@ -105,6 +105,23 @@ public abstract class AbstractColorsScheme implements EditorColorsScheme { @NonNls private static final String CONSOLE_LIGATURES = "CONSOLE_LIGATURES"; @NonNls private static final String EDITOR_QUICK_JAVADOC_FONT_SIZE = "EDITOR_QUICK_DOC_FONT_SIZE"; + + //region Meta info-related fields + private final Properties myMetaInfo = new Properties(); + private final static SimpleDateFormat META_INFO_DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss"); + + @NonNls private static final String META_INFO_ELEMENT = "metaInfo"; + @NonNls private static final String PROPERTY_ELEMENT = "property"; + @NonNls private static final String PROPERTY_NAME_ATTR = "name"; + + @NonNls private static final String META_INFO_CREATION_TIME = "created"; + @NonNls private static final String META_INFO_MODIFIED_TIME = "modified"; + @NonNls private static final String META_INFO_IDE = "ide"; + @NonNls private static final String META_INFO_IDE_VERSION = "ideVersion"; + @NonNls private static final String META_INFO_ORIGINAL = "originalScheme"; + + //endregion + protected AbstractColorsScheme(EditorColorsScheme parentScheme) { myParentScheme = parentScheme; myFontPreferences.setChangeListener(new Runnable() { @@ -117,6 +134,16 @@ public abstract class AbstractColorsScheme implements EditorColorsScheme { public AbstractColorsScheme() { } + + + public void setDefaultMetaInfo(@Nullable AbstractColorsScheme parentScheme) { + myMetaInfo.setProperty(META_INFO_CREATION_TIME, META_INFO_DATE_FORMAT.format(new Date())); + myMetaInfo.setProperty(META_INFO_IDE, PlatformUtils.getPlatformPrefix()); + myMetaInfo.setProperty(META_INFO_IDE_VERSION, ApplicationInfoEx.getInstanceEx().getStrictVersion()); + if (parentScheme != null && parentScheme != EmptyColorScheme.INSTANCE) { + myMetaInfo.setProperty(META_INFO_ORIGINAL, parentScheme.getName()); + } + } @NotNull @Override @@ -315,6 +342,7 @@ public abstract class AbstractColorsScheme implements EditorColorsScheme { myParentScheme = getDefaultScheme(node.getAttributeValue(PARENT_SCHEME_ATTR, EmptyColorScheme.NAME)); } + myMetaInfo.clear(); for (final Object o : node.getChildren()) { Element childNode = (Element)o; String childName = childNode.getName(); @@ -333,6 +361,10 @@ public abstract class AbstractColorsScheme implements EditorColorsScheme { else if (ATTRIBUTES_ELEMENT.equals(childName)) { readAttributes(childNode); } + else if(META_INFO_ELEMENT.equals(childName)) { + readMetaInfo(childNode); + } + } if (myDeprecatedBackgroundColor != null) { @@ -362,6 +394,19 @@ public abstract class AbstractColorsScheme implements EditorColorsScheme { } return defaultScheme; } + + + private void readMetaInfo(@NotNull Element metaInfoElement) { + myMetaInfo.clear(); + for (Element e: metaInfoElement.getChildren()) { + if (META_INFO_ELEMENT.equals(e.getName())) { + String propertyName = e.getAttributeValue(PROPERTY_NAME_ATTR); + if (propertyName != null) { + myMetaInfo.setProperty(propertyName, e.getText()); + } + } + } + } public void readAttributes(@NotNull Element childNode) { for (Element e : childNode.getChildren(OPTION_ELEMENT)) { @@ -493,6 +538,10 @@ public abstract class AbstractColorsScheme implements EditorColorsScheme { if (myParentScheme != null && myParentScheme != EmptyColorScheme.INSTANCE) { parentNode.setAttribute(PARENT_SCHEME_ATTR, myParentScheme.getName()); } + + if (!myMetaInfo.isEmpty()) { + parentNode.addContent(metaInfoToElement()); + } Element element = new Element(OPTION_ELEMENT); element.setAttribute(NAME_ATTR, LINE_SPACING); @@ -626,6 +675,23 @@ public abstract class AbstractColorsScheme implements EditorColorsScheme { } } } + + @NotNull + private Element metaInfoToElement() { + Element metaInfoElement = new Element(META_INFO_ELEMENT); + myMetaInfo.setProperty(META_INFO_MODIFIED_TIME, META_INFO_DATE_FORMAT.format(new Date())); + ArrayList sortedPropertyNames = new ArrayList<>(myMetaInfo.size()); + sortedPropertyNames.addAll(myMetaInfo.stringPropertyNames()); + Collections.sort(sortedPropertyNames); + for (String propertyName : sortedPropertyNames) { + String value = myMetaInfo.getProperty(propertyName); + Element propertyInfo = new Element(PROPERTY_ELEMENT); + propertyInfo.setAttribute(PROPERTY_NAME_ATTR, propertyName); + propertyInfo.setText(value); + metaInfoElement.addContent(propertyInfo); + } + return metaInfoElement; + } private boolean isParentOverwritingInheritance(@NotNull TextAttributesKey key) { TextAttributes parentAttrs = diff --git a/platform/editor-ui-ex/src/com/intellij/openapi/editor/colors/impl/DefaultColorsScheme.java b/platform/editor-ui-ex/src/com/intellij/openapi/editor/colors/impl/DefaultColorsScheme.java index 0673b97dddad..e55ecdd5cfac 100644 --- a/platform/editor-ui-ex/src/com/intellij/openapi/editor/colors/impl/DefaultColorsScheme.java +++ b/platform/editor-ui-ex/src/com/intellij/openapi/editor/colors/impl/DefaultColorsScheme.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2014 JetBrains s.r.o. + * Copyright 2000-2016 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. @@ -14,9 +14,6 @@ * limitations under the License. */ -/** - * @author Yura Cangea - */ package com.intellij.openapi.editor.colors.impl; import com.intellij.openapi.editor.colors.ColorKey; @@ -93,6 +90,7 @@ public class DefaultColorsScheme extends AbstractColorsScheme implements ReadOnl EditorColorsSchemeImpl newScheme = new EditorColorsSchemeImpl(this); copyTo(newScheme); newScheme.setName(DEFAULT_SCHEME_NAME); + newScheme.setDefaultMetaInfo(this); return newScheme; } } diff --git a/platform/editor-ui-ex/src/com/intellij/openapi/editor/colors/impl/EditorColorsSchemeImpl.java b/platform/editor-ui-ex/src/com/intellij/openapi/editor/colors/impl/EditorColorsSchemeImpl.java index 784fb54d1b13..888546bcf7d6 100644 --- a/platform/editor-ui-ex/src/com/intellij/openapi/editor/colors/impl/EditorColorsSchemeImpl.java +++ b/platform/editor-ui-ex/src/com/intellij/openapi/editor/colors/impl/EditorColorsSchemeImpl.java @@ -80,6 +80,7 @@ public class EditorColorsSchemeImpl extends AbstractColorsScheme implements Exte EditorColorsSchemeImpl newScheme = new EditorColorsSchemeImpl(myParentScheme); copyTo(newScheme); newScheme.setName(getName()); + newScheme.setDefaultMetaInfo(this); return newScheme; } } diff --git a/platform/external-system-impl/src/com/intellij/openapi/externalSystem/service/RemoteExternalSystemCommunicationManager.java b/platform/external-system-impl/src/com/intellij/openapi/externalSystem/service/RemoteExternalSystemCommunicationManager.java index 2b9a4e344244..e0e4b4139828 100644 --- a/platform/external-system-impl/src/com/intellij/openapi/externalSystem/service/RemoteExternalSystemCommunicationManager.java +++ b/platform/external-system-impl/src/com/intellij/openapi/externalSystem/service/RemoteExternalSystemCommunicationManager.java @@ -65,6 +65,8 @@ import com.intellij.util.PathUtil; import com.intellij.util.SystemProperties; import com.intellij.util.containers.ContainerUtil; import com.intellij.util.containers.ContainerUtilRt; +import kotlin.Unit; +import kotlin.reflect.KotlinReflectionInternalError; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; @@ -151,6 +153,10 @@ public class RemoteExternalSystemCommunicationManager implements ExternalSystemC ContainerUtil.addIfNotNull(PathUtil.getJarPathForClass(EmptyModuleType.class), classPath); ContainerUtil.addIfNotNull(PathUtil.getJarPathForClass(LanguageLevel.class), classPath); + // add Kotlin runtime + ContainerUtil.addIfNotNull(PathUtil.getJarPathForClass(Unit.class), classPath); + ContainerUtil.addIfNotNull(PathUtil.getJarPathForClass(KotlinReflectionInternalError.class), classPath); + // External system module jars ContainerUtil.addIfNotNull(PathUtil.getJarPathForClass(getClass()), classPath); // external-system-rt.jar diff --git a/platform/indexing-api/src/com/intellij/psi/search/PsiReferenceProcessor.java b/platform/indexing-api/src/com/intellij/psi/search/PsiReferenceProcessor.java index ed4e6fcb2b15..a12f8b97191e 100644 --- a/platform/indexing-api/src/com/intellij/psi/search/PsiReferenceProcessor.java +++ b/platform/indexing-api/src/com/intellij/psi/search/PsiReferenceProcessor.java @@ -51,7 +51,7 @@ public interface PsiReferenceProcessor{ } class FindElement implements PsiReferenceProcessor{ - private volatile PsiReference myFoundElement = null; + private volatile PsiReference myFoundElement; public boolean isFound() { return myFoundElement != null; diff --git a/platform/indexing-api/src/com/intellij/psi/search/SearchRequestCollector.java b/platform/indexing-api/src/com/intellij/psi/search/SearchRequestCollector.java index fef43be72ba5..8cd180e967c3 100644 --- a/platform/indexing-api/src/com/intellij/psi/search/SearchRequestCollector.java +++ b/platform/indexing-api/src/com/intellij/psi/search/SearchRequestCollector.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2013 JetBrains s.r.o. + * Copyright 2000-2016 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. @@ -102,10 +102,10 @@ public class SearchRequestCollector { return refElement.getParent(); } - @Deprecated /** use {@link #searchWord(java.lang.String, com.intellij.psi.search.SearchScope, short, boolean, com.intellij.psi.PsiElement)} * instead */ + @Deprecated public void searchWord(@NotNull String word, @NotNull SearchScope searchScope, short searchContext, diff --git a/platform/indexing-api/src/com/intellij/psi/stubs/SerializationManager.java b/platform/indexing-api/src/com/intellij/psi/stubs/SerializationManager.java index 22a7161857be..61c82b9b8a81 100644 --- a/platform/indexing-api/src/com/intellij/psi/stubs/SerializationManager.java +++ b/platform/indexing-api/src/com/intellij/psi/stubs/SerializationManager.java @@ -31,7 +31,7 @@ import java.util.List; public abstract class SerializationManager { protected final List myAllSerializers = new ArrayList(); - private volatile boolean mySerializersLoaded = false; + private volatile boolean mySerializersLoaded; public static SerializationManager getInstance() { return ApplicationManager.getApplication().getComponent(SerializationManager.class); diff --git a/platform/lang-api/src/com/intellij/codeInsight/intention/BaseElementAtCaretIntentionAction.java b/platform/lang-api/src/com/intellij/codeInsight/intention/BaseElementAtCaretIntentionAction.java index a0b79ca7e76b..0b5f75e95e72 100644 --- a/platform/lang-api/src/com/intellij/codeInsight/intention/BaseElementAtCaretIntentionAction.java +++ b/platform/lang-api/src/com/intellij/codeInsight/intention/BaseElementAtCaretIntentionAction.java @@ -29,7 +29,7 @@ import org.jetbrains.annotations.Nullable; * @author Danila Ponomarenko */ public abstract class BaseElementAtCaretIntentionAction extends BaseIntentionAction { - private volatile boolean useElementToTheLeft = false; + private volatile boolean useElementToTheLeft; @Override public final boolean isAvailable(@NotNull Project project, Editor editor, PsiFile file) { diff --git a/platform/lang-api/src/com/intellij/execution/runners/GenericProgramRunner.java b/platform/lang-api/src/com/intellij/execution/runners/GenericProgramRunner.java index 3c59227eb85a..22c17726ef7f 100644 --- a/platform/lang-api/src/com/intellij/execution/runners/GenericProgramRunner.java +++ b/platform/lang-api/src/com/intellij/execution/runners/GenericProgramRunner.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2014 JetBrains s.r.o. + * Copyright 2000-2016 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. @@ -50,11 +50,11 @@ public abstract class GenericProgramRunner exte return doExecute(environment.getProject(), state, environment.getContentToReuse(), environment); } - @Deprecated - @Nullable /** * @deprecated to remove in IDEA 16 */ + @Deprecated + @Nullable protected RunContentDescriptor doExecute(@NotNull Project project, @NotNull RunProfileState state, @Nullable RunContentDescriptor contentToReuse, diff --git a/platform/lang-api/src/com/intellij/facet/FacetTypeId.java b/platform/lang-api/src/com/intellij/facet/FacetTypeId.java index ab133bcba8d8..07996f5df030 100644 --- a/platform/lang-api/src/com/intellij/facet/FacetTypeId.java +++ b/platform/lang-api/src/com/intellij/facet/FacetTypeId.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2009 JetBrains s.r.o. + * Copyright 2000-2016 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. @@ -24,10 +24,10 @@ import org.jetbrains.annotations.NonNls; public final class FacetTypeId { private final String myDebugName; - @Deprecated /** * @deprecated use {@link FacetTypeId#FacetTypeId(String)} instead */ + @Deprecated public FacetTypeId() { this("unknown"); } diff --git a/platform/lang-api/src/com/intellij/ide/util/frameworkSupport/FrameworkRole.java b/platform/lang-api/src/com/intellij/ide/util/frameworkSupport/FrameworkRole.java index 2331b27c9cae..0e22f8e082e7 100644 --- a/platform/lang-api/src/com/intellij/ide/util/frameworkSupport/FrameworkRole.java +++ b/platform/lang-api/src/com/intellij/ide/util/frameworkSupport/FrameworkRole.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2013 JetBrains s.r.o. + * Copyright 2000-2016 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. @@ -25,7 +25,7 @@ public class FrameworkRole { public static FrameworkRole[] UNKNOWN = new FrameworkRole[0]; - /** Groovy etc. */ + /* Groovy etc. */ // public static FrameworkRole JVM_LANGUAGES = new FrameworkRole(); /** servlet-based frameworks like Struts, Tapestry etc. */ diff --git a/platform/lang-api/src/com/intellij/openapi/module/ModuleUtil.java b/platform/lang-api/src/com/intellij/openapi/module/ModuleUtil.java index 54a87b825afe..e6eacfe84d4d 100644 --- a/platform/lang-api/src/com/intellij/openapi/module/ModuleUtil.java +++ b/platform/lang-api/src/com/intellij/openapi/module/ModuleUtil.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2015 JetBrains s.r.o. + * Copyright 2000-2016 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. @@ -14,9 +14,6 @@ * limitations under the License. */ -/** - * @author cdr - */ package com.intellij.openapi.module; import com.intellij.openapi.project.Project; diff --git a/platform/lang-api/src/com/intellij/openapi/project/ProjectUtil.java b/platform/lang-api/src/com/intellij/openapi/project/ProjectUtil.java index dcd0e8ae3513..0792a22f57df 100644 --- a/platform/lang-api/src/com/intellij/openapi/project/ProjectUtil.java +++ b/platform/lang-api/src/com/intellij/openapi/project/ProjectUtil.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2014 JetBrains s.r.o. + * Copyright 2000-2016 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. @@ -88,10 +88,10 @@ public class ProjectUtil { return guessProjectForContentFile(file, file.getFileType()); } - @Nullable /*** * guessProjectForFile works incorrectly - even if file is config (idea config file) first opened project will be returned */ + @Nullable public static Project guessProjectForContentFile(@NotNull VirtualFile file, @NotNull FileType fileType) { if (isProjectOrWorkspaceFile(file, fileType)) { return null; diff --git a/platform/lang-api/src/com/intellij/psi/codeStyle/CodeStyleSettings.java b/platform/lang-api/src/com/intellij/psi/codeStyle/CodeStyleSettings.java index d6472836103a..fd7fe543f17c 100644 --- a/platform/lang-api/src/com/intellij/psi/codeStyle/CodeStyleSettings.java +++ b/platform/lang-api/src/com/intellij/psi/codeStyle/CodeStyleSettings.java @@ -173,9 +173,9 @@ public class CodeStyleSettings extends CommonCodeStyleSettings implements Clonea } - public boolean USE_SAME_INDENTS = false; + public boolean USE_SAME_INDENTS; - public boolean IGNORE_SAME_INDENTS_FOR_LANGUAGES = false; + public boolean IGNORE_SAME_INDENTS_FOR_LANGUAGES; public boolean AUTODETECT_INDENTS = true; @@ -228,8 +228,8 @@ public class CodeStyleSettings extends CommonCodeStyleSettings implements Clonea public final TypeToNameMap LOCAL_VARIABLE_TYPE_TO_NAME = new TypeToNameMap(); //----------------- 'final' modifier settings ------- - public boolean GENERATE_FINAL_LOCALS = false; - public boolean GENERATE_FINAL_PARAMETERS = false; + public boolean GENERATE_FINAL_LOCALS; + public boolean GENERATE_FINAL_PARAMETERS; //----------------- visibility ----------------------------- public String VISIBILITY = "public"; @@ -238,7 +238,7 @@ public class CodeStyleSettings extends CommonCodeStyleSettings implements Clonea public boolean PARENTHESES_AROUND_METHOD_ARGUMENTS = true; //----------------- annotations ---------------- - public boolean USE_EXTERNAL_ANNOTATIONS = false; + public boolean USE_EXTERNAL_ANNOTATIONS; public boolean INSERT_OVERRIDE_ANNOTATION = true; //----------------- override ------------------- @@ -247,12 +247,12 @@ public class CodeStyleSettings extends CommonCodeStyleSettings implements Clonea //----------------- IMPORTS -------------------- public boolean LAYOUT_STATIC_IMPORTS_SEPARATELY = true; - public boolean USE_FQ_CLASS_NAMES = false; + public boolean USE_FQ_CLASS_NAMES; @Deprecated public boolean USE_FQ_CLASS_NAMES_IN_JAVADOC = true; public boolean USE_SINGLE_CLASS_IMPORTS = true; - public boolean INSERT_INNER_CLASS_IMPORTS = false; + public boolean INSERT_INNER_CLASS_IMPORTS; public int CLASS_COUNT_TO_USE_IMPORT_ON_DEMAND = 5; public int NAMES_COUNT_TO_USE_IMPORT_ON_DEMAND = 3; public final PackageEntryTable PACKAGES_TO_USE_IMPORT_ON_DEMAND = new PackageEntryTable(); @@ -280,7 +280,7 @@ public class CodeStyleSettings extends CommonCodeStyleSettings implements Clonea * * @see #WRAP_ON_TYPING */ - public boolean WRAP_WHEN_TYPING_REACHES_RIGHT_MARGIN = false; + public boolean WRAP_WHEN_TYPING_REACHES_RIGHT_MARGIN; // ---------------------------------- Javadoc formatting options ------------------------- @@ -296,14 +296,14 @@ public class CodeStyleSettings extends CommonCodeStyleSettings implements Clonea */ public boolean JD_ALIGN_EXCEPTION_COMMENTS = true; - public boolean JD_ADD_BLANK_AFTER_PARM_COMMENTS = false; - public boolean JD_ADD_BLANK_AFTER_RETURN = false; + public boolean JD_ADD_BLANK_AFTER_PARM_COMMENTS; + public boolean JD_ADD_BLANK_AFTER_RETURN; public boolean JD_ADD_BLANK_AFTER_DESCRIPTION = true; public boolean JD_P_AT_EMPTY_LINES = true; public boolean JD_KEEP_INVALID_TAGS = true; public boolean JD_KEEP_EMPTY_LINES = true; - public boolean JD_DO_NOT_WRAP_ONE_LINE_COMMENTS = false; + public boolean JD_DO_NOT_WRAP_ONE_LINE_COMMENTS; public boolean JD_USE_THROWS_NOT_EXCEPTION = true; public boolean JD_KEEP_EMPTY_PARAMETER = true; @@ -313,8 +313,8 @@ public class CodeStyleSettings extends CommonCodeStyleSettings implements Clonea public boolean JD_LEADING_ASTERISKS_ARE_ENABLED = true; - public boolean JD_PRESERVE_LINE_FEEDS = false; - public boolean JD_PARAM_DESCRIPTION_ON_NEW_LINE = false; + public boolean JD_PRESERVE_LINE_FEEDS; + public boolean JD_PARAM_DESCRIPTION_ON_NEW_LINE; // --------------------------------------------------------------------------------------- @@ -324,7 +324,7 @@ public class CodeStyleSettings extends CommonCodeStyleSettings implements Clonea /** * @deprecated Use XmlCodeStyleSettings. */ - public boolean XML_KEEP_WHITESPACES = false; + public boolean XML_KEEP_WHITESPACES; /** * @deprecated Use XmlCodeStyleSettings. */ @@ -353,32 +353,32 @@ public class CodeStyleSettings extends CommonCodeStyleSettings implements Clonea /** * @deprecated Use XmlCodeStyleSettings. */ - public boolean XML_ALIGN_TEXT = false; + public boolean XML_ALIGN_TEXT; /** * @deprecated Use XmlCodeStyleSettings. */ - public boolean XML_SPACE_AROUND_EQUALITY_IN_ATTRIBUTE = false; + public boolean XML_SPACE_AROUND_EQUALITY_IN_ATTRIBUTE; /** * @deprecated Use XmlCodeStyleSettings. */ - public boolean XML_SPACE_AFTER_TAG_NAME = false; + public boolean XML_SPACE_AFTER_TAG_NAME; /** * @deprecated Use XmlCodeStyleSettings. */ - public boolean XML_SPACE_INSIDE_EMPTY_TAG = false; + public boolean XML_SPACE_INSIDE_EMPTY_TAG; /** * @deprecated Use XmlCodeStyleSettings. */ - public boolean XML_KEEP_WHITE_SPACES_INSIDE_CDATA = false; + public boolean XML_KEEP_WHITE_SPACES_INSIDE_CDATA; /** * @deprecated Use XmlCodeStyleSettings. */ - public int XML_WHITE_SPACE_AROUND_CDATA = 0; + public int XML_WHITE_SPACE_AROUND_CDATA; // --------------------------------------------------------------------------------------- // ---------------------------------- HTML formatting options ------------------------- - public boolean HTML_KEEP_WHITESPACES = false; + public boolean HTML_KEEP_WHITESPACES; public int HTML_ATTRIBUTE_WRAP = WRAP_AS_NEEDED; public int HTML_TEXT_WRAP = WRAP_AS_NEEDED; @@ -387,16 +387,16 @@ public class CodeStyleSettings extends CommonCodeStyleSettings implements Clonea public int HTML_KEEP_BLANK_LINES = 2; public boolean HTML_ALIGN_ATTRIBUTES = true; - public boolean HTML_ALIGN_TEXT = false; + public boolean HTML_ALIGN_TEXT; - public boolean HTML_SPACE_AROUND_EQUALITY_IN_ATTRINUTE = false; - public boolean HTML_SPACE_AFTER_TAG_NAME = false; - public boolean HTML_SPACE_INSIDE_EMPTY_TAG = false; + public boolean HTML_SPACE_AROUND_EQUALITY_IN_ATTRINUTE; + public boolean HTML_SPACE_AFTER_TAG_NAME; + public boolean HTML_SPACE_INSIDE_EMPTY_TAG; @NonNls public String HTML_ELEMENTS_TO_INSERT_NEW_LINE_BEFORE = "body,div,p,form,h1,h2,h3"; @NonNls public String HTML_ELEMENTS_TO_REMOVE_NEW_LINE_BEFORE = "br"; @NonNls public String HTML_DO_NOT_INDENT_CHILDREN_OF = "html,body,thead,tbody,tfoot"; - public int HTML_DO_NOT_ALIGN_CHILDREN_OF_MIN_LINES = 0; + public int HTML_DO_NOT_ALIGN_CHILDREN_OF_MIN_LINES; @NonNls public String HTML_KEEP_WHITESPACES_INSIDE = "span,pre,textarea"; @NonNls public String HTML_INLINE_ELEMENTS = @@ -409,19 +409,19 @@ public class CodeStyleSettings extends CommonCodeStyleSettings implements Clonea // true if <%page import="x.y.z, x.y.t"%> // false if <%page import="x.y.z"%> // <%page import="x.y.t"%> - public boolean JSP_PREFER_COMMA_SEPARATED_IMPORT_LIST = false; + public boolean JSP_PREFER_COMMA_SEPARATED_IMPORT_LIST; //---------------------------------------------------------------------------------------- // region Formatter control - public boolean FORMATTER_TAGS_ENABLED = false; + public boolean FORMATTER_TAGS_ENABLED; public String FORMATTER_ON_TAG = "@formatter:on"; public String FORMATTER_OFF_TAG = "@formatter:off"; - public volatile boolean FORMATTER_TAGS_ACCEPT_REGEXP = false; - private volatile Pattern myFormatterOffPattern = null; - private volatile Pattern myFormatterOnPattern = null; + public volatile boolean FORMATTER_TAGS_ACCEPT_REGEXP; + private volatile Pattern myFormatterOffPattern; + private volatile Pattern myFormatterOnPattern; @Nullable public Pattern getFormatterOffPattern() { diff --git a/platform/lang-api/src/com/intellij/psi/codeStyle/CodeStyleSettingsManager.java b/platform/lang-api/src/com/intellij/psi/codeStyle/CodeStyleSettingsManager.java index 26a189660e01..67df2be8350b 100644 --- a/platform/lang-api/src/com/intellij/psi/codeStyle/CodeStyleSettingsManager.java +++ b/platform/lang-api/src/com/intellij/psi/codeStyle/CodeStyleSettingsManager.java @@ -33,11 +33,11 @@ import org.jetbrains.annotations.Nullable; public class CodeStyleSettingsManager implements PersistentStateComponent { private static final Logger LOG = Logger.getInstance("#" + CodeStyleSettingsManager.class.getName()); - public volatile CodeStyleSettings PER_PROJECT_SETTINGS = null; - public volatile boolean USE_PER_PROJECT_SETTINGS = false; - public volatile String PREFERRED_PROJECT_CODE_STYLE = null; + public volatile CodeStyleSettings PER_PROJECT_SETTINGS; + public volatile boolean USE_PER_PROJECT_SETTINGS; + public volatile String PREFERRED_PROJECT_CODE_STYLE; private volatile CodeStyleSettings myTemporarySettings; - private volatile boolean myIsLoaded = false; + private volatile boolean myIsLoaded; public static CodeStyleSettingsManager getInstance(@Nullable Project project) { if (project == null || project.isDefault()) return getInstance(); diff --git a/platform/lang-api/src/com/intellij/refactoring/rename/RenameInputValidatorRegistry.java b/platform/lang-api/src/com/intellij/refactoring/rename/RenameInputValidatorRegistry.java index 8320ce6dab3e..a03753d76590 100644 --- a/platform/lang-api/src/com/intellij/refactoring/rename/RenameInputValidatorRegistry.java +++ b/platform/lang-api/src/com/intellij/refactoring/rename/RenameInputValidatorRegistry.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2009 JetBrains s.r.o. + * Copyright 2000-2016 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. @@ -14,9 +14,6 @@ * limitations under the License. */ -/** - * @author Dmitry Avdeev - */ package com.intellij.refactoring.rename; import com.intellij.openapi.extensions.Extensions; @@ -27,9 +24,6 @@ import com.intellij.util.ProcessingContext; import com.intellij.util.containers.hash.LinkedHashMap; import org.jetbrains.annotations.Nullable; -import java.util.ArrayList; -import java.util.List; - public class RenameInputValidatorRegistry { private RenameInputValidatorRegistry() { } diff --git a/platform/lang-impl/src/com/intellij/analysis/AnalysisUIOptions.java b/platform/lang-impl/src/com/intellij/analysis/AnalysisUIOptions.java index 3836da904d92..494cb1902fa3 100644 --- a/platform/lang-impl/src/com/intellij/analysis/AnalysisUIOptions.java +++ b/platform/lang-impl/src/com/intellij/analysis/AnalysisUIOptions.java @@ -44,11 +44,9 @@ public class AnalysisUIOptions implements PersistentStateComponent - * Intended usage scenario is to collect information about format preview document changes occurred during - * tweaking format options and highlight corresponding sections. - *

- * Note: current algorithm does consider changing particular text by the same text to be a document change, i.e. consider - * the document like 'abcde'. Suppose it's text from range [2; 4) ('cd') is replaced by the same - * text. It's still to be considered as a change. - *

- * Not thread-safe. - * - * @author Denis Zhdanov - * @since 10/11/10 5:10 PM - */ -public class DocumentChangesCollector implements DocumentListener { - - /** - * Holds merged document changes. - *

- * Is assumed to be always sorted by change start offset in ascending order. - */ - private final List myChanges = new ArrayList(); - - private boolean myCollectChanges; - - @Override - public void beforeDocumentChange(DocumentEvent event) { - } - - @Override - public void documentChanged(DocumentEvent event) { - if (!myCollectChanges) { - return; - } - - // The general algorithm is as follows: - // 1. Drop or cut stored change ranges for removed range if any; - // 2. Update offsets of all ranges that lays after the last change range identified by the given document change event; - // 3. Merge added range with registered changes if any; - // 4. Merge all adjacent ranges if any; - StringBuilder oldText = new StringBuilder(event.getOldFragment()); - - cutChangesIfNecessary(event, oldText); - updateChanges(event, oldText); - mergeChangesIfNecessary(event); - } - - /** - * Cuts or removes stored change ranges for the given interval if any. - * - * @param event event for just occurred document change - * @param oldText our main idea is to merge all changes in order to have aggregated change against original document. So, there is - * a possible case that subsequent change affects text inserted by the previous one. We don't want to reflect that - * at aggregated change as it didn't appear in initial document. Hence, we have a mutable symbols buffer that holds - * symbols from initial document affected by the given change - */ - private void cutChangesIfNecessary(DocumentEvent event, StringBuilder oldText) { - if (myChanges.isEmpty()) { - return; - } - - int start = event.getOffset(); - int end = event.getOffset() + event.getOldLength(); - int diff = event.getNewLength() - event.getOldLength(); - - int forwardIndex = findIndex(start); - int backwardIndexStart = forwardIndex - 1; - if (forwardIndex < 0) { - backwardIndexStart = myChanges.size() - 1; - } - else { - TIntArrayList indices = new TIntArrayList(); - for (; forwardIndex < myChanges.size(); forwardIndex++) { - TextChangeImpl change = myChanges.get(forwardIndex); - // Stored change is not affected by the current change. - if (change.getStart() >= end) { - change.advance(diff); - } - - // Stored change region is completely covered by the given change. - else if (change.getEnd() <= end) { - indices.add(forwardIndex); - - int deleteStart = start - change.getStart(); - deleteStart = Math.max(0, deleteStart); - - int deleteEnd = change.getEnd() - change.getStart(); - deleteEnd = Math.min(oldText.length(), Math.max(0, deleteEnd)); - - oldText.delete(deleteStart, deleteEnd); - oldText.insert(0, change.getText()); - } - - // Stored change region's start is covered by the current change. - else { - int deleteStart = change.getStart() - start; - deleteStart = Math.min(oldText.length(), Math.max(0, deleteStart)); - - int deleteEnd = oldText.length(); - deleteEnd = Math.min(oldText.length(), Math.max(0, deleteEnd)); - - oldText.delete(deleteStart, deleteEnd); - myChanges.set(forwardIndex, new TextChangeImpl(change.getText(), end + diff, change.getEnd() + diff)); - } - } - - if (!indices.isEmpty()) { - for (int i = indices.size() - 1; i >= 0; i--) { - myChanges.remove(indices.get(i)); - } - } - } - - for (int i = Math.min(backwardIndexStart, myChanges.size() - 1); i >= 0; i--) { - TextChangeImpl change = myChanges.get(i); - if (change.getEnd() <= start) { - break; - } - - CharSequence textToUse = change.getText(); - int symbolsToCut = Math.min(change.getEnd(), end) - start; - if (textToUse.length() >= symbolsToCut) { - oldText.insert(symbolsToCut, textToUse.subSequence(textToUse.length() - symbolsToCut, textToUse.length())); - textToUse = textToUse.subSequence(0, textToUse.length() - symbolsToCut); - } - oldText.delete(0, symbolsToCut); - myChanges.set(i, new TextChangeImpl(textToUse, change.getStart(), start)); - if (change.getEnd() > end) { - int shift = event.getOffset() + event.getNewLength() - end; - TextChangeImpl changeTail = new TextChangeImpl("", end + shift, change.getEnd() + shift); - if (i >= myChanges.size() - 1) { - myChanges.add(changeTail); - } - else { - myChanges.add(i + 1, changeTail); - } - } - } - } - - /** - * Updates current object's state on the basis of the given event assuming that there are no stored change ranges that - * start after offset denoted by the given event. - * - * @param event event for just occurred document change - * @param oldText our main idea is to merge all changes in order to have aggregated change against original document. So, there is - * a possible case that subsequent change affects text inserted by the previous one. We don't want to reflect that - * at aggregated change as it didn't appear in initial document. Hence, we have a mutable symbols buffer that holds - * symbols from initial document affected by the given change - */ - private void updateChanges(DocumentEvent event, StringBuilder oldText) { - int i = findIndex(event.getOffset()); - int endOffset = event.getOffset() + event.getNewLength(); - TextChangeImpl change = new TextChangeImpl(oldText, event.getOffset(), endOffset); - if (i < 0) { - myChanges.add(change); - } - else { - myChanges.add(i, change); - } - } - - private void mergeChangesIfNecessary(DocumentEvent event) { - // There is a possible case that we had more than one scattered change (e.g. (3; 5) and (8; 10)) and current document change affects - // both of them (e.g. remove all symbols from offset (4; 9)). We have two changes then: (3; 4) and (4; 5) and want to merge them - // into a single one. - if (myChanges.size() < 2) { - return; - } - TextChangeImpl next = myChanges.get(myChanges.size() - 1); - for (int i = myChanges.size() - 2; i >= 0; i--) { - TextChangeImpl current = myChanges.get(i); - if (current.getEnd() < event.getOffset()) { - // Assuming that change ranges are always kept at normalized form. - break; - } - if (current.getEnd() == next.getStart()) { - myChanges.set(i, next = new TextChangeImpl(current.getText().toString() + next.getText(), current.getStart(), next.getEnd())); - myChanges.remove(i + 1); - } - else { - next = current; - } - } - } - - /** - * Returns aggregated and merged document changes sorted by their start offsets in ascending order. - *

- * Example - *

-   * 
    - *
  1. Suppose we have a document with text '0123456';
  2. - *
  3. - * Document range [1; 3) is removed (text '12' is removed, current text is - * '03456'); - *
  4. - *
  5. - * Document range [1; 4) ('345') is replaced to 'abc' - * (current text is '0abc6'); - *
  6. - *
- *
- *

- * So, initial document is '0123456'; final one is '0abc6'. We expect single aggregated change - * to be returned then - [1; 4) with text '12345', i.e. the range defines offset within the - * current document and text shows initial document text at that range. - * - * @return aggregated and merged document changes sorted by their start offsets in ascending order - */ - @NotNull - public List getChanges() { - return myChanges; - } - - /** - * Allows to switch 'collect document changes' mode. - *

- * Default value is 'false', i.e. document changes are not collected. - * - * @param collectChanges new value of 'collect document changes' mode - */ - public void setCollectChanges(boolean collectChanges) { - myCollectChanges = collectChanges; - } - - /** - * Forces current object to drop all information about document changes if any. - */ - public void reset() { - myChanges.clear(); - } - - /** - * Finds index of the {@link #myCollectChanges first stored changed document ranges} which start offset is equal or greater to the - * given one. - * - * @param offset start offset of target document change - * @return non-negative value as an indication that there is not stored changed document range which start offset is equal - * or greater than the given offset; negative value otherwise - */ - private int findIndex(int offset) { - if (myChanges.isEmpty()) { - return -1; - } - - // We assume that document is changed sequentially from start to end, hence, it's worth to perform quick offset comparison with - // the last stored change if any - TextChangeImpl change = myChanges.get(myChanges.size() - 1); - if (offset > change.getStart()) { - return -1; - } - - int start = 0; - int end = myChanges.size() - 1; - int result = -1; - - // We inline binary search here mainly because TextChange class is immutable and we don't want unnecessary expenses on - // new key object construction on every method call. - while (start <= end) { - result = (end + start) >>> 1; - change = myChanges.get(result); - if (change.getStart() < offset) { - start = ++result; - continue; - } - if (change.getStart() > offset) { - end = result - 1; - continue; - } - break; - } - - return result; - } -} diff --git a/platform/lang-impl/src/com/intellij/application/options/colors/ClickNavigator.java b/platform/lang-impl/src/com/intellij/application/options/colors/ClickNavigator.java index be76c42b985c..043aa0fd9bca 100644 --- a/platform/lang-impl/src/com/intellij/application/options/colors/ClickNavigator.java +++ b/platform/lang-impl/src/com/intellij/application/options/colors/ClickNavigator.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2015 JetBrains s.r.o. + * Copyright 2000-2016 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. @@ -14,9 +14,6 @@ * limitations under the License. */ -/** - * @author Yura Cangea - */ package com.intellij.application.options.colors; import com.intellij.application.options.colors.highlighting.HighlightData; diff --git a/platform/lang-impl/src/com/intellij/application/options/colors/SchemesPanel.java b/platform/lang-impl/src/com/intellij/application/options/colors/SchemesPanel.java index 856a26b48acc..c640cd996bc8 100644 --- a/platform/lang-impl/src/com/intellij/application/options/colors/SchemesPanel.java +++ b/platform/lang-impl/src/com/intellij/application/options/colors/SchemesPanel.java @@ -21,6 +21,7 @@ import com.intellij.application.options.SaveSchemeDialog; import com.intellij.application.options.SkipSelfSearchComponent; import com.intellij.openapi.application.ApplicationBundle; import com.intellij.openapi.editor.colors.EditorColorsScheme; +import com.intellij.openapi.editor.colors.impl.AbstractColorsScheme; import com.intellij.openapi.editor.colors.impl.EditorColorsSchemeImpl; import com.intellij.openapi.editor.colors.impl.EmptyColorScheme; import com.intellij.openapi.extensions.Extensions; @@ -233,8 +234,9 @@ public class SchemesPanel extends JPanel implements SkipSelfSearchComponent { importer.importScheme(DefaultProjectFactory.getInstance().getDefaultProject(), importSource, myOptions.getSelectedScheme(), name -> { String newName = myOptions.getUniqueName(name); - EditorColorsScheme newScheme = new EditorColorsSchemeImpl(EmptyColorScheme.INSTANCE); + AbstractColorsScheme newScheme = new EditorColorsSchemeImpl(EmptyColorScheme.INSTANCE); newScheme.setName(newName); + newScheme.setDefaultMetaInfo(EmptyColorScheme.INSTANCE); return newScheme; }); if (imported != null) { diff --git a/platform/lang-impl/src/com/intellij/application/options/colors/TailPanel.java b/platform/lang-impl/src/com/intellij/application/options/colors/TailPanel.java index dace582b3ef9..6475ea3d32ee 100644 --- a/platform/lang-impl/src/com/intellij/application/options/colors/TailPanel.java +++ b/platform/lang-impl/src/com/intellij/application/options/colors/TailPanel.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2009 JetBrains s.r.o. + * Copyright 2000-2016 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. @@ -14,9 +14,6 @@ * limitations under the License. */ -/** - * @author cdr - */ package com.intellij.application.options.colors; import javax.swing.*; diff --git a/platform/lang-impl/src/com/intellij/application/options/colors/TextAttributesDescription.java b/platform/lang-impl/src/com/intellij/application/options/colors/TextAttributesDescription.java index 9d74f83dbbc8..85ca6d564168 100644 --- a/platform/lang-impl/src/com/intellij/application/options/colors/TextAttributesDescription.java +++ b/platform/lang-impl/src/com/intellij/application/options/colors/TextAttributesDescription.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2009 JetBrains s.r.o. + * Copyright 2000-2016 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. @@ -14,9 +14,6 @@ * limitations under the License. */ -/** - * @author cdr - */ package com.intellij.application.options.colors; import com.intellij.openapi.editor.colors.EditorColorsScheme; diff --git a/platform/lang-impl/src/com/intellij/application/options/colors/highlighting/HighlightData.java b/platform/lang-impl/src/com/intellij/application/options/colors/highlighting/HighlightData.java index dad941f9eeca..7d64bc12bd64 100644 --- a/platform/lang-impl/src/com/intellij/application/options/colors/highlighting/HighlightData.java +++ b/platform/lang-impl/src/com/intellij/application/options/colors/highlighting/HighlightData.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2009 JetBrains s.r.o. + * Copyright 2000-2016 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. @@ -14,9 +14,6 @@ * limitations under the License. */ -/** - * @author Yura Cangea - */ package com.intellij.application.options.colors.highlighting; import com.intellij.openapi.editor.Editor; diff --git a/platform/lang-impl/src/com/intellij/application/options/colors/highlighting/HighlightsExtractor.java b/platform/lang-impl/src/com/intellij/application/options/colors/highlighting/HighlightsExtractor.java index ee6325271b7f..0acca2686198 100644 --- a/platform/lang-impl/src/com/intellij/application/options/colors/highlighting/HighlightsExtractor.java +++ b/platform/lang-impl/src/com/intellij/application/options/colors/highlighting/HighlightsExtractor.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2012 JetBrains s.r.o. + * Copyright 2000-2016 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. @@ -14,9 +14,6 @@ * limitations under the License. */ -/** - * @author Yura Cangea - */ package com.intellij.application.options.colors.highlighting; import com.intellij.openapi.editor.colors.TextAttributesKey; diff --git a/platform/lang-impl/src/com/intellij/codeInsight/daemon/impl/HighlightInfoComposite.java b/platform/lang-impl/src/com/intellij/codeInsight/daemon/impl/HighlightInfoComposite.java index 9e61d0708db1..864eaf1fec86 100644 --- a/platform/lang-impl/src/com/intellij/codeInsight/daemon/impl/HighlightInfoComposite.java +++ b/platform/lang-impl/src/com/intellij/codeInsight/daemon/impl/HighlightInfoComposite.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2013 JetBrains s.r.o. + * Copyright 2000-2016 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. @@ -14,9 +14,6 @@ * limitations under the License. */ -/** - * @author cdr - */ package com.intellij.codeInsight.daemon.impl; import com.intellij.openapi.editor.RangeMarker; diff --git a/platform/lang-impl/src/com/intellij/codeInsight/daemon/impl/analysis/DefaultHighlightingSettingProvider.java b/platform/lang-impl/src/com/intellij/codeInsight/daemon/impl/analysis/DefaultHighlightingSettingProvider.java index 1b0e6921c8b5..5b9275d4775b 100644 --- a/platform/lang-impl/src/com/intellij/codeInsight/daemon/impl/analysis/DefaultHighlightingSettingProvider.java +++ b/platform/lang-impl/src/com/intellij/codeInsight/daemon/impl/analysis/DefaultHighlightingSettingProvider.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2013 JetBrains s.r.o. + * Copyright 2000-2016 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. @@ -22,10 +22,6 @@ import com.intellij.openapi.vfs.VirtualFile; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; -/** - * @author ksafonov - */ - /** * Implementation can provide default level of highlighting (one of "none", "syntax checks", "inspections") for a file. diff --git a/platform/lang-impl/src/com/intellij/codeInsight/documentation/AbstractExternalFilter.java b/platform/lang-impl/src/com/intellij/codeInsight/documentation/AbstractExternalFilter.java index c839358be3ae..b7b95c201f59 100644 --- a/platform/lang-impl/src/com/intellij/codeInsight/documentation/AbstractExternalFilter.java +++ b/platform/lang-impl/src/com/intellij/codeInsight/documentation/AbstractExternalFilter.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2015 JetBrains s.r.o. + * Copyright 2000-2016 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. @@ -440,15 +440,15 @@ public abstract class AbstractExternalFilter { * Settings used for parsing of external documentation */ protected static class ParseSettings { - @NotNull /** * Pattern defining the start of target fragment */ - private final Pattern startPattern; @NotNull + private final Pattern startPattern; /** * Pattern defining the end of target fragment */ + @NotNull private final Pattern endPattern; /** * If false, and line matching start pattern is not found, whole document will be processed diff --git a/platform/lang-impl/src/com/intellij/codeInsight/documentation/QuickDocOnMouseOverManager.java b/platform/lang-impl/src/com/intellij/codeInsight/documentation/QuickDocOnMouseOverManager.java index 593bc04f5813..cbd89ce27393 100644 --- a/platform/lang-impl/src/com/intellij/codeInsight/documentation/QuickDocOnMouseOverManager.java +++ b/platform/lang-impl/src/com/intellij/codeInsight/documentation/QuickDocOnMouseOverManager.java @@ -64,7 +64,7 @@ public class QuickDocOnMouseOverManager { @NotNull private final Runnable myHintCloseCallback = new MyCloseDocCallback(); @NotNull private final Map myMonitoredDocuments = new WeakHashMap(); - private final Map /** PSI element which is located under the current mouse position */> myActiveElements + private final Map /* PSI element which is located under the current mouse position */> myActiveElements = new WeakHashMap<>(); /** Holds a reference (if any) to the documentation manager used last time to show an 'auto quick doc' popup. */ diff --git a/platform/lang-impl/src/com/intellij/codeInsight/editorActions/moveUpDown/MoveStatementHandler.java b/platform/lang-impl/src/com/intellij/codeInsight/editorActions/moveUpDown/MoveStatementHandler.java index 73ddbaf5ae24..b438fa749aec 100644 --- a/platform/lang-impl/src/com/intellij/codeInsight/editorActions/moveUpDown/MoveStatementHandler.java +++ b/platform/lang-impl/src/com/intellij/codeInsight/editorActions/moveUpDown/MoveStatementHandler.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2009 JetBrains s.r.o. + * Copyright 2000-2016 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. @@ -14,9 +14,6 @@ * limitations under the License. */ -/** - * @author cdr - */ package com.intellij.codeInsight.editorActions.moveUpDown; import com.intellij.openapi.editor.Editor; diff --git a/platform/lang-impl/src/com/intellij/codeInsight/generation/CommentByBlockCommentHandler.java b/platform/lang-impl/src/com/intellij/codeInsight/generation/CommentByBlockCommentHandler.java index 57100e14ebbe..8775a6b1c247 100644 --- a/platform/lang-impl/src/com/intellij/codeInsight/generation/CommentByBlockCommentHandler.java +++ b/platform/lang-impl/src/com/intellij/codeInsight/generation/CommentByBlockCommentHandler.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2014 JetBrains s.r.o. + * Copyright 2000-2016 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. @@ -655,9 +655,9 @@ public class CommentByBlockCommentHandler extends MultiCaretCodeInsightActionHan if (commenter instanceof CustomUncommenter) { - /** - * In case of custom uncommenter, we need to ask it for list of [commentOpen-start,commentOpen-end], [commentClose-start,commentClose-end] - * and shift if according to current offset + /* + In case of custom uncommenter, we need to ask it for list of [commentOpen-start,commentOpen-end], [commentClose-start,commentClose-end] + and shift if according to current offset */ CustomUncommenter customUncommenter = (CustomUncommenter)commenter; for (Couple coupleFromCommenter : customUncommenter.getCommentRangesToDelete(text)) { diff --git a/platform/lang-impl/src/com/intellij/codeInsight/highlighting/HighlightUsagesHandler.java b/platform/lang-impl/src/com/intellij/codeInsight/highlighting/HighlightUsagesHandler.java index f9fae6eb033b..e16bac126f08 100644 --- a/platform/lang-impl/src/com/intellij/codeInsight/highlighting/HighlightUsagesHandler.java +++ b/platform/lang-impl/src/com/intellij/codeInsight/highlighting/HighlightUsagesHandler.java @@ -411,12 +411,12 @@ public class HighlightUsagesHandler extends HighlightHandlerBase { highlightRanges(highlightManager, editor, attributes, clearHighlights, textRanges); } - @SuppressWarnings("unused") - @NotNull - @Deprecated /** * @deprecated Use {@link #collectRangesToHighlight} */ + @SuppressWarnings("unused") + @NotNull + @Deprecated public static List getRangesToHighlight(@NotNull PsiReference ref) { return collectRangesToHighlight(ref, new ArrayList()); } diff --git a/platform/lang-impl/src/com/intellij/codeInsight/intention/impl/config/IntentionActionMetaData.java b/platform/lang-impl/src/com/intellij/codeInsight/intention/impl/config/IntentionActionMetaData.java index 671c8f538c5f..2d2e23a8aeb1 100644 --- a/platform/lang-impl/src/com/intellij/codeInsight/intention/impl/config/IntentionActionMetaData.java +++ b/platform/lang-impl/src/com/intellij/codeInsight/intention/impl/config/IntentionActionMetaData.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2015 JetBrains s.r.o. + * Copyright 2000-2016 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. @@ -14,9 +14,6 @@ * limitations under the License. */ -/** - * @author cdr - */ package com.intellij.codeInsight.intention.impl.config; import com.intellij.codeInsight.intention.IntentionAction; diff --git a/platform/lang-impl/src/com/intellij/codeInsight/intention/impl/config/IntentionDescriptionPanel.java b/platform/lang-impl/src/com/intellij/codeInsight/intention/impl/config/IntentionDescriptionPanel.java index 5c6c77fbf1d0..7de978eef4af 100644 --- a/platform/lang-impl/src/com/intellij/codeInsight/intention/impl/config/IntentionDescriptionPanel.java +++ b/platform/lang-impl/src/com/intellij/codeInsight/intention/impl/config/IntentionDescriptionPanel.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2015 JetBrains s.r.o. + * Copyright 2000-2016 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. @@ -14,13 +14,11 @@ * limitations under the License. */ -/** - * @author cdr - */ package com.intellij.codeInsight.intention.impl.config; import com.intellij.codeInsight.CodeInsightBundle; import com.intellij.codeInsight.hint.HintUtil; +import com.intellij.ide.BrowserUtil; import com.intellij.ide.plugins.IdeaPluginDescriptor; import com.intellij.ide.plugins.PluginManager; import com.intellij.ide.plugins.PluginManagerConfigurable; @@ -69,6 +67,18 @@ public class IntentionDescriptionPanel { @NonNls private static final String BEFORE_TEMPLATE = "before.java.template"; @NonNls private static final String AFTER_TEMPLATE = "after.java.template"; + public IntentionDescriptionPanel() { + myDescriptionBrowser.addHyperlinkListener( + new HyperlinkListener() { + public void hyperlinkUpdate(HyperlinkEvent e) { + if (e.getEventType() == HyperlinkEvent.EventType.ACTIVATED) { + BrowserUtil.browse(e.getURL()); + } + } + } + ); + } + // TODO 134099: see SingleInspectionProfilePanel#readHTML private boolean readHTML(String text) { try { diff --git a/platform/lang-impl/src/com/intellij/codeInsight/intention/impl/config/IntentionSettingsTree.java b/platform/lang-impl/src/com/intellij/codeInsight/intention/impl/config/IntentionSettingsTree.java index a252ebd52690..cec29cf56516 100644 --- a/platform/lang-impl/src/com/intellij/codeInsight/intention/impl/config/IntentionSettingsTree.java +++ b/platform/lang-impl/src/com/intellij/codeInsight/intention/impl/config/IntentionSettingsTree.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2014 JetBrains s.r.o. + * Copyright 2000-2016 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. @@ -14,9 +14,6 @@ * limitations under the License. */ -/** - * @author cdr - */ package com.intellij.codeInsight.intention.impl.config; import com.intellij.codeInsight.intention.IntentionManager; diff --git a/platform/lang-impl/src/com/intellij/codeInsight/intention/impl/config/IntentionUsagePanel.java b/platform/lang-impl/src/com/intellij/codeInsight/intention/impl/config/IntentionUsagePanel.java index 68c1a2547266..a99abb9d1842 100644 --- a/platform/lang-impl/src/com/intellij/codeInsight/intention/impl/config/IntentionUsagePanel.java +++ b/platform/lang-impl/src/com/intellij/codeInsight/intention/impl/config/IntentionUsagePanel.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2014 JetBrains s.r.o. + * Copyright 2000-2016 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. @@ -14,9 +14,6 @@ * limitations under the License. */ -/** - * @author cdr - */ package com.intellij.codeInsight.intention.impl.config; class IntentionUsagePanel extends ActionUsagePanel { diff --git a/platform/lang-impl/src/com/intellij/codeInsight/navigation/BackgroundUpdaterTask.java b/platform/lang-impl/src/com/intellij/codeInsight/navigation/BackgroundUpdaterTask.java index 85cd0952c0ad..539481824bfb 100644 --- a/platform/lang-impl/src/com/intellij/codeInsight/navigation/BackgroundUpdaterTask.java +++ b/platform/lang-impl/src/com/intellij/codeInsight/navigation/BackgroundUpdaterTask.java @@ -50,7 +50,7 @@ public abstract class BackgroundUpdaterTask extends Task.Backgroundable { private final Alarm myAlarm = new Alarm(Alarm.ThreadToUse.SWING_THREAD); private final Object lock = new Object(); - private volatile boolean myCanceled = false; + private volatile boolean myCanceled; public BackgroundUpdaterTask(Project project, String title, boolean canBeCancelled) { super(project, title, canBeCancelled); diff --git a/platform/lang-impl/src/com/intellij/codeInsight/template/impl/TableMap.java b/platform/lang-impl/src/com/intellij/codeInsight/template/impl/TableMap.java index 4f4e2a986f5c..81861bdec639 100644 --- a/platform/lang-impl/src/com/intellij/codeInsight/template/impl/TableMap.java +++ b/platform/lang-impl/src/com/intellij/codeInsight/template/impl/TableMap.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2009 JetBrains s.r.o. + * Copyright 2000-2016 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. @@ -16,16 +16,16 @@ package com.intellij.codeInsight.template.impl; -/** - * In a chain of data manipulators some behaviour is common. TableMap - * provides most of this behavour and can be subclassed by filters - * that only need to override a handful of specific methods. TableMap - * implements TableModel by routing all requests to its model, and - * TableModelListener by routing all events to its listeners. Inserting - * a TableMap which has not been subclassed into a chain of table filters - * should have no effect. - * - * @version 1.4 12/17/97 +/* + In a chain of data manipulators some behaviour is common. TableMap + provides most of this behavour and can be subclassed by filters + that only need to override a handful of specific methods. TableMap + implements TableModel by routing all requests to its model, and + TableModelListener by routing all events to its listeners. Inserting + a TableMap which has not been subclassed into a chain of table filters + should have no effect. + + @version 1.4 12/17/97 * @author Philip Milne */ import javax.swing.event.TableModelEvent; diff --git a/platform/lang-impl/src/com/intellij/codeInsight/template/postfix/completion/PostfixTemplatesCompletionProvider.java b/platform/lang-impl/src/com/intellij/codeInsight/template/postfix/completion/PostfixTemplatesCompletionProvider.java index ee05406fbe6e..21e7c212a6a8 100644 --- a/platform/lang-impl/src/com/intellij/codeInsight/template/postfix/completion/PostfixTemplatesCompletionProvider.java +++ b/platform/lang-impl/src/com/intellij/codeInsight/template/postfix/completion/PostfixTemplatesCompletionProvider.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2014 JetBrains s.r.o. + * Copyright 2000-2016 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. @@ -37,8 +37,8 @@ class PostfixTemplatesCompletionProvider extends CompletionProvider myPresentationMap = ContainerUtil.newConcurrentMap(); + private final ConcurrentMap myPresentationMap = ContainerUtil.newConcurrentMap(); @NotNull public InspectionToolPresentation getPresentation(@NotNull InspectionToolWrapper toolWrapper) { - InspectionToolPresentation presentation = myPresentationMap.get(toolWrapper); + final String shortName = toolWrapper.getShortName(); + InspectionToolPresentation presentation = myPresentationMap.get(shortName); if (presentation == null) { String presentationClass = StringUtil.notNullize(toolWrapper.myEP == null ? null : toolWrapper.myEP.presentation, DefaultInspectionToolPresentation.class.getName()); @@ -878,7 +881,7 @@ public class GlobalInspectionContextImpl extends GlobalInspectionContextBase imp LOG.error(e); throw new RuntimeException(e); } - presentation = ConcurrencyUtil.cacheOrGet(myPresentationMap, toolWrapper, presentation); + presentation = ConcurrencyUtil.cacheOrGet(myPresentationMap, shortName, presentation); } return presentation; } diff --git a/platform/lang-impl/src/com/intellij/codeInspection/ex/InspectionRVContentProviderImpl.java b/platform/lang-impl/src/com/intellij/codeInspection/ex/InspectionRVContentProviderImpl.java index d99ef3bd36f9..2997ee63fbb1 100644 --- a/platform/lang-impl/src/com/intellij/codeInspection/ex/InspectionRVContentProviderImpl.java +++ b/platform/lang-impl/src/com/intellij/codeInspection/ex/InspectionRVContentProviderImpl.java @@ -26,11 +26,9 @@ import com.intellij.codeInspection.ui.*; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.Comparing; import com.intellij.openapi.util.TextRange; -import com.intellij.openapi.vcs.FileStatus; import com.intellij.psi.PsiElement; import com.intellij.psi.search.LocalSearchScope; import com.intellij.psi.search.SearchScope; -import com.intellij.util.Function; import com.intellij.util.containers.HashSet; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; @@ -92,13 +90,8 @@ public class InspectionRVContentProviderImpl extends InspectionRVContentProvider @NotNull final Map> contents, @NotNull final Map problems) { final InspectionToolWrapper toolWrapper = toolNode.getToolWrapper(); + merge(toolNode, parentNode, false); - Function> computeContainer = new Function>() { - @Override - public UserObjectContainer fun(final RefEntity refElement) { - return new RefElementContainer(refElement, problems.get(refElement)); - } - }; InspectionToolPresentation presentation = context.getPresentation(toolWrapper); final Set moduleProblems = presentation.getModuleProblems(); if (!moduleProblems.isEmpty()) { @@ -113,28 +106,9 @@ public class InspectionRVContentProviderImpl extends InspectionRVContentProvider contents, false, toolWrapper, - computeContainer, + refElement -> new RefElementContainer(refElement, problems.get(refElement)), showStructure, node -> merge(node, toolNode, true)); - - if (presentation.isOldProblemsIncluded()) { - final Map oldProblems = presentation.getOldProblemElements(); - computeContainer = new Function>() { - @Override - public UserObjectContainer fun(final RefEntity refElement) { - return new RefElementContainer(refElement, oldProblems != null ? oldProblems.get(refElement) : null); - } - }; - - buildTree(context, - presentation.getOldContent(), - true, - toolWrapper, - computeContainer, - showStructure, - node -> merge(node, toolNode, true)); - } - merge(toolNode, parentNode, false); } @Override @@ -146,15 +120,11 @@ public class InspectionRVContentProviderImpl extends InspectionRVContentProvider final RefElementContainer refElementDescriptor = (RefElementContainer)container; final RefEntity refElement = refElementDescriptor.getUserObject(); InspectionToolPresentation presentation = context.getPresentation(toolWrapper); - if (context.getUIOptions().SHOW_ONLY_DIFF && presentation.getElementStatus(refElement) == FileStatus.NOT_CHANGED) return; final CommonProblemDescriptor[] problems = refElementDescriptor.getProblemDescriptors(); if (problems != null) { final RefElementNode elemNode = addNodeToParent(container, presentation, pNode); for (CommonProblemDescriptor problem : problems) { assert problem != null; - if (context.getUIOptions().SHOW_ONLY_DIFF && presentation.getProblemStatus(problem) == FileStatus.NOT_CHANGED) { - continue; - } insertByIndex(new ProblemDescriptionNode(refElement, problem, toolWrapper,presentation), elemNode); if (problems.length == 1) { elemNode.setProblem(problems[0]); diff --git a/platform/lang-impl/src/com/intellij/codeInspection/ex/QuickFixAction.java b/platform/lang-impl/src/com/intellij/codeInspection/ex/QuickFixAction.java index d463e718d57b..bdf3efbef189 100644 --- a/platform/lang-impl/src/com/intellij/codeInspection/ex/QuickFixAction.java +++ b/platform/lang-impl/src/com/intellij/codeInspection/ex/QuickFixAction.java @@ -19,6 +19,7 @@ package com.intellij.codeInspection.ex; import com.intellij.codeInsight.FileModificationService; import com.intellij.codeInspection.CommonProblemDescriptor; import com.intellij.codeInspection.InspectionManager; +import com.intellij.codeInspection.InspectionsBundle; import com.intellij.codeInspection.ProblemDescriptor; import com.intellij.codeInspection.reference.RefElement; import com.intellij.codeInspection.reference.RefEntity; @@ -30,11 +31,14 @@ import com.intellij.ide.DataManager; import com.intellij.openapi.actionSystem.*; import com.intellij.openapi.actionSystem.ex.CustomComponentAction; import com.intellij.openapi.application.ApplicationManager; +import com.intellij.openapi.application.ReadAction; import com.intellij.openapi.command.CommandProcessor; import com.intellij.openapi.diagnostic.Logger; +import com.intellij.openapi.progress.ProgressIndicator; import com.intellij.openapi.progress.ProgressManager; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.IconLoader; +import com.intellij.openapi.util.Ref; import com.intellij.openapi.vfs.ReadonlyStatusHandler; import com.intellij.openapi.vfs.VfsUtilCore; import com.intellij.openapi.vfs.VirtualFile; @@ -112,11 +116,18 @@ public class QuickFixAction extends AnAction implements CustomComponentAction { public void actionPerformed(final AnActionEvent e) { final InspectionResultsView view = getInvoker(e); final InspectionTree tree = view.getTree(); - final CommonProblemDescriptor[] descriptors; try { - view.setApplyingFix(true); - if (isProblemDescriptorsAcceptable() && (descriptors = tree.getSelectedDescriptors(true)).length > 0) { - doApplyFix(view.getProject(), descriptors, tree.getContext()); + Ref descriptors = Ref.create(); + Set readOnlyFiles = new THashSet<>(); + if (!ProgressManager.getInstance().runProcessWithProgressSynchronously(() -> ReadAction.run(() -> { + final ProgressIndicator indicator = ProgressManager.getInstance().getProgressIndicator(); + indicator.setText("Checking problem descriptors..."); + descriptors.set(tree.getSelectedDescriptors(true, readOnlyFiles)); + }), InspectionsBundle.message("preparing.for.apply.fix"), true, e.getProject())) { + return; + } + if (isProblemDescriptorsAcceptable() && descriptors.get().length > 0) { + doApplyFix(view.getProject(), descriptors.get(), readOnlyFiles, tree.getContext()); } else { doApplyFix(getSelectedElements(e), view); } @@ -134,19 +145,11 @@ public class QuickFixAction extends AnAction implements CustomComponentAction { private void doApplyFix(@NotNull final Project project, @NotNull final CommonProblemDescriptor[] descriptors, + @NotNull Set readOnlyFiles, @NotNull final GlobalInspectionContextImpl context) { - final Set readOnlyFiles = new THashSet(); - for (CommonProblemDescriptor descriptor : descriptors) { - final PsiElement psiElement = descriptor instanceof ProblemDescriptor ? ((ProblemDescriptor)descriptor).getPsiElement() : null; - if (psiElement != null && !psiElement.isWritable()) { - readOnlyFiles.add(psiElement.getContainingFile().getVirtualFile()); - } - } - if (!FileModificationService.getInstance().prepareVirtualFilesForWrite(project, readOnlyFiles)) return; final RefManagerImpl refManager = (RefManagerImpl)context.getRefManager(); - final boolean initial = refManager.isInProcess(); refManager.inspectionReadActionFinished(); diff --git a/platform/lang-impl/src/com/intellij/codeInspection/offlineViewer/OfflineInspectionRVContentProvider.java b/platform/lang-impl/src/com/intellij/codeInspection/offlineViewer/OfflineInspectionRVContentProvider.java index c39ef74da145..00f4ea65efde 100644 --- a/platform/lang-impl/src/com/intellij/codeInspection/offlineViewer/OfflineInspectionRVContentProvider.java +++ b/platform/lang-impl/src/com/intellij/codeInspection/offlineViewer/OfflineInspectionRVContentProvider.java @@ -35,7 +35,6 @@ import com.intellij.util.ui.tree.TreeUtil; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; -import javax.swing.tree.DefaultTreeModel; import javax.swing.tree.TreeNode; import javax.swing.tree.TreePath; import java.util.*; @@ -72,7 +71,7 @@ public class OfflineInspectionRVContentProvider extends InspectionRVContentProvi TreeUtil.traverseDepth((TreeNode)selectionPath.getLastPathComponent(), node -> { if (!((InspectionTreeNode)node).isValid()) return true; if (node instanceof OfflineProblemDescriptorNode) { - if (!((OfflineProblemDescriptorNode)node).isQuickFixAppliedFromView()) return true; + if (((OfflineProblemDescriptorNode)node).isQuickFixAppliedFromView()) return true; final OfflineProblemDescriptorNode descriptorNode = (OfflineProblemDescriptorNode)node; final RefEntity element = descriptorNode.getElement(); selectedElements.add(element); diff --git a/platform/lang-impl/src/com/intellij/codeInspection/ui/CachedInspectionTreeNode.java b/platform/lang-impl/src/com/intellij/codeInspection/ui/CachedInspectionTreeNode.java index ab3fde339d79..ef2d2ffd57e7 100644 --- a/platform/lang-impl/src/com/intellij/codeInspection/ui/CachedInspectionTreeNode.java +++ b/platform/lang-impl/src/com/intellij/codeInspection/ui/CachedInspectionTreeNode.java @@ -24,8 +24,8 @@ import javax.swing.tree.TreeNode; * @author Dmitry Batkovich */ public abstract class CachedInspectionTreeNode extends InspectionTreeNode implements RefElementAndDescriptorAware { - private volatile String myPresentableName = null; - private volatile Boolean myValid = null; + private volatile String myPresentableName; + private volatile Boolean myValid; protected CachedInspectionTreeNode(Object userObject) { super(userObject); diff --git a/platform/lang-impl/src/com/intellij/codeInspection/ui/DefaultInspectionToolPresentation.java b/platform/lang-impl/src/com/intellij/codeInspection/ui/DefaultInspectionToolPresentation.java index 4b983b8b52d0..3513d4247aa9 100644 --- a/platform/lang-impl/src/com/intellij/codeInspection/ui/DefaultInspectionToolPresentation.java +++ b/platform/lang-impl/src/com/intellij/codeInspection/ui/DefaultInspectionToolPresentation.java @@ -75,7 +75,6 @@ public class DefaultInspectionToolPresentation implements ProblemDescriptionsPro private final Map> myQuickFixActions = Collections.synchronizedMap(new THashMap>(TObjectHashingStrategy.IDENTITY)); private final Map myIgnoredElements = Collections.synchronizedMap(new THashMap(TObjectHashingStrategy.IDENTITY)); - private Map myOldProblemElements = null; protected static final Logger LOG = Logger.getInstance("#com.intellij.codeInspection.ex.DescriptorProviderInspection"); private volatile boolean isDisposed; @@ -186,13 +185,6 @@ public class DefaultInspectionToolPresentation implements ProblemDescriptionsPro }); } - @Override - public boolean isOldProblemsIncluded() { - final GlobalInspectionContextImpl context = getContext(); - return context.getUIOptions().SHOW_DIFF_WITH_PREVIOUS_RUN && getOldContent() != null; - } - - @Override public void addProblemElement(RefEntity refElement, @NotNull CommonProblemDescriptor... descriptions){ addProblemElement(refElement, true, descriptions); @@ -439,8 +431,6 @@ public class DefaultInspectionToolPresentation implements ProblemDescriptionsPro @Override public void cleanup() { - myOldProblemElements = null; - synchronized (lock) { myProblemElements.clear(); myProblemToElements.clear(); @@ -455,7 +445,6 @@ public class DefaultInspectionToolPresentation implements ProblemDescriptionsPro @Override public void finalCleanup() { - myOldProblemElements = null; cleanup(); } @@ -569,24 +558,7 @@ public class DefaultInspectionToolPresentation implements ProblemDescriptionsPro @Override public boolean hasReportedProblems() { - final GlobalInspectionContextImpl context = getContext(); - if (!isDisposed() && context.getUIOptions().SHOW_ONLY_DIFF) { - for (CommonProblemDescriptor descriptor : getProblemToElements().keySet()) { - if (getProblemStatus(descriptor) != FileStatus.NOT_CHANGED) { - return true; - } - } - if (myOldProblemElements != null) { - for (RefEntity entity : myOldProblemElements.keySet()) { - if (getElementStatus(entity) != FileStatus.NOT_CHANGED) { - return true; - } - } - } - return false; - } - if (!getProblemElements().isEmpty()) return true; - return !isDisposed() && context.getUIOptions().SHOW_DIFF_WITH_PREVIOUS_RUN && myOldProblemElements != null && !myOldProblemElements.isEmpty(); + return !getProblemElements().isEmpty(); } @Override @@ -617,28 +589,6 @@ public class DefaultInspectionToolPresentation implements ProblemDescriptionsPro return myContents; } - @Override - public Map> getOldContent() { - if (myOldProblemElements == null) return null; - final Map> oldContents = new com.intellij.util.containers.HashMap>(); - final Set elements = myOldProblemElements.keySet(); - for (RefEntity element : elements) { - String groupName = element instanceof RefElement ? element.getRefManager().getGroupName((RefElement)element) : element.getName(); - final Set collection = myContents.get(groupName); - if (collection != null) { - final Set currentElements = new HashSet(collection); - if (RefUtil.contains(element, currentElements)) continue; - } - Set oldContent = oldContents.get(groupName); - if (oldContent == null) { - oldContent = new HashSet(); - oldContents.put(groupName, oldContent); - } - oldContent.add(element); - } - return oldContents; - } - @NotNull @Override public Set getModuleProblems() { @@ -750,53 +700,12 @@ public class DefaultInspectionToolPresentation implements ProblemDescriptionsPro @Override @NotNull public FileStatus getProblemStatus(@NotNull final CommonProblemDescriptor descriptor) { - final GlobalInspectionContextImpl context = getContext(); - if (!isDisposed() && context.getUIOptions().SHOW_DIFF_WITH_PREVIOUS_RUN){ - if (myOldProblemElements != null){ - final Set allAvailable = new HashSet(); - for (CommonProblemDescriptor[] descriptors : myOldProblemElements.values()) { - if (descriptors != null) { - ContainerUtil.addAll(allAvailable, descriptors); - } - } - final boolean old = containsDescriptor(descriptor, allAvailable); - final boolean current = containsDescriptor(descriptor, getProblemToElements().keySet()); - return calcStatus(old, current); - } - } return FileStatus.NOT_CHANGED; } - private static boolean containsDescriptor(@NotNull CommonProblemDescriptor descriptor, Collection descriptors){ - PsiElement element = null; - if (descriptor instanceof ProblemDescriptor){ - element = ((ProblemDescriptor)descriptor).getPsiElement(); - } - for (CommonProblemDescriptor problemDescriptor : descriptors) { - if (problemDescriptor instanceof ProblemDescriptor){ - if (!Comparing.equal(element, ((ProblemDescriptor)problemDescriptor).getPsiElement())){ - continue; - } - } - if (Comparing.strEqual(problemDescriptor.getDescriptionTemplate(), descriptor.getDescriptionTemplate())){ - return true; - } - } - return false; - } - - @NotNull @Override public FileStatus getElementStatus(final RefEntity element) { - final GlobalInspectionContextImpl context = getContext(); - if (!isDisposed() && context.getUIOptions().SHOW_DIFF_WITH_PREVIOUS_RUN){ - if (myOldProblemElements != null){ - final boolean old = RefUtil.contains(element, myOldProblemElements.keySet()); - final boolean current = RefUtil.contains(element, getProblemElements().keySet()); - return calcStatus(old, current); - } - } return FileStatus.NOT_CHANGED; } @@ -812,12 +721,6 @@ public class DefaultInspectionToolPresentation implements ProblemDescriptionsPro return myProblemElements; } - @Override - @Nullable - public Map getOldProblemElements() { - return myOldProblemElements; - } - @NotNull private Map getProblemToElements() { return myProblemToElements; diff --git a/platform/lang-impl/src/com/intellij/codeInspection/ui/InspectionResultsView.java b/platform/lang-impl/src/com/intellij/codeInspection/ui/InspectionResultsView.java index defe2dbd80cd..ccd8225a27f9 100644 --- a/platform/lang-impl/src/com/intellij/codeInspection/ui/InspectionResultsView.java +++ b/platform/lang-impl/src/com/intellij/codeInspection/ui/InspectionResultsView.java @@ -291,8 +291,6 @@ public class InspectionResultsView extends JPanel implements Disposable, Occuren specialGroup.add(myGlobalInspectionContext.getUIOptions().createGroupBySeverityAction(this)); specialGroup.add(myGlobalInspectionContext.getUIOptions().createGroupByDirectoryAction(this)); specialGroup.add(myGlobalInspectionContext.getUIOptions().createFilterResolvedItemsAction(this)); - specialGroup.add(myGlobalInspectionContext.getUIOptions().createShowOutdatedProblemsAction(this)); - specialGroup.add(myGlobalInspectionContext.getUIOptions().createShowDiffOnlyAction(this)); specialGroup.add(ActionManager.getInstance().getAction("EditInspectionSettings")); specialGroup.add(new InvokeQuickFixAction(this)); specialGroup.add(new InspectionsOptionsToolbarAction(this)); @@ -520,6 +518,9 @@ public class InspectionResultsView extends JPanel implements Disposable, Occuren } final PsiFile file = selectedElement.getContainingFile(); final Document document = PsiDocumentManager.getInstance(file.getProject()).getDocument(file); + if (document == null) { + return Pair.create(InspectionResultsViewUtil.createLabelForText("Can't open preview for \'" + file.getName() + "\'"), null); + } if (reuseEditorFor(document)) { myPreviewEditor.putUserData(PREVIEW_EDITOR_IS_REUSED_KEY, true); @@ -540,6 +541,9 @@ public class InspectionResultsView extends JPanel implements Disposable, Occuren myPreviewEditor.getColorsScheme().setColor(EditorColors.GUTTER_BACKGROUND, myPreviewEditor.getColorsScheme().getDefaultBackground()); myPreviewEditor.getScrollPane().setBorder(IdeBorderFactory.createEmptyBorder()); } + if (problemCount == 0) { + myPreviewEditor.getScrollingModel().scrollTo(myPreviewEditor.offsetToLogicalPosition(selectedElement.getTextOffset()), ScrollType.CENTER_UP); + } myPreviewEditor.getSettings().setFoldingOutlineShown(problemCount != 1); myPreviewEditor.getComponent().setBorder(IdeBorderFactory.createEmptyBorder()); return Pair.create(myPreviewEditor.getComponent(), myPreviewEditor); @@ -674,8 +678,7 @@ public class InspectionResultsView extends JPanel implements Disposable, Occuren setUpdating(true); synchronized (getTreeStructureUpdateLock()) { myGroups.clear(); - final Map tools = myGlobalInspectionContext.getTools(); - addTools(tools.values()); + addTools(myGlobalInspectionContext.getTools().values()); } } finally { diff --git a/platform/lang-impl/src/com/intellij/codeInspection/ui/InspectionResultsViewUtil.java b/platform/lang-impl/src/com/intellij/codeInspection/ui/InspectionResultsViewUtil.java index f8bd048de864..95a483ec31fb 100644 --- a/platform/lang-impl/src/com/intellij/codeInspection/ui/InspectionResultsViewUtil.java +++ b/platform/lang-impl/src/com/intellij/codeInspection/ui/InspectionResultsViewUtil.java @@ -69,7 +69,7 @@ public class InspectionResultsViewUtil { } @NotNull - private static JLabel createLabelForText(String text) { + static JLabel createLabelForText(String text) { final JLabel multipleSelectionLabel = new JBLabel(text); multipleSelectionLabel.setVerticalAlignment(SwingConstants.TOP); multipleSelectionLabel.setBorder(IdeBorderFactory.createEmptyBorder(16, 12, 0, 0)); diff --git a/platform/lang-impl/src/com/intellij/codeInspection/ui/InspectionToolPresentation.java b/platform/lang-impl/src/com/intellij/codeInspection/ui/InspectionToolPresentation.java index 1ecff38661ff..9356ef20eaa2 100644 --- a/platform/lang-impl/src/com/intellij/codeInspection/ui/InspectionToolPresentation.java +++ b/platform/lang-impl/src/com/intellij/codeInspection/ui/InspectionToolPresentation.java @@ -50,7 +50,6 @@ public interface InspectionToolPresentation extends ProblemDescriptionsProcessor @NotNull Map> getContent(); - Map> getOldContent(); void ignoreCurrentElement(RefEntity refEntity); void amnesty(RefEntity refEntity); void cleanup(); @@ -76,9 +75,6 @@ public interface InspectionToolPresentation extends ProblemDescriptionsProcessor Collection getProblemDescriptors(); @NotNull FileStatus getProblemStatus(@NotNull CommonProblemDescriptor descriptor); - boolean isOldProblemsIncluded(); - @Nullable - Map getOldProblemElements(); boolean isProblemResolved(RefEntity refEntity, CommonProblemDescriptor descriptor); void ignoreCurrentElementProblem(RefEntity refEntity, CommonProblemDescriptor descriptor); void addProblemElement(RefEntity refElement, boolean filterSuppressed, @NotNull CommonProblemDescriptor... descriptions); diff --git a/platform/lang-impl/src/com/intellij/codeInspection/ui/InspectionTree.java b/platform/lang-impl/src/com/intellij/codeInspection/ui/InspectionTree.java index 982f73785e76..72c1224c3b71 100644 --- a/platform/lang-impl/src/com/intellij/codeInspection/ui/InspectionTree.java +++ b/platform/lang-impl/src/com/intellij/codeInspection/ui/InspectionTree.java @@ -27,14 +27,16 @@ import com.intellij.codeInspection.ProblemDescriptor; import com.intellij.codeInspection.ex.GlobalInspectionContextImpl; import com.intellij.codeInspection.ex.InspectionToolWrapper; import com.intellij.codeInspection.reference.RefEntity; +import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.project.Project; +import com.intellij.openapi.vfs.VirtualFile; import com.intellij.profile.codeInspection.ui.inspectionsTree.InspectionsConfigTreeComparator; +import com.intellij.psi.PsiElement; import com.intellij.psi.util.PsiUtilCore; import com.intellij.ui.TreeSpeedSearch; import com.intellij.ui.treeStructure.Tree; import com.intellij.util.SmartList; import com.intellij.util.containers.ContainerUtil; -import com.intellij.util.containers.Convertor; import com.intellij.util.containers.MultiMap; import com.intellij.util.ui.UIUtil; import com.intellij.util.ui.tree.TreeUtil; @@ -42,16 +44,17 @@ import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.swing.event.TreeExpansionEvent; -import javax.swing.event.TreeSelectionEvent; -import javax.swing.event.TreeSelectionListener; import javax.swing.event.TreeWillExpandListener; import javax.swing.tree.DefaultTreeModel; import javax.swing.tree.ExpandVetoException; import javax.swing.tree.TreeNode; import javax.swing.tree.TreePath; import java.util.*; +import java.util.stream.Collectors; +import java.util.stream.Stream; public class InspectionTree extends Tree { + private static final Logger LOG = Logger.getInstance(InspectionTree.class); private static final Comparator DESCRIPTOR_COMPARATOR = (c1, c2) -> { if (c1 instanceof ProblemDescriptor && c2 instanceof ProblemDescriptor) { return PsiUtilCore.compareElementsByPosition(((ProblemDescriptor)c2).getPsiElement(), @@ -81,20 +84,12 @@ public class InspectionTree extends Tree { myState.getExpandedUserObjects().add(project); TreeUtil.installActions(this); - new TreeSpeedSearch(this, new Convertor() { - @Override - public String convert(TreePath o) { - return InspectionsConfigTreeComparator.getDisplayTextToSort(o.getLastPathComponent().toString()); - } - }); + new TreeSpeedSearch(this, o -> InspectionsConfigTreeComparator.getDisplayTextToSort(o.getLastPathComponent().toString())); - addTreeSelectionListener(new TreeSelectionListener() { - @Override - public void valueChanged(TreeSelectionEvent e) { - TreePath newSelection = e.getNewLeadSelectionPath(); - if (newSelection != null && !isUnderQueueUpdate()) { - myState.setSelectionPath(newSelection); - } + addTreeSelectionListener(e -> { + TreePath newSelection = e.getNewLeadSelectionPath(); + if (newSelection != null && !isUnderQueueUpdate()) { + myState.setSelectionPath(newSelection); } }); } @@ -213,16 +208,16 @@ public class InspectionTree extends Tree { } public CommonProblemDescriptor[] getSelectedDescriptors() { - return getSelectedDescriptors(false); + return getSelectedDescriptors(false, null); } - public CommonProblemDescriptor[] getSelectedDescriptors(boolean sortedByPosition) { + public CommonProblemDescriptor[] getSelectedDescriptors(boolean sortedByPosition, @Nullable Set readOnlyFilesSink) { final TreePath[] paths = getSelectionPaths(); if (paths == null) return CommonProblemDescriptor.EMPTY_ARRAY; final TreePath[] selectionPaths = TreeUtil.selectMaximals(paths); final LinkedHashSet descriptors = new LinkedHashSet(); - MultiMap parentToChildNode = new MultiMap<>(); + MultiMap parentToChildNode = new MultiMap<>(); final List nonDescriptorNodes = new SmartList<>(); for (TreePath path : selectionPaths) { final Object[] pathAsArray = path.getPath(); @@ -230,11 +225,10 @@ public class InspectionTree extends Tree { final Object node = pathAsArray[length - 1]; if (node instanceof ProblemDescriptionNode) { if (isNodeValidAndIncluded((ProblemDescriptionNode)node)) { - final CommonProblemDescriptor descriptor = ((ProblemDescriptionNode)node).getDescriptor(); if (length >= 2) { - parentToChildNode.putValue(pathAsArray[length - 2], descriptor); + parentToChildNode.putValue(pathAsArray[length - 2], (ProblemDescriptionNode)node); } else { - parentToChildNode.putValue(node, descriptor); + parentToChildNode.putValue(node, (ProblemDescriptionNode)node); } } } else { @@ -243,22 +237,29 @@ public class InspectionTree extends Tree { } for (InspectionTreeNode node : nonDescriptorNodes) { - processChildDescriptorsDeep(node, descriptors, sortedByPosition); + processChildDescriptorsDeep(node, descriptors, sortedByPosition, readOnlyFilesSink); } - for (Map.Entry> entry : parentToChildNode.entrySet()) { - final Collection siblings = entry.getValue(); + for (Map.Entry> entry : parentToChildNode.entrySet()) { + final Collection siblings = entry.getValue(); if (siblings.size() == 1) { - @SuppressWarnings("ConstantConditions") - final CommonProblemDescriptor descriptor = ContainerUtil.getFirstItem(siblings); + final ProblemDescriptionNode descriptorNode = ContainerUtil.getFirstItem(siblings); + LOG.assertTrue(descriptorNode != null); + CommonProblemDescriptor descriptor = descriptorNode.getDescriptor(); if (descriptor != null) { descriptors.add(descriptor); + if (readOnlyFilesSink != null) { + checkDescriptorFileIsWritable(descriptor, readOnlyFilesSink); + } } } else { + Stream descriptorStream = siblings.stream().map(ProblemDescriptionNode::getDescriptor); if (sortedByPosition) { - siblings.stream().sorted(DESCRIPTOR_COMPARATOR).forEach(descriptors::add); - } else { - descriptors.addAll(siblings); + descriptorStream = descriptorStream.sorted(DESCRIPTOR_COMPARATOR); + } + descriptorStream = descriptorStream.filter(descriptors::add); + if (readOnlyFilesSink != null) { + checkDescriptorsFileIsWritable(descriptorStream.collect(Collectors.toList()), readOnlyFilesSink); } } } @@ -280,7 +281,7 @@ public class InspectionTree extends Tree { public int getSelectedProblemCount() { if (getSelectionCount() == 0) return 0; final TreePath[] paths = getSelectionPaths(); - + LOG.assertTrue(paths != null); Set result = new HashSet<>(); MultiMap rootDependencies = new MultiMap<>(); for (TreePath path : paths) { @@ -315,7 +316,8 @@ public class InspectionTree extends Tree { private void processChildDescriptorsDeep(InspectionTreeNode node, LinkedHashSet descriptors, - boolean sortedByPosition) { + boolean sortedByPosition, + @Nullable Set readOnlyFilesSink) { List descriptorChildren = null; for (int i = 0; i < node.getChildCount(); i++) { final TreeNode child = node.getChildAt(i); @@ -332,7 +334,7 @@ public class InspectionTree extends Tree { } } else { - processChildDescriptorsDeep((InspectionTreeNode)child, descriptors, sortedByPosition); + processChildDescriptorsDeep((InspectionTreeNode)child, descriptors, sortedByPosition, readOnlyFilesSink); } } @@ -340,6 +342,10 @@ public class InspectionTree extends Tree { if (descriptorChildren.size() > 1) { Collections.sort(descriptorChildren, DESCRIPTOR_COMPARATOR); } + if (readOnlyFilesSink != null) { + checkDescriptorsFileIsWritable(descriptorChildren, readOnlyFilesSink); + } + descriptors.addAll(descriptorChildren); } } @@ -393,4 +399,23 @@ public class InspectionTree extends Tree { public GlobalInspectionContextImpl getContext() { return myContext; } + + private static void checkDescriptorsFileIsWritable(@NotNull Collection descriptors, @NotNull Set readOnlySink) { + for (CommonProblemDescriptor descriptor : descriptors) { + if (checkDescriptorFileIsWritable(descriptor, readOnlySink)) { + return; + } + } + } + + private static boolean checkDescriptorFileIsWritable(@NotNull CommonProblemDescriptor descriptor, @NotNull Set readOnlySink) { + if (descriptor instanceof ProblemDescriptor) { + PsiElement psiElement = ((ProblemDescriptor)descriptor).getPsiElement(); + if (psiElement != null && !psiElement.isWritable()) { + readOnlySink.add(psiElement.getContainingFile().getVirtualFile()); + return true; + } + } + return false; + } } diff --git a/platform/lang-impl/src/com/intellij/codeInspection/ui/InspectionTreeCellRenderer.java b/platform/lang-impl/src/com/intellij/codeInspection/ui/InspectionTreeCellRenderer.java index 484f39a685df..92972ba66802 100644 --- a/platform/lang-impl/src/com/intellij/codeInspection/ui/InspectionTreeCellRenderer.java +++ b/platform/lang-impl/src/com/intellij/codeInspection/ui/InspectionTreeCellRenderer.java @@ -28,10 +28,10 @@ import com.intellij.ui.JBColor; import com.intellij.ui.SimpleTextAttributes; import com.intellij.util.containers.FactoryMap; import com.intellij.util.containers.SoftHashMap; +import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.swing.*; -import java.util.Comparator; import java.util.Locale; import java.util.Map; import java.util.TreeMap; @@ -59,20 +59,14 @@ class InspectionTreeCellRenderer extends ColoredTreeCellRenderer { @Override protected Map createMap() { - return new TreeMap<>(new Comparator() { - - @Override - public int compare(Object o1, Object o2) { - return -myRegistrar.compare(((HighlightDisplayLevel) o1).getSeverity(), ((HighlightDisplayLevel) o2).getSeverity()); - } - }); + return new TreeMap<>((o1, o2) -> -myRegistrar.compare(o1.getSeverity(), o2.getSeverity())); } }; myView = view; } @Override - public void customizeCellRenderer(JTree tree, + public void customizeCellRenderer(@NotNull JTree tree, Object value, boolean selected, boolean expanded, diff --git a/platform/lang-impl/src/com/intellij/diagnostic/logging/DebuggerLogConsoleManager.java b/platform/lang-impl/src/com/intellij/diagnostic/logging/DebuggerLogConsoleManager.java index c24c0e869b97..970c932441b2 100644 --- a/platform/lang-impl/src/com/intellij/diagnostic/logging/DebuggerLogConsoleManager.java +++ b/platform/lang-impl/src/com/intellij/diagnostic/logging/DebuggerLogConsoleManager.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2009 JetBrains s.r.o. + * Copyright 2000-2016 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. @@ -17,9 +17,5 @@ package com.intellij.diagnostic.logging; @Deprecated -/** - * User: anna - * Date: 01-Feb-2006 - */ public interface DebuggerLogConsoleManager extends LogConsoleManager { } \ No newline at end of file diff --git a/platform/lang-impl/src/com/intellij/execution/TerminateRemoteProcessDialog.java b/platform/lang-impl/src/com/intellij/execution/TerminateRemoteProcessDialog.java index 64c60c29620b..d43eaa464e0c 100644 --- a/platform/lang-impl/src/com/intellij/execution/TerminateRemoteProcessDialog.java +++ b/platform/lang-impl/src/com/intellij/execution/TerminateRemoteProcessDialog.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2014 JetBrains s.r.o. + * Copyright 2000-2016 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. @@ -14,10 +14,6 @@ * limitations under the License. */ -/** - * created at Dec 14, 2001 - * @author Jeka - */ package com.intellij.execution; import com.intellij.CommonBundle; diff --git a/platform/lang-impl/src/com/intellij/execution/impl/MyDiffContainer.java b/platform/lang-impl/src/com/intellij/execution/impl/MyDiffContainer.java index 0c2abff9291d..a998999a328e 100644 --- a/platform/lang-impl/src/com/intellij/execution/impl/MyDiffContainer.java +++ b/platform/lang-impl/src/com/intellij/execution/impl/MyDiffContainer.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2015 JetBrains s.r.o. + * Copyright 2000-2016 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. @@ -75,8 +75,8 @@ class MyDiffContainer extends JBLayeredPane implements Disposable { private class MyOverlayLayout extends AbstractLayoutManager { @Override public void layoutContainer(Container parent) { - /** - * Propogate bound to all children + /* + Propogate bound to all children */ for(int i = 0; i< getComponentCount(); i++) { getComponent(i).setBounds(0, 0, getWidth(), getHeight()); diff --git a/platform/lang-impl/src/com/intellij/execution/impl/RunConfigurable.java b/platform/lang-impl/src/com/intellij/execution/impl/RunConfigurable.java index 5570c7a74d61..94778ea7f7fb 100644 --- a/platform/lang-impl/src/com/intellij/execution/impl/RunConfigurable.java +++ b/platform/lang-impl/src/com/intellij/execution/impl/RunConfigurable.java @@ -80,7 +80,7 @@ class RunConfigurable extends BaseConfigurable { } }; - private volatile boolean isDisposed = false; + private volatile boolean isDisposed; private final Project myProject; private RunDialogBase myRunDialog; diff --git a/platform/lang-impl/src/com/intellij/execution/impl/RunConfigurationBeforeRunProvider.java b/platform/lang-impl/src/com/intellij/execution/impl/RunConfigurationBeforeRunProvider.java index 8f89f437a764..f82ea6036394 100644 --- a/platform/lang-impl/src/com/intellij/execution/impl/RunConfigurationBeforeRunProvider.java +++ b/platform/lang-impl/src/com/intellij/execution/impl/RunConfigurationBeforeRunProvider.java @@ -177,6 +177,10 @@ extends BeforeRunTaskProvider result = new Ref(false); final Disposable disposable = Disposer.newDisposable(); - myProject.getMessageBus().connect(disposable).subscribe(ExecutionManager.EXECUTION_TOPIC, new ExecutionAdapter() { + env.getProject().getMessageBus().connect(disposable).subscribe(ExecutionManager.EXECUTION_TOPIC, new ExecutionAdapter() { @Override public void processStartScheduled(final String executorIdLocal, final ExecutionEnvironment environmentLocal) { if (executorId.equals(executorIdLocal) && environment.equals(environmentLocal)) { diff --git a/platform/lang-impl/src/com/intellij/find/findInProject/FindInProjectManager.java b/platform/lang-impl/src/com/intellij/find/findInProject/FindInProjectManager.java index c99a1c25182b..abf70c2f1905 100644 --- a/platform/lang-impl/src/com/intellij/find/findInProject/FindInProjectManager.java +++ b/platform/lang-impl/src/com/intellij/find/findInProject/FindInProjectManager.java @@ -40,7 +40,7 @@ import org.jetbrains.annotations.NotNull; public class FindInProjectManager { private final Project myProject; - private volatile boolean myIsFindInProgress = false; + private volatile boolean myIsFindInProgress; public static FindInProjectManager getInstance(Project project) { return ServiceManager.getService(project, FindInProjectManager.class); diff --git a/platform/lang-impl/src/com/intellij/find/findUsages/FindUsagesManager.java b/platform/lang-impl/src/com/intellij/find/findUsages/FindUsagesManager.java index 7332f764d0a5..39bc690367cd 100644 --- a/platform/lang-impl/src/com/intellij/find/findUsages/FindUsagesManager.java +++ b/platform/lang-impl/src/com/intellij/find/findUsages/FindUsagesManager.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2014 JetBrains s.r.o. + * Copyright 2000-2016 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. @@ -38,6 +38,8 @@ import com.intellij.openapi.keymap.KeymapUtil; import com.intellij.openapi.progress.ProcessCanceledException; import com.intellij.openapi.progress.ProgressIndicator; import com.intellij.openapi.progress.ProgressManager; +import com.intellij.openapi.progress.Task; +import com.intellij.openapi.progress.impl.ProgressManagerImpl; import com.intellij.openapi.progress.util.ProgressIndicatorBase; import com.intellij.openapi.project.DumbService; import com.intellij.openapi.project.IndexNotReadyException; @@ -47,12 +49,14 @@ import com.intellij.openapi.ui.DialogWrapper; import com.intellij.openapi.ui.Messages; import com.intellij.openapi.util.Comparing; import com.intellij.openapi.util.Computable; -import com.intellij.openapi.util.Factory; import com.intellij.openapi.util.Key; import com.intellij.openapi.util.text.StringUtil; import com.intellij.openapi.wm.StatusBar; import com.intellij.openapi.wm.ex.ProgressIndicatorEx; -import com.intellij.psi.*; +import com.intellij.psi.PsiDocumentManager; +import com.intellij.psi.PsiElement; +import com.intellij.psi.PsiFile; +import com.intellij.psi.PsiManager; import com.intellij.psi.search.*; import com.intellij.psi.util.PsiUtilCore; import com.intellij.ui.LightweightHint; @@ -62,7 +66,6 @@ import com.intellij.usageView.UsageViewManager; import com.intellij.usageView.UsageViewUtil; import com.intellij.usages.*; import com.intellij.util.CommonProcessors; -import com.intellij.util.Function; import com.intellij.util.Processor; import com.intellij.util.containers.ContainerUtil; import com.intellij.util.pico.ConstructorInjectionComponentAdapter; @@ -281,24 +284,17 @@ public class FindUsagesManager { @NotNull final Processor processor, @NotNull final FindUsagesOptions findUsagesOptions, @NotNull final Runnable onComplete) { + ApplicationManager.getApplication().assertIsDispatchThread(); final ProgressIndicatorBase indicator = new ProgressIndicatorBase(); - ApplicationManager.getApplication().executeOnPooledThread(new Runnable() { + Task.Backgroundable task = new Task.Backgroundable(handler.getProject(), "Finding Usages") { @Override - public void run() { - try { - ProgressManager.getInstance().runProcess(new Runnable() { - @Override - public void run() { - final UsageSearcher usageSearcher = createUsageSearcher(primaryElements, secondaryElements, handler, findUsagesOptions, null); - usageSearcher.generate(processor); - } - }, indicator); - } - finally { - onComplete.run(); - } + public void run(@NotNull ProgressIndicator indicator) { + final UsageSearcher usageSearcher = createUsageSearcher(primaryElements, secondaryElements, handler, findUsagesOptions, null); + usageSearcher.generate(processor); } - }); + }; + + ((ProgressManagerImpl)ProgressManager.getInstance()).runProcessWithProgressAsynchronously(task, indicator, onComplete); return indicator; } @@ -333,82 +329,70 @@ public class FindUsagesManager { @NotNull FindUsagesOptions options, final PsiFile scopeFile) { final FindUsagesOptions optionsClone = options.clone(); - return new UsageSearcher() { - @Override - public void generate(@NotNull final Processor processor) { - Project project = ApplicationManager.getApplication().runReadAction(new Computable() { - @Override - public Project compute() { - return scopeFile != null ? scopeFile.getProject() : primaryElements[0].getProject(); - } - }); - dropResolveCacheRegularly(ProgressManager.getInstance().getProgressIndicator(), project); - - if (scopeFile != null) { - optionsClone.searchScope = new LocalSearchScope(scopeFile); + return processor -> { + Project project = ApplicationManager.getApplication().runReadAction(new Computable() { + @Override + public Project compute() { + return scopeFile != null ? scopeFile.getProject() : primaryElements[0].getProject(); } - final Processor usageInfoProcessor = new CommonProcessors.UniqueProcessor(new Processor() { - @Override - public boolean process(final UsageInfo usageInfo) { - Usage usage = ApplicationManager.getApplication().runReadAction(new Computable() { - @Override - public Usage compute() { - return UsageInfoToUsageConverter.convert(primaryElements, usageInfo); - } - }); - return processor.process(usage); - } - }); - final Iterable elements = ContainerUtil.concat(primaryElements, secondaryElements); + }); + dropResolveCacheRegularly(ProgressManager.getInstance().getProgressIndicator(), project); - optionsClone.fastTrack = new SearchRequestCollector(new SearchSession()); - if (optionsClone.searchScope instanceof GlobalSearchScope) { - // we will search in project scope always but warn if some usage is out of scope - optionsClone.searchScope = optionsClone.searchScope.union(GlobalSearchScope.projectScope(project)); - } - try { - for (final PsiElement element : elements) { - ApplicationManager.getApplication().runReadAction(new Runnable() { - @Override - public void run() { - PsiUtilCore.ensureValid(element); - } - }); - handler.processElementUsages(element, usageInfoProcessor, optionsClone); - for (CustomUsageSearcher searcher : Extensions.getExtensions(CustomUsageSearcher.EP_NAME)) { - try { - searcher.processElementUsages(element, processor, optionsClone); - } - catch (IndexNotReadyException e) { - DumbService.getInstance(element.getProject()).showDumbModeNotification("Find usages is not available during indexing"); - } - catch (ProcessCanceledException e) { - throw e; - } - catch (Exception e) { - LOG.error(e); - } + if (scopeFile != null) { + optionsClone.searchScope = new LocalSearchScope(scopeFile); + } + final Processor usageInfoProcessor = new CommonProcessors.UniqueProcessor<>(usageInfo -> { + Usage usage = ApplicationManager.getApplication().runReadAction(new Computable() { + @Override + public Usage compute() { + return UsageInfoToUsageConverter.convert(primaryElements, usageInfo); + } + }); + return processor.process(usage); + }); + final Iterable elements = ContainerUtil.concat(primaryElements, secondaryElements); + + optionsClone.fastTrack = new SearchRequestCollector(new SearchSession()); + if (optionsClone.searchScope instanceof GlobalSearchScope) { + // we will search in project scope always but warn if some usage is out of scope + optionsClone.searchScope = optionsClone.searchScope.union(GlobalSearchScope.projectScope(project)); + } + try { + for (final PsiElement element : elements) { + ApplicationManager.getApplication().runReadAction(() -> { + PsiUtilCore.ensureValid(element); + }); + handler.processElementUsages(element, usageInfoProcessor, optionsClone); + for (CustomUsageSearcher searcher : Extensions.getExtensions(CustomUsageSearcher.EP_NAME)) { + try { + searcher.processElementUsages(element, processor, optionsClone); + } + catch (IndexNotReadyException e) { + DumbService.getInstance(element.getProject()).showDumbModeNotification("Find usages is not available during indexing"); + } + catch (ProcessCanceledException e) { + throw e; + } + catch (Exception e) { + LOG.error(e); } } + } - PsiSearchHelper.SERVICE.getInstance(project) - .processRequests(optionsClone.fastTrack, new Processor() { + PsiSearchHelper.SERVICE.getInstance(project) + .processRequests(optionsClone.fastTrack, ref -> { + UsageInfo info = ApplicationManager.getApplication().runReadAction(new Computable() { @Override - public boolean process(final PsiReference ref) { - UsageInfo info = ApplicationManager.getApplication().runReadAction(new Computable() { - @Override - public UsageInfo compute() { - if (!ref.getElement().isValid()) return null; - return new UsageInfo(ref); - } - }); - return info == null || usageInfoProcessor.process(info); + public UsageInfo compute() { + if (!ref.getElement().isValid()) return null; + return new UsageInfo(ref); } }); - } - finally { - optionsClone.fastTrack = null; - } + return info == null || usageInfoProcessor.process(info); + }); + } + finally { + optionsClone.fastTrack = null; } }; } @@ -417,11 +401,8 @@ public class FindUsagesManager { private static PsiElement2UsageTargetAdapter[] convertToUsageTargets(@NotNull Iterable elementsToSearch, @NotNull final FindUsagesOptions findUsagesOptions) { final List targets = ContainerUtil.map(elementsToSearch, - new Function() { - @Override - public PsiElement2UsageTargetAdapter fun(PsiElement element) { - return convertToUsageTarget(element, findUsagesOptions); - } + element -> { + return convertToUsageTarget(element, findUsagesOptions); }); return targets.toArray(new PsiElement2UsageTargetAdapter[targets.size()]); } @@ -436,12 +417,8 @@ public class FindUsagesManager { } Iterable allElements = ContainerUtil.concat(primaryElements, secondaryElements); final PsiElement2UsageTargetAdapter[] targets = convertToUsageTargets(allElements, findUsagesOptions); - myAnotherManager.searchAndShowUsages(targets, new Factory() { - @Override - public UsageSearcher create() { - return createUsageSearcher(primaryElements, secondaryElements, handler, findUsagesOptions, null); - } - }, !toSkipUsagePanelWhenOneUsage, true, createPresentation(primaryElements[0], findUsagesOptions, shouldOpenInNewTab()), null); + myAnotherManager.searchAndShowUsages(targets, + () -> createUsageSearcher(primaryElements, secondaryElements, handler, findUsagesOptions, null), !toSkipUsagePanelWhenOneUsage, true, createPresentation(primaryElements[0], findUsagesOptions, shouldOpenInNewTab()), null); myHistory.add(targets[0]); } @@ -571,41 +548,38 @@ public class FindUsagesManager { final FileSearchScope direction = dir; - final AtomicReference foundUsage = new AtomicReference(); - usageSearcher.generate(new Processor() { - @Override - public boolean process(Usage usage) { - usagesWereFound.set(true); - if (direction == FileSearchScope.FROM_START) { - foundUsage.compareAndSet(null, usage); + final AtomicReference foundUsage = new AtomicReference<>(); + usageSearcher.generate(usage -> { + usagesWereFound.set(true); + if (direction == FileSearchScope.FROM_START) { + foundUsage.compareAndSet(null, usage); + return false; + } + if (direction == FileSearchScope.FROM_END) { + foundUsage.set(usage); + } + else if (direction == FileSearchScope.AFTER_CARET) { + if (Comparing.compare(usage.getLocation(), currentLocation) > 0) { + foundUsage.set(usage); return false; } - if (direction == FileSearchScope.FROM_END) { - foundUsage.set(usage); - } - else if (direction == FileSearchScope.AFTER_CARET) { - if (Comparing.compare(usage.getLocation(), currentLocation) > 0) { - foundUsage.set(usage); - return false; - } - } - else if (direction == FileSearchScope.BEFORE_CARET) { - if (Comparing.compare(usage.getLocation(), currentLocation) >= 0) { - return false; - } - while (true) { - Usage found = foundUsage.get(); - if (found == null) { - if (foundUsage.compareAndSet(null, usage)) break; - } - else { - if (Comparing.compare(found.getLocation(), usage.getLocation()) < 0 && foundUsage.compareAndSet(found, usage)) break; - } - } - } - - return true; } + else if (direction == FileSearchScope.BEFORE_CARET) { + if (Comparing.compare(usage.getLocation(), currentLocation) >= 0) { + return false; + } + while (true) { + Usage found = foundUsage.get(); + if (found == null) { + if (foundUsage.compareAndSet(null, usage)) break; + } + else { + if (Comparing.compare(found.getLocation(), usage.getLocation()) < 0 && foundUsage.compareAndSet(found, usage)) break; + } + } + } + + return true; }); fileEditor.putUserData(KEY_START_USAGE_AGAIN, null); diff --git a/platform/lang-impl/src/com/intellij/ide/actions/TogglePopupHintsAction.java b/platform/lang-impl/src/com/intellij/ide/actions/TogglePopupHintsAction.java index 7a27b8ea315e..a731d901b635 100644 --- a/platform/lang-impl/src/com/intellij/ide/actions/TogglePopupHintsAction.java +++ b/platform/lang-impl/src/com/intellij/ide/actions/TogglePopupHintsAction.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2009 JetBrains s.r.o. + * Copyright 2000-2016 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. @@ -14,9 +14,6 @@ * limitations under the License. */ -/** - * @author Vladimir Kondratyev - */ package com.intellij.ide.actions; import com.intellij.codeInsight.daemon.DaemonCodeAnalyzer; @@ -25,7 +22,6 @@ import com.intellij.openapi.actionSystem.AnAction; import com.intellij.openapi.actionSystem.AnActionEvent; import com.intellij.openapi.actionSystem.CommonDataKeys; import com.intellij.openapi.actionSystem.DataContext; -import com.intellij.openapi.actionSystem.PlatformDataKeys; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.fileEditor.FileEditorManager; import com.intellij.openapi.project.Project; 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 15be726409f4..ccbfc7922a85 100644 --- a/platform/lang-impl/src/com/intellij/ide/bookmarks/Bookmark.java +++ b/platform/lang-impl/src/com/intellij/ide/bookmarks/Bookmark.java @@ -65,7 +65,7 @@ public class Bookmark implements Navigatable, Comparable { public static final Icon DEFAULT_ICON = new MyCheckedIcon(); private final VirtualFile myFile; - @NotNull private final OpenFileDescriptor myTarget; + @NotNull private OpenFileDescriptor myTarget; private final Project myProject; private String myDescription; @@ -90,7 +90,7 @@ public class Bookmark implements Navigatable, Comparable { if (i != 0) return i; i = myFile.getName().compareTo(o.getFile().getName()); if (i != 0) return i; - return myTarget.compareTo(o.myTarget); + return getTarget().compareTo(o.getTarget()); } public void updateHighlighter() { @@ -161,8 +161,8 @@ public class Bookmark implements Navigatable, Comparable { if (document == null) return null; MarkupModelEx markup = (MarkupModelEx)DocumentMarkupModel.forDocument(document, myProject, true); final Document markupDocument = markup.getDocument(); - final int startOffset = markupDocument.getLineStartOffset(0); - final int endOffset = markupDocument.getLineEndOffset(markupDocument.getLineCount() - 1); + final int startOffset = 0; + final int endOffset = markupDocument.getTextLength(); final Ref found = new Ref(); markup.processRangeHighlightersOverlappingWith(startOffset, endOffset, new Processor() { @@ -213,23 +213,26 @@ public class Bookmark implements Navigatable, Comparable { if (!getFile().isValid()) { return false; } + if (getLine() ==-1) { + return true; + } RangeHighlighterEx highlighter = findMyHighlighter(); return highlighter != null && highlighter.isValid(); } @Override public boolean canNavigate() { - return myTarget.canNavigate(); + return getTarget().canNavigate(); } @Override public boolean canNavigateToSource() { - return myTarget.canNavigateToSource(); + return getTarget().canNavigateToSource(); } @Override public void navigate(boolean requestFocus) { - myTarget.navigate(requestFocus); + getTarget().navigate(requestFocus); } public int getLine() { @@ -251,6 +254,14 @@ public class Bookmark implements Navigatable, Comparable { return targetLine; } + private OpenFileDescriptor getTarget() { + int line = getLine(); + if (line != myTarget.getLine()) { + myTarget = new OpenFileDescriptor(myProject, myFile, line, -1, true); + } + return myTarget; + } + @Override public String toString() { StringBuilder result = new StringBuilder(getQualifiedName()); 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 c3588e65d797..acfa80c3feed 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 @@ -27,6 +27,7 @@ import com.intellij.openapi.project.DumbAware; import com.intellij.openapi.project.Project; import com.intellij.openapi.ui.popup.JBPopup; import com.intellij.openapi.ui.popup.PopupChooserBuilder; +import com.intellij.openapi.util.Comparing; import com.intellij.openapi.util.DimensionService; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.openapi.wm.IdeFocusManager; @@ -67,7 +68,10 @@ public class BookmarksAction extends AnAction implements DumbAware, MasterDetail final Project project = e.getProject(); if (project == null) return; - if (myPopup != null && myPopup.isVisible()) return; + if (myPopup != null && myPopup.isVisible()) { + myPopup.cancel(); + return; + } final JBList list = new JBList(buildModel(project)); @@ -246,14 +250,24 @@ public class BookmarksAction extends AnAction implements DumbAware, MasterDetail myLine = -1; BookmarkManager bookmarkManager = BookmarkManager.getInstance(myProject); - if (ToolWindowManager.getInstance(myProject).isEditorComponentActive()) { - Editor editor = CommonDataKeys.EDITOR.getData(myDataContext); - if (editor != null) { + Editor editor = CommonDataKeys.EDITOR.getData(myDataContext); + if (editor != null) { + if (ToolWindowManager.getInstance(myProject).isEditorComponentActive()) { Document document = editor.getDocument(); myLine = editor.getCaretModel().getLogicalPosition().line; myFile = FileDocumentManager.getInstance().getFile(document); myBookmarkAtPlace = bookmarkManager.findEditorBookmark(document, myLine); } + else { + myFile = CommonDataKeys.VIRTUAL_FILE.getData(myDataContext); + if (myFile != null) { + Document document = editor.getDocument(); + if (Comparing.equal(myFile, FileDocumentManager.getInstance().getFile(document))) { + myLine = editor.getCaretModel().getLogicalPosition().line; + myBookmarkAtPlace = bookmarkManager.findEditorBookmark(document, myLine); + } + } + } } if (myFile == null) { diff --git a/platform/lang-impl/src/com/intellij/ide/extensionResources/ExtensionsRootType.java b/platform/lang-impl/src/com/intellij/ide/extensionResources/ExtensionsRootType.java index 6b4fa1225cf6..c0c70cc9ae56 100644 --- a/platform/lang-impl/src/com/intellij/ide/extensionResources/ExtensionsRootType.java +++ b/platform/lang-impl/src/com/intellij/ide/extensionResources/ExtensionsRootType.java @@ -152,11 +152,12 @@ public class ExtensionsRootType extends RootType { private File findExtensionsDirectoryImpl(@NotNull PluginId pluginId, @NotNull String path, boolean createIfMissing) throws IOException { String fullPath = getPath(pluginId, path); File dir = new File(FileUtil.toSystemDependentName(fullPath)); - if (createIfMissing && !dir.exists()) { - //noinspection ResultOfMethodCallIgnored - dir.mkdirs(); + if (createIfMissing && !dir.exists() && !dir.mkdirs()) { + throw new IOException("Failed to create directory: " + dir.getPath()); } - return dir.exists() && dir.isDirectory()? dir : null; + if (!dir.exists()) return null; + if (!dir.isDirectory()) throw new IOException("Not a directory: " + dir.getPath()); + return dir; } @Nullable diff --git a/platform/lang-impl/src/com/intellij/ide/fileTemplates/FileTemplateManager.java b/platform/lang-impl/src/com/intellij/ide/fileTemplates/FileTemplateManager.java index 0f3ffc83935a..ea9c47b2be76 100644 --- a/platform/lang-impl/src/com/intellij/ide/fileTemplates/FileTemplateManager.java +++ b/platform/lang-impl/src/com/intellij/ide/fileTemplates/FileTemplateManager.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2014 JetBrains s.r.o. + * Copyright 2000-2016 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. @@ -93,8 +93,9 @@ public abstract class FileTemplateManager{ @NotNull public abstract Properties getDefaultProperties(); - @Deprecated /** Use {@link #getDefaultProperties()} instead */ + /** Use {@link #getDefaultProperties()} instead */ @NotNull + @Deprecated public Properties getDefaultProperties(@NotNull Project project) { Properties properties = getDefaultProperties(); properties.setProperty(PROJECT_NAME_VARIABLE, project.getName()); diff --git a/platform/lang-impl/src/com/intellij/ide/projectView/actions/MoveModulesOutsideGroupAction.java b/platform/lang-impl/src/com/intellij/ide/projectView/actions/MoveModulesOutsideGroupAction.java index c5b9df3c8a02..48473fd5a703 100644 --- a/platform/lang-impl/src/com/intellij/ide/projectView/actions/MoveModulesOutsideGroupAction.java +++ b/platform/lang-impl/src/com/intellij/ide/projectView/actions/MoveModulesOutsideGroupAction.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2009 JetBrains s.r.o. + * Copyright 2000-2016 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. @@ -14,9 +14,6 @@ * limitations under the License. */ -/** - * @author cdr - */ package com.intellij.ide.projectView.actions; import com.intellij.ide.IdeBundle; diff --git a/platform/lang-impl/src/com/intellij/ide/projectView/actions/MoveModulesToGroupAction.java b/platform/lang-impl/src/com/intellij/ide/projectView/actions/MoveModulesToGroupAction.java index 16ba0d5645f6..86629502bb34 100644 --- a/platform/lang-impl/src/com/intellij/ide/projectView/actions/MoveModulesToGroupAction.java +++ b/platform/lang-impl/src/com/intellij/ide/projectView/actions/MoveModulesToGroupAction.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2009 JetBrains s.r.o. + * Copyright 2000-2016 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. @@ -14,9 +14,6 @@ * limitations under the License. */ -/** - * @author cdr - */ package com.intellij.ide.projectView.actions; import com.intellij.ide.IdeBundle; diff --git a/platform/lang-impl/src/com/intellij/ide/projectView/actions/MoveModulesToSubGroupAction.java b/platform/lang-impl/src/com/intellij/ide/projectView/actions/MoveModulesToSubGroupAction.java index e6c022e97749..c3aab4b8f1ab 100644 --- a/platform/lang-impl/src/com/intellij/ide/projectView/actions/MoveModulesToSubGroupAction.java +++ b/platform/lang-impl/src/com/intellij/ide/projectView/actions/MoveModulesToSubGroupAction.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2009 JetBrains s.r.o. + * Copyright 2000-2016 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. @@ -14,9 +14,6 @@ * limitations under the License. */ -/** - * @author cdr - */ package com.intellij.ide.projectView.actions; import com.intellij.ide.IdeBundle; diff --git a/platform/lang-impl/src/com/intellij/ide/projectView/impl/AbstractProjectViewPSIPane.java b/platform/lang-impl/src/com/intellij/ide/projectView/impl/AbstractProjectViewPSIPane.java index ba94527576a1..77582269d90a 100644 --- a/platform/lang-impl/src/com/intellij/ide/projectView/impl/AbstractProjectViewPSIPane.java +++ b/platform/lang-impl/src/com/intellij/ide/projectView/impl/AbstractProjectViewPSIPane.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2015 JetBrains s.r.o. + * Copyright 2000-2016 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. @@ -14,9 +14,6 @@ * limitations under the License. */ -/** - * @author cdr - */ package com.intellij.ide.projectView.impl; import com.intellij.ide.DataManager; diff --git a/platform/lang-impl/src/com/intellij/ide/projectView/impl/AbstractProjectViewPane.java b/platform/lang-impl/src/com/intellij/ide/projectView/impl/AbstractProjectViewPane.java index 64d245d4512e..ba2df7a215de 100644 --- a/platform/lang-impl/src/com/intellij/ide/projectView/impl/AbstractProjectViewPane.java +++ b/platform/lang-impl/src/com/intellij/ide/projectView/impl/AbstractProjectViewPane.java @@ -14,9 +14,6 @@ * limitations under the License. */ -/** - * @author cdr - */ package com.intellij.ide.projectView.impl; import com.intellij.ide.DataManager; diff --git a/platform/lang-impl/src/com/intellij/ide/projectView/impl/ModuleGroup.java b/platform/lang-impl/src/com/intellij/ide/projectView/impl/ModuleGroup.java index 11f20f4736f1..cc6930c1efd4 100644 --- a/platform/lang-impl/src/com/intellij/ide/projectView/impl/ModuleGroup.java +++ b/platform/lang-impl/src/com/intellij/ide/projectView/impl/ModuleGroup.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2013 JetBrains s.r.o. + * Copyright 2000-2016 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. @@ -14,12 +14,12 @@ * limitations under the License. */ -/** - * @author cdr - */ package com.intellij.ide.projectView.impl; -import com.intellij.openapi.actionSystem.*; +import com.intellij.openapi.actionSystem.CommonDataKeys; +import com.intellij.openapi.actionSystem.DataContext; +import com.intellij.openapi.actionSystem.DataKey; +import com.intellij.openapi.actionSystem.LangDataKeys; import com.intellij.openapi.module.ModifiableModuleModel; import com.intellij.openapi.module.Module; import com.intellij.openapi.module.ModuleManager; diff --git a/platform/lang-impl/src/com/intellij/ide/projectView/impl/MoveModuleToGroup.java b/platform/lang-impl/src/com/intellij/ide/projectView/impl/MoveModuleToGroup.java index a3264d2fcbbe..f385c35cf3f4 100644 --- a/platform/lang-impl/src/com/intellij/ide/projectView/impl/MoveModuleToGroup.java +++ b/platform/lang-impl/src/com/intellij/ide/projectView/impl/MoveModuleToGroup.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2009 JetBrains s.r.o. + * Copyright 2000-2016 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. @@ -14,9 +14,6 @@ * limitations under the License. */ -/** - * @author cdr - */ package com.intellij.ide.projectView.impl; import com.intellij.ide.IdeBundle; diff --git a/platform/lang-impl/src/com/intellij/ide/projectView/impl/MoveModuleToGroupTopLevel.java b/platform/lang-impl/src/com/intellij/ide/projectView/impl/MoveModuleToGroupTopLevel.java index 28c3d9d81836..4f7e3a77c9c8 100644 --- a/platform/lang-impl/src/com/intellij/ide/projectView/impl/MoveModuleToGroupTopLevel.java +++ b/platform/lang-impl/src/com/intellij/ide/projectView/impl/MoveModuleToGroupTopLevel.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2013 JetBrains s.r.o. + * Copyright 2000-2016 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. @@ -14,9 +14,6 @@ * limitations under the License. */ -/** - * @author cdr - */ package com.intellij.ide.projectView.impl; import com.intellij.ide.projectView.actions.MoveModulesOutsideGroupAction; diff --git a/platform/lang-impl/src/com/intellij/ide/projectView/impl/ProjectViewPane.java b/platform/lang-impl/src/com/intellij/ide/projectView/impl/ProjectViewPane.java index 52c17502e4a7..59a5574c2b21 100644 --- a/platform/lang-impl/src/com/intellij/ide/projectView/impl/ProjectViewPane.java +++ b/platform/lang-impl/src/com/intellij/ide/projectView/impl/ProjectViewPane.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2013 JetBrains s.r.o. + * Copyright 2000-2016 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. @@ -14,9 +14,6 @@ * limitations under the License. */ -/** - * @author cdr - */ package com.intellij.ide.projectView.impl; import com.intellij.icons.AllIcons; diff --git a/platform/lang-impl/src/com/intellij/ide/script/IdeStartupScripts.java b/platform/lang-impl/src/com/intellij/ide/script/IdeStartupScripts.java index 63fe343d6419..6c56d61f7a50 100644 --- a/platform/lang-impl/src/com/intellij/ide/script/IdeStartupScripts.java +++ b/platform/lang-impl/src/com/intellij/ide/script/IdeStartupScripts.java @@ -21,6 +21,7 @@ import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.components.ApplicationComponent; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.extensions.PluginId; +import com.intellij.openapi.progress.ProcessCanceledException; import com.intellij.openapi.project.Project; import com.intellij.openapi.project.ProjectManager; import com.intellij.openapi.project.ProjectManagerAdapter; @@ -30,7 +31,6 @@ import com.intellij.openapi.util.text.StringUtil; import com.intellij.openapi.vfs.VfsUtil; import com.intellij.openapi.vfs.VfsUtilCore; import com.intellij.openapi.vfs.VirtualFile; -import com.intellij.util.Function; import com.intellij.util.ObjectUtils; import com.intellij.util.containers.ContainerUtil; import org.jetbrains.annotations.NotNull; @@ -41,157 +41,128 @@ import org.jetbrains.ide.script.IdeScriptEngineManager; import org.jetbrains.ide.script.IdeScriptException; import java.io.IOException; -import java.util.Comparator; import java.util.List; -import java.util.concurrent.Callable; import java.util.concurrent.ExecutionException; import java.util.concurrent.Future; import java.util.concurrent.atomic.AtomicBoolean; class IdeStartupScripts extends ApplicationComponent.Adapter { - @SuppressWarnings("FieldCanBeLocal") - private static String SCRIPT_DIR_NAME = "startup"; - - private static Logger LOG = Logger.getInstance(IdeStartupScripts.class); + private static final Logger LOG = Logger.getInstance(IdeStartupScripts.class); + private static final String SCRIPT_DIR_NAME = "startup"; @Override public void initComponent() { - if (ApplicationManager.getApplication().isUnitTestMode()) { - return; - } + if (ApplicationManager.getApplication().isUnitTestMode()) return; - List scripts = getScripts(); - if (scripts.isEmpty()) { - LOG.debug("No startup scripts detected"); - } - else { - scheduleStartupScriptsExecution(scripts); - } + scheduleStartupScriptsExecution(); } - private static void scheduleStartupScriptsExecution(@NotNull List scripts) { + private static void scheduleStartupScriptsExecution() { + List scripts = getScripts(); + LOG.info(scripts.size() + " startup script(s) found"); + if (scripts.isEmpty()) return; + final Future>> scriptsAndEnginesFuture = prepareScriptEnginesAsync(scripts); ProjectManager.getInstance().addProjectManagerListener(new ProjectManagerAdapter() { - private final AtomicBoolean myScriptsExecutionStarted = new AtomicBoolean(); + final AtomicBoolean myScriptsExecutionStarted = new AtomicBoolean(); @Override public void projectOpened(final Project project) { - StartupManager.getInstance(project).runWhenProjectIsInitialized(new Runnable() { - @Override - public void run() { - if (myScriptsExecutionStarted.compareAndSet(false, true)) { - executeScriptsAndDispose(project); - } - } + StartupManager.getInstance(project).runWhenProjectIsInitialized(() -> { + if (project.isDisposed()) return; + if (!myScriptsExecutionStarted.compareAndSet(false, true)) return; + ProjectManager.getInstance().removeProjectManagerListener(this); + runAllScriptsImpl(project); }); } - private void executeScriptsAndDispose(@NotNull Project project) { - for (Pair scriptAndEngine : getScriptsAndEngines()) { - executeScript(project.isDisposed() ? null : project, scriptAndEngine.first, scriptAndEngine.second); - } - ProjectManager.getInstance().removeProjectManagerListener(this); - } - - @NotNull - private List> getScriptsAndEngines() { + private void runAllScriptsImpl(@NotNull Project project) { try { - return scriptsAndEnginesFuture.get(); + for (Pair pair : scriptsAndEnginesFuture.get()) { + try { + if (pair.second == null) { + LOG.warn(pair.first.getPath() + " not supported (no script engine)"); + } + else { + runImpl(project, pair.first, pair.second); + } + } + catch (Exception e) { + LOG.warn(e); + } + } + } + catch (ProcessCanceledException e) { + LOG.warn("... cancelled"); } catch (InterruptedException e) { - LOG.info("Script engines initialization cancelled"); + LOG.warn("... interrupted"); } - catch (ExecutionException e) { - LOG.error("Failed to initialize script engines", e); + catch (Exception e) { + LOG.error(e); } - return ContainerUtil.emptyList(); } }); } @NotNull private static Future>> prepareScriptEnginesAsync(@NotNull final List scripts) { - return PooledThreadExecutor.INSTANCE.submit(new Callable>>() { - @Override - public List> call() throws Exception { - return prepareScriptEngines(scripts); - } - }); + return PooledThreadExecutor.INSTANCE.submit(() -> prepareScriptEngines(scripts)); } @NotNull - private static List> prepareScriptEngines(@NotNull final List scripts) { - final IdeScriptEngineManager scriptEngineManager = IdeScriptEngineManager.getInstance(); - return ContainerUtil.map(scripts, new Function>() { - @Override - public Pair fun(VirtualFile script) { - String extension = script.getExtension(); - return Pair.create(script, extension != null ? scriptEngineManager.getEngineForFileExtension(extension, null) : null); - } - }); + private static List> prepareScriptEngines(@NotNull List scripts) { + IdeScriptEngineManager scriptEngineManager = IdeScriptEngineManager.getInstance(); + List> result = ContainerUtil.newArrayList(); + for (VirtualFile script : scripts) { + String extension = script.getExtension(); + IdeScriptEngine engine = extension != null ? scriptEngineManager.getEngineForFileExtension(extension, null) : null; + result.add(Pair.create(script, engine)); + } + return result; } - private static void executeScript(@Nullable Project project, @NotNull VirtualFile script, @Nullable IdeScriptEngine scriptEngine) { - if (scriptEngine == null) { - LOG.warn("No script engine found for script: " + script.getPath()); - return; - } - - String scriptText; - try { - scriptText = VfsUtilCore.loadText(script); - } - catch (IOException e) { - LOG.warn("Cannot load script: " + script.getPath(), e); - return; - } - - IdeScriptBindings.ensureIdeIsBound(project, scriptEngine); + private static void runImpl(@NotNull Project project, + @NotNull VirtualFile script, + @NotNull IdeScriptEngine engine) throws ExecutionException, IOException, IdeScriptException { + String scriptText = VfsUtilCore.loadText(script); + IdeScriptBindings.ensureIdeIsBound(project, engine); + LOG.info(script.getPath()); long start = System.currentTimeMillis(); try { - LOG.info("Running script: " + script.getPath()); - scriptEngine.eval(scriptText); - } - catch (IdeScriptException e) { - LOG.error("Error in script: " + script.getPath(), e); + engine.eval(scriptText); } finally { - long end = System.currentTimeMillis(); - LOG.info(script.getPath() + " completed in " + (end - start) + " ms"); + LOG.info("... completed in " + StringUtil.formatDuration(System.currentTimeMillis() - start)); } } @NotNull private static List getScripts() { - VirtualFile root = getScriptsRootDirectory(); + VirtualFile root = null; + try { + root = getScriptsRootDirectory(); + } + catch (IOException e) { + LOG.warn(e); + } if (root == null) return ContainerUtil.emptyList(); VfsUtil.markDirtyAndRefresh(false, true, true, root); List scripts = VfsUtil.collectChildrenRecursively(root); scripts = ContainerUtil.filter(scripts, ExtensionsRootType.regularFileFilter()); - ContainerUtil.sort(scripts, new FileNameComparator()); + ContainerUtil.sort(scripts, (f1, f2) -> { + String f1Name = f1 != null ? f1.getName() : null; + String f2Name = f2 != null ? f2.getName() : null; + return StringUtil.compare(f1Name, f2Name, false); + }); return scripts; } @Nullable - private static VirtualFile getScriptsRootDirectory() { - try { - PluginId corePlugin = ObjectUtils.assertNotNull(PluginId.findId(PluginManagerCore.CORE_PLUGIN_ID)); - return ExtensionsRootType.getInstance().findResourceDirectory(corePlugin, SCRIPT_DIR_NAME, false); - } - catch (IOException e) { - LOG.warn("Failed to open/create startup scripts directory", e); - } - return null; - } - - private static class FileNameComparator implements Comparator { - @Override - public int compare(VirtualFile f1, VirtualFile f2) { - String f1Name = f1 != null ? f1.getName() : null; - String f2Name = f2 != null ? f2.getName() : null; - return StringUtil.compare(f1Name, f2Name, false); - } + private static VirtualFile getScriptsRootDirectory() throws IOException { + PluginId corePlugin = ObjectUtils.assertNotNull(PluginId.findId(PluginManagerCore.CORE_PLUGIN_ID)); + return ExtensionsRootType.getInstance().findResourceDirectory(corePlugin, SCRIPT_DIR_NAME, false); } } diff --git a/platform/lang-impl/src/com/intellij/ide/structureView/newStructureView/StructureTreeBuilder.java b/platform/lang-impl/src/com/intellij/ide/structureView/newStructureView/StructureTreeBuilder.java index c7b1dc708606..65441460a689 100644 --- a/platform/lang-impl/src/com/intellij/ide/structureView/newStructureView/StructureTreeBuilder.java +++ b/platform/lang-impl/src/com/intellij/ide/structureView/newStructureView/StructureTreeBuilder.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2014 JetBrains s.r.o. + * Copyright 2000-2016 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. @@ -166,7 +166,6 @@ public class StructureTreeBuilder extends AbstractTreeBuilder { @Override public void childReplaced(@NotNull PsiTreeChangeEvent event) { - /** Test comment */ PsiElement oldChild = event.getOldChild(); PsiElement newChild = event.getNewChild(); if (oldChild instanceof PsiWhiteSpace && newChild instanceof PsiWhiteSpace) return; //optimization diff --git a/platform/lang-impl/src/com/intellij/ide/todo/AllTodosTreeBuilder.java b/platform/lang-impl/src/com/intellij/ide/todo/AllTodosTreeBuilder.java index eeab60860582..92f27f6444df 100644 --- a/platform/lang-impl/src/com/intellij/ide/todo/AllTodosTreeBuilder.java +++ b/platform/lang-impl/src/com/intellij/ide/todo/AllTodosTreeBuilder.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2009 JetBrains s.r.o. + * Copyright 2000-2016 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. @@ -14,9 +14,6 @@ * limitations under the License. */ -/** - * @author Vladimir Kondratyev - */ package com.intellij.ide.todo; import com.intellij.openapi.project.Project; diff --git a/platform/lang-impl/src/com/intellij/ide/todo/ChangeListTodosTreeBuilder.java b/platform/lang-impl/src/com/intellij/ide/todo/ChangeListTodosTreeBuilder.java index 1ae869e530fa..85d46c379c24 100644 --- a/platform/lang-impl/src/com/intellij/ide/todo/ChangeListTodosTreeBuilder.java +++ b/platform/lang-impl/src/com/intellij/ide/todo/ChangeListTodosTreeBuilder.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2009 JetBrains s.r.o. + * Copyright 2000-2016 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. @@ -14,9 +14,6 @@ * limitations under the License. */ -/** - * @author Vladimir Kondratyev - */ package com.intellij.ide.todo; import com.intellij.openapi.project.Project; diff --git a/platform/lang-impl/src/com/intellij/ide/todo/ScopeBasedTodosTreeBuilder.java b/platform/lang-impl/src/com/intellij/ide/todo/ScopeBasedTodosTreeBuilder.java index 0dc79f911852..243bede1f246 100644 --- a/platform/lang-impl/src/com/intellij/ide/todo/ScopeBasedTodosTreeBuilder.java +++ b/platform/lang-impl/src/com/intellij/ide/todo/ScopeBasedTodosTreeBuilder.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2012 JetBrains s.r.o. + * Copyright 2000-2016 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. @@ -14,9 +14,6 @@ * limitations under the License. */ -/** - * @author Vladimir Kondratyev - */ package com.intellij.ide.todo; import com.intellij.ide.util.scopeChooser.ScopeChooserCombo; diff --git a/platform/lang-impl/src/com/intellij/ide/todo/TodoFileDirAndModuleComparator.java b/platform/lang-impl/src/com/intellij/ide/todo/TodoFileDirAndModuleComparator.java index 2394ab3ae6fa..c2dae9126c29 100644 --- a/platform/lang-impl/src/com/intellij/ide/todo/TodoFileDirAndModuleComparator.java +++ b/platform/lang-impl/src/com/intellij/ide/todo/TodoFileDirAndModuleComparator.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2009 JetBrains s.r.o. + * Copyright 2000-2016 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. @@ -14,9 +14,6 @@ * limitations under the License. */ -/** - * @author Vladimir Kondratyev - */ package com.intellij.ide.todo; import com.intellij.ide.projectView.ProjectViewNode; diff --git a/platform/lang-impl/src/com/intellij/internal/psiView/ViewerNodeDescriptor.java b/platform/lang-impl/src/com/intellij/internal/psiView/ViewerNodeDescriptor.java index 2ca4c1af2b5d..056ebf7d2fae 100644 --- a/platform/lang-impl/src/com/intellij/internal/psiView/ViewerNodeDescriptor.java +++ b/platform/lang-impl/src/com/intellij/internal/psiView/ViewerNodeDescriptor.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2009 JetBrains s.r.o. + * Copyright 2000-2016 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. @@ -14,11 +14,6 @@ * limitations under the License. */ -/** - * class ViewerNodeDescriptor - * created Aug 25, 2001 - * @author Jeka - */ package com.intellij.internal.psiView; import com.intellij.ide.util.treeView.NodeDescriptor; diff --git a/platform/lang-impl/src/com/intellij/internal/psiView/ViewerTreeBuilder.java b/platform/lang-impl/src/com/intellij/internal/psiView/ViewerTreeBuilder.java index 64f6ad07361c..702625819afc 100644 --- a/platform/lang-impl/src/com/intellij/internal/psiView/ViewerTreeBuilder.java +++ b/platform/lang-impl/src/com/intellij/internal/psiView/ViewerTreeBuilder.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2009 JetBrains s.r.o. + * Copyright 2000-2016 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. @@ -14,25 +14,18 @@ * limitations under the License. */ -/** - * class ViewerTreeBuilder - * created Aug 25, 2001 - * @author Jeka - */ package com.intellij.internal.psiView; import com.intellij.ide.util.treeView.AbstractTreeBuilder; -import com.intellij.ide.util.treeView.NodeDescriptor; import com.intellij.ide.util.treeView.IndexComparator; -import com.intellij.openapi.project.Project; import com.intellij.openapi.progress.ProgressIndicator; import com.intellij.openapi.progress.util.StatusBarProgress; +import com.intellij.openapi.project.Project; +import org.jetbrains.annotations.NotNull; import javax.swing.*; import javax.swing.tree.DefaultTreeModel; -import org.jetbrains.annotations.NotNull; - public class ViewerTreeBuilder extends AbstractTreeBuilder { public ViewerTreeBuilder(Project project, JTree tree) { super(tree, (DefaultTreeModel)tree.getModel(), new ViewerTreeStructure(project), IndexComparator.INSTANCE); diff --git a/platform/lang-impl/src/com/intellij/internal/psiView/ViewerTreeStructure.java b/platform/lang-impl/src/com/intellij/internal/psiView/ViewerTreeStructure.java index 48f1e2d4c506..5380bff0d4ad 100644 --- a/platform/lang-impl/src/com/intellij/internal/psiView/ViewerTreeStructure.java +++ b/platform/lang-impl/src/com/intellij/internal/psiView/ViewerTreeStructure.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2009 JetBrains s.r.o. + * Copyright 2000-2016 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. @@ -14,11 +14,6 @@ * limitations under the License. */ -/** - * class ViewerTreeStructure - * created Aug 25, 2001 - * @author Jeka - */ package com.intellij.internal.psiView; import com.intellij.ide.util.treeView.AbstractTreeStructure; diff --git a/platform/lang-impl/src/com/intellij/mock/MockPsiManager.java b/platform/lang-impl/src/com/intellij/mock/MockPsiManager.java index c1572ccb7941..0486377dd92a 100644 --- a/platform/lang-impl/src/com/intellij/mock/MockPsiManager.java +++ b/platform/lang-impl/src/com/intellij/mock/MockPsiManager.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2014 JetBrains s.r.o. + * Copyright 2000-2016 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. @@ -21,6 +21,7 @@ import com.intellij.openapi.project.Project; import com.intellij.openapi.util.Comparing; import com.intellij.openapi.util.Key; import com.intellij.openapi.vfs.VirtualFile; +import com.intellij.openapi.vfs.VirtualFileFilter; import com.intellij.psi.*; import com.intellij.psi.impl.PsiManagerEx; import com.intellij.psi.impl.PsiModificationTrackerImpl; @@ -35,7 +36,7 @@ import java.util.Map; public class MockPsiManager extends PsiManagerEx { private final Project myProject; - private final Map myDirectories = new THashMap(); + private final Map myDirectories = new THashMap<>(); private MockFileManager myMockFileManager; private PsiModificationTrackerImpl myPsiModificationTracker; @@ -185,4 +186,9 @@ public class MockPsiManager extends PsiManagerEx { @Override public void beforeChildAddition(@NotNull PsiTreeChangeEventImpl event) { } + + @Override + public void setAssertOnFileLoadingFilter(@NotNull VirtualFileFilter filter, @NotNull Disposable parentDisposable) { + + } } diff --git a/platform/lang-impl/src/com/intellij/openapi/roots/impl/OrderEntryUtil.java b/platform/lang-impl/src/com/intellij/openapi/roots/impl/OrderEntryUtil.java index c3099047ead0..2f349f7cd159 100644 --- a/platform/lang-impl/src/com/intellij/openapi/roots/impl/OrderEntryUtil.java +++ b/platform/lang-impl/src/com/intellij/openapi/roots/impl/OrderEntryUtil.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2009 JetBrains s.r.o. + * Copyright 2000-2016 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. @@ -14,9 +14,6 @@ * limitations under the License. */ -/** - * @author cdr - */ package com.intellij.openapi.roots.impl; import com.intellij.openapi.module.Module; diff --git a/platform/lang-impl/src/com/intellij/profile/codeInspection/ui/SingleInspectionProfilePanel.java b/platform/lang-impl/src/com/intellij/profile/codeInspection/ui/SingleInspectionProfilePanel.java index 01ab1f67dace..e9bf7ea4e0df 100644 --- a/platform/lang-impl/src/com/intellij/profile/codeInspection/ui/SingleInspectionProfilePanel.java +++ b/platform/lang-impl/src/com/intellij/profile/codeInspection/ui/SingleInspectionProfilePanel.java @@ -754,10 +754,10 @@ public class SingleInspectionProfilePanel extends JPanel { if (filter != null && !filter.isEmpty() && !isDescriptorAccepted(descriptor, filter, forceInclude, keySetList, quoted)) { continue; } - if (!emptyFilter && !myInspectionsFilter.matches(mySelectedProfile.getTools(toolDescriptors.getDefaultDescriptor().getKey().toString(), project))) { + final InspectionConfigTreeNode node = new InspectionConfigTreeNode(toolDescriptors); + if (!emptyFilter && !myInspectionsFilter.matches(mySelectedProfile.getTools(toolDescriptors.getDefaultDescriptor().getKey().toString(), project), node)) { continue; } - final InspectionConfigTreeNode node = new InspectionConfigTreeNode(toolDescriptors); getGroupNode(myRoot, toolDescriptors.getDefaultDescriptor().getGroup()).add(node); myRoot.dropCache(); } diff --git a/platform/lang-impl/src/com/intellij/profile/codeInspection/ui/filter/InspectionFilterAction.java b/platform/lang-impl/src/com/intellij/profile/codeInspection/ui/filter/InspectionFilterAction.java index ceafcf5c5d24..9db40ed9ea99 100644 --- a/platform/lang-impl/src/com/intellij/profile/codeInspection/ui/filter/InspectionFilterAction.java +++ b/platform/lang-impl/src/com/intellij/profile/codeInspection/ui/filter/InspectionFilterAction.java @@ -79,6 +79,7 @@ public class InspectionFilterAction extends DefaultActionGroup implements Toggle addAction(new ShowEnabledOrDisabledInspectionsAction(true)); addAction(new ShowEnabledOrDisabledInspectionsAction(false)); + addAction(new ShowOnlyModifiedInspectionsAction()); addSeparator(); final SortedSet severities = LevelChooserAction.getSeverities(mySeverityRegistrar); @@ -107,12 +108,7 @@ public class InspectionFilterAction extends DefaultActionGroup implements Toggle final DefaultActionGroup languageActionGroupParent = new DefaultActionGroup("Filter by Language", languages.size() >= MIN_LANGUAGE_COUNT_TO_WRAP); add(languageActionGroupParent); - Collections.sort(languages, new Comparator() { - @Override - public int compare(Language l1, Language l2) { - return l1.getDisplayName().compareTo(l2.getDisplayName()); - } - }); + Collections.sort(languages, (l1, l2) -> l1.getDisplayName().compareTo(l2.getDisplayName())); for (Language language : languages) { languageActionGroupParent.add(new LanguageFilterAction(language)); } @@ -251,7 +247,7 @@ public class InspectionFilterAction extends DefaultActionGroup implements Toggle (StringUtil.isEmptyOrSpaces(StringUtil.trimStart(ApplicationInfo.getInstance().getMinorVersion(),"0")) ? "" : "."+ApplicationInfo.getInstance().getMinorVersion()); private final String presentableVersion = ApplicationNamesInfo.getInstance().getProductName() + " " + version; - private class ShowNewInspectionsAction extends AnAction { + private class ShowNewInspectionsAction extends AnAction implements DumbAware { private ShowNewInspectionsAction() { super("Show New Inspections in " + presentableVersion, "Shows new inspections which are available since " + presentableVersion, @@ -263,4 +259,20 @@ public class InspectionFilterAction extends DefaultActionGroup implements Toggle myFilterComponent.setFilter("\"New in " + version + "\""); } } + + private class ShowOnlyModifiedInspectionsAction extends CheckboxAction implements DumbAware { + public ShowOnlyModifiedInspectionsAction() { + super("Show Only Modified Inspections"); + } + + @Override + public boolean isSelected(AnActionEvent e) { + return myInspectionsFilter.isShowOnlyModifiedInspections(); + } + + @Override + public void setSelected(AnActionEvent e, boolean state) { + myInspectionsFilter.setShowOnlyModifiedInspections(state); + } + } } \ No newline at end of file diff --git a/platform/lang-impl/src/com/intellij/profile/codeInspection/ui/filter/InspectionsFilter.java b/platform/lang-impl/src/com/intellij/profile/codeInspection/ui/filter/InspectionsFilter.java index 2e873bec81cc..afe2f175e77d 100644 --- a/platform/lang-impl/src/com/intellij/profile/codeInspection/ui/filter/InspectionsFilter.java +++ b/platform/lang-impl/src/com/intellij/profile/codeInspection/ui/filter/InspectionsFilter.java @@ -20,6 +20,7 @@ import com.intellij.codeInspection.ex.InspectionToolWrapper; import com.intellij.codeInspection.ex.ScopeToolState; import com.intellij.codeInspection.ex.Tools; import com.intellij.lang.annotation.HighlightSeverity; +import com.intellij.profile.codeInspection.ui.inspectionsTree.InspectionConfigTreeNode; import com.intellij.util.containers.HashSet; import org.jetbrains.annotations.Nullable; @@ -35,6 +36,7 @@ public abstract class InspectionsFilter { private Boolean mySuitableInspectionsStates; private boolean myAvailableOnlyForAnalyze; private boolean myShowOnlyCleanupInspections; + private boolean myShowOnlyModifiedInspections; public boolean isAvailableOnlyForAnalyze() { return myAvailableOnlyForAnalyze; @@ -61,6 +63,11 @@ public abstract class InspectionsFilter { filterChanged(); } + public void setShowOnlyModifiedInspections(boolean showOnlyModifiedInspections) { + myShowOnlyModifiedInspections = showOnlyModifiedInspections; + filterChanged(); + } + public void setAvailableOnlyForAnalyze(final boolean availableOnlyForAnalyze) { myAvailableOnlyForAnalyze = availableOnlyForAnalyze; filterChanged(); @@ -95,6 +102,7 @@ public abstract class InspectionsFilter { mySuitableInspectionsStates = null; myAvailableOnlyForAnalyze = false; myShowOnlyCleanupInspections = false; + myShowOnlyModifiedInspections = false; mySuitableSeverities.clear(); mySuitableLanguageIds.clear(); filterChanged(); @@ -104,11 +112,12 @@ public abstract class InspectionsFilter { return mySuitableInspectionsStates == null && !myAvailableOnlyForAnalyze && !myShowOnlyCleanupInspections + && !myShowOnlyModifiedInspections && mySuitableSeverities.isEmpty() && mySuitableLanguageIds.isEmpty(); } - public boolean matches(final Tools tools) { + public boolean matches(final Tools tools, final InspectionConfigTreeNode node) { if (myShowOnlyCleanupInspections && !tools.getTool().isCleanupTool()) { return false; } @@ -138,7 +147,12 @@ public abstract class InspectionsFilter { } final String languageId = tools.getDefaultState().getTool().getLanguage(); - return mySuitableLanguageIds.isEmpty() || mySuitableLanguageIds.contains(languageId); + final boolean containsInSuitableLanguages = mySuitableLanguageIds.isEmpty() || mySuitableLanguageIds.contains(languageId); + if (!containsInSuitableLanguages) { + return false; + } + + return !myShowOnlyModifiedInspections || node.isProperSetting(); } protected abstract void filterChanged(); @@ -147,4 +161,8 @@ public abstract class InspectionsFilter { final InspectionToolWrapper tool = tools.getTool(); return tool instanceof GlobalInspectionToolWrapper && ((GlobalInspectionToolWrapper)tool).worksInBatchModeOnly(); } + + public boolean isShowOnlyModifiedInspections() { + return myShowOnlyModifiedInspections; + } } \ No newline at end of file diff --git a/platform/lang-impl/src/com/intellij/psi/impl/file/impl/PsiVFSListener.java b/platform/lang-impl/src/com/intellij/psi/impl/file/impl/PsiVFSListener.java index 3f13fa015525..271708941e0a 100644 --- a/platform/lang-impl/src/com/intellij/psi/impl/file/impl/PsiVFSListener.java +++ b/platform/lang-impl/src/com/intellij/psi/impl/file/impl/PsiVFSListener.java @@ -610,8 +610,8 @@ public class PsiVFSListener extends VirtualFileAdapter { } private class MyModuleRootListener implements ModuleRootListener { - private VirtualFile[] myOldContentRoots = null; - private volatile int depthCounter = 0; + private VirtualFile[] myOldContentRoots; + private volatile int depthCounter; @Override public void beforeRootsChange(final ModuleRootEvent event) { if (!myFileManager.isInitialized()) return; diff --git a/platform/lang-impl/src/com/intellij/psi/stubs/StubTreeLoaderImpl.java b/platform/lang-impl/src/com/intellij/psi/stubs/StubTreeLoaderImpl.java index 252a75cd3647..d44abf71d787 100644 --- a/platform/lang-impl/src/com/intellij/psi/stubs/StubTreeLoaderImpl.java +++ b/platform/lang-impl/src/com/intellij/psi/stubs/StubTreeLoaderImpl.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2012 JetBrains s.r.o. + * Copyright 2000-2016 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. @@ -27,7 +27,6 @@ import com.intellij.openapi.util.RecursionManager; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.psi.PsiDocumentManager; import com.intellij.psi.PsiFile; -import com.intellij.psi.PsiManager; import com.intellij.psi.impl.PsiManagerEx; import com.intellij.psi.impl.source.PsiFileImpl; import com.intellij.psi.search.GlobalSearchScope; @@ -130,7 +129,7 @@ public class StubTreeLoaderImpl extends StubTreeLoader { if (vFile.getFileType().isBinary()) { return -1; } - PsiFile psiFile = ((PsiManagerEx)PsiManager.getInstance(project)).getFileManager().getCachedPsiFile(vFile); + PsiFile psiFile = PsiManagerEx.getInstanceEx(project).getFileManager().getCachedPsiFile(vFile); if (psiFile instanceof PsiFileImpl && ((PsiFileImpl)psiFile).isContentsLoaded()) { return psiFile.getTextLength(); } @@ -172,7 +171,7 @@ public class StubTreeLoaderImpl extends StubTreeLoader { VirtualFile file = virtualFile; int count = 0; for (Project project : ProjectManager.getInstance().getOpenProjects()) { - if (((PsiManagerEx)PsiManager.getInstance(project)).getFileManager().findCachedViewProvider(file) != null) { + if (PsiManagerEx.getInstanceEx(project).getFileManager().findCachedViewProvider(file) != null) { count++; } } diff --git a/platform/lang-impl/src/com/intellij/refactoring/actions/InlineAction.java b/platform/lang-impl/src/com/intellij/refactoring/actions/InlineAction.java index 6602c71749b4..bee1c3aaee1f 100644 --- a/platform/lang-impl/src/com/intellij/refactoring/actions/InlineAction.java +++ b/platform/lang-impl/src/com/intellij/refactoring/actions/InlineAction.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2009 JetBrains s.r.o. + * Copyright 2000-2016 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. @@ -14,11 +14,6 @@ * limitations under the License. */ -/** - * class InlineAction - * created Aug 28, 2001 - * @author Jeka - */ package com.intellij.refactoring.actions; import com.intellij.lang.Language; @@ -37,7 +32,6 @@ import com.intellij.refactoring.inline.InlineRefactoringActionHandler; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; -import java.util.Collections; import java.util.List; public class InlineAction extends BasePlatformRefactoringAction { diff --git a/platform/lang-impl/src/com/intellij/refactoring/inline/InlineRefactoringActionHandler.java b/platform/lang-impl/src/com/intellij/refactoring/inline/InlineRefactoringActionHandler.java index 84582f776261..0b6dd58e02cd 100644 --- a/platform/lang-impl/src/com/intellij/refactoring/inline/InlineRefactoringActionHandler.java +++ b/platform/lang-impl/src/com/intellij/refactoring/inline/InlineRefactoringActionHandler.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2009 JetBrains s.r.o. + * Copyright 2000-2016 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. @@ -14,10 +14,6 @@ * limitations under the License. */ -/** - * created at Nov 21, 2001 - * @author Jeka - */ package com.intellij.refactoring.inline; import com.intellij.ide.DataManager; @@ -26,8 +22,6 @@ import com.intellij.lang.refactoring.InlineHandler; import com.intellij.lang.refactoring.InlineHandlers; import com.intellij.openapi.actionSystem.CommonDataKeys; import com.intellij.openapi.actionSystem.DataContext; -import com.intellij.openapi.actionSystem.LangDataKeys; -import com.intellij.openapi.actionSystem.PlatformDataKeys; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.editor.Editor; import com.intellij.openapi.editor.ScrollType; diff --git a/platform/lang-impl/src/com/intellij/refactoring/introduceParameterObject/IntroduceParameterObjectClassDescriptor.java b/platform/lang-impl/src/com/intellij/refactoring/introduceParameterObject/IntroduceParameterObjectClassDescriptor.java index 61729453e934..211a7bc0c8f7 100644 --- a/platform/lang-impl/src/com/intellij/refactoring/introduceParameterObject/IntroduceParameterObjectClassDescriptor.java +++ b/platform/lang-impl/src/com/intellij/refactoring/introduceParameterObject/IntroduceParameterObjectClassDescriptor.java @@ -15,19 +15,59 @@ */ package com.intellij.refactoring.introduceParameterObject; +import com.intellij.codeInsight.highlighting.ReadWriteAccessDetector; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiNamedElement; import com.intellij.refactoring.changeSignature.ParameterInfo; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; +/** + * Describes parameter class to create or existing class, chosen to wrap parameters + */ public abstract class IntroduceParameterObjectClassDescriptor { + /** + * Class name to create/existing class short name + */ private final String myClassName; + /** + * Package name where class should be created/package name of the existing class. Won't be used if 'create inner class' option is chosen + */ private final String myPackageName; + + /** + * Flag to search for existing class with fqn: myPackageName.myClassName + */ private final boolean myUseExistingClass; + + /** + * Flag that inner class with name myClassName should be created in outer class: method.getContainingClass() + */ private final boolean myCreateInnerClass; + + /** + * Visibility for newly created class + */ private final String myNewVisibility; + + /** + * Flag to generate accessors for existing class when fields won't be accessible from new usages + */ private final boolean myGenerateAccessors; + + /** + * Bundle of method parameters which should correspond to the newly created/existing class fields + */ private final P[] myParamsToMerge; + + /** + * Store existing class found by fqn / created class in refactoring#performRefactoring + */ private PsiElement myExistingClass; + /** + * Detected compatible constructor of the existing class + */ + private M myExistingClassCompatibleConstructor; public IntroduceParameterObjectClassDescriptor(String className, String packageName, @@ -81,19 +121,32 @@ public abstract class IntroduceParameterObjectClassDescriptor> { - /** - * If language does not provide implicit accessors, then accessors must be generated based on usages of parameters inside method and it's overriders - */ - public enum Accessor { - /** - * Only read usages were detected - */ - Getter, - /** - * Write usages were detected. Currently it's assumed that if field requires setter, getter would be generated unconditionally - */ - Setter - } public static final LanguageExtension EP_NAME = new LanguageExtension("com.intellij.refactoring.introduceParameterObject"); @@ -128,29 +116,37 @@ public abstract class IntroduceParameterObjectDelegate method type of the original delegate * @param parameter info type of the original delegate * - * @return access level which is required for a parameter (@link {@link Accessor}) + * @return access level which is required for a parameter {@link ReadWriteAccessDetector.Access}. If write access is needed, both accessors are expected. */ @Nullable public abstract - Accessor collectInternalUsages(Collection usages, - M overridingMethod, - IntroduceParameterObjectClassDescriptor classDescriptor, - P1 parameterInfo, - String mergedParamName); + ReadWriteAccessDetector.Access collectInternalUsages(Collection usages, + M overridingMethod, + IntroduceParameterObjectClassDescriptor classDescriptor, + P1 parameterInfo, + String mergedParamName); /** - * Collect in usages accessibility fixes. + * Collect in usages fixes to generate field's accessors. * If {@link #collectInternalUsages(Collection, PsiNamedElement, IntroduceParameterObjectClassDescriptor, ParameterInfo, String)} - * did return @NotNull value, corresponding parameter requires some accessor. If current language doesn't provide implicitly accessors, - * then they should be generated according to the accessors[descriptor.getParamsToMerge()[paramIdx].getOldIdx()] + * returns @NotNull value, corresponding to the parameter field requires an accessor. + * + * To detect what accessor is required, use accessors[descriptor.getParamsToMerge()[paramIdx].getOldIdx()] */ - public abstract void collectAccessibilityUsages(Collection usages, - M method, - C descriptor, - Accessor[] accessors); + public abstract void collectUsagesToGenerateMissedFieldAccessors(Collection usages, + M method, + C descriptor, + ReadWriteAccessDetector.Access[] accessors); /** - * Collect conflicts in conflicts + * Collect in usages necessary fixes to change visibility, javadocs, etc + */ + public abstract void collectAdditionalFixes(Collection usages, + M method, + C descriptor); + + /** + * Collect conflicts in conflicts */ public abstract void collectConflicts(MultiMap conflicts, UsageInfo[] infos, M method, C classDescriptor); } diff --git a/platform/lang-impl/src/com/intellij/refactoring/introduceParameterObject/IntroduceParameterObjectProcessor.java b/platform/lang-impl/src/com/intellij/refactoring/introduceParameterObject/IntroduceParameterObjectProcessor.java index 8645fde3d0c4..8daf2ddb5a0f 100644 --- a/platform/lang-impl/src/com/intellij/refactoring/introduceParameterObject/IntroduceParameterObjectProcessor.java +++ b/platform/lang-impl/src/com/intellij/refactoring/introduceParameterObject/IntroduceParameterObjectProcessor.java @@ -15,6 +15,7 @@ */ package com.intellij.refactoring.introduceParameterObject; +import com.intellij.codeInsight.highlighting.ReadWriteAccessDetector; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.util.Ref; import com.intellij.psi.PsiElement; @@ -46,7 +47,7 @@ public class IntroduceParameterObjectProcessor myDelegate; - private final IntroduceParameterObjectDelegate.Accessor[] myAccessors; + private final ReadWriteAccessDetector.Access[] myAccessors; public IntroduceParameterObjectProcessor(M method, C classDescriptor, @@ -78,13 +79,13 @@ public class IntroduceParameterObjectProcessor usages) { if (myClassDescriptor.isUseExistingClass()) { - myClassDescriptor.initExistingClass(myMethod); + myClassDescriptor.setExistingClassCompatibleConstructor(myClassDescriptor.findCompatibleConstructorInExistingClass(myMethod)); } List methodHierarchy = new ArrayList<>(); methodHierarchy.add(myMethod); @@ -100,17 +101,20 @@ public class IntroduceParameterObjectProcessor * Implementations are supposed to override this method when overriding default behaviour for the language, * e.g. pushing members from groovy class to java, groovy could provide additional delegate which inherits delegate for java and accepts groovy sources. * Methods to process target class should be updated to cope with source of another language (e.g. calling super on PushDownData translated to java): - * {@link #checkTargetClassConflicts(PsiElement, PushDownData, MultiMap) }, + * {@link #checkTargetClassConflicts(PsiElement, PushDownData, MultiMap, NewSubClassData) }, * {@link #pushDownToClass(PsiElement, PushDownData)} */ protected abstract boolean isApplicableForSource(@NotNull PsiElement sourceClass); @@ -78,10 +78,13 @@ public abstract class PushDownDelegate * Collect conflicts inside targetClass assuming methods would be pushed, * e.g. check if target class already has field with the same name, some references types * won't be accessible anymore, etc + * + * If targetClass == null (target class should be created), then subClassData would be not null */ - protected abstract void checkTargetClassConflicts(PsiElement targetClass, + protected abstract void checkTargetClassConflicts(@Nullable PsiElement targetClass, PushDownData pushDownData, - MultiMap conflicts); + MultiMap conflicts, + @Nullable NewSubClassData subClassData); /** * Could be used e.g. to encode mutual references between moved members diff --git a/platform/lang-impl/src/com/intellij/refactoring/memberPushDown/PushDownProcessor.java b/platform/lang-impl/src/com/intellij/refactoring/memberPushDown/PushDownProcessor.java index eab53508ba7e..1f280b23da73 100644 --- a/platform/lang-impl/src/com/intellij/refactoring/memberPushDown/PushDownProcessor.java +++ b/platform/lang-impl/src/com/intellij/refactoring/memberPushDown/PushDownProcessor.java @@ -109,7 +109,7 @@ public class PushDownProcessor, } Runnable runnable = () -> ApplicationManager.getApplication().runReadAction(() -> { if (mySubClassData != null) { - myDelegate.checkTargetClassConflicts(null, myPushDownData, conflicts); + myDelegate.checkTargetClassConflicts(null, myPushDownData, conflicts, mySubClassData); } else { for (UsageInfo usage : usagesIn) { @@ -117,7 +117,7 @@ public class PushDownProcessor, if (element != null) { final PushDownDelegate delegate = PushDownDelegate.findDelegateForTarget(myPushDownData.getSourceClass(), element); if (delegate != null) { - delegate.checkTargetClassConflicts(element, myPushDownData, conflicts); + delegate.checkTargetClassConflicts(element, myPushDownData, conflicts, null); } else { conflicts.putValue(element, "Not supported source/target pair detected"); diff --git a/platform/lang-impl/src/com/intellij/refactoring/move/MoveCallback.java b/platform/lang-impl/src/com/intellij/refactoring/move/MoveCallback.java index 3bc1f1ab3821..08cdcf82f8fa 100644 --- a/platform/lang-impl/src/com/intellij/refactoring/move/MoveCallback.java +++ b/platform/lang-impl/src/com/intellij/refactoring/move/MoveCallback.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2009 JetBrains s.r.o. + * Copyright 2000-2016 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. @@ -14,14 +14,8 @@ * limitations under the License. */ -/** - * created at Nov 27, 2001 - * @author Jeka - */ package com.intellij.refactoring.move; -import org.jetbrains.annotations.Nullable; - public interface MoveCallback { void refactoringCompleted(); } diff --git a/platform/lang-impl/src/com/intellij/refactoring/move/MoveHandler.java b/platform/lang-impl/src/com/intellij/refactoring/move/MoveHandler.java index 05741af23893..749b0bdca88c 100644 --- a/platform/lang-impl/src/com/intellij/refactoring/move/MoveHandler.java +++ b/platform/lang-impl/src/com/intellij/refactoring/move/MoveHandler.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2009 JetBrains s.r.o. + * Copyright 2000-2016 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. @@ -14,10 +14,6 @@ * limitations under the License. */ -/** - * created at Nov 26, 2001 - * @author Jeka - */ package com.intellij.refactoring.move; import com.intellij.openapi.actionSystem.DataContext; diff --git a/platform/lang-impl/src/com/intellij/refactoring/move/MoveMemberViewDescriptor.java b/platform/lang-impl/src/com/intellij/refactoring/move/MoveMemberViewDescriptor.java index 7a67b1864dc0..f1b32885d0c6 100644 --- a/platform/lang-impl/src/com/intellij/refactoring/move/MoveMemberViewDescriptor.java +++ b/platform/lang-impl/src/com/intellij/refactoring/move/MoveMemberViewDescriptor.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2009 JetBrains s.r.o. + * Copyright 2000-2016 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. @@ -14,16 +14,12 @@ * limitations under the License. */ -/** - * created at Sep 11, 2001 - * @author Jeka - */ package com.intellij.refactoring.move; import com.intellij.psi.PsiElement; -import com.intellij.usageView.UsageViewDescriptor; -import com.intellij.usageView.UsageViewBundle; import com.intellij.refactoring.RefactoringBundle; +import com.intellij.usageView.UsageViewBundle; +import com.intellij.usageView.UsageViewDescriptor; import org.jetbrains.annotations.NotNull; public class MoveMemberViewDescriptor implements UsageViewDescriptor { diff --git a/platform/lang-impl/src/com/intellij/refactoring/move/MoveMultipleElementsViewDescriptor.java b/platform/lang-impl/src/com/intellij/refactoring/move/MoveMultipleElementsViewDescriptor.java index 8751c4f783d8..07ec83923285 100644 --- a/platform/lang-impl/src/com/intellij/refactoring/move/MoveMultipleElementsViewDescriptor.java +++ b/platform/lang-impl/src/com/intellij/refactoring/move/MoveMultipleElementsViewDescriptor.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2009 JetBrains s.r.o. + * Copyright 2000-2016 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. @@ -14,10 +14,6 @@ * limitations under the License. */ -/** - * created at Sep 17, 2001 - * @author Jeka - */ package com.intellij.refactoring.move; import com.intellij.openapi.util.text.StringUtil; diff --git a/platform/lang-impl/src/com/intellij/refactoring/safeDelete/UnsafeUsagesDialog.java b/platform/lang-impl/src/com/intellij/refactoring/safeDelete/UnsafeUsagesDialog.java index 2944ee9f172d..709ad66242e6 100644 --- a/platform/lang-impl/src/com/intellij/refactoring/safeDelete/UnsafeUsagesDialog.java +++ b/platform/lang-impl/src/com/intellij/refactoring/safeDelete/UnsafeUsagesDialog.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2015 JetBrains s.r.o. + * Copyright 2000-2016 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. @@ -14,10 +14,6 @@ * limitations under the License. */ -/** - * created at Sep 12, 2001 - * @author Jeka - */ package com.intellij.refactoring.safeDelete; import com.intellij.openapi.project.Project; 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 b91cc283a9eb..6f934fe443c8 100644 --- a/platform/lang-impl/src/com/intellij/refactoring/ui/ConflictsDialog.java +++ b/platform/lang-impl/src/com/intellij/refactoring/ui/ConflictsDialog.java @@ -14,10 +14,6 @@ * limitations under the License. */ -/** - * created at Sep 12, 2001 - * @author Jeka - */ package com.intellij.refactoring.ui; import com.intellij.codeInsight.highlighting.ReadWriteAccessDetector; diff --git a/platform/lang-impl/src/com/intellij/tools/FilterDialog.java b/platform/lang-impl/src/com/intellij/tools/FilterDialog.java index 6600c6d63c50..45bb0860b0f1 100644 --- a/platform/lang-impl/src/com/intellij/tools/FilterDialog.java +++ b/platform/lang-impl/src/com/intellij/tools/FilterDialog.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2015 JetBrains s.r.o. + * Copyright 2000-2016 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. @@ -14,9 +14,6 @@ * limitations under the License. */ -/** - * @author Yura Cangea - */ package com.intellij.tools; import com.intellij.CommonBundle; diff --git a/platform/lang-impl/src/com/intellij/tools/OutputFiltersDialog.java b/platform/lang-impl/src/com/intellij/tools/OutputFiltersDialog.java index 5f6ebe1f611c..3233028ed214 100644 --- a/platform/lang-impl/src/com/intellij/tools/OutputFiltersDialog.java +++ b/platform/lang-impl/src/com/intellij/tools/OutputFiltersDialog.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2015 JetBrains s.r.o. + * Copyright 2000-2016 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. @@ -14,9 +14,6 @@ * limitations under the License. */ -/** - * @author Yura Cangea - */ package com.intellij.tools; import com.intellij.openapi.help.HelpManager; diff --git a/platform/lang-impl/src/com/intellij/ui/ColorLineMarkerProvider.java b/platform/lang-impl/src/com/intellij/ui/ColorLineMarkerProvider.java index 6e1379a355e1..1b29a50cee65 100644 --- a/platform/lang-impl/src/com/intellij/ui/ColorLineMarkerProvider.java +++ b/platform/lang-impl/src/com/intellij/ui/ColorLineMarkerProvider.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2015 JetBrains s.r.o. + * Copyright 2000-2016 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. @@ -102,7 +102,7 @@ public final class ColorLineMarkerProvider implements LineMarkerProvider { @Override public Icon getCommonIcon(@NotNull List infos) { if (infos.size() == 2 && infos.get(0) instanceof MyInfo && infos.get(1) instanceof MyInfo) { - return new TwoColorsIcon(12, ((MyInfo)infos.get(1)).myColor, ((MyInfo)infos.get(0)).myColor); + return new TwoColorsIcon(12, ((MyInfo)infos.get(0)).myColor, ((MyInfo)infos.get(1)).myColor); } return AllIcons.Gutter.Colors; } diff --git a/platform/lang-impl/src/com/intellij/ui/popup/util/DetailViewImpl.java b/platform/lang-impl/src/com/intellij/ui/popup/util/DetailViewImpl.java index eaeba3187f01..e2e2ad06d014 100644 --- a/platform/lang-impl/src/com/intellij/ui/popup/util/DetailViewImpl.java +++ b/platform/lang-impl/src/com/intellij/ui/popup/util/DetailViewImpl.java @@ -149,6 +149,9 @@ public class DetailViewImpl extends JPanel implements DetailView, UserDataHolder getEditor().getCaretModel().moveToLogicalPosition(positionToNavigate); validate(); getEditor().getScrollingModel().scrollToCaret(ScrollType.CENTER); + } else { + revalidate(); + repaint(); } getEditor().setBorder(IdeBorderFactory.createBorder(SideBorder.TOP)); diff --git a/platform/lang-impl/src/com/intellij/unscramble/AnalyzeStacktraceUtil.java b/platform/lang-impl/src/com/intellij/unscramble/AnalyzeStacktraceUtil.java index edc2b6156d79..ddff95488b2c 100644 --- a/platform/lang-impl/src/com/intellij/unscramble/AnalyzeStacktraceUtil.java +++ b/platform/lang-impl/src/com/intellij/unscramble/AnalyzeStacktraceUtil.java @@ -39,7 +39,6 @@ import com.intellij.openapi.editor.EditorFactory; import com.intellij.openapi.editor.EditorSettings; import com.intellij.openapi.extensions.ExtensionPointName; import com.intellij.openapi.extensions.Extensions; -import com.intellij.openapi.ide.CopyPasteManager; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.Disposer; import com.intellij.openapi.util.text.StringUtil; @@ -49,7 +48,8 @@ import org.jetbrains.annotations.Nullable; import javax.swing.*; import java.awt.*; -import java.awt.datatransfer.DataFlavor; + +import static com.intellij.openapi.application.ex.ClipboardUtil.getTextInClipboard; /** * @author yole @@ -71,11 +71,6 @@ public class AnalyzeStacktraceUtil { } } - @Nullable - public static String getTextInClipboard() { - return CopyPasteManager.getInstance().getContents(DataFlavor.stringFlavor); - } - public interface ConsoleFactory { JComponent createConsoleComponent(ConsoleView consoleView, DefaultActionGroup toolbarActions); } diff --git a/platform/lang-impl/src/com/intellij/usageView/FindUsagesCommand.java b/platform/lang-impl/src/com/intellij/usageView/FindUsagesCommand.java index 38a8ab96152e..868adef25f0e 100644 --- a/platform/lang-impl/src/com/intellij/usageView/FindUsagesCommand.java +++ b/platform/lang-impl/src/com/intellij/usageView/FindUsagesCommand.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2009 JetBrains s.r.o. + * Copyright 2000-2016 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. @@ -14,10 +14,6 @@ * limitations under the License. */ -/** - * created at Oct 15, 2001 - * @author Jeka - */ package com.intellij.usageView; import com.intellij.psi.PsiElement; diff --git a/platform/lang-impl/src/com/intellij/util/indexing/ValueContainer.java b/platform/lang-impl/src/com/intellij/util/indexing/ValueContainer.java index 145388a3310a..983a4d257c63 100644 --- a/platform/lang-impl/src/com/intellij/util/indexing/ValueContainer.java +++ b/platform/lang-impl/src/com/intellij/util/indexing/ValueContainer.java @@ -84,7 +84,7 @@ public abstract class ValueContainer { return true; } - private volatile boolean myNeedsCompacting = false; + private volatile boolean myNeedsCompacting; boolean needsCompacting() { return myNeedsCompacting; diff --git a/platform/platform-api/src/com/intellij/ide/BrowserUtil.java b/platform/platform-api/src/com/intellij/ide/BrowserUtil.java index 129f41539ba9..526e6b336327 100644 --- a/platform/platform-api/src/com/intellij/ide/BrowserUtil.java +++ b/platform/platform-api/src/com/intellij/ide/BrowserUtil.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2014 JetBrains s.r.o. + * Copyright 2000-2016 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. @@ -80,11 +80,11 @@ public class BrowserUtil { browse(url.toExternalForm()); } - @SuppressWarnings("UnusedDeclaration") - @Deprecated /** * @deprecated Use {@link #browse(String)} */ + @SuppressWarnings("UnusedDeclaration") + @Deprecated public static void launchBrowser(@NotNull @NonNls String url) { browse(url); } diff --git a/platform/platform-api/src/com/intellij/ide/GeneralSettings.java b/platform/platform-api/src/com/intellij/ide/GeneralSettings.java index d5df3eafc71d..604a722f57f4 100644 --- a/platform/platform-api/src/com/intellij/ide/GeneralSettings.java +++ b/platform/platform-api/src/com/intellij/ide/GeneralSettings.java @@ -76,20 +76,20 @@ public class GeneralSettings implements PersistentStateComponent { } } - @Deprecated /** * @deprecated Use {@link com.intellij.ide.util.PropertiesComponent} */ + @Deprecated public void setExtendedState(String key, int extendedState) { myKey2ExtendedState.put(key, extendedState); } - @Deprecated /** * @deprecated Use {@link com.intellij.ide.util.PropertiesComponent} */ + @Deprecated public int getExtendedState(String key) { if (!myKey2ExtendedState.containsKey(key)) return -1; return myKey2ExtendedState.get(key); diff --git a/platform/platform-api/src/com/intellij/ui/ColorChooser.java b/platform/platform-api/src/com/intellij/ui/ColorChooser.java index 9c566e820bb3..1c2c3bf7a1a3 100644 --- a/platform/platform-api/src/com/intellij/ui/ColorChooser.java +++ b/platform/platform-api/src/com/intellij/ui/ColorChooser.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2013 JetBrains s.r.o. + * Copyright 2000-2016 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. @@ -30,11 +30,11 @@ import java.util.List; * @author Konstantin Bulenkov */ public class ColorChooser { - @Nullable - @Deprecated /** * @deprecated Use {@link #chooseColor(Component, String, Color, boolean, java.util.List, boolean)} */ + @Nullable + @Deprecated public static Color chooseColor(Component parent, @Nls(capitalization = Nls.Capitalization.Title) String caption, @Nullable Color preselectedColor, diff --git a/platform/platform-api/src/com/intellij/ui/ColorChooserService.java b/platform/platform-api/src/com/intellij/ui/ColorChooserService.java index 9bb1273d1cc3..c81d808e7fb2 100644 --- a/platform/platform-api/src/com/intellij/ui/ColorChooserService.java +++ b/platform/platform-api/src/com/intellij/ui/ColorChooserService.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2013 JetBrains s.r.o. + * Copyright 2000-2016 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. @@ -30,19 +30,19 @@ public abstract class ColorChooserService { return ServiceManager.getService(ColorChooserService.class); } - @Nullable - @Deprecated /** * @deprecated Use {@link #showDialog(Component, String, Color, boolean, java.util.List, boolean)} */ + @Nullable + @Deprecated public abstract Color showDialog(Component parent, @Nls(capitalization = Nls.Capitalization.Title) String caption, Color preselectedColor, boolean enableOpacity, ColorPickerListener[] listeners); - @Nullable - @Deprecated /** * @deprecated Use {@link #showDialog(Component, String, Color, boolean, java.util.List, boolean)} */ + @Nullable + @Deprecated public abstract Color showDialog(Component parent, @Nls(capitalization = Nls.Capitalization.Title) String caption, Color preselectedColor, boolean enableOpacity, ColorPickerListener[] listeners, boolean opacityInPercent); diff --git a/platform/platform-api/src/com/intellij/ui/SimpleColoredComponent.java b/platform/platform-api/src/com/intellij/ui/SimpleColoredComponent.java index 1a99262a5fcf..ffff9c38e76e 100644 --- a/platform/platform-api/src/com/intellij/ui/SimpleColoredComponent.java +++ b/platform/platform-api/src/com/intellij/ui/SimpleColoredComponent.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2015 JetBrains s.r.o. + * Copyright 2000-2016 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. @@ -221,11 +221,11 @@ public class SimpleColoredComponent extends JComponent implements Accessible, Co myFragmentTags.add(tag); } - @Deprecated /** * fragment width isn't a right name, it is actually a padding * @deprecated remove in IDEA 16 */ + @Deprecated public synchronized void appendFixedTextFragmentWidth(int width) { appendTextPadding(width); } diff --git a/platform/platform-api/src/com/intellij/ui/treeStructure/Tree.java b/platform/platform-api/src/com/intellij/ui/treeStructure/Tree.java index 50e261846b8b..6b7fe73d504a 100644 --- a/platform/platform-api/src/com/intellij/ui/treeStructure/Tree.java +++ b/platform/platform-api/src/com/intellij/ui/treeStructure/Tree.java @@ -679,10 +679,10 @@ public class Tree extends JTree implements ComponentWithEmptyText, ComponentWith e.consume(); } } - /** - * Returns true if mouseX falls - * in the area of row that is used to expand/collapse the node and - * the node at row does not represent a leaf. + /* + Returns true if mouseX falls + in the area of row that is used to expand/collapse the node and + the node at row does not represent a leaf. */ } diff --git a/platform/platform-api/src/com/intellij/util/config/Storage.java b/platform/platform-api/src/com/intellij/util/config/Storage.java index c83e54c1f2f4..51901bcf7c4a 100644 --- a/platform/platform-api/src/com/intellij/util/config/Storage.java +++ b/platform/platform-api/src/com/intellij/util/config/Storage.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2015 JetBrains s.r.o. + * Copyright 2000-2016 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. @@ -24,11 +24,11 @@ import java.util.Collections; import java.util.Iterator; import java.util.Map; -@Deprecated /** * @deprecated Use {@link PropertiesComponent} directly. - * @see {@link JBSplitter} + * @see com.intellij.ui.JBSplitter */ +@Deprecated public interface Storage { void put(String key, String value); String get(String key); diff --git a/platform/platform-api/src/com/intellij/util/config/StorageAccessors.java b/platform/platform-api/src/com/intellij/util/config/StorageAccessors.java index 6f064a36ba78..d3839b69239e 100644 --- a/platform/platform-api/src/com/intellij/util/config/StorageAccessors.java +++ b/platform/platform-api/src/com/intellij/util/config/StorageAccessors.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2015 JetBrains s.r.o. + * Copyright 2000-2016 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. @@ -18,15 +18,16 @@ package com.intellij.util.config; import com.intellij.ide.util.PropertiesComponent; import com.intellij.openapi.application.Application; import com.intellij.openapi.application.ApplicationManager; +import com.intellij.ui.JBSplitter; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; -@SuppressWarnings("unused") -@Deprecated /** * @deprecated Use {@link PropertiesComponent} directly. - * @see {@link JBSplitter} + * @see JBSplitter */ +@SuppressWarnings("unused") +@Deprecated public class StorageAccessors { private final Storage myStorage; diff --git a/platform/platform-api/src/com/intellij/util/proxy/CommonProxy.java b/platform/platform-api/src/com/intellij/util/proxy/CommonProxy.java index 890d6de95a85..b7b7899bc808 100644 --- a/platform/platform-api/src/com/intellij/util/proxy/CommonProxy.java +++ b/platform/platform-api/src/com/intellij/util/proxy/CommonProxy.java @@ -46,7 +46,7 @@ public class CommonProxy extends ProxySelector { public final static List NO_PROXY_LIST = Collections.singletonList(Proxy.NO_PROXY); private final static long ourErrorInterval = TimeUnit.MINUTES.toMillis(3); private static volatile int ourNotificationCount; - private volatile static long ourErrorTime = 0; + private volatile static long ourErrorTime; private volatile static ProxySelector ourWrong; private static final AtomicReference> ourProps = new AtomicReference>(); diff --git a/platform/platform-api/src/com/intellij/util/ui/Animator.java b/platform/platform-api/src/com/intellij/util/ui/Animator.java index 6259307949d0..cd4ac6c02c86 100644 --- a/platform/platform-api/src/com/intellij/util/ui/Animator.java +++ b/platform/platform-api/src/com/intellij/util/ui/Animator.java @@ -40,7 +40,7 @@ public abstract class Animator implements Disposable { private long myStartTime; private long myStartDeltaTime; private boolean myInitialStep; - private volatile boolean myDisposed = false; + private volatile boolean myDisposed; public Animator(@NonNls final String name, final int totalFrames, diff --git a/platform/platform-impl/src/com/intellij/application/options/SaveSchemeDialog.java b/platform/platform-impl/src/com/intellij/application/options/SaveSchemeDialog.java index 966db2a3bdf7..1ac010575004 100644 --- a/platform/platform-impl/src/com/intellij/application/options/SaveSchemeDialog.java +++ b/platform/platform-impl/src/com/intellij/application/options/SaveSchemeDialog.java @@ -14,9 +14,6 @@ * limitations under the License. */ -/** - * @author Yura Cangea - */ package com.intellij.application.options; import com.intellij.CommonBundle; diff --git a/platform/platform-impl/src/com/intellij/codeInsight/hint/TooltipGroup.java b/platform/platform-impl/src/com/intellij/codeInsight/hint/TooltipGroup.java index 50959ae6b20b..3af74d4202ba 100644 --- a/platform/platform-impl/src/com/intellij/codeInsight/hint/TooltipGroup.java +++ b/platform/platform-impl/src/com/intellij/codeInsight/hint/TooltipGroup.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2009 JetBrains s.r.o. + * Copyright 2000-2016 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. @@ -14,9 +14,6 @@ * limitations under the License. */ -/** - * @author cdr - */ package com.intellij.codeInsight.hint; import org.jetbrains.annotations.NonNls; diff --git a/platform/platform-impl/src/com/intellij/diagnostic/DialogAppender.java b/platform/platform-impl/src/com/intellij/diagnostic/DialogAppender.java index b0826439d9ed..2a8cb06e8520 100644 --- a/platform/platform-impl/src/com/intellij/diagnostic/DialogAppender.java +++ b/platform/platform-impl/src/com/intellij/diagnostic/DialogAppender.java @@ -40,7 +40,7 @@ public class DialogAppender extends AppenderSkeleton { private static final ErrorLogger DEFAULT_LOGGER = new DefaultIdeaErrorLogger(); private static final int MAX_ASYNC_LOGGING_EVENTS = 5; - private volatile Runnable myDialogRunnable = null; + private volatile Runnable myDialogRunnable; private final AtomicInteger myPendingAppendCounts = new AtomicInteger(); @Override diff --git a/platform/platform-impl/src/com/intellij/diagnostic/IdeMessagePanel.java b/platform/platform-impl/src/com/intellij/diagnostic/IdeMessagePanel.java index bae2154e508d..9ef2e3764c71 100644 --- a/platform/platform-impl/src/com/intellij/diagnostic/IdeMessagePanel.java +++ b/platform/platform-impl/src/com/intellij/diagnostic/IdeMessagePanel.java @@ -16,8 +16,20 @@ package com.intellij.diagnostic; import com.intellij.icons.AllIcons; +import com.intellij.notification.Notification; +import com.intellij.notification.NotificationAction; +import com.intellij.notification.NotificationType; +import com.intellij.notification.impl.NotificationsManagerImpl; +import com.intellij.openapi.actionSystem.AnActionEvent; +import com.intellij.openapi.project.Project; +import com.intellij.openapi.ui.popup.Balloon; +import com.intellij.openapi.util.Ref; import com.intellij.openapi.wm.IconLikeCustomStatusBarWidget; +import com.intellij.openapi.wm.IdeFrame; import com.intellij.openapi.wm.StatusBar; +import com.intellij.ui.BalloonLayout; +import com.intellij.ui.BalloonLayoutData; +import com.intellij.ui.JBColor; import com.intellij.ui.LightColors; import com.intellij.ui.popup.NotificationPopup; import com.intellij.util.concurrency.EdtExecutorService; @@ -214,6 +226,10 @@ public class IdeMessagePanel extends JPanel implements MessagePoolListener, Icon SwingUtilities.invokeLater(new Runnable() { public void run() { String notificationText = tryGetFromMessages(myMessagePool.getFatalErrors(false, false)); + if (NotificationsManagerImpl.newEnabled()) { + showErrorNotification(notificationText); + return; + } if (notificationText == null) { notificationText = INTERNAL_ERROR_NOTICE; } @@ -230,6 +246,44 @@ public class IdeMessagePanel extends JPanel implements MessagePoolListener, Icon } } + private static final String ERROR_TITLE = DiagnosticBundle.message("error.new.notification.title"); + private static final String ERROR_LINK = DiagnosticBundle.message("error.new.notification.link"); + + private void showErrorNotification(@Nullable String notificationText) { + Notification notification = new Notification("", AllIcons.Ide.FatalError, notificationText == null ? ERROR_TITLE : "", null, + notificationText == null ? "" : notificationText, NotificationType.ERROR, null); + + if (notificationText == null) { + notification.addAction(new NotificationAction(ERROR_LINK) { + @Override + public void actionPerformed(@NotNull AnActionEvent e, @NotNull Notification notification) { + notification.expire(); + _openFatals(null); + } + }); + } + + Window window = SwingUtilities.getWindowAncestor(this); + assert window instanceof IdeFrame; + + IdeFrame frame = (IdeFrame)window; + BalloonLayout layout = frame.getBalloonLayout(); + assert layout != null; + + BalloonLayoutData layoutData = new BalloonLayoutData(); + layoutData.groupId = ""; + layoutData.showSettingButton = false; + layoutData.fadeoutTime = 5000; + layoutData.fillColor = new JBColor(0XF5E6E7, 0X593D41); + layoutData.borderColor = new JBColor(0XE0A8A9, 0X73454B); + + Project project = frame.getProject(); + assert project != null; + + Balloon balloon = NotificationsManagerImpl.createBalloon(frame, notification, false, false, new Ref<>(layoutData), project); + layout.add(balloon); +} + private static String tryGetFromMessages(List messages) { String result = null; for (AbstractMessage message : messages) { diff --git a/platform/platform-impl/src/com/intellij/execution/DelayedDocumentWatcher.java b/platform/platform-impl/src/com/intellij/execution/DelayedDocumentWatcher.java index 787d60fbdaeb..3eb4730d0308 100644 --- a/platform/platform-impl/src/com/intellij/execution/DelayedDocumentWatcher.java +++ b/platform/platform-impl/src/com/intellij/execution/DelayedDocumentWatcher.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2014 JetBrains s.r.o. + * Copyright 2000-2016 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. @@ -117,9 +117,9 @@ public class DelayedDocumentWatcher { @Override public void documentChanged(DocumentEvent event) { if (myDocumentSavingInProgress) { - /** When {@link FileDocumentManager#saveAllDocuments} is called, - * {@link com.intellij.openapi.editor.impl.TrailingSpacesStripper} can change a document. - * These needless 'documentChanged' events should be filtered out. + /* When {@link FileDocumentManager#saveAllDocuments} is called, + {@link com.intellij.openapi.editor.impl.TrailingSpacesStripper} can change a document. + These needless 'documentChanged' events should be filtered out. */ return; } diff --git a/platform/platform-impl/src/com/intellij/execution/process/OSProcessUtil.java b/platform/platform-impl/src/com/intellij/execution/process/OSProcessUtil.java index 75c9dc9f365e..1ab41a7fa0e6 100644 --- a/platform/platform-impl/src/com/intellij/execution/process/OSProcessUtil.java +++ b/platform/platform-impl/src/com/intellij/execution/process/OSProcessUtil.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2015 JetBrains s.r.o. + * Copyright 2000-2016 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. @@ -14,17 +14,6 @@ * limitations under the License. */ -/****************************************************************************** - * Copyright (C) 2013 Fabio Zadrozny - * - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * Fabio Zadrozny - initial API and implementation - ******************************************************************************/ package com.intellij.execution.process; import com.intellij.execution.process.impl.ProcessListUtil; @@ -38,6 +27,17 @@ import java.util.ArrayList; import java.util.Collections; import java.util.List; +/****************************************************************************** + * Copyright (C) 2013 Fabio Zadrozny + * + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Fabio Zadrozny - initial API and implementation + ******************************************************************************/ public class OSProcessUtil { private static final Logger LOG = Logger.getInstance(OSProcessUtil.class); diff --git a/platform/platform-impl/src/com/intellij/ide/IdeTooltipManager.java b/platform/platform-impl/src/com/intellij/ide/IdeTooltipManager.java index 54b2c1cac00d..f8d92720e3ee 100644 --- a/platform/platform-impl/src/com/intellij/ide/IdeTooltipManager.java +++ b/platform/platform-impl/src/com/intellij/ide/IdeTooltipManager.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2013 JetBrains s.r.o. + * Copyright 2000-2016 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. @@ -39,6 +39,7 @@ import com.intellij.util.Alarm; import com.intellij.util.IJSwingUtilities; import com.intellij.util.ui.Html; import com.intellij.util.ui.JBInsets; +import com.intellij.util.ui.JBUI; import com.intellij.util.ui.UIUtil; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; @@ -46,7 +47,6 @@ import org.jetbrains.annotations.Nullable; import javax.swing.*; import javax.swing.border.Border; -import javax.swing.border.EmptyBorder; import javax.swing.text.*; import javax.swing.text.html.HTML; import javax.swing.text.html.HTMLEditorKit; @@ -314,7 +314,7 @@ public class IdeTooltipManager implements ApplicationComponent, AWTEventListener .setRequestFocus(tooltip.isRequestFocus()) .setLayer(tooltip.getLayer()); tooltip.getTipComponent().setForeground(fg); - tooltip.getTipComponent().setBorder(new EmptyBorder(1, 3, 2, 3)); + tooltip.getTipComponent().setBorder(JBUI.Borders.empty(1, 3, 2, 3)); tooltip.getTipComponent().setFont(tooltip.getFont() != null ? tooltip.getFont() : getTextFont(true)); @@ -368,7 +368,7 @@ public class IdeTooltipManager implements ApplicationComponent, AWTEventListener @SuppressWarnings({"MethodMayBeStatic", "UnusedParameters"}) public Color getBorderColor(boolean awtTooltip) { - return new JBColor(Gray._160, new Color(154, 154, 102)); + return new JBColor(Gray._160, new Color(147, 149, 151)); } @SuppressWarnings({"MethodMayBeStatic", "UnusedParameters"}) @@ -629,7 +629,7 @@ public class IdeTooltipManager implements ApplicationComponent, AWTEventListener public static void setBorder(JComponent pane) { pane.setBorder( - BorderFactory.createCompoundBorder(BorderFactory.createLineBorder(Color.black), BorderFactory.createEmptyBorder(0, 5, 0, 5))); + BorderFactory.createCompoundBorder(BorderFactory.createLineBorder(Color.black), JBUI.Borders.empty(0, 5))); } @NotNull diff --git a/platform/platform-impl/src/com/intellij/ide/SaveAndSyncHandlerImpl.java b/platform/platform-impl/src/com/intellij/ide/SaveAndSyncHandlerImpl.java index 5c8954a05894..00bdb83eff4d 100644 --- a/platform/platform-impl/src/com/intellij/ide/SaveAndSyncHandlerImpl.java +++ b/platform/platform-impl/src/com/intellij/ide/SaveAndSyncHandlerImpl.java @@ -56,7 +56,7 @@ public class SaveAndSyncHandlerImpl extends SaveAndSyncHandler implements Dispos private final SingleAlarm myRefreshDelayAlarm = new SingleAlarm(this::doScheduledRefresh, 300, this); private final AtomicInteger myBlockSaveOnFrameDeactivationCount = new AtomicInteger(); private final AtomicInteger myBlockSyncOnFrameActivationCount = new AtomicInteger(); - private volatile long myRefreshSessionId = 0; + private volatile long myRefreshSessionId; public SaveAndSyncHandlerImpl(@NotNull GeneralSettings generalSettings, @NotNull ProgressManager progressManager, diff --git a/platform/platform-impl/src/com/intellij/ide/actions/RunGcAction.java b/platform/platform-impl/src/com/intellij/ide/actions/RunGcAction.java index d726cba544aa..50ae53f42ad8 100644 --- a/platform/platform-impl/src/com/intellij/ide/actions/RunGcAction.java +++ b/platform/platform-impl/src/com/intellij/ide/actions/RunGcAction.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2009 JetBrains s.r.o. + * Copyright 2000-2016 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. @@ -14,9 +14,6 @@ * limitations under the License. */ -/** - * @author Vladimir Kondratyev - */ package com.intellij.ide.actions; import com.intellij.openapi.actionSystem.AnAction; diff --git a/platform/platform-impl/src/com/intellij/ide/actions/ToggleReadOnlyAttributeAction.java b/platform/platform-impl/src/com/intellij/ide/actions/ToggleReadOnlyAttributeAction.java index a09bc3ff0749..ca6d17ced163 100644 --- a/platform/platform-impl/src/com/intellij/ide/actions/ToggleReadOnlyAttributeAction.java +++ b/platform/platform-impl/src/com/intellij/ide/actions/ToggleReadOnlyAttributeAction.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2009 JetBrains s.r.o. + * Copyright 2000-2016 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. @@ -14,9 +14,6 @@ * limitations under the License. */ -/** - * @author Vladimir Kondratyev - */ package com.intellij.ide.actions; import com.intellij.CommonBundle; diff --git a/platform/platform-impl/src/com/intellij/ide/actions/ViewStatusBarAction.java b/platform/platform-impl/src/com/intellij/ide/actions/ViewStatusBarAction.java index 76e6ad8a3b60..82c4853d4cc3 100644 --- a/platform/platform-impl/src/com/intellij/ide/actions/ViewStatusBarAction.java +++ b/platform/platform-impl/src/com/intellij/ide/actions/ViewStatusBarAction.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2009 JetBrains s.r.o. + * Copyright 2000-2016 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. @@ -14,9 +14,6 @@ * limitations under the License. */ -/** - * @author Vladimir Kondratyev - */ package com.intellij.ide.actions; import com.intellij.ide.ui.UISettings; diff --git a/platform/platform-impl/src/com/intellij/ide/errorTreeView/NewErrorTreeViewPanel.java b/platform/platform-impl/src/com/intellij/ide/errorTreeView/NewErrorTreeViewPanel.java index 3bcae0962ca0..5970bdd58fcc 100644 --- a/platform/platform-impl/src/com/intellij/ide/errorTreeView/NewErrorTreeViewPanel.java +++ b/platform/platform-impl/src/com/intellij/ide/errorTreeView/NewErrorTreeViewPanel.java @@ -64,12 +64,12 @@ import java.util.List; public class NewErrorTreeViewPanel extends JPanel implements DataProvider, OccurenceNavigator, MutableErrorTreeView, CopyProvider { protected static final Logger LOG = Logger.getInstance("#com.intellij.ide.errorTreeView.NewErrorTreeViewPanel"); private volatile String myProgressText = ""; - private volatile float myFraction = 0.0f; + private volatile float myFraction; private final boolean myCreateExitAction; private final ErrorViewStructure myErrorViewStructure; private final ErrorViewTreeBuilder myBuilder; private final Alarm myUpdateAlarm = new Alarm(Alarm.ThreadToUse.SWING_THREAD); - private volatile boolean myIsDisposed = false; + private volatile boolean myIsDisposed; private final ErrorTreeViewConfiguration myConfiguration; public interface ProcessController { diff --git a/platform/platform-impl/src/com/intellij/ide/passwordSafe/config/PasswordSafeSettings.java b/platform/platform-impl/src/com/intellij/ide/passwordSafe/config/PasswordSafeSettings.java index 9ab8f7f3c70f..669b99de4955 100644 --- a/platform/platform-impl/src/com/intellij/ide/passwordSafe/config/PasswordSafeSettings.java +++ b/platform/platform-impl/src/com/intellij/ide/passwordSafe/config/PasswordSafeSettings.java @@ -22,8 +22,6 @@ import com.intellij.openapi.components.Storage; /** * The password safe settings - */ -/** * The password database. The internal component for {@link com.intellij.ide.passwordSafe.impl.providers.masterKey.MasterKeyPasswordSafe}. */ @State( diff --git a/platform/platform-impl/src/com/intellij/ide/plugins/RepositoryContentHandler.java b/platform/platform-impl/src/com/intellij/ide/plugins/RepositoryContentHandler.java index 461878fb2974..254eff85b6f4 100644 --- a/platform/platform-impl/src/com/intellij/ide/plugins/RepositoryContentHandler.java +++ b/platform/platform-impl/src/com/intellij/ide/plugins/RepositoryContentHandler.java @@ -94,7 +94,7 @@ class RepositoryContentHandler extends DefaultHandler { } else if (qName.equals(IDEA_VERSION)) { currentPlugin.setSinceBuild(attributes.getValue(SINCE_BUILD)); - currentPlugin.setUntilBuild(attributes.getValue(UNTIL_BUILD)); + currentPlugin.setUntilBuild(IdeaPluginDescriptorImpl.convertExplicitBigNumberInUntilBuildToStar(attributes.getValue(UNTIL_BUILD))); } else if (qName.equals(VENDOR)) { currentPlugin.setVendorEmail(attributes.getValue(EMAIL)); diff --git a/platform/platform-impl/src/com/intellij/ide/startup/impl/StartupManagerImpl.java b/platform/platform-impl/src/com/intellij/ide/startup/impl/StartupManagerImpl.java index 02e295b8f3a6..dcf12da8b06b 100644 --- a/platform/platform-impl/src/com/intellij/ide/startup/impl/StartupManagerImpl.java +++ b/platform/platform-impl/src/com/intellij/ide/startup/impl/StartupManagerImpl.java @@ -65,11 +65,11 @@ public class StartupManagerImpl extends StartupManagerEx { private final List myDumbAwarePostStartupActivities = Collections.synchronizedList(new LinkedList()); private final List myNotDumbAwarePostStartupActivities = Collections.synchronizedList(new LinkedList()); - private boolean myPostStartupActivitiesPassed = false; // guarded by this + private boolean myPostStartupActivitiesPassed; // guarded by this - private volatile boolean myPreStartupActivitiesPassed = false; - private volatile boolean myStartupActivitiesRunning = false; - private volatile boolean myStartupActivitiesPassed = false; + private volatile boolean myPreStartupActivitiesPassed; + private volatile boolean myStartupActivitiesRunning; + private volatile boolean myStartupActivitiesPassed; private final Project myProject; diff --git a/platform/platform-impl/src/com/intellij/ide/ui/laf/darcula/darcula.properties b/platform/platform-impl/src/com/intellij/ide/ui/laf/darcula/darcula.properties index 82f7766dfa97..4d8aed5f1dbe 100644 --- a/platform/platform-impl/src/com/intellij/ide/ui/laf/darcula/darcula.properties +++ b/platform/platform-impl/src/com/intellij/ide/ui/laf/darcula/darcula.properties @@ -140,7 +140,7 @@ MenuItem.acceleratorForeground=bbbbbb MenuItem.acceleratorSelectionForeground=bbbbbb PopupMenu.translucentBackground=3c3f41 -ToolTip.background=5C5C42 +ToolTip.background=3c3f41 SpinnerUI=com.intellij.ide.ui.laf.darcula.ui.DarculaSpinnerUI Spinner.border=com.intellij.ide.ui.laf.darcula.ui.DarculaSpinnerBorder diff --git a/platform/platform-impl/src/com/intellij/internal/statistic/connect/StatisticsHttpClientSender.java b/platform/platform-impl/src/com/intellij/internal/statistic/connect/StatisticsHttpClientSender.java index 292b6c4304b0..17392e3a14f2 100644 --- a/platform/platform-impl/src/com/intellij/internal/statistic/connect/StatisticsHttpClientSender.java +++ b/platform/platform-impl/src/com/intellij/internal/statistic/connect/StatisticsHttpClientSender.java @@ -15,9 +15,8 @@ */ package com.intellij.internal.statistic.connect; -import com.intellij.ide.util.PropertiesComponent; import com.intellij.openapi.application.ApplicationNamesInfo; -import com.intellij.openapi.updateSettings.impl.UpdateChecker; +import com.intellij.openapi.application.PermanentInstallationID; import com.intellij.openapi.util.text.StringUtil; import com.intellij.util.net.HttpConfigurable; import org.apache.http.Header; @@ -36,7 +35,7 @@ public class StatisticsHttpClientSender implements StatisticsDataSender { Response response = Request.Post(url).bodyForm(Form.form(). add("content", content). - add("uuid", UpdateChecker.getInstallationUID(PropertiesComponent.getInstance())). + add("uuid", PermanentInstallationID.get()). add("patch", String.valueOf(false)). add("ide", ApplicationNamesInfo.getInstance().getProductName()).build()).execute(); diff --git a/platform/platform-impl/src/com/intellij/notification/impl/NotificationsManagerImpl.java b/platform/platform-impl/src/com/intellij/notification/impl/NotificationsManagerImpl.java index 7e2c479f01cf..136dbe0da5db 100644 --- a/platform/platform-impl/src/com/intellij/notification/impl/NotificationsManagerImpl.java +++ b/platform/platform-impl/src/com/intellij/notification/impl/NotificationsManagerImpl.java @@ -36,6 +36,7 @@ import com.intellij.openapi.ui.DialogWrapperDialog; import com.intellij.openapi.ui.MessageType; import com.intellij.openapi.ui.popup.*; import com.intellij.openapi.util.Disposer; +import com.intellij.openapi.util.Pair; import com.intellij.openapi.util.Ref; import com.intellij.openapi.util.SystemInfo; import com.intellij.openapi.util.registry.Registry; @@ -55,10 +56,7 @@ import com.intellij.util.ArrayUtil; import com.intellij.util.FontUtil; import com.intellij.util.Function; import com.intellij.util.IconUtil; -import com.intellij.util.ui.AbstractLayoutManager; -import com.intellij.util.ui.ButtonlessScrollBarUI; -import com.intellij.util.ui.JBUI; -import com.intellij.util.ui.UIUtil; +import com.intellij.util.ui.*; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; @@ -76,8 +74,7 @@ import javax.swing.text.html.HTMLEditorKit; import javax.swing.text.html.ParagraphView; import javax.swing.text.html.StyleSheet; import java.awt.*; -import java.awt.event.AdjustmentEvent; -import java.awt.event.AdjustmentListener; +import java.awt.event.*; import java.awt.geom.Rectangle2D; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; @@ -520,6 +517,13 @@ public class NotificationsManagerImpl extends NotificationsManager { } layoutDataRef.set(layoutData); + if (layoutData.fillColor == null) { + layoutData.fillColor = FILL_COLOR; + } + if (layoutData.borderColor == null) { + layoutData.borderColor = BORDER_COLOR; + } + boolean actions = !notification.getActions().isEmpty(); boolean showFullContent = layoutData.showFullContent || notification instanceof NotificationActionProvider; @@ -647,7 +651,7 @@ public class NotificationsManagerImpl extends NotificationsManager { @Nullable @Override protected Color getViewColor() { - return FILL_COLOR; + return layoutData.fillColor; } @Override @@ -659,7 +663,7 @@ public class NotificationsManagerImpl extends NotificationsManager { }); } - configureBalloonScrollPane(pane); + configureBalloonScrollPane(pane, layoutData.fillColor); if (showFullContent) { pane.setPreferredSize(text.getPreferredSize()); @@ -726,12 +730,13 @@ public class NotificationsManagerImpl extends NotificationsManager { int height = title instanceof JEditorPane ? getFirstLineHeight((JEditorPane)title) : title.getHeight(); - g.setColor(FILL_COLOR); + g.setColor(layoutData.fillColor); g.fillRect(x, y, width, height); width = layoutData.configuration.beforeGearSpace; x -= width; - ((Graphics2D)g).setPaint(new GradientPaint(x, y, ColorUtil.withAlpha(FILL_COLOR, 0.2), x + width, y, FILL_COLOR)); + ((Graphics2D)g) + .setPaint(new GradientPaint(x, y, ColorUtil.withAlpha(layoutData.fillColor, 0.2), x + width, y, layoutData.fillColor)); g.fillRect(x, y, width, height); } } @@ -782,10 +787,20 @@ public class NotificationsManagerImpl extends NotificationsManager { buttons.setBorder(new EmptyBorder(0, 0, JBUI.scale(5), JBUI.scale(7))); } - if (buttons == null && actions) { - createActionPanel(notification, centerPanel, layoutData.configuration.actionGap); + HoverAdapter hoverAdapter = new HoverAdapter(); + hoverAdapter.addSource(content); + hoverAdapter.addSource(centerPanel); + + if (expandAction != null) { + hoverAdapter.addComponent(expandAction, new Insets(5, 5, 7, 7)); } + if (buttons == null && actions) { + createActionPanel(notification, centerPanel, layoutData.configuration.actionGap, hoverAdapter); + } + + hoverAdapter.initListeners(); + if (layoutData.mergeData != null) { createMergeAction(layoutData, content); } @@ -802,7 +817,7 @@ public class NotificationsManagerImpl extends NotificationsManager { } final BalloonBuilder builder = JBPopupFactory.getInstance().createBalloonBuilder(content); - builder.setFillColor(FILL_COLOR) + builder.setFillColor(layoutData.fillColor) .setCloseButtonEnabled(buttons == null) .setShowCallout(showCallout) .setShadow(false) @@ -810,14 +825,18 @@ public class NotificationsManagerImpl extends NotificationsManager { .setHideOnAction(hideOnClickOutside) .setHideOnKeyOutside(hideOnClickOutside) .setHideOnFrameResize(false) - .setBorderColor(BORDER_COLOR) + .setBorderColor(layoutData.borderColor) .setBorderInsets(new Insets(0, 0, 0, 0)); + if (layoutData.fadeoutTime != 0) { + builder.setFadeoutTime(layoutData.fadeoutTime); + } + final BalloonImpl balloon = (BalloonImpl)builder.createBalloon(); balloon.setAnimationEnabled(false); notification.setBalloon(balloon); - balloon.setShadowBorderProvider(new NotificationBalloonShadowBorderProvider(FILL_COLOR, BORDER_COLOR)); + balloon.setShadowBorderProvider(new NotificationBalloonShadowBorderProvider(layoutData.fillColor, layoutData.borderColor)); if (!layoutData.welcomeScreen && buttons == null) { balloon.setActionProvider( @@ -832,23 +851,26 @@ public class NotificationsManagerImpl extends NotificationsManager { public static JScrollPane createBalloonScrollPane(@NotNull Component content, boolean configure) { JScrollPane pane = ScrollPaneFactory.createScrollPane(content, true); if (configure) { - configureBalloonScrollPane(pane); + configureBalloonScrollPane(pane, FILL_COLOR); } return pane; } - public static void configureBalloonScrollPane(@NotNull JScrollPane pane) { + public static void configureBalloonScrollPane(@NotNull JScrollPane pane, @NotNull Color fillColor) { pane.setOpaque(false); pane.getViewport().setOpaque(false); if (!Registry.is("ide.scroll.new.layout")) { pane.getVerticalScrollBar().setUI(ButtonlessScrollBarUI.createTransparent()); } - pane.setBackground(FILL_COLOR); - pane.getViewport().setBackground(FILL_COLOR); - pane.getVerticalScrollBar().setBackground(FILL_COLOR); + pane.setBackground(fillColor); + pane.getViewport().setBackground(fillColor); + pane.getVerticalScrollBar().setBackground(fillColor); } - private static void createActionPanel(@NotNull final Notification notification, @NotNull JPanel centerPanel, int gap) { + private static void createActionPanel(@NotNull final Notification notification, + @NotNull JPanel centerPanel, + int gap, + @NotNull HoverAdapter hoverAdapter) { JPanel actionPanel = new NonOpaquePanel(new HorizontalLayout(gap, SwingConstants.CENTER)); centerPanel.add(BorderLayout.SOUTH, actionPanel); @@ -885,6 +907,110 @@ public class NotificationsManagerImpl extends NotificationsManager { } }, action)); } + + Insets hover = new Insets(8, 5, 8, 7); + int count = actionPanel.getComponentCount(); + + for (int i = 0; i < count; i++) { + hoverAdapter.addComponent(actionPanel.getComponent(i), hover); + } + + hoverAdapter.addSource(actionPanel); + } + + private static class HoverAdapter extends MouseAdapter implements MouseMotionListener { + private final List> myComponents = new ArrayList<>(); + private List mySources = new ArrayList<>(); + private Component myLastComponent; + + public void addComponent(@NotNull Component component, @NotNull Insets hover) { + myComponents.add(Pair.create(component, hover)); + } + + public void addSource(@NotNull Component component) { + mySources.add(component); + } + + public void initListeners() { + if (!myComponents.isEmpty()) { + for (Component source : mySources) { + source.addMouseMotionListener(this); + source.addMouseListener(this); + } + mySources = null; + } + } + + public void mousePressed(MouseEvent e) { + handleEvent(e, true, false); + } + + public void mouseReleased(MouseEvent e) { + handleEvent(e, false, false); + } + + public void mouseMoved(MouseEvent e) { + handleEvent(e, false, true); + } + + public void mouseExited(MouseEvent e) { + if (myLastComponent != null) { + mouseExited(e, myLastComponent); + myLastComponent = null; + } + } + + private void handleEvent(MouseEvent e, boolean pressed, boolean moved) { + for (Pair p : myComponents) { + Component component = p.first; + Rectangle bounds = component.getBounds(); + JBInsets.addTo(bounds, p.second); + if (bounds.contains(SwingUtilities.convertPoint(e.getComponent(), e.getPoint(), component.getParent()))) { + if (myLastComponent != null && myLastComponent != component) { + mouseExited(e, myLastComponent); + } + myLastComponent = component; + + MouseEvent event = createEvent(e, component); + if (moved) { + for (MouseMotionListener listener : component.getMouseMotionListeners()) { + listener.mouseMoved(event); + } + } + else { + MouseListener[] listeners = component.getMouseListeners(); + if (pressed) { + for (MouseListener listener : listeners) { + listener.mousePressed(event); + } + } + else { + for (MouseListener listener : listeners) { + listener.mouseReleased(event); + } + } + } + return; + } + else if (component == myLastComponent) { + myLastComponent = null; + mouseExited(e, component); + } + } + } + + private static void mouseExited(MouseEvent e, Component component) { + MouseEvent event = createEvent(e, component); + MouseListener[] listeners = component.getMouseListeners(); + for (MouseListener listener : listeners) { + listener.mouseExited(event); + } + } + + @NotNull + private static MouseEvent createEvent(MouseEvent e, Component c) { + return new MouseEvent(c, e.getID(), e.getWhen(), e.getModifiers(), 5, 5, e.getClickCount(), e.isPopupTrigger(), e.getButton()); + } } private static void createMergeAction(@NotNull final BalloonLayoutData layoutData, @NotNull JPanel panel) { diff --git a/platform/platform-impl/src/com/intellij/notification/impl/actions/NotificationTestAction.java b/platform/platform-impl/src/com/intellij/notification/impl/actions/NotificationTestAction.java index 95fae4f3f789..b46254eb6a1c 100644 --- a/platform/platform-impl/src/com/intellij/notification/impl/actions/NotificationTestAction.java +++ b/platform/platform-impl/src/com/intellij/notification/impl/actions/NotificationTestAction.java @@ -29,6 +29,7 @@ import com.intellij.openapi.ui.DialogWrapper; import com.intellij.openapi.ui.MessageDialogBuilder; import com.intellij.openapi.util.IconLoader; import com.intellij.openapi.util.text.StringUtil; +import com.intellij.openapi.wm.ToolWindowId; import com.intellij.util.messages.MessageBus; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; @@ -47,6 +48,8 @@ public class NotificationTestAction extends AnAction implements DumbAware { public static final String TEST_GROUP_ID = "Test Notification"; private static final NotificationGroup TEST_STICKY_GROUP = new NotificationGroup("Test Sticky Notification", NotificationDisplayType.STICKY_BALLOON, true); + private static final NotificationGroup TEST_TOOLWINDOW_GROUP = + NotificationGroup.toolWindowGroup("Test ToolWindow Notification", ToolWindowId.TODO_VIEW, true); private static final String MESSAGE_KEY = "NotificationTestAction_Message"; public void actionPerformed(@NotNull AnActionEvent event) { @@ -184,6 +187,9 @@ public class NotificationTestAction extends AnAction implements DumbAware { else if (line.startsWith("Listener:")) { notification.setAddListener("true".equals(StringUtil.substringAfter(line, ":"))); } + else if (line.startsWith("Toolwindow:")) { + notification.setToolwindow("true".equals(StringUtil.substringAfter(line, ":"))); + } } ApplicationManager.getApplication().executeOnPooledThread(new Runnable() { @@ -206,6 +212,7 @@ public class NotificationTestAction extends AnAction implements DumbAware { private NotificationType myType = NotificationType.INFORMATION; private boolean mySticky; private boolean myAddListener; + private boolean myToolwindow; private Notification myNotification; @@ -219,6 +226,9 @@ public class NotificationTestAction extends AnAction implements DumbAware { return myNotification = new StatisticsNotification(StatisticsNotificationManager.GROUP_DISPLAY_ID, getListener()).setIcon(icon); } String displayId = mySticky ? TEST_STICKY_GROUP.getDisplayId() : TEST_GROUP_ID; + if (myToolwindow) { + displayId = TEST_TOOLWINDOW_GROUP.getDisplayId(); + } String content = myContent == null ? "" : StringUtil.join(myContent, "\n"); if (icon == null) { myNotification = @@ -272,6 +282,10 @@ public class NotificationTestAction extends AnAction implements DumbAware { mySticky = sticky; } + public void setToolwindow(boolean toolwindow) { + myToolwindow = toolwindow; + } + public void setType(@Nullable String type) { if ("info".equals(type)) { myType = NotificationType.INFORMATION; diff --git a/platform/platform-impl/src/com/intellij/openapi/application/ClipboardAnalyzeListener.java b/platform/platform-impl/src/com/intellij/openapi/application/ClipboardAnalyzeListener.java new file mode 100644 index 000000000000..40976e67ff8b --- /dev/null +++ b/platform/platform-impl/src/com/intellij/openapi/application/ClipboardAnalyzeListener.java @@ -0,0 +1,62 @@ +/* + * Copyright 2000-2016 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.application; + +import com.intellij.Patches; +import com.intellij.openapi.application.ex.ClipboardUtil; +import com.intellij.openapi.project.Project; +import com.intellij.openapi.util.SystemInfo; +import com.intellij.openapi.wm.IdeFrame; +import com.intellij.util.Alarm; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +public abstract class ClipboardAnalyzeListener extends ApplicationActivationListener.Adapter { + private static final int MAX_SIZE = 100 * 1024; + @Nullable private String myCachedClipboardValue; + + @Override + public void applicationActivated(final IdeFrame ideFrame) { + final Runnable processClipboard = () -> { + final String clipboard = ClipboardUtil.getTextInClipboard(); + if (clipboard != null && clipboard.length() < MAX_SIZE && !clipboard.equals(myCachedClipboardValue)) { + myCachedClipboardValue = clipboard; + final Project project = ideFrame.getProject(); + if (project != null && !project.isDefault() && canHandle(myCachedClipboardValue)) { + handle(project, myCachedClipboardValue); + } + } + }; + + if (Patches.SLOW_GETTING_CLIPBOARD_CONTENTS) { + //IDEA's clipboard is synchronized with the system clipboard on frame activation so we need to postpone clipboard processing + new Alarm().addRequest(processClipboard, 300); + } + else { + processClipboard.run(); + } + } + + protected abstract void handle(@NotNull Project project, @NotNull String value); + + @Override + public void applicationDeactivated(IdeFrame ideFrame) { + if (SystemInfo.isMac) return; + myCachedClipboardValue = ClipboardUtil.getTextInClipboard(); + } + + public abstract boolean canHandle(@NotNull String value); +} diff --git a/platform/platform-impl/src/com/intellij/openapi/application/PermanentInstallationID.java b/platform/platform-impl/src/com/intellij/openapi/application/PermanentInstallationID.java new file mode 100644 index 000000000000..8eab31d0a9e3 --- /dev/null +++ b/platform/platform-impl/src/com/intellij/openapi/application/PermanentInstallationID.java @@ -0,0 +1,109 @@ +/* + * Copyright 2000-2016 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.application; + +import com.intellij.openapi.util.SystemInfo; +import com.intellij.openapi.util.io.FileUtilRt; +import com.intellij.openapi.vfs.CharsetToolkit; +import org.jetbrains.annotations.NotNull; + +import java.io.*; +import java.util.UUID; +import java.util.prefs.Preferences; + +/** + * UUID identifying pair user@computer + */ +public class PermanentInstallationID { + private static final String OLD_USER_ON_MACHINE_ID_KEY = "JetBrains.UserIdOnMachine"; + private static final String INSTALLATION_ID_KEY = "user_id_on_machine"; + private static final String INSTALLATION_ID = calculateInstallationId(); + + public static String get() { + return INSTALLATION_ID; + } + + private static String calculateInstallationId() { + final Preferences oldPrefs = Preferences.userRoot(); + final String oldValue = oldPrefs.get(OLD_USER_ON_MACHINE_ID_KEY, null); // compatibility with previous versions + final Preferences prefs = Preferences.userRoot().node("jetbrains"); + + String installationId = prefs.get(INSTALLATION_ID_KEY, null); + if (installationId == null || installationId.isEmpty()) { + installationId = oldValue != null && !oldValue.isEmpty() ? oldValue : UUID.randomUUID().toString(); + prefs.put(INSTALLATION_ID_KEY, installationId); + } + + // for Windows attempt to use PermanentUserId, so that DotNet products and IDEA would use the same ID. + if (SystemInfo.isWindows) { + final String appdata = System.getenv("APPDATA"); + if (appdata != null) { + final File dir = new File(appdata, "JetBrains"); + if (dir.exists() || dir.mkdirs()) { + final File permanentIdFile = new File(dir, "PermanentUserId"); + try { + String fromFile = ""; + if (permanentIdFile.exists()) { + fromFile = loadFromFile(permanentIdFile).trim(); + } + if (!fromFile.isEmpty()) { + if (!fromFile.equals(installationId)) { + installationId = fromFile; + prefs.put(INSTALLATION_ID_KEY, installationId); + } + } + else { + writeToFile(permanentIdFile, installationId); + } + } + catch (IOException ignored) { + } + } + } + } + + // make sure values in older location and in the new location are the same + if (!installationId.equals(oldValue)) { + oldPrefs.put(OLD_USER_ON_MACHINE_ID_KEY, installationId); + } + + return installationId; + } + + @NotNull + private static String loadFromFile(@NotNull File file) throws IOException { + final FileInputStream is = new FileInputStream(file); + try { + final byte[] bytes = FileUtilRt.loadBytes(is); + final int offset = CharsetToolkit.hasUTF8Bom(bytes) ? CharsetToolkit.UTF8_BOM.length : 0; + return new String(bytes, offset, bytes.length - offset, CharsetToolkit.UTF8_CHARSET); + } + finally { + is.close(); + } + } + + private static void writeToFile(@NotNull File file, @NotNull String text) throws IOException { + final DataOutputStream stream = new DataOutputStream(new FileOutputStream(file)); + try { + stream.write(text.getBytes(CharsetToolkit.UTF8_CHARSET)); + } + finally { + stream.close(); + } + } + +} diff --git a/platform/platform-impl/src/com/intellij/openapi/diff/actions/DiffActions.java b/platform/platform-impl/src/com/intellij/openapi/application/ex/ClipboardUtil.java similarity index 59% rename from platform/platform-impl/src/com/intellij/openapi/diff/actions/DiffActions.java rename to platform/platform-impl/src/com/intellij/openapi/application/ex/ClipboardUtil.java index 3d5a2646adfa..a51e3eeeb1aa 100644 --- a/platform/platform-impl/src/com/intellij/openapi/diff/actions/DiffActions.java +++ b/platform/platform-impl/src/com/intellij/openapi/application/ex/ClipboardUtil.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2009 JetBrains s.r.o. + * Copyright 2000-2016 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. @@ -13,13 +13,17 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.intellij.openapi.diff.actions; +package com.intellij.openapi.application.ex; -import org.jetbrains.annotations.NonNls; +import com.intellij.openapi.ide.CopyPasteManager; +import org.jetbrains.annotations.Nullable; -/** - * @author dyoma - */ -public interface DiffActions { - @NonNls String COMPARE_WITH_CLIPBOARD = "CompareClipboardWithSelection"; +import java.awt.datatransfer.DataFlavor; + +public class ClipboardUtil { + + @Nullable + public static String getTextInClipboard() { + return CopyPasteManager.getInstance().getContents(DataFlavor.stringFlavor); + } } diff --git a/platform/platform-impl/src/com/intellij/openapi/application/impl/ApplicationImpl.java b/platform/platform-impl/src/com/intellij/openapi/application/impl/ApplicationImpl.java index 857297f0a23b..4a213e254ab9 100644 --- a/platform/platform-impl/src/com/intellij/openapi/application/impl/ApplicationImpl.java +++ b/platform/platform-impl/src/com/intellij/openapi/application/impl/ApplicationImpl.java @@ -1145,12 +1145,12 @@ public class ApplicationImpl extends PlatformComponentManagerImpl implements App fireWriteActionFinished(clazz); // fire listeners before popping stack because if somebody starts write action in a listener, // there is a danger of unlocking the write lock before other listeners have been run (since write lock became non-reentrant). + } + finally { myWriteActionsStack.pop(); if (gatherWriteActionStatistics && myWriteActionsStack.isEmpty() && !myWriteActionPending) { writePauses.finished("write action ("+clazz+")"); } - } - finally { if (myWriteActionsStack.isEmpty()) { myLock.writeUnlock(); } diff --git a/platform/platform-impl/src/com/intellij/openapi/components/impl/stores/IProjectStore.java b/platform/platform-impl/src/com/intellij/openapi/components/impl/stores/IProjectStore.java index 49d5795a1828..4c6c02b83651 100644 --- a/platform/platform-impl/src/com/intellij/openapi/components/impl/stores/IProjectStore.java +++ b/platform/platform-impl/src/com/intellij/openapi/components/impl/stores/IProjectStore.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2015 JetBrains s.r.o. + * Copyright 2000-2016 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. @@ -21,10 +21,10 @@ import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; public interface IProjectStore extends IComponentStore { - @Nullable /** * System-independent path. */ + @Nullable String getProjectBasePath(); @NotNull @@ -33,16 +33,16 @@ public interface IProjectStore extends IComponentStore { @NotNull StorageScheme getStorageScheme(); - @NotNull /** * System-independent path. */ + @NotNull String getProjectFilePath(); - @Nullable /** * System-independent path. */ + @Nullable String getWorkspaceFilePath(); void loadProjectFromTemplate(@NotNull Project project); diff --git a/platform/platform-impl/src/com/intellij/openapi/diff/actions/ClipboardVsValueContents.java b/platform/platform-impl/src/com/intellij/openapi/diff/actions/ClipboardVsValueContents.java deleted file mode 100644 index dcff8bacfb62..000000000000 --- a/platform/platform-impl/src/com/intellij/openapi/diff/actions/ClipboardVsValueContents.java +++ /dev/null @@ -1,78 +0,0 @@ -/* - * Copyright 2000-2014 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.diff.actions; - -import com.intellij.openapi.diff.DiffBundle; -import com.intellij.openapi.diff.DiffContent; -import com.intellij.openapi.diff.DiffRequest; -import com.intellij.openapi.diff.SimpleContent; -import com.intellij.openapi.ide.CopyPasteManager; -import com.intellij.openapi.project.Project; -import com.intellij.openapi.util.SystemInfo; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -import java.awt.datatransfer.DataFlavor; - -/** - * @author Jeka - */ -@Deprecated -public class ClipboardVsValueContents extends DiffRequest { - - private DiffContent[] myContents = null; - private final String myValue; - - public ClipboardVsValueContents(String value, Project project) { - super(project); - myValue = value; - } - - public String[] getContentTitles() { - return new String[]{ - DiffBundle.message("diff.content.clipboard.content.title"), - DiffBundle.message("diff.content.selected.value") - }; - } - - @Override - public boolean isSafeToCallFromUpdate() { - return !SystemInfo.isMac; - } - - @NotNull - public DiffContent[] getContents() { - if (myContents != null) return myContents; - DiffContent clipboardContent = createClipboardContent(); - if (clipboardContent == null) clipboardContent = new SimpleContent(""); - - myContents = new DiffContent[2]; - myContents[0] = clipboardContent; - - myContents[1] = new SimpleContent(myValue); - return myContents; - } - - public String getWindowTitle() { - return DiffBundle.message("diff.clipboard.vs.value.dialog.title"); - } - - @Nullable - public static DiffContent createClipboardContent() { - String text = CopyPasteManager.getInstance().getContents(DataFlavor.stringFlavor); - return text != null ? new SimpleContent(text) : null; - } -} diff --git a/platform/platform-impl/src/com/intellij/openapi/diff/actions/CompareClipboardWithSelection.java b/platform/platform-impl/src/com/intellij/openapi/diff/actions/CompareClipboardWithSelection.java deleted file mode 100644 index 39a6dffcd747..000000000000 --- a/platform/platform-impl/src/com/intellij/openapi/diff/actions/CompareClipboardWithSelection.java +++ /dev/null @@ -1,103 +0,0 @@ -/* - * Copyright 2000-2013 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.diff.actions; - -import com.intellij.openapi.actionSystem.CommonDataKeys; -import com.intellij.openapi.actionSystem.DataContext; -import com.intellij.openapi.actionSystem.PlatformDataKeys; -import com.intellij.openapi.diff.*; -import com.intellij.openapi.editor.Document; -import com.intellij.openapi.editor.Editor; -import com.intellij.openapi.editor.SelectionModel; -import com.intellij.openapi.fileEditor.FileEditorManager; -import com.intellij.openapi.project.Project; -import com.intellij.openapi.util.SystemInfo; -import com.intellij.openapi.util.TextRange; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -/** - * @deprecated use {@link com.intellij.diff.actions.CompareClipboardWithSelectionAction} instead - */ -@Deprecated -public class CompareClipboardWithSelection extends BaseDiffAction { - @Nullable - protected DiffRequest getDiffData(DataContext dataContext) { - Project project = CommonDataKeys.PROJECT.getData(dataContext); - if (project == null) return null; - Editor editorData = CommonDataKeys.EDITOR.getData(dataContext); - Editor editor = editorData != null ? editorData : FileEditorManager.getInstance(project).getSelectedTextEditor(); - if (editor == null) return null; - return new ClipboardSelectionContents(editor, project); - } - - private static class ClipboardSelectionContents extends DiffRequest { - private DiffContent[] myContents = null; - private final Editor myEditor; - - public ClipboardSelectionContents(Editor editor, Project project) { - super(project); - myEditor = editor; - } - - public String[] getContentTitles() { - return new String[]{DiffBundle.message("diff.content.clipboard.content.title"), - isEditorContent(getDocument()) ? - DiffBundle.message("diff.content.selection.from.editor.content.title") : - DiffBundle.message("diff.content.selection.from.file.content.title", getDocumentFileUrl(getDocument())) - }; - } - - @Override - public boolean isSafeToCallFromUpdate() { - return !SystemInfo.isMac; - } - - @NotNull - public DiffContent[] getContents() { - if (myContents != null) return myContents; - DiffContent clipboardContent = ClipboardVsValueContents.createClipboardContent(); - if (clipboardContent == null) clipboardContent = new SimpleContent(""); - myContents = new DiffContent[2]; - myContents[0] = clipboardContent; - - SelectionModel selectionModel = myEditor.getSelectionModel(); - if (selectionModel.hasSelection()) { - TextRange range = new TextRange(selectionModel.getSelectionStart(), selectionModel.getSelectionEnd()); - boolean forceReadOnly = myEditor.isViewer(); - myContents[1] = new FragmentContent(DiffContent.fromDocument(getProject(), getDocument()), - range, getProject(), getDocumentFile(getDocument()), forceReadOnly); - } - else { - myContents [1] = DiffContent.fromDocument(getProject(), getDocument()); - } - return myContents; - } - - private Document getDocument() { - return myEditor.getDocument(); - } - - public String getWindowTitle() { - if (isEditorContent(getDocument())) { - return DiffBundle.message("diff.clipboard.vs.editor.dialog.title"); - } else { - return DiffBundle.message("diff.clipboard.vs.file.dialog.title", getDocumentFileUrl(getDocument())); - } - } - - } -} diff --git a/platform/platform-impl/src/com/intellij/openapi/diff/actions/CompareDirectoriesAction.java b/platform/platform-impl/src/com/intellij/openapi/diff/actions/CompareDirectoriesAction.java deleted file mode 100644 index bd270a98b880..000000000000 --- a/platform/platform-impl/src/com/intellij/openapi/diff/actions/CompareDirectoriesAction.java +++ /dev/null @@ -1,91 +0,0 @@ -/* - * Copyright 2000-2014 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.diff.actions; - -import com.intellij.featureStatistics.FeatureUsageTracker; -import com.intellij.ide.diff.DirDiffSettings; -import com.intellij.ide.diff.VirtualFileDiffElement; -import com.intellij.ide.util.PropertiesComponent; -import com.intellij.openapi.actionSystem.AnActionEvent; -import com.intellij.openapi.actionSystem.CommonDataKeys; -import com.intellij.openapi.diff.DirDiffManager; -import com.intellij.openapi.fileChooser.FileChooser; -import com.intellij.openapi.fileChooser.FileChooserDescriptor; -import com.intellij.openapi.project.DumbAwareAction; -import com.intellij.openapi.project.Project; -import com.intellij.openapi.vfs.LocalFileSystem; -import com.intellij.openapi.vfs.VirtualFile; - -/** - * @author Konstantin Bulenkov - */ -@Deprecated -public class CompareDirectoriesAction extends DumbAwareAction { - - public static final String LAST_USED_KEY = "dir.diff.last.used.directory"; - - @Override - public void actionPerformed(AnActionEvent e) { - final Project project = getEventProject(e); - final VirtualFile[] files = e.getData(CommonDataKeys.VIRTUAL_FILE_ARRAY); - FeatureUsageTracker.getInstance().triggerFeatureUsed("dir.diff"); - if (project != null && files != null) { - VirtualFileDiffElement src = null; - VirtualFileDiffElement trg = null; - if (files.length == 2 && files[0].isDirectory() && files[1].isDirectory()) { - src = new VirtualFileDiffElement(files[0]); - trg = new VirtualFileDiffElement(files[1]); - } - else if (files.length == 1 && files[0].isDirectory()) { - src = new VirtualFileDiffElement(files[0]); - final FileChooserDescriptor descriptor = new FileChooserDescriptor(false, true, false, false, false, false); - final String path = PropertiesComponent.getInstance(project).getValue(LAST_USED_KEY); - VirtualFile toSelect = null; - if (path != null) { - toSelect = LocalFileSystem.getInstance().findFileByPath(path); - } - if (toSelect == null) { - toSelect = project.getBaseDir(); - } - final VirtualFile[] result = FileChooser.chooseFiles(descriptor, project, toSelect); - if (result.length == 1 && result[0] != null && result[0].isDirectory()) { - PropertiesComponent.getInstance(project).setValue(LAST_USED_KEY, result[0].getPath()); - trg = new VirtualFileDiffElement(result[0]); - } - } - final DirDiffManager mgr = DirDiffManager.getInstance(project); - if (src != null && trg != null && mgr.canShow(src, trg)) { - mgr.showDiff(src, trg, new DirDiffSettings(), null); - } - } - } - - @Override - public void update(AnActionEvent e) { - final VirtualFile[] files = e.getData(CommonDataKeys.VIRTUAL_FILE_ARRAY); - if (files != null && files.length > 0 && files.length < 3) { - if (files[0].isDirectory() && (files.length == 1 || files[1].isDirectory())) { - e.getPresentation().setEnabled(true); - e.getPresentation().setVisible(true); - e.getPresentation().setText(files.length == 1 ? "Compare Directory with..." : "Compare Directories"); - return; - } - } - - e.getPresentation().setEnabled(false); - e.getPresentation().setVisible(false); - } -} diff --git a/platform/platform-impl/src/com/intellij/openapi/diff/actions/CompareFileWithEditor.java b/platform/platform-impl/src/com/intellij/openapi/diff/actions/CompareFileWithEditor.java deleted file mode 100644 index 9d70d29eeeb8..000000000000 --- a/platform/platform-impl/src/com/intellij/openapi/diff/actions/CompareFileWithEditor.java +++ /dev/null @@ -1,141 +0,0 @@ -/* - * Copyright 2000-2012 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.diff.actions; - -import com.intellij.openapi.actionSystem.*; -import com.intellij.openapi.diff.*; -import com.intellij.openapi.editor.Document; -import com.intellij.openapi.editor.Editor; -import com.intellij.openapi.fileEditor.FileDocumentManager; -import com.intellij.openapi.fileEditor.FileEditorManager; -import com.intellij.openapi.project.Project; -import com.intellij.openapi.vfs.VirtualFile; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; -import org.jetbrains.annotations.NonNls; - -/** - * @deprecated use {@link com.intellij.diff.actions.CompareFileWithEditorAction} instead - */ -@Deprecated -public class CompareFileWithEditor extends BaseDiffAction { - @Nullable - private static Document getEditingDocument(final DataContext dataContext) { - Project project = CommonDataKeys.PROJECT.getData(dataContext); - if (project == null) return null; - VirtualFile[] selectedFiles = FileEditorManager.getInstance(project).getSelectedFiles(); - if (selectedFiles.length == 0) return null; - VirtualFile selectedFile = selectedFiles[0]; - final Editor editor = FileEditorManager.getInstance(project).getSelectedTextEditor(); - // find document for latest selected editor - if (editor != null) { - for (VirtualFile file : selectedFiles) { - final Document document = FileDocumentManager.getInstance().getDocument(file); - if (document == editor.getDocument()) { - selectedFile = file; - } - } - } - if (!DiffContentUtil.isTextFile(selectedFile)) return null; - return FileDocumentManager.getInstance().getDocument(selectedFile); - } - - public void update(AnActionEvent e) { - boolean enabled = true; - Presentation presentation = e.getPresentation(); - presentation.setText(DiffBundle.message("diff.compare.element.type.with.editor.action.name")); - if (getDiffData(e.getDataContext()) == null) { - enabled = false; - } - if (ActionPlaces.isPopupPlace(e.getPlace())) { - presentation.setVisible(enabled); - } - else { - presentation.setEnabled(enabled); - } - } - - protected FileEditorContents getDiffData(DataContext dataContext) { - Project project = CommonDataKeys.PROJECT.getData(dataContext); - VirtualFile[] array = CommonDataKeys.VIRTUAL_FILE_ARRAY.getData(dataContext); - Document document = getEditingDocument(dataContext); - if (array == null || array.length != 1 || document == null) { - return null; - } - if (array[0].isDirectory()) { - return null; - } - if (isSameFile(document, array [0])) { - return null; - } - return new FileEditorContents(document, array [0], project); - } - - private static boolean isSameFile(Document document, VirtualFile elementFile) { - VirtualFile documentFile = FileDocumentManager.getInstance().getFile(document); - - return documentFile != null && documentFile.isValid() && - documentFile.equals(elementFile); - } - - protected void disableAction(Presentation presentation) { - presentation.setVisible(false); - } - - - private static class FileEditorContents extends DiffRequest { - private final VirtualFile myFile; - private final Document myDocument; - - public FileEditorContents(Document document, VirtualFile file, Project project) { - super(project); - myDocument = document; - myFile = file; - } - - public String[] getContentTitles() { - VirtualFile documentFile = getDocumentFile(myDocument); - String documentTitle = documentFile != null - ? getVirtualFileContentTitle(documentFile) - : DiffBundle.message("diff.content.editor.content.title"); - return new String[]{getVirtualFileContentTitle(myFile), documentTitle}; - } - - @NotNull - public DiffContent[] getContents() { - return new DiffContent[]{ - DiffContent.fromFile(getProject(), myFile), - DiffContent.fromDocument(getProject(), myDocument) - }; - } - - public String getWindowTitle() { - if (isEditorContent(myDocument)) { - return DiffBundle.message("diff.element.qualified.name.vs.editor.dialog.title", getVirtualFileContentTitle(myFile)); - } else { - return DiffBundle.message("diff.element.qualified.name.vs.file.dialog.title", getVirtualFileContentTitle(myFile), - getVirtualFileContentTitle(getDocumentFile(myDocument))); - } - - } - - @NonNls - @Override - public String toString() { - return "FileEditorContents:" + myFile.getPath(); - } - } -} diff --git a/platform/platform-impl/src/com/intellij/openapi/diff/actions/CompareJarsAction.java b/platform/platform-impl/src/com/intellij/openapi/diff/actions/CompareJarsAction.java deleted file mode 100644 index 14795ed33371..000000000000 --- a/platform/platform-impl/src/com/intellij/openapi/diff/actions/CompareJarsAction.java +++ /dev/null @@ -1,90 +0,0 @@ -/* - * Copyright 2000-2012 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.diff.actions; - -import com.intellij.featureStatistics.FeatureUsageTracker; -import com.intellij.ide.diff.DirDiffSettings; -import com.intellij.ide.diff.JarFileDiffElement; -import com.intellij.ide.diff.VirtualFileDiffElement; -import com.intellij.ide.highlighter.ArchiveFileType; -import com.intellij.openapi.actionSystem.AnAction; -import com.intellij.openapi.actionSystem.AnActionEvent; -import com.intellij.openapi.actionSystem.CommonDataKeys; -import com.intellij.openapi.actionSystem.PlatformDataKeys; -import com.intellij.openapi.diff.DirDiffManager; -import com.intellij.openapi.fileChooser.FileChooser; -import com.intellij.openapi.fileChooser.FileChooserDescriptor; -import com.intellij.openapi.project.Project; -import com.intellij.openapi.vfs.VirtualFile; - -/** - * @author Konstantin Bulenkov - */ -@Deprecated -public class CompareJarsAction extends AnAction { - @Override - public void actionPerformed(AnActionEvent e) { - final Project project = getEventProject(e); - final VirtualFile[] files = e.getData(CommonDataKeys.VIRTUAL_FILE_ARRAY); - FeatureUsageTracker.getInstance().triggerFeatureUsed("jar.diff"); - if (project != null && files != null) { - VirtualFileDiffElement src = null; - VirtualFileDiffElement trg = null; - if (files.length == 2 && isArchive(files[0]) && isArchive(files[1])) { - src = new JarFileDiffElement(files[0]); - trg = new JarFileDiffElement(files[1]); - } - else if (files.length == 1 && isArchive(files[0])) { - src = new JarFileDiffElement(files[0]); - final FileChooserDescriptor descriptor = new FileChooserDescriptor(true, false, true, true, false, false) { - @Override - public boolean isFileVisible(VirtualFile file, boolean showHiddenFiles) { - return file.isDirectory() - || (!file.isDirectory() && isArchive(file)); - } - }; - final VirtualFile[] result = FileChooser.chooseFiles(descriptor, project, project.getBaseDir()); - if (result.length == 1 && result[0] != null && isArchive(result[0])) { - trg = new JarFileDiffElement(result[0]); - } - } - final DirDiffManager mgr = DirDiffManager.getInstance(project); - if (src != null && trg != null && mgr.canShow(src, trg)) { - mgr.showDiff(src, trg, new DirDiffSettings(), null); - } - } - } - - @Override - public void update(AnActionEvent e) { - final VirtualFile[] files = e.getData(CommonDataKeys.VIRTUAL_FILE_ARRAY); - if (files != null && files.length > 0 && files.length < 3) { - if (isArchive(files[0]) && (files.length == 1 || isArchive(files[1]))) { - e.getPresentation().setEnabled(true); - e.getPresentation().setVisible(true); - e.getPresentation().setText(files.length == 1 ? "Compare Archive File with..." : "Compare Archives"); - return; - } - } - - e.getPresentation().setEnabled(false); - e.getPresentation().setVisible(false); - } - - private static boolean isArchive(VirtualFile file) { - return file.getFileType() instanceof ArchiveFileType; - } -} diff --git a/platform/platform-impl/src/com/intellij/openapi/diff/impl/CaptionIcon.java b/platform/platform-impl/src/com/intellij/openapi/diff/impl/CaptionIcon.java deleted file mode 100644 index 388341394c47..000000000000 --- a/platform/platform-impl/src/com/intellij/openapi/diff/impl/CaptionIcon.java +++ /dev/null @@ -1,124 +0,0 @@ -/* - * Copyright 2000-2012 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.diff.impl; - -import com.intellij.openapi.ui.GraphicsConfig; -import com.intellij.ui.JBColor; -import com.intellij.util.ui.GraphicsUtil; -import com.intellij.util.ui.UIUtil; - -import javax.swing.*; -import java.awt.*; -import java.awt.geom.Rectangle2D; - -public class CaptionIcon implements Icon { - private final Component mySomeComponent; - private final Form myForm; - private final boolean myWithContinuation; - private final boolean myEmphasize; - private final Color myBgrnd; - private Font myFont; - private final String myText; - - private int myHeight; - private int myWidth; - private Font myPlusFont; - private int myAddWidth; - - public CaptionIcon(Color bgrnd, Font font, String text, final Component someComponent, Form form, boolean withContionuation, - final boolean emphasize) { - myBgrnd = bgrnd; - myFont = font; - myText = text; - mySomeComponent = someComponent; - myForm = form; - myWithContinuation = withContionuation; - myEmphasize = emphasize; - - fontBasedCalculations(); - } - - private void fontBasedCalculations() { - final FontMetrics fm = mySomeComponent.getFontMetrics(myFont); - final Rectangle2D bounds = fm.getStringBounds(myText, mySomeComponent.getGraphics()); - final double height = bounds.getHeight() - fm.getMaxDescent(); // +- - myPlusFont = myFont.deriveFont(Font.BOLD); - if (myWithContinuation) { - myAddWidth = mySomeComponent.getFontMetrics(myPlusFont).stringWidth(" +"); - } else { - myAddWidth = 0; - } - myHeight = (int) height + 4; - myWidth = (int) bounds.getWidth() + 4 + myAddWidth; - } - - public void setFont(Font font) { - myFont = font; - fontBasedCalculations(); - } - - public int getIconHeight() { - return myHeight; - } - - public void paintIcon(Component c, Graphics g, int x, int y) { - final GraphicsConfig config = GraphicsUtil.setupAAPainting(g); - - ((Graphics2D)g).setPaint(myBgrnd); - - myForm.draw(c, (Graphics2D)g, myWidth, myHeight, x, y, myWithContinuation, myEmphasize); - - g.setFont(myFont); - g.setColor(UIUtil.getTextAreaForeground()); - g.drawString(myText, x + 4, y + myHeight - 3); // -2 - - g.setColor(myBgrnd.darker().darker()); - g.setFont(myPlusFont); - if (myWithContinuation) { - g.drawString(" +", x + myWidth - 2 - myAddWidth, y + myHeight - 3); - } - - config.restore(); - } - - public int getIconWidth() { - return myWidth + 4; - } - - public static enum Form { - SQUARE() { - @Override - public void draw(Component c, Graphics2D g, int width, int height, int x, int y, boolean withPlus, boolean emphasize) { - g.fillRect(x + 2, y, width, height); - g.setColor(new JBColor(Color.gray, Color.gray.darker())); - g.drawRect(x + 2, y, width, height - 1); - } - }, - ROUNDED() { - @Override - public void draw(Component c, Graphics2D g, int width, int height, int x, int y, boolean withPlus, boolean emphasize) { - g.fillRoundRect(x + 2, y, width, height, 5, 5); - - final BasicStroke stroke = new BasicStroke(1); - g.setColor(new JBColor(Color.gray, Color.gray.darker())); - g.setStroke(stroke); - g.drawRoundRect(x + 2, y, width, height - 1, 5, 5); - } - }; - - public abstract void draw(Component c, Graphics2D g, int width, int height, int x, int y, final boolean withPlus, boolean emphasize); - } -} diff --git a/platform/platform-impl/src/com/intellij/openapi/diff/impl/FragmentNumberGutterIconRenderer.java b/platform/platform-impl/src/com/intellij/openapi/diff/impl/FragmentNumberGutterIconRenderer.java deleted file mode 100644 index ef8a15a88cfa..000000000000 --- a/platform/platform-impl/src/com/intellij/openapi/diff/impl/FragmentNumberGutterIconRenderer.java +++ /dev/null @@ -1,60 +0,0 @@ -package com.intellij.openapi.diff.impl; - -import com.intellij.openapi.editor.Editor; -import com.intellij.openapi.editor.colors.EditorColorsManager; -import com.intellij.openapi.editor.colors.EditorColorsScheme; -import com.intellij.openapi.editor.colors.EditorFontType; -import com.intellij.openapi.editor.colors.TextAttributesKey; -import com.intellij.openapi.editor.ex.EditorEx; -import com.intellij.openapi.editor.markup.GutterIconRenderer; -import com.intellij.openapi.project.DumbAware; -import org.jetbrains.annotations.NotNull; - -import javax.swing.*; -import java.awt.*; - -/** - * @author irengrig - * Date: 8/12/11 - * Time: 3:12 PM - */ -public class FragmentNumberGutterIconRenderer extends GutterIconRenderer implements DumbAware { - private final String myPresentation; - private CaptionIcon myIcon; - - public FragmentNumberGutterIconRenderer(String presentation, final TextAttributesKey key, final Component component, EditorEx editor) { - myPresentation = presentation; - final EditorColorsScheme globalScheme = EditorColorsManager.getInstance().getGlobalScheme(); - final Color color = globalScheme.getAttributes(key).getBackgroundColor(); - - myIcon = new CaptionIcon(color, editor.getColorsScheme().getFont(EditorFontType.PLAIN), - presentation, component, CaptionIcon.Form.ROUNDED, false, false); - } - - public void resetFont(final Editor editor) { - myIcon.setFont(editor.getColorsScheme().getFont(EditorFontType.PLAIN)); - } - - @NotNull - @Override - public Icon getIcon() { - return myIcon; - } - - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; - - FragmentNumberGutterIconRenderer that = (FragmentNumberGutterIconRenderer)o; - - if (!myPresentation.equals(that.myPresentation)) return false; - - return true; - } - - @Override - public int hashCode() { - return myPresentation.hashCode(); - } -} diff --git a/platform/platform-impl/src/com/intellij/openapi/diff/impl/highlighting/DiffMarkup.java b/platform/platform-impl/src/com/intellij/openapi/diff/impl/highlighting/DiffMarkup.java index 27c56f8f4f0b..98f4b467d0f5 100644 --- a/platform/platform-impl/src/com/intellij/openapi/diff/impl/highlighting/DiffMarkup.java +++ b/platform/platform-impl/src/com/intellij/openapi/diff/impl/highlighting/DiffMarkup.java @@ -131,21 +131,6 @@ public abstract class DiffMarkup implements EditorSource, Disposable { } } - void setSeparatorMarker(int line, Consumer consumer) { - EditorEx editor = getEditor(); - MarkupModel markupModel = getMarkupModel(); - if (editor == null || markupModel == null) { - return; - } - RangeHighlighter marker = markupModel.addLineHighlighter(line, LAYER, null); - marker.setLineSeparatorPlacement(SeparatorPlacement.TOP); - final FragmentBoundRenderer renderer = new FragmentBoundRenderer(editor.getLineHeight(), editor, consumer); - marker.setLineSeparatorColor(renderer.getColor()); - marker.setLineSeparatorRenderer(renderer); - marker.setLineMarkerRenderer(renderer); - myExtraHighLighters.add(marker); - } - @Nullable private RangeHighlighter createLineMarker(@Nullable final TextDiffType type, int line, SeparatorPlacement placement) { MarkupModel markupModel = getMarkupModel(); diff --git a/platform/platform-impl/src/com/intellij/openapi/diff/impl/highlighting/FragmentBoundRenderer.java b/platform/platform-impl/src/com/intellij/openapi/diff/impl/highlighting/FragmentBoundRenderer.java deleted file mode 100644 index 1839f3563b63..000000000000 --- a/platform/platform-impl/src/com/intellij/openapi/diff/impl/highlighting/FragmentBoundRenderer.java +++ /dev/null @@ -1,249 +0,0 @@ -/* - * Copyright 2000-2014 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.diff.impl.highlighting; - -import com.intellij.openapi.editor.Editor; -import com.intellij.openapi.editor.ex.EditorEx; -import com.intellij.openapi.editor.impl.EditorImpl; -import com.intellij.openapi.editor.markup.LineMarkerRendererEx; -import com.intellij.openapi.editor.markup.LineSeparatorRenderer; -import com.intellij.openapi.util.Couple; -import com.intellij.util.Consumer; -import com.intellij.util.ui.UIUtil; - -import java.awt.*; -import java.util.ArrayList; -import java.util.Iterator; -import java.util.List; -import java.util.Random; - -/** - * @author irengrig - * Date: 7/6/11 - * Time: 7:44 PM - */ -public class FragmentBoundRenderer implements LineMarkerRendererEx, LineSeparatorRenderer { - private final int myLineHeight; - private final Editor myEditor; - private final Consumer myOffsetsConsumer; - private final ShoeneLine myShoeneLine; - private final Color myMainColor; - - public FragmentBoundRenderer(int lineHeight, final Editor editor, final Consumer offsetsConsumer) { - myLineHeight = lineHeight; - myEditor = editor; - myOffsetsConsumer = offsetsConsumer; - myShoeneLine = new ShoeneLine(2); - myMainColor = darkerBorder(); - } - - public static Color darkerBorder() { - final Color borderColor = UIUtil.getBorderColor(); - return new Color(borderColor.getRed() + 10, borderColor.getGreen() + 10, borderColor.getBlue() + 10); - } - // only top - - @Override - public void paint(Editor editor, Graphics g, Rectangle r) { - final Graphics gr = g.create(); - try { - ((Graphics2D) gr).setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); - - gr.setColor(getColor()); - final int width = ((EditorEx)editor).getGutterComponentEx().getWidth(); - final int editorWidth = editor.getScrollingModel().getVisibleArea().width; - myShoeneLine.ensureLastX(editorWidth + width + width); - - if (((EditorImpl) editor).isMirrored()) { - // continue - List> points = myShoeneLine.getPoints(); - int i = 0; - for (; i < points.size(); i++) { - Couple integerIntegerPair = points.get(i); - if (integerIntegerPair.getFirst() - width >= editorWidth) { - break; - } - } - // take previous - i = i == 0 ? 0 : i - 1; - points = points.subList(i, points.size()); - - drawCurved(gr, 0, r.y, TornLineParams.ourDark, points, width + editorWidth, true,width); - gr.setColor(getColor().darker()); - drawCurved(gr, 0, r.y, TornLineParams.ourLight, points, width + editorWidth, true,width); - - int j = points.size() - 1; - final int finalX = width + editorWidth; - for (; j > 0; j--) { - if (points.get(j).getFirst() >= finalX) break; - } - myOffsetsConsumer.consume(points.get(j).getSecond()); - - } else { - List> points = myShoeneLine.getPoints(); - drawCurved(gr, 0, r.y, TornLineParams.ourDark, points, 0, false,0); - gr.setColor(getColor().darker()); - drawCurved(gr, 0, r.y, TornLineParams.ourLight, points, 0, false,0); - - myOffsetsConsumer.consume(points.get(0).getSecond()); - } - } finally { - gr.dispose(); - } - } - - @Override - public Position getPosition() { - return Position.CUSTOM; - } - - public Color getColor() { - return myMainColor; - } - - @Override - public void drawLine(Graphics g, int x1, int x2, int y) { - - final int length = x2 - x1; - if (length == 0) return; - - final int width = ((EditorEx) myEditor).getGutterComponentEx().getWidth(); - - myShoeneLine.ensureLastX(length + width); - - final Graphics gr = g.create(); - - try { - ((Graphics2D) gr).setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); - gr.setColor(getColor()); - List> points = myShoeneLine.getPoints(); - int i = getLastPointInBeforeGutter(width, points); - points = points.subList(i, points.size()); - drawCurved(gr, x1, y, TornLineParams.ourDark, points, width, false,0); - gr.setColor(getColor().darker()); - drawCurved(gr, x1, y, TornLineParams.ourLight, points, width, false,0); - } finally { - gr.dispose(); - } - } - - private int getLastPointInBeforeGutter(int width, List> points) { - int i = 0; - for (; i < points.size(); i++) { - if (points.get(i).getFirst() >= width) break; - } - i = i == 0 ? 0 : i - 1; - return i; - } - - private void drawCurved(Graphics g, - final int x1, - int y, - final int offset, - final List> points, - final int subtractX, - final boolean mirrorX, final int mirrorSize) { - final Iterator> iterator = points.iterator(); - assert iterator.hasNext(); - - int[] xPoints = new int[points.size()]; - int[] yPoints1 = new int[points.size()]; - int[] yPoints2 = new int[points.size()]; - int n = 0; - - Couple previous = iterator.next(); - while (iterator.hasNext()) { - final Couple next = iterator.next(); - - xPoints[n] = convert(previous.getFirst(), x1, subtractX, mirrorX, mirrorSize); - yPoints1[n] = y + offset + previous.getSecond() - myLineHeight / 2; - yPoints2[n] = y - offset + previous.getSecond() - myLineHeight / 2; - n++; - previous = next; - } - xPoints[n] = convert(previous.getFirst(), x1, subtractX, mirrorX, mirrorSize); - yPoints1[n] = y + offset + previous.getSecond() - myLineHeight / 2; - yPoints2[n] = y - offset + previous.getSecond() - myLineHeight / 2; - - g.drawPolyline(xPoints, yPoints1, points.size()); - g.drawPolyline(xPoints, yPoints2, points.size()); - } - - private static int convert(int value, int x1, int subtractX, boolean mirrorX, int mirrorSize) { - final int val = x1 + value - subtractX; - if (mirrorX) { - return mirrorSize - val; - } - return val; - } - - private static class ShoeneLine { - private List> myPoints; - private final int myYDiff; - - private ShoeneLine(final int yDiff) { - myYDiff = yDiff; - myPoints = new ArrayList>(); - } - - public void ensureLastX(final int x) { - if (myPoints.isEmpty() || myPoints.get(myPoints.size() - 1).getFirst() < x) { - if (myPoints.isEmpty()) { - myPoints.add(Couple.of(0, 0)); - myPoints.addAll(generateLine(0,0,x,0,myYDiff,0)); - } else { - final Couple lastPoint = myPoints.get(myPoints.size() - 1); - int finalX = (x - lastPoint.getFirst()) < 5 ? x + 10 : x; - myPoints.addAll(generateLine(lastPoint.getFirst(),lastPoint.getSecond(),finalX,0,myYDiff,lastPoint.getSecond())); - } - //myPoints.set(myPoints.size() - 1, new Pair(x, 0)); - } - } - - public List> getPoints() { - return myPoints; - } - } - - private final static int xVariation = 7; - - private static List> generateLine(final int startX, int startY, int finalX, final int yBase, final int yDiff, - final int wasPrevStep) { - int xCurrent = startX; - int yCurrent = startY; - - final List> result = new ArrayList>(); - - final Random xRnd = new Random(); - final Random yRnd = new Random(); - int prevStep = wasPrevStep; - while (xCurrent < finalX) { - int yStep = prevStep; - while (prevStep == yStep) { - yStep = yRnd.nextInt(yDiff * 2) - yDiff; - } - prevStep = yStep; - int newY = yBase + yStep; - int newX = xCurrent + 4 + xRnd.nextInt(xVariation); - newX = Math.min(newX, finalX); - - result.add(Couple.of(newX, newY)); - xCurrent = newX; - } - - return result; - } -} diff --git a/platform/platform-impl/src/com/intellij/openapi/diff/impl/highlighting/FragmentSeparatorsPositionConsumer.java b/platform/platform-impl/src/com/intellij/openapi/diff/impl/highlighting/FragmentSeparatorsPositionConsumer.java deleted file mode 100644 index 2bb3c7dccc91..000000000000 --- a/platform/platform-impl/src/com/intellij/openapi/diff/impl/highlighting/FragmentSeparatorsPositionConsumer.java +++ /dev/null @@ -1,98 +0,0 @@ -/* - * Copyright 2000-2011 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.diff.impl.highlighting; - -import java.util.TreeMap; - -/** -* Created by IntelliJ IDEA. -* User: Irina.Chernushina -* Date: 10/13/11 -* Time: 12:08 PM -*/ -public class FragmentSeparatorsPositionConsumer { - // line to offset - private final TreeMap myLeft; - private final TreeMap myRight; - - public FragmentSeparatorsPositionConsumer() { - myLeft = new TreeMap(); - myRight = new TreeMap(); - } - - public void prepare(final int left, final int right) { - final TornSeparator tornSeparator = new TornSeparator(left, right); - myLeft.put(left, tornSeparator); - myRight.put(right, tornSeparator); - } - - public void addLeft(final int line, final int offset) { - myLeft.get(line).setLeftOffset(offset); - } - - public void addRight(final int line, final int offset) { - myRight.get(line).setRightOffset(offset); - } - - public TreeMap getLeft() { - return myLeft; - } - - public TreeMap getRight() { - return myRight; - } - - public void clear() { - myLeft.clear(); - myRight.clear(); - } - - public static class TornSeparator { - private final int myLeftLine; - private final int myRightLine; - private int myLeftOffset; - private int myRightOffset; - - public TornSeparator(int leftLine, int rightLine) { - myLeftLine = leftLine; - myRightLine = rightLine; - } - - public int getLeftOffset() { - return myLeftOffset; - } - - public void setLeftOffset(int leftOffset) { - myLeftOffset = leftOffset; - } - - public int getRightOffset() { - return myRightOffset; - } - - public void setRightOffset(int rightOffset) { - myRightOffset = rightOffset; - } - - public int getLeftLine() { - return myLeftLine; - } - - public int getRightLine() { - return myRightLine; - } - } -} diff --git a/platform/platform-impl/src/com/intellij/openapi/diff/impl/highlighting/FragmentedDiffPanelState.java b/platform/platform-impl/src/com/intellij/openapi/diff/impl/highlighting/FragmentedDiffPanelState.java deleted file mode 100644 index 2ceffb5651c5..000000000000 --- a/platform/platform-impl/src/com/intellij/openapi/diff/impl/highlighting/FragmentedDiffPanelState.java +++ /dev/null @@ -1,270 +0,0 @@ -/* - * Copyright 2000-2011 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.diff.impl.highlighting; - -import com.intellij.openapi.Disposable; -import com.intellij.openapi.diff.DiffContent; -import com.intellij.openapi.diff.impl.ContentChangeListener; -import com.intellij.openapi.diff.impl.fragments.FragmentListImpl; -import com.intellij.openapi.diff.impl.fragments.LineFragment; -import com.intellij.openapi.diff.impl.processing.DiffPolicy; -import com.intellij.openapi.diff.impl.processing.TextCompareProcessor; -import com.intellij.openapi.diff.impl.splitter.LineBlocks; -import com.intellij.openapi.editor.Editor; -import com.intellij.openapi.editor.LogicalPosition; -import com.intellij.openapi.editor.markup.TextAttributes; -import com.intellij.openapi.project.Project; -import com.intellij.openapi.util.TextRange; -import com.intellij.util.BeforeAfter; -import com.intellij.util.Consumer; -import com.intellij.util.diff.FilesTooBigForDiffException; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -import javax.swing.*; -import java.awt.*; -import java.util.*; -import java.util.List; - -/** - * for read-only documents.. - * - * @author irengrig - * Date: 7/6/11 - * Time: 7:31 PM - */ -public class FragmentedDiffPanelState extends DiffPanelState { - // fragment _start_ lines - private List> myRanges; - private final NumberedFragmentHighlighter myFragmentHighlighter; - private FragmentSeparatorsPositionConsumer mySeparatorsPositionConsumer; - - public FragmentedDiffPanelState(ContentChangeListener changeListener, - Project project, - int diffDividerPolygonsOffset, - boolean drawNumber, - @NotNull Disposable parentDisposable) { - super(changeListener, project, diffDividerPolygonsOffset, parentDisposable); - myFragmentHighlighter = new NumberedFragmentHighlighter(myAppender1, myAppender2, drawNumber); - mySeparatorsPositionConsumer = new FragmentSeparatorsPositionConsumer(); - } - - @Override - public void setContents(DiffContent content1, DiffContent content2) { - myAppender1.setContent(content1); - myAppender2.setContent(content2); - myFragmentHighlighter.reset(); - } - - private LineBlocks addMarkup(final List lines) { - myFragmentHighlighter.precalculateNumbers(lines); - - for (Iterator iterator = lines.iterator(); iterator.hasNext(); ) { - LineFragment line = iterator.next(); - myFragmentHighlighter.setIsLast(!iterator.hasNext()); - line.highlight(myFragmentHighlighter); - } - ArrayList allLineFragments = new ArrayList(); - for (LineFragment lineFragment : lines) { - allLineFragments.add(lineFragment); - lineFragment.addAllDescendantsTo(allLineFragments); - } - myFragmentList = FragmentListImpl.fromList(allLineFragments); - return LineBlocks.fromLineFragments(allLineFragments); - } - - public void addRangeHighlighter(final boolean left, int start, int end, final TextAttributes attributes) { - myFragmentHighlighter.addRangeHighlighter(left, start, end, attributes); - } - - private void resetMarkup() { - myAppender1.resetHighlighters(); - myAppender2.resetHighlighters(); - } - - @Nullable - public LineBlocks updateEditors() throws FilesTooBigForDiffException { - resetMarkup(); - mySeparatorsPositionConsumer.clear(); - if (myAppender1.getEditor() == null || myAppender2.getEditor() == null) { - return null; - } - - int previousBefore = -1; - int previousAfter = -1; - - final List> ranges = new ArrayList>(); - for (int i = 0; i < myRanges.size(); i++) { - final BeforeAfter start = lineStarts(i); - final BeforeAfter end = i == myRanges.size() - 1 ? - new BeforeAfter(myAppender1.getDocument().getTextLength(), - myAppender2.getDocument().getTextLength()) : - lineStarts(i + 1); - - ranges.add(new BeforeAfter(new TextRange(start.getBefore(), end.getBefore()), - new TextRange(start.getAfter(), end.getAfter()))); - - if (previousBefore > 0 && previousAfter > 0) { - final int finalPreviousBefore = previousBefore; - mySeparatorsPositionConsumer.prepare(previousBefore, previousAfter); - - myAppender1.setSeparatorMarker(previousBefore, new Consumer() { - @Override - public void consume(Integer integer) { - mySeparatorsPositionConsumer.addLeft(finalPreviousBefore, integer); - } - }); - final int finalPreviousAfter = previousAfter; - myAppender2.setSeparatorMarker(previousAfter, new Consumer() { - @Override - public void consume(Integer integer) { - mySeparatorsPositionConsumer.addRight(finalPreviousAfter, integer); - } - }); - } - previousBefore = myRanges.get(i).getBefore(); - previousAfter = myRanges.get(i).getAfter(); - } - - final PresetBlocksDiffPolicy diffPolicy = new PresetBlocksDiffPolicy(DiffPolicy.LINES_WO_FORMATTING); - // shouldn't be set since component is reused. or no getDiffPolicy for delegate initialization - //setDiffPolicy(diffPolicy); - diffPolicy.setRanges(ranges); - - return addMarkup( - new TextCompareProcessor(myComparisonPolicy, diffPolicy, myHighlightMode).process(myAppender1.getText(), myAppender2.getText())); - } - - private BeforeAfter lineStarts(int i) { - return new BeforeAfter(myAppender1.getDocument().getLineStartOffset(myRanges.get(i).getBefore()), - myAppender2.getDocument().getLineStartOffset(myRanges.get(i).getAfter())); - } - - public void setRanges(List> ranges) { - myRanges = new ArrayList>(); - if (!ranges.isEmpty()) { - if (ranges.get(0).getAfter() != 0 && ranges.get(0).getBefore() != 0) { - myRanges.add(new BeforeAfter(0, 0)); - } - } - myRanges.addAll(ranges); - } - - public List getLeftLines() { - return myFragmentHighlighter.getLeftLines(); - } - - public List getRightLines() { - return myFragmentHighlighter.getRightLines(); - } - - public FragmentSeparatorsPositionConsumer getSeparatorsPositionConsumer() { - return mySeparatorsPositionConsumer; - } - - @Override - public void drawOnDivider(Graphics gr, JComponent component) { - if (myAppender1.getEditor() == null || myAppender2.getEditor() == null) return; - - final int startLeft = getStartVisibleLine(myAppender1.getEditor()); - final int startRight = getStartVisibleLine(myAppender2.getEditor()); - - final int width = component.getWidth(); - final int lineHeight = myAppender1.getEditor().getLineHeight(); - - final TreeMap left = mySeparatorsPositionConsumer.getLeft(); - - final int leftScrollOffset = myAppender1.getEditor().getScrollingModel().getVerticalScrollOffset(); - final int rightScrollOffset = myAppender2.getEditor().getScrollingModel().getVerticalScrollOffset(); - - final Graphics g = gr.create(); - - try { - ((Graphics2D)g).setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); - for (Map.Entry entry : left.entrySet()) { - final FragmentSeparatorsPositionConsumer.TornSeparator tornSeparator = entry.getValue(); - if (tornSeparator.getLeftLine() >= startLeft || tornSeparator.getRightLine() >= startRight) { - final int leftOffset = tornSeparator.getLeftOffset(); - int leftBaseY = - myAppender1.getEditor().logicalPositionToXY(new LogicalPosition(tornSeparator.getLeftLine(), 0)).y - lineHeight / 2 - - leftScrollOffset + myDiffDividerPolygonsOffset; - - final int rightOffset = tornSeparator.getRightOffset(); - int rightBaseY = - myAppender2.getEditor().logicalPositionToXY(new LogicalPosition(tornSeparator.getRightLine(), 0)).y - lineHeight / 2 - - rightScrollOffset + myDiffDividerPolygonsOffset; - - int x1 = 0; - int x2 = width; - int y1 = leftBaseY + leftOffset; - int y2 = rightBaseY + rightOffset; - - if (Math.abs(x2 - x1) < Math.abs(y2 - y1)) { - int dx = TornLineParams.ourDark; - int dy = TornLineParams.ourLight; - if (y2 < y1) { - g.setColor(FragmentBoundRenderer.darkerBorder()); - g.drawLine(x1 + dx, y1 - dy + TornLineParams.ourDark, x2, y2 + TornLineParams.ourDark); - g.drawLine(x1, y1 - TornLineParams.ourDark, x2 - dx, y2 + dy - TornLineParams.ourDark); - - g.drawLine(x1, y1 + TornLineParams.ourDark, x1 + dx, y1 - dy + TornLineParams.ourDark); - g.drawLine(x2, y2 - TornLineParams.ourDark, x2 - dx, y2 + dy - TornLineParams.ourDark); - - g.setColor(FragmentBoundRenderer.darkerBorder().darker()); - g.drawLine(x1 + dx, y1 - dy + TornLineParams.ourLight, x2, y2 + TornLineParams.ourLight); - g.drawLine(x1, y1 - TornLineParams.ourLight, x2 - dx, y2 + dy - TornLineParams.ourLight); - - g.drawLine(x1, y1 + TornLineParams.ourLight, x1 + dx, y1 - dy + TornLineParams.ourLight); - g.drawLine(x2, y2 - TornLineParams.ourLight, x2 - dx, y2 + dy - TornLineParams.ourLight); - } else { - g.setColor(FragmentBoundRenderer.darkerBorder()); - g.drawLine(x1, y1 + TornLineParams.ourDark, x2 - dx, y2 - dy + TornLineParams.ourDark); - g.drawLine(x1 + dx, y1 + dy - TornLineParams.ourDark, x2, y2 - TornLineParams.ourDark); - - g.drawLine(x2, y2 + TornLineParams.ourDark, x2 - dx, y2 - dy + TornLineParams.ourDark); - g.drawLine(x1, y1 - TornLineParams.ourDark, x1 + dx, y1 + dy - TornLineParams.ourDark); - - g.setColor(FragmentBoundRenderer.darkerBorder().darker()); - g.drawLine(x1, y1 + TornLineParams.ourLight, x2 - dx, y2 - dy + TornLineParams.ourLight); - g.drawLine(x1 + dx, y1 + dy - TornLineParams.ourLight, x2, y2 - TornLineParams.ourLight); - - g.drawLine(x2, y2 + TornLineParams.ourLight, x2 - dx, y2 - dy + TornLineParams.ourLight); - g.drawLine(x1, y1 - TornLineParams.ourLight, x1 + dx, y1 + dy - TornLineParams.ourLight); - } - - } else { - g.setColor(FragmentBoundRenderer.darkerBorder()); - g.drawLine(x1, y1 + TornLineParams.ourDark, x2, y2 + TornLineParams.ourDark); - g.drawLine(x1, y1 - TornLineParams.ourDark, x2, y2 - TornLineParams.ourDark); - - g.setColor(FragmentBoundRenderer.darkerBorder().darker()); - g.drawLine(x1, y1 + TornLineParams.ourLight, x2, y2 + TornLineParams.ourLight); - g.drawLine(x1, y1 - TornLineParams.ourLight, x2, y2 - TornLineParams.ourLight); - } - } - } - } - finally { - g.dispose(); - } - } - - private int getStartVisibleLine(final Editor editor) { - int offset = editor.getScrollingModel().getVerticalScrollOffset(); - LogicalPosition logicalPosition = editor.xyToLogicalPosition(new Point(0, offset)); - return logicalPosition.line; - } -} diff --git a/platform/platform-impl/src/com/intellij/openapi/diff/impl/highlighting/NumberedFragmentHighlighter.java b/platform/platform-impl/src/com/intellij/openapi/diff/impl/highlighting/NumberedFragmentHighlighter.java deleted file mode 100644 index bc8b9638e725..000000000000 --- a/platform/platform-impl/src/com/intellij/openapi/diff/impl/highlighting/NumberedFragmentHighlighter.java +++ /dev/null @@ -1,222 +0,0 @@ -/* - * Copyright 2000-2014 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.diff.impl.highlighting; - -import com.intellij.codeInsight.daemon.GutterMark; -import com.intellij.openapi.diff.DiffColors; -import com.intellij.openapi.diff.impl.FragmentNumberGutterIconRenderer; -import com.intellij.openapi.diff.impl.fragments.Fragment; -import com.intellij.openapi.diff.impl.fragments.FragmentHighlighterImpl; -import com.intellij.openapi.diff.impl.fragments.LineFragment; -import com.intellij.openapi.diff.impl.util.TextDiffTypeEnum; -import com.intellij.openapi.editor.colors.TextAttributesKey; -import com.intellij.openapi.editor.ex.EditorEx; -import com.intellij.openapi.editor.markup.HighlighterLayer; -import com.intellij.openapi.editor.markup.HighlighterTargetArea; -import com.intellij.openapi.editor.markup.RangeHighlighter; -import com.intellij.openapi.editor.markup.TextAttributes; -import com.intellij.openapi.util.Pair; -import com.intellij.openapi.util.TextRange; -import com.intellij.util.containers.MultiMap; - -import java.beans.PropertyChangeEvent; -import java.beans.PropertyChangeListener; -import java.util.*; - -/** - * @author irengrig - * Date: 8/12/11 - * Time: 4:01 PM - */ -public class NumberedFragmentHighlighter extends FragmentHighlighterImpl { - private final boolean myDrawNumber; - private final Map> myLeftPrecalculated; - private final Map> myRightPrecalculated; - private int myPreviousLineLeft; - private int myPreviousLineRight; - private NumberedFragmentHighlighter.MyPropertyChangeListener myPropertyChangeListener; - - public NumberedFragmentHighlighter(DiffMarkup appender1, DiffMarkup appender2, boolean drawNumber) { - super(appender1, appender2); - myDrawNumber = drawNumber; - myLeftPrecalculated = new HashMap>(); - myRightPrecalculated = new HashMap>(); - myPreviousLineLeft = -1; - myPreviousLineRight = -1; - } - - private class MyPropertyChangeListener implements PropertyChangeListener { - @Override - public void propertyChange(PropertyChangeEvent evt) { - if (!EditorEx.PROP_FONT_SIZE.equals(evt.getPropertyName())) return; - if (evt.getOldValue().equals(evt.getNewValue())) return; - RangeHighlighter[] allHighlighters = myAppender1.getEditor().getMarkupModel().getAllHighlighters(); - resetFont(allHighlighters); - RangeHighlighter[] allHighlighters2 = myAppender2.getEditor().getMarkupModel().getAllHighlighters(); - resetFont(allHighlighters2); - } - - private void resetFont(RangeHighlighter[] allHighlighters) { - for (RangeHighlighter highlighter : allHighlighters) { - GutterMark renderer = highlighter.getGutterIconRenderer(); - if (renderer instanceof FragmentNumberGutterIconRenderer) { - ((FragmentNumberGutterIconRenderer)renderer).resetFont(myAppender1.getEditor()); - } - } - } - } - - private TextAttributesKey getColorAttributesKey(final TextDiffTypeEnum textDiffTypeEnum) { - if (TextDiffTypeEnum.CHANGED.equals(textDiffTypeEnum)) { - return DiffColors.DIFF_MODIFIED; - } else if (TextDiffTypeEnum.INSERT.equals(textDiffTypeEnum)) { - return DiffColors.DIFF_INSERTED; - } else if (TextDiffTypeEnum.DELETED.equals(textDiffTypeEnum)) { - return DiffColors.DIFF_DELETED; - } else if (TextDiffTypeEnum.CONFLICT.equals(textDiffTypeEnum)) { - return DiffColors.DIFF_CONFLICT; - } else { - return null; - } - } - - @Override - protected void highlightFragmentImpl(Fragment fragment) { - if (! myDrawNumber || fragment.getType() == null || TextDiffTypeEnum.NONE.equals(fragment.getType())) { - myAppender1.highlightText(fragment, null); - myAppender2.highlightText(fragment, null); - return; - } - int lineLeft = myAppender1.getDocument().getLineNumber(fragment.getRange(FragmentSide.SIDE1).getStartOffset()); - int lineRight = myAppender2.getDocument().getLineNumber(fragment.getRange(FragmentSide.SIDE2).getStartOffset()); - Pair left = myLeftPrecalculated.get(lineLeft); - if (myPreviousLineLeft == lineLeft || left == null) { - myAppender1.highlightText(fragment, null); - } else { - // draw border == true for range marker with highlighting and number be set anyway, even if range is empty - myAppender1.highlightText(fragment, new FragmentNumberGutterIconRenderer(left.getFirst(), getColorAttributesKey(left.getSecond()), myAppender1.getEditor().getScrollPane(), myAppender1.getEditor())); - myPreviousLineLeft = lineLeft; - } - - Pair right = myRightPrecalculated.get(lineRight); - if (myPreviousLineRight == lineRight || right == null) { - myAppender2.highlightText(fragment, null); - } else { - // draw border == true for range marker with highlighting and number be set anyway, even if range is empty - myAppender2.highlightText(fragment, new FragmentNumberGutterIconRenderer(right.getFirst(), getColorAttributesKey(right.getSecond()), myAppender1.getEditor().getScrollPane(), - myAppender1.getEditor())); - myPreviousLineRight = lineRight; - } - } - - public void addRangeHighlighter(final boolean left, int start, int end, final TextAttributes attributes) { - if (left) { - myAppender1.getEditor().getMarkupModel().addRangeHighlighter(start, end, HighlighterLayer.SELECTION - 3, attributes, - HighlighterTargetArea.EXACT_RANGE); - } else { - myAppender2.getEditor().getMarkupModel().addRangeHighlighter(start, end, HighlighterLayer.SELECTION - 3, attributes, - HighlighterTargetArea.EXACT_RANGE); - } - } - - public void reset() { - myLeftPrecalculated.clear(); - myRightPrecalculated.clear(); - myPreviousLineLeft = -1; - myPreviousLineRight = -1; - } - - public void precalculateNumbers(List lines) { - if (myPropertyChangeListener == null) { - myPropertyChangeListener = new MyPropertyChangeListener(); - myAppender1.getEditor().addPropertyChangeListener(myPropertyChangeListener); - } - final MultiMap> leftMap = new MultiMap>(); - final MultiMap> rightMap = new MultiMap>(); - - int cnt = 1; - for (LineFragment line : lines) { - if (line.getType() == null || TextDiffTypeEnum.NONE.equals(line.getType())) continue; - - final Iterator iterator = line.getChildrenIterator(); - if (iterator == null) { - TextRange left = line.getRange(FragmentSide.SIDE1); - TextRange right = line.getRange(FragmentSide.SIDE2); - - leftMap.putValue(myAppender1.getDocument().getLineNumber(left.getStartOffset()), new Pair(cnt, line.getType())); - rightMap.putValue(myAppender2.getDocument().getLineNumber(right.getStartOffset()), new Pair(cnt, line.getType())); - ++ cnt; - continue; - } - while (iterator.hasNext()) { - final Fragment next = iterator.next(); - if (next.getType() == null || TextDiffTypeEnum.NONE.equals(next.getType())) continue; - - TextRange left = next.getRange(FragmentSide.SIDE1); - TextRange right = next.getRange(FragmentSide.SIDE2); - - leftMap.putValue(myAppender1.getDocument().getLineNumber(left.getStartOffset()), new Pair(cnt, next.getType())); - rightMap.putValue(myAppender2.getDocument().getLineNumber(right.getStartOffset()), new Pair(cnt, next.getType())); - ++ cnt; - } - } - - // merge - merge(leftMap, myLeftPrecalculated); - merge(rightMap, myRightPrecalculated); - } - - private void merge(MultiMap> leftMap, - final Map> whereTo) { - for (Map.Entry>> entry : leftMap.entrySet()) { - List> value = (List>) entry.getValue(); - if (value.size() > 1) { - Pair pair1 = value.iterator().next(); - Pair pair2 = value.get(value.size() - 1); - TextDiffTypeEnum type = mergeDiffType(value); - whereTo.put(entry.getKey(), Pair.create(String.valueOf(pair1.getFirst()) + "-" + - String.valueOf(pair2.getFirst()), type)); - } else { - Pair pair = value.iterator().next(); - whereTo.put(entry.getKey(), Pair.create(String.valueOf(pair.getFirst()), pair.getSecond())); - } - } - } - - private TextDiffTypeEnum mergeDiffType(List> value) { - TextDiffTypeEnum previous = null; - for (Pair pair : value) { - if (previous == null) { - previous = pair.getSecond(); - continue; - } - if (! previous.equals(pair.getSecond())) return TextDiffTypeEnum.CHANGED; - } - return previous; - } - - public List getLeftLines() { - List list = new ArrayList(myLeftPrecalculated.keySet()); - Collections.sort(list); - return list; - } - - public List getRightLines() { - List list = new ArrayList(myRightPrecalculated.keySet()); - Collections.sort(list); - return list; - } -} diff --git a/platform/platform-impl/src/com/intellij/openapi/diff/impl/highlighting/PresetBlocksDiffPolicy.java b/platform/platform-impl/src/com/intellij/openapi/diff/impl/highlighting/PresetBlocksDiffPolicy.java deleted file mode 100644 index 3fd7df130e45..000000000000 --- a/platform/platform-impl/src/com/intellij/openapi/diff/impl/highlighting/PresetBlocksDiffPolicy.java +++ /dev/null @@ -1,69 +0,0 @@ -/* - * Copyright 2000-2011 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.diff.impl.highlighting; - -import com.intellij.openapi.diff.impl.string.DiffString; -import com.intellij.openapi.diff.ex.DiffFragment; -import com.intellij.openapi.diff.impl.processing.DiffPolicy; -import com.intellij.openapi.util.TextRange; -import com.intellij.util.BeforeAfter; -import com.intellij.util.diff.FilesTooBigForDiffException; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.TestOnly; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; - -/** - * @author irengrig - * Date: 7/7/11 - * Time: 12:49 PM - */ -public class PresetBlocksDiffPolicy implements DiffPolicy { - // fragment _start_ offsets - private List> myRanges; - @NotNull private final DiffPolicy myDelegate; - - public PresetBlocksDiffPolicy(@NotNull DiffPolicy delegate) { - myDelegate = delegate; - } - - @TestOnly - @NotNull - @Override - public DiffFragment[] buildFragments(@NotNull String text1, @NotNull String text2) throws FilesTooBigForDiffException { - return buildFragments(DiffString.create(text1), DiffString.create(text2)); - } - - @NotNull - @Override - public DiffFragment[] buildFragments(@NotNull DiffString text1, @NotNull DiffString text2) throws FilesTooBigForDiffException { - final List fragments = new ArrayList(); - for (int i = 0; i < myRanges.size(); i++) { - final BeforeAfter range = myRanges.get(i); - fragments.addAll(Arrays.asList(myDelegate.buildFragments( - text1.substring(range.getBefore().getStartOffset(), range.getBefore().getEndOffset()).copy(), - text2.substring(range.getAfter().getStartOffset(), range.getAfter().getEndOffset()).copy()))); - } - - return fragments.toArray(new DiffFragment[fragments.size()]); - } - - public void setRanges(List> ranges) { - myRanges = ranges; - } -} diff --git a/platform/platform-impl/src/com/intellij/openapi/editor/CustomFileDropHandler.java b/platform/platform-impl/src/com/intellij/openapi/editor/CustomFileDropHandler.java new file mode 100644 index 000000000000..376f93a85108 --- /dev/null +++ b/platform/platform-impl/src/com/intellij/openapi/editor/CustomFileDropHandler.java @@ -0,0 +1,31 @@ +/* + * Copyright 2000-2016 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.editor; + +import com.intellij.openapi.extensions.ExtensionPointName; +import com.intellij.openapi.project.Project; +import org.jetbrains.annotations.NotNull; + +import java.awt.datatransfer.Transferable; + +public abstract class CustomFileDropHandler { + public static final ExtensionPointName CUSTOM_DROP_HANDLER_EP = + ExtensionPointName.create("com.intellij.customFileDropHandler"); + + public abstract boolean canHandle(@NotNull Transferable t); + + public abstract boolean handleDrop(@NotNull Transferable t, final Project project); +} diff --git a/platform/platform-impl/src/com/intellij/openapi/editor/actions/AbstractToggleUseSoftWrapsAction.java b/platform/platform-impl/src/com/intellij/openapi/editor/actions/AbstractToggleUseSoftWrapsAction.java index 5c0158d63a66..bab77c5ad3eb 100644 --- a/platform/platform-impl/src/com/intellij/openapi/editor/actions/AbstractToggleUseSoftWrapsAction.java +++ b/platform/platform-impl/src/com/intellij/openapi/editor/actions/AbstractToggleUseSoftWrapsAction.java @@ -66,18 +66,22 @@ public abstract class AbstractToggleUseSoftWrapsAction extends ToggleAction impl return; } + toggleSoftWraps(editor, myGlobal ? myAppliancePlace : null, state); + } + + public static void toggleSoftWraps(@NotNull Editor editor, @Nullable SoftWrapAppliancePlaces places, boolean state) { Point point = editor.getScrollingModel().getVisibleArea().getLocation(); LogicalPosition anchorPosition = editor.xyToLogicalPosition(point); int intraLineShift = point.y - editor.logicalPositionToXY(anchorPosition).y; - - if (myGlobal) { - EditorSettingsExternalizable.getInstance().setUseSoftWraps(state, myAppliancePlace); + + if (places != null) { + EditorSettingsExternalizable.getInstance().setUseSoftWraps(state, places); EditorFactory.getInstance().refreshAllEditors(); } if (editor.getSettings().isUseSoftWraps() != state) { editor.getSettings().setUseSoftWraps(state); } - + editor.getScrollingModel().disableAnimation(); editor.getScrollingModel().scrollVertically(editor.logicalPositionToXY(anchorPosition).y + intraLineShift); editor.getScrollingModel().enableAnimation(); diff --git a/platform/platform-impl/src/com/intellij/openapi/editor/impl/EditorGutterComponentImpl.java b/platform/platform-impl/src/com/intellij/openapi/editor/impl/EditorGutterComponentImpl.java index 2dde34d73c69..f112110da92a 100644 --- a/platform/platform-impl/src/com/intellij/openapi/editor/impl/EditorGutterComponentImpl.java +++ b/platform/platform-impl/src/com/intellij/openapi/editor/impl/EditorGutterComponentImpl.java @@ -867,11 +867,11 @@ class EditorGutterComponentImpl extends EditorGutterComponentEx implements Mouse @Override public void process(@NotNull RangeHighlighter highlighter) { LineMarkerRenderer renderer = highlighter.getLineMarkerRenderer(); - if (renderer != null && isLineMarkerVisible(highlighter)) highlighters.add(highlighter); + if (renderer != null) highlighters.add(highlighter); } }); - ContainerUtil.sort(highlighters, (h1, h2) -> h1.getLayer() - h2.getLayer()); + ContainerUtil.sort(highlighters, Comparator.comparingInt(RangeHighlighter::getLayer)); for (RangeHighlighter highlighter : highlighters) { paintLineMarkerRenderer(highlighter, g); diff --git a/platform/platform-impl/src/com/intellij/openapi/fileChooser/impl/FileComparator.java b/platform/platform-impl/src/com/intellij/openapi/fileChooser/impl/FileComparator.java index a78b783e0366..96f2415d9ffa 100644 --- a/platform/platform-impl/src/com/intellij/openapi/fileChooser/impl/FileComparator.java +++ b/platform/platform-impl/src/com/intellij/openapi/fileChooser/impl/FileComparator.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2009 JetBrains s.r.o. + * Copyright 2000-2016 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. @@ -14,14 +14,11 @@ * limitations under the License. */ -/** - * @author Yura Cangea - */ package com.intellij.openapi.fileChooser.impl; +import com.intellij.ide.util.treeView.NodeDescriptor; import com.intellij.openapi.fileChooser.ex.FileNodeDescriptor; import com.intellij.openapi.vfs.VirtualFile; -import com.intellij.ide.util.treeView.NodeDescriptor; import java.util.Comparator; diff --git a/platform/platform-impl/src/com/intellij/openapi/fileEditor/impl/FileEditorManagerImpl.java b/platform/platform-impl/src/com/intellij/openapi/fileEditor/impl/FileEditorManagerImpl.java index d85e45404fa0..cc69e40fbdd0 100644 --- a/platform/platform-impl/src/com/intellij/openapi/fileEditor/impl/FileEditorManagerImpl.java +++ b/platform/platform-impl/src/com/intellij/openapi/fileEditor/impl/FileEditorManagerImpl.java @@ -1510,8 +1510,8 @@ public class FileEditorManagerImpl extends FileEditorManagerEx implements Persis final FileStatusManager fileStatusManager = FileStatusManager.getInstance(myProject); if (fileStatusManager != null) { - /** - * Updates tabs colors + /* + Updates tabs colors */ final MyFileStatusListener myFileStatusListener = new MyFileStatusListener(); fileStatusManager.addFileStatusListener(myFileStatusListener, myProject); @@ -1519,13 +1519,13 @@ public class FileEditorManagerImpl extends FileEditorManagerEx implements Persis connection.subscribe(FileTypeManager.TOPIC, new MyFileTypeListener()); connection.subscribe(ProjectTopics.PROJECT_ROOTS, new MyRootsListener()); - /** - * Updates tabs names + /* + Updates tabs names */ final MyVirtualFileListener myVirtualFileListener = new MyVirtualFileListener(); VirtualFileManager.getInstance().addVirtualFileListener(myVirtualFileListener, myProject); - /** - * Extends/cuts number of opened tabs. Also updates location of tabs. + /* + Extends/cuts number of opened tabs. Also updates location of tabs. */ final MyUISettingsListener myUISettingsListener = new MyUISettingsListener(); UISettings.getInstance().addUISettingsListener(myUISettingsListener, myProject); diff --git a/platform/platform-impl/src/com/intellij/openapi/fileEditor/impl/text/FileDropHandler.java b/platform/platform-impl/src/com/intellij/openapi/fileEditor/impl/text/FileDropHandler.java index 342cb0959f88..61160ad5b376 100644 --- a/platform/platform-impl/src/com/intellij/openapi/fileEditor/impl/text/FileDropHandler.java +++ b/platform/platform-impl/src/com/intellij/openapi/fileEditor/impl/text/FileDropHandler.java @@ -16,9 +16,11 @@ package com.intellij.openapi.fileEditor.impl.text; import com.intellij.ide.dnd.FileCopyPasteUtil; +import com.intellij.openapi.editor.CustomFileDropHandler; import com.intellij.openapi.editor.Document; import com.intellij.openapi.editor.Editor; import com.intellij.openapi.editor.EditorDropHandler; +import com.intellij.openapi.extensions.Extensions; import com.intellij.openapi.fileEditor.*; import com.intellij.openapi.fileEditor.ex.FileEditorManagerEx; import com.intellij.openapi.fileEditor.impl.EditorWindow; @@ -26,6 +28,7 @@ import com.intellij.openapi.fileEditor.impl.EditorWithProviderComposite; import com.intellij.openapi.project.Project; import com.intellij.openapi.vfs.LocalFileSystem; import com.intellij.openapi.vfs.VirtualFile; +import com.intellij.util.containers.ContainerUtil; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; @@ -54,6 +57,10 @@ public class FileDropHandler implements EditorDropHandler { if (project != null) { final List fileList = FileCopyPasteUtil.getFileList(t); if (fileList != null) { + boolean dropResult = ContainerUtil.process(Extensions.getExtensions(CustomFileDropHandler.CUSTOM_DROP_HANDLER_EP, project), + handler -> !(handler.canHandle(t) && handler.handleDrop(t, project))); + if (!dropResult) return; + openFiles(project, fileList, editorWindow); } } diff --git a/platform/platform-impl/src/com/intellij/openapi/fileTypes/ex/FileTypeChooser.java b/platform/platform-impl/src/com/intellij/openapi/fileTypes/ex/FileTypeChooser.java index c533834f4c5b..80431efbcbf8 100644 --- a/platform/platform-impl/src/com/intellij/openapi/fileTypes/ex/FileTypeChooser.java +++ b/platform/platform-impl/src/com/intellij/openapi/fileTypes/ex/FileTypeChooser.java @@ -25,7 +25,6 @@ import com.intellij.openapi.ui.DialogWrapper; import com.intellij.openapi.util.text.StringUtil; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.openapi.vfs.newvfs.impl.FakeVirtualFile; -import com.intellij.psi.PsiManager; import com.intellij.psi.impl.PsiManagerEx; import com.intellij.ui.CollectionComboBoxModel; import com.intellij.ui.DoubleClickListener; @@ -128,7 +127,7 @@ public class FileTypeChooser extends DialogWrapper { @Nullable public static FileType getKnownFileTypeOrAssociate(@NotNull VirtualFile file, @Nullable Project project) { if (project != null && !(file instanceof FakeVirtualFile)) { - ((PsiManagerEx)PsiManager.getInstance(project)).getFileManager().findFile(file); // autodetect text file if needed + PsiManagerEx.getInstanceEx(project).getFileManager().findFile(file); // autodetect text file if needed } FileType type = file.getFileType(); if (type == FileTypes.UNKNOWN) { diff --git a/platform/platform-impl/src/com/intellij/openapi/fileTypes/impl/IgnoredFileCache.java b/platform/platform-impl/src/com/intellij/openapi/fileTypes/impl/IgnoredFileCache.java index 20a2af19453d..20c7e7770988 100644 --- a/platform/platform-impl/src/com/intellij/openapi/fileTypes/impl/IgnoredFileCache.java +++ b/platform/platform-impl/src/com/intellij/openapi/fileTypes/impl/IgnoredFileCache.java @@ -37,7 +37,7 @@ class IgnoredFileCache { private final ConcurrentBitSet myCheckedIds = new ConcurrentBitSet(); private final ConcurrentIntObjectMap myIgnoredIds = ContainerUtil.createConcurrentIntObjectMap(); private final IgnoredPatternSet myIgnoredPatterns; - private volatile int myVfsEventNesting = 0; + private volatile int myVfsEventNesting; IgnoredFileCache(@NotNull IgnoredPatternSet ignoredPatterns) { myIgnoredPatterns = ignoredPatterns; diff --git a/platform/platform-impl/src/com/intellij/openapi/keymap/impl/ui/ActionsTree.java b/platform/platform-impl/src/com/intellij/openapi/keymap/impl/ui/ActionsTree.java index 192b329abe1d..bd7fb1a9beea 100644 --- a/platform/platform-impl/src/com/intellij/openapi/keymap/impl/ui/ActionsTree.java +++ b/platform/platform-impl/src/com/intellij/openapi/keymap/impl/ui/ActionsTree.java @@ -106,7 +106,15 @@ public class ActionsTree { } } } + } + @Override + public String convertValueToText(Object value, boolean selected, boolean expanded, boolean leaf, int row, boolean hasFocus) { + if (value instanceof DefaultMutableTreeNode) { + String path = ActionsTree.this.getPath((DefaultMutableTreeNode)value); + return StringUtil.notNullize(path); + } + return super.convertValueToText(value, selected, expanded, leaf, row, hasFocus); } }; myTree.setRootVisible(false); diff --git a/platform/platform-impl/src/com/intellij/openapi/project/DumbServiceImpl.java b/platform/platform-impl/src/com/intellij/openapi/project/DumbServiceImpl.java index 1c050c8112b6..c07e78b23ad8 100644 --- a/platform/platform-impl/src/com/intellij/openapi/project/DumbServiceImpl.java +++ b/platform/platform-impl/src/com/intellij/openapi/project/DumbServiceImpl.java @@ -58,7 +58,7 @@ public class DumbServiceImpl extends DumbService implements Disposable, Modifica } }; private static Throwable ourForcedTrace; - private volatile boolean myDumb = false; + private volatile boolean myDumb; private volatile Throwable myDumbStart; private volatile TransactionId myDumbStartTransaction; private boolean myUpdateFinishedQueued; diff --git a/platform/platform-impl/src/com/intellij/openapi/project/ex/ProjectManagerEx.java b/platform/platform-impl/src/com/intellij/openapi/project/ex/ProjectManagerEx.java index ed44bae8514c..b341b77568ad 100644 --- a/platform/platform-impl/src/com/intellij/openapi/project/ex/ProjectManagerEx.java +++ b/platform/platform-impl/src/com/intellij/openapi/project/ex/ProjectManagerEx.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2015 JetBrains s.r.o. + * Copyright 2000-2016 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. @@ -54,12 +54,12 @@ public abstract class ProjectManagerEx extends ProjectManager { @TestOnly public abstract void openTestProject(@NotNull Project project); - @TestOnly - @NotNull /** * Without save and "check can close". * Returns remaining open test projects. */ + @TestOnly + @NotNull public abstract Collection closeTestProject(@NotNull Project project); // returns true on success diff --git a/platform/platform-impl/src/com/intellij/openapi/updateSettings/impl/PluginDownloader.java b/platform/platform-impl/src/com/intellij/openapi/updateSettings/impl/PluginDownloader.java index c2afb17d7f27..273183fa2854 100644 --- a/platform/platform-impl/src/com/intellij/openapi/updateSettings/impl/PluginDownloader.java +++ b/platform/platform-impl/src/com/intellij/openapi/updateSettings/impl/PluginDownloader.java @@ -18,11 +18,7 @@ package com.intellij.openapi.updateSettings.impl; import com.intellij.ide.IdeBundle; import com.intellij.ide.plugins.*; import com.intellij.ide.startup.StartupActionScriptManager; -import com.intellij.ide.util.PropertiesComponent; -import com.intellij.openapi.application.Application; -import com.intellij.openapi.application.ApplicationInfo; -import com.intellij.openapi.application.ApplicationManager; -import com.intellij.openapi.application.PathManager; +import com.intellij.openapi.application.*; import com.intellij.openapi.application.ex.ApplicationInfoEx; import com.intellij.openapi.application.impl.ApplicationInfoImpl; import com.intellij.openapi.diagnostic.Logger; @@ -46,7 +42,6 @@ import java.net.*; import java.util.ArrayList; import java.util.Arrays; import java.util.List; -import java.util.UUID; /** * @author anna @@ -342,13 +337,11 @@ public class PluginDownloader { app != null ? ApplicationInfo.getInstance().getApiVersion() : appInfo.getBuild().asString(); - String uuid = app != null ? UpdateChecker.getInstallationUID(PropertiesComponent.getInstance()) : UUID.randomUUID().toString(); - URIBuilder uriBuilder = new URIBuilder(appInfo.getPluginsDownloadUrl()); uriBuilder.addParameter("action", "download"); uriBuilder.addParameter("id", descriptor.getPluginId().getIdString()); uriBuilder.addParameter("build", buildNumberAsString); - uriBuilder.addParameter("uuid", uuid); + uriBuilder.addParameter("uuid", PermanentInstallationID.get()); return uriBuilder.build().toString(); } } diff --git a/platform/platform-impl/src/com/intellij/openapi/updateSettings/impl/UpdateChecker.kt b/platform/platform-impl/src/com/intellij/openapi/updateSettings/impl/UpdateChecker.kt index 5f9847f74923..9d1a7d256fd6 100644 --- a/platform/platform-impl/src/com/intellij/openapi/updateSettings/impl/UpdateChecker.kt +++ b/platform/platform-impl/src/com/intellij/openapi/updateSettings/impl/UpdateChecker.kt @@ -43,7 +43,6 @@ import com.intellij.openapi.util.BuildNumber import com.intellij.openapi.util.SystemInfo import com.intellij.openapi.util.io.FileUtil import com.intellij.openapi.util.text.StringUtil -import com.intellij.openapi.vfs.CharsetToolkit import com.intellij.util.PlatformUtils import com.intellij.util.SystemProperties import com.intellij.util.containers.ContainerUtil @@ -72,7 +71,6 @@ object UpdateChecker { @JvmField val NOTIFICATIONS = NotificationGroup(IdeBundle.message("update.notifications.group"), NotificationDisplayType.STICKY_BALLOON, true) - private val INSTALLATION_UID = "installation.uid" private val DISABLED_UPDATE = "disabled_update.txt" private val NO_PLATFORM_UPDATE = "ide.no.platform.update" @@ -422,54 +420,14 @@ object UpdateChecker { } } + /** + * @Deprecated, left for compatibility. Use PermanentInstallationID.get() directly + */ @JvmStatic fun getInstallationUID(propertiesComponent: PropertiesComponent): String { - if (SystemInfo.isWindows) { - val uid = getInstallationUIDOnWindows(propertiesComponent) - if (uid != null) { - return uid - } - } - - var uid = propertiesComponent.getValue(INSTALLATION_UID) - if (uid == null) { - uid = generateUUID() - propertiesComponent.setValue(INSTALLATION_UID, uid) - } - return uid + return PermanentInstallationID.get(); } - private fun getInstallationUIDOnWindows(propertiesComponent: PropertiesComponent): String? { - val appdata = System.getenv("APPDATA") - if (appdata != null) { - val jetBrainsDir = File(appdata, "JetBrains") - if (jetBrainsDir.isDirectory || jetBrainsDir.mkdirs()) { - val permanentIdFile = File(jetBrainsDir, "PermanentUserId") - try { - if (permanentIdFile.exists()) { - val bytes = permanentIdFile.readBytes() - val offset = if (CharsetToolkit.hasUTF8Bom(bytes)) CharsetToolkit.UTF8_BOM.size else 0 - return String(bytes, offset, bytes.size - offset, Charsets.UTF_8) - } - - val uuid = propertiesComponent.getValue(INSTALLATION_UID) ?: generateUUID() - permanentIdFile.writeText(uuid, Charsets.UTF_8) - return uuid - } - catch (e: IOException) { - LOG.debug(e) - } - } - } - - return null - } - - private fun generateUUID(): String = - try { UUID.randomUUID().toString() } - catch (ignored: Exception) { "" } - catch (ignored: InternalError) { "" } - @JvmStatic @Throws(IOException::class) fun installPlatformUpdate(patch: PatchInfo, toBuild: BuildNumber, forceHttps: Boolean) { diff --git a/platform/platform-impl/src/com/intellij/openapi/vfs/impl/local/NativeFileWatcherImpl.java b/platform/platform-impl/src/com/intellij/openapi/vfs/impl/local/NativeFileWatcherImpl.java index 605deccdba95..d629b7734d81 100644 --- a/platform/platform-impl/src/com/intellij/openapi/vfs/impl/local/NativeFileWatcherImpl.java +++ b/platform/platform-impl/src/com/intellij/openapi/vfs/impl/local/NativeFileWatcherImpl.java @@ -65,8 +65,8 @@ public class NativeFileWatcherImpl extends PluggableFileWatcher { private File myExecutable; private volatile MyProcessHandler myProcessHandler; - private volatile int myStartAttemptCount = 0; - private volatile boolean myIsShuttingDown = false; + private volatile int myStartAttemptCount; + private volatile boolean myIsShuttingDown; private final AtomicInteger mySettingRoots = new AtomicInteger(0); private volatile List myRecursiveWatchRoots = Collections.emptyList(); private volatile List myFlatWatchRoots = Collections.emptyList(); @@ -287,7 +287,7 @@ public class NativeFileWatcherImpl extends PluggableFileWatcher { private class MyProcessHandler extends OSProcessHandler { private final BufferedWriter myWriter; - private WatcherOp myLastOp = null; + private WatcherOp myLastOp; private final List myLines = ContainerUtil.newArrayList(); @SuppressWarnings("IOResourceOpenedButNotSafelyClosed") diff --git a/platform/platform-impl/src/com/intellij/openapi/vfs/impl/win32/Win32FsCache.java b/platform/platform-impl/src/com/intellij/openapi/vfs/impl/win32/Win32FsCache.java index f2cfe47b4153..f194789a0fca 100644 --- a/platform/platform-impl/src/com/intellij/openapi/vfs/impl/win32/Win32FsCache.java +++ b/platform/platform-impl/src/com/intellij/openapi/vfs/impl/win32/Win32FsCache.java @@ -19,52 +19,58 @@ import com.intellij.openapi.util.io.FileAttributes; import com.intellij.openapi.util.io.FileUtil; import com.intellij.openapi.util.io.win32.FileInfo; import com.intellij.openapi.util.io.win32.IdeaWin32; -import com.intellij.openapi.util.text.StringUtil; import com.intellij.openapi.vfs.VirtualFile; +import com.intellij.openapi.vfs.VirtualFileWithId; import com.intellij.util.ArrayUtil; import gnu.trove.THashMap; +import gnu.trove.TIntObjectHashMap; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.lang.ref.Reference; import java.lang.ref.SoftReference; -import java.util.Map; /** * @author Dmitry Avdeev */ class Win32FsCache { private final IdeaWin32 myKernel = IdeaWin32.getInstance(); - private Reference> myCache; + private Reference>> myCache; void clearCache() { myCache = null; } @NotNull - private Map getMap() { - Map map = com.intellij.reference.SoftReference.dereference(myCache); + private TIntObjectHashMap> getMap() { + TIntObjectHashMap> map = com.intellij.reference.SoftReference.dereference(myCache); if (map == null) { - map = new THashMap(FileUtil.PATH_HASHING_STRATEGY); - myCache = new SoftReference>(map); + map = new TIntObjectHashMap>(); + myCache = new SoftReference>>(map); } return map; } @NotNull - String[] list(@NotNull String path) { + String[] list(@NotNull VirtualFile file) { + String path = file.getPath(); FileInfo[] fileInfo = myKernel.listChildren(path); if (fileInfo == null || fileInfo.length == 0) { return ArrayUtil.EMPTY_STRING_ARRAY; } - if (!StringUtil.endsWithChar(path, '/')) path += "/"; String[] names = new String[fileInfo.length]; - Map map = getMap(); + TIntObjectHashMap> map = getMap(); + int parentId = ((VirtualFileWithId)file).getId(); + THashMap nestedMap = map.get(parentId); + if (nestedMap == null) { + nestedMap = new THashMap(fileInfo.length, FileUtil.PATH_HASHING_STRATEGY); + map.put(parentId, nestedMap); + } for (int i = 0, length = fileInfo.length; i < length; i++) { FileInfo info = fileInfo[i]; String name = info.getName(); - map.put(path + name, info.toFileAttributes()); + nestedMap.put(name, info.toFileAttributes()); names[i] = name; } return names; @@ -72,16 +78,24 @@ class Win32FsCache { @Nullable FileAttributes getAttributes(@NotNull VirtualFile file) { - String path = file.getPath(); - Map map = getMap(); - FileAttributes attributes = map.get(path); + VirtualFile parent = file.getParent(); + int parentId = parent instanceof VirtualFileWithId ? ((VirtualFileWithId)parent).getId() : -((VirtualFileWithId)file).getId(); + TIntObjectHashMap> map = getMap(); + THashMap nestedMap = map.get(parentId); + String name = file.getName(); + FileAttributes attributes = nestedMap != null ? nestedMap.get(name) : null; + if (attributes == null) { - FileInfo info = myKernel.getInfo(path); + FileInfo info = myKernel.getInfo(file.getPath()); if (info == null) { return null; } attributes = info.toFileAttributes(); - map.put(path, attributes); + if (nestedMap == null) { + nestedMap = new THashMap(FileUtil.PATH_HASHING_STRATEGY); + map.put(parentId, nestedMap); + } + nestedMap.put(name, attributes); } return attributes; } 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 f462437f5e48..2fa89eb60402 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 @@ -54,7 +54,7 @@ public class Win32LocalFileSystem extends LocalFileSystemBase { @NotNull @Override public String[] list(@NotNull VirtualFile file) { - return myFsCache.list(file.getPath()); + return myFsCache.list(file); } @Override @@ -69,4 +69,4 @@ public class Win32LocalFileSystem extends LocalFileSystemBase { @Nullable Collection flatRoots) { throw new UnsupportedOperationException(); } -} \ No newline at end of file +} diff --git a/platform/platform-impl/src/com/intellij/openapi/vfs/newvfs/persistent/RefreshWorker.java b/platform/platform-impl/src/com/intellij/openapi/vfs/newvfs/persistent/RefreshWorker.java index 687ec5eca330..e6770fcc9c50 100644 --- a/platform/platform-impl/src/com/intellij/openapi/vfs/newvfs/persistent/RefreshWorker.java +++ b/platform/platform-impl/src/com/intellij/openapi/vfs/newvfs/persistent/RefreshWorker.java @@ -59,7 +59,7 @@ public class RefreshWorker { private final boolean myIsRecursive; private final Queue> myRefreshQueue = new Queue>(100); private final List myEvents = new ArrayList(); - private volatile boolean myCancelled = false; + private volatile boolean myCancelled; public RefreshWorker(@NotNull NewVirtualFile refreshRoot, boolean isRecursive) { myIsRecursive = isRecursive; @@ -418,7 +418,7 @@ public class RefreshWorker { } } - private static Function ourCancellingCondition = null; + private static Function ourCancellingCondition; @TestOnly public static void setCancellingCondition(@Nullable Function condition) { diff --git a/platform/platform-impl/src/com/intellij/openapi/wm/ex/IdeFocusTraversalPolicy.java b/platform/platform-impl/src/com/intellij/openapi/wm/ex/IdeFocusTraversalPolicy.java index 2ecb28327857..b5764e05d603 100644 --- a/platform/platform-impl/src/com/intellij/openapi/wm/ex/IdeFocusTraversalPolicy.java +++ b/platform/platform-impl/src/com/intellij/openapi/wm/ex/IdeFocusTraversalPolicy.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2014 JetBrains s.r.o. + * Copyright 2000-2016 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. @@ -116,7 +116,7 @@ public class IdeFocusTraversalPolicy extends LayoutFocusTraversalPolicyExt { return false; } - /** TODO[anton,vova] implement Policy in Editor component instead */ + /* TODO[anton,vova] implement Policy in Editor component instead */ if (component instanceof EditorComponentImpl || component instanceof EditorWindowHolder) { return true; } diff --git a/platform/platform-impl/src/com/intellij/openapi/wm/ex/ToolWindowManagerAdapter.java b/platform/platform-impl/src/com/intellij/openapi/wm/ex/ToolWindowManagerAdapter.java index b7a11a17c76e..d277d0e6520d 100644 --- a/platform/platform-impl/src/com/intellij/openapi/wm/ex/ToolWindowManagerAdapter.java +++ b/platform/platform-impl/src/com/intellij/openapi/wm/ex/ToolWindowManagerAdapter.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2012 JetBrains s.r.o. + * Copyright 2000-2016 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. @@ -14,9 +14,6 @@ * limitations under the License. */ -/** - * @author Vladimir Kondratyev - */ package com.intellij.openapi.wm.ex; import org.jetbrains.annotations.NotNull; diff --git a/platform/platform-impl/src/com/intellij/openapi/wm/impl/StripeButtonUI.java b/platform/platform-impl/src/com/intellij/openapi/wm/impl/StripeButtonUI.java index 5c56758aae26..2c8022e7b864 100644 --- a/platform/platform-impl/src/com/intellij/openapi/wm/impl/StripeButtonUI.java +++ b/platform/platform-impl/src/com/intellij/openapi/wm/impl/StripeButtonUI.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2015 JetBrains s.r.o. + * Copyright 2000-2016 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. @@ -160,11 +160,11 @@ public final class StripeButtonUI extends MetalToggleButtonUI{ } /* Draw the Text */ if(model.isEnabled()){ - /*** paint the text normally */ + /* paint the text normally */ g2.setColor(UIUtil.isUnderDarcula() && model.isSelected() ? button.getForeground().brighter() : button.getForeground()); BasicGraphicsUtils.drawString(g2,clippedText,button.getMnemonic2(),ourTextRect.x,ourTextRect.y+fm.getAscent()); } else{ - /*** paint the text disabled ***/ + /* paint the text disabled ***/ if(model.isSelected()){ g2.setColor(c.getBackground()); } else{ diff --git a/platform/platform-impl/src/com/intellij/openapi/wm/impl/ToolWindowHeadlessManagerImpl.java b/platform/platform-impl/src/com/intellij/openapi/wm/impl/ToolWindowHeadlessManagerImpl.java index a59ea310f010..3c89e2642939 100644 --- a/platform/platform-impl/src/com/intellij/openapi/wm/impl/ToolWindowHeadlessManagerImpl.java +++ b/platform/platform-impl/src/com/intellij/openapi/wm/impl/ToolWindowHeadlessManagerImpl.java @@ -512,6 +512,7 @@ public class ToolWindowHeadlessManagerImpl extends ToolWindowManagerEx { @Override public void addContent(@NotNull final Content content) { myContents.add(content); + Disposer.register(this, content); ContentManagerEvent e = new ContentManagerEvent(this, content, myContents.indexOf(content), ContentManagerEvent.ContentOperation.add); myDispatcher.getMulticaster().contentAdded(e); if (mySelected == null) setSelectedContent(content); @@ -520,6 +521,7 @@ public class ToolWindowHeadlessManagerImpl extends ToolWindowManagerEx { @Override public void addContent(@NotNull Content content, int order) { myContents.add(order, content); + Disposer.register(this, content); ContentManagerEvent e = new ContentManagerEvent(this, content, myContents.indexOf(content), ContentManagerEvent.ContentOperation.add); myDispatcher.getMulticaster().contentAdded(e); if (mySelected == null) setSelectedContent(content); diff --git a/platform/platform-impl/src/com/intellij/openapi/wm/impl/commands/ApplyWindowInfoCmd.java b/platform/platform-impl/src/com/intellij/openapi/wm/impl/commands/ApplyWindowInfoCmd.java index 27c4df1a8fb9..49dcba6dd63c 100644 --- a/platform/platform-impl/src/com/intellij/openapi/wm/impl/commands/ApplyWindowInfoCmd.java +++ b/platform/platform-impl/src/com/intellij/openapi/wm/impl/commands/ApplyWindowInfoCmd.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2014 JetBrains s.r.o. + * Copyright 2000-2016 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. @@ -14,9 +14,6 @@ * limitations under the License. */ -/** - * @author Vladimir Kondratyev - */ package com.intellij.openapi.wm.impl.commands; import com.intellij.openapi.wm.impl.InternalDecorator; diff --git a/platform/platform-impl/src/com/intellij/openapi/wm/impl/commands/RequestFocusInEditorComponentCmd.java b/platform/platform-impl/src/com/intellij/openapi/wm/impl/commands/RequestFocusInEditorComponentCmd.java index f9685ad1666c..3cb5c702b751 100644 --- a/platform/platform-impl/src/com/intellij/openapi/wm/impl/commands/RequestFocusInEditorComponentCmd.java +++ b/platform/platform-impl/src/com/intellij/openapi/wm/impl/commands/RequestFocusInEditorComponentCmd.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2014 JetBrains s.r.o. + * Copyright 2000-2016 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. @@ -14,9 +14,6 @@ * limitations under the License. */ -/** - * @author Vladimir Kondratyev - */ package com.intellij.openapi.wm.impl.commands; import com.intellij.openapi.diagnostic.Logger; diff --git a/platform/platform-impl/src/com/intellij/remote/VagrantBasedCredentialsHolder.java b/platform/platform-impl/src/com/intellij/remote/VagrantBasedCredentialsHolder.java index 1eabdc20b34c..ed605b396812 100644 --- a/platform/platform-impl/src/com/intellij/remote/VagrantBasedCredentialsHolder.java +++ b/platform/platform-impl/src/com/intellij/remote/VagrantBasedCredentialsHolder.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2014 JetBrains s.r.o. + * Copyright 2000-2016 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. @@ -35,10 +35,10 @@ public class VagrantBasedCredentialsHolder { myVagrantFolder = ""; } - @Deprecated /** * @deprecated use constructor supporting multiple machines configuration */ + @Deprecated public VagrantBasedCredentialsHolder(@NotNull String folder) { myVagrantFolder = folder; } diff --git a/platform/platform-impl/src/com/intellij/ui/BalloonImpl.java b/platform/platform-impl/src/com/intellij/ui/BalloonImpl.java index 7ba74b8a90f2..d9960e4604c3 100644 --- a/platform/platform-impl/src/com/intellij/ui/BalloonImpl.java +++ b/platform/platform-impl/src/com/intellij/ui/BalloonImpl.java @@ -223,7 +223,7 @@ public class BalloonImpl implements Balloon, IdeTooltip.Ui { private JLabel myTitleLabel; private boolean myAnimationEnabled = true; - private boolean myShadow = false; + private boolean myShadow = UIUtil.isUnderDarcula(); private final Layer myLayer; private final boolean myBlockClicks; private RelativePoint myPrevMousePoint = null; diff --git a/platform/platform-impl/src/com/intellij/ui/BalloonLayoutData.java b/platform/platform-impl/src/com/intellij/ui/BalloonLayoutData.java index e1681e64e283..0b5f696a231c 100644 --- a/platform/platform-impl/src/com/intellij/ui/BalloonLayoutData.java +++ b/platform/platform-impl/src/com/intellij/ui/BalloonLayoutData.java @@ -20,6 +20,8 @@ import com.intellij.openapi.project.Project; import com.intellij.openapi.util.Computable; import org.jetbrains.annotations.NotNull; +import java.awt.*; + /** * @author Alexander Lobas */ @@ -52,6 +54,11 @@ public class BalloonLayoutData { public Runnable lafHandler; + public long fadeoutTime; + + public Color fillColor; + public Color borderColor; + @NotNull public MergeInfo merge() { return mergeData == null ? new MergeInfo(id, 1) : new MergeInfo(mergeData.linkId, mergeData.count + 1); diff --git a/platform/platform-impl/src/com/intellij/ui/ScrollPaneActions.java b/platform/platform-impl/src/com/intellij/ui/ScrollPaneActions.java index e1c2c35df4dd..37f01d7adbbf 100644 --- a/platform/platform-impl/src/com/intellij/ui/ScrollPaneActions.java +++ b/platform/platform-impl/src/com/intellij/ui/ScrollPaneActions.java @@ -22,9 +22,12 @@ import com.intellij.util.ui.UIUtil; import javax.swing.Action; import javax.swing.ActionMap; import javax.swing.JScrollPane; +import java.awt.Component; import java.awt.KeyboardFocusManager; import java.awt.event.ActionEvent; +import static com.intellij.openapi.actionSystem.PlatformDataKeys.CONTEXT_COMPONENT; + /** * @author Sergey.Malenkov */ @@ -50,9 +53,9 @@ public abstract class ScrollPaneActions extends AnAction { action.actionPerformed(new ActionEvent(pane, ActionEvent.ACTION_PERFORMED, mySwingActionId)); } - private JScrollPane getScrollPane(@SuppressWarnings("UnusedParameters") AnActionEvent event) { - KeyboardFocusManager manager = KeyboardFocusManager.getCurrentKeyboardFocusManager(); - return manager == null ? null : UIUtil.getParentOfType(JScrollPane.class, manager.getPermanentFocusOwner()); + private JScrollPane getScrollPane(AnActionEvent event) { + Component component = event.getData(CONTEXT_COMPONENT); + return UIUtil.getParentOfType(JScrollPane.class, component); } private Action getSwingAction(JScrollPane pane) { diff --git a/platform/platform-impl/src/com/intellij/ui/mac/MacMainFrameDecorator.java b/platform/platform-impl/src/com/intellij/ui/mac/MacMainFrameDecorator.java index fc75a0613de1..cc3bc7ba8217 100644 --- a/platform/platform-impl/src/com/intellij/ui/mac/MacMainFrameDecorator.java +++ b/platform/platform-impl/src/com/intellij/ui/mac/MacMainFrameDecorator.java @@ -175,6 +175,7 @@ public class MacMainFrameDecorator extends IdeFrameDecorator implements UISettin } }; + @SuppressWarnings("Convert2Lambda") public static final Function NAVBAR_GETTER = new Function() { @Override public Boolean fun(Object o) { @@ -182,6 +183,7 @@ public class MacMainFrameDecorator extends IdeFrameDecorator implements UISettin } }; + @SuppressWarnings("Convert2Lambda") public static final Function TOOLBAR_GETTER = new Function() { @Override public Boolean fun(Object o) { diff --git a/platform/platform-impl/src/com/intellij/ui/popup/BalloonPopupBuilderImpl.java b/platform/platform-impl/src/com/intellij/ui/popup/BalloonPopupBuilderImpl.java index 2784526b71a5..2703460b6aea 100644 --- a/platform/platform-impl/src/com/intellij/ui/popup/BalloonPopupBuilderImpl.java +++ b/platform/platform-impl/src/com/intellij/ui/popup/BalloonPopupBuilderImpl.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2015 JetBrains s.r.o. + * Copyright 2000-2016 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. @@ -15,6 +15,7 @@ */ package com.intellij.ui.popup; +import com.intellij.ide.IdeTooltipManager; import com.intellij.openapi.Disposable; import com.intellij.openapi.ui.MessageType; import com.intellij.openapi.ui.popup.Balloon; @@ -23,8 +24,7 @@ import com.intellij.openapi.ui.popup.JBPopupAdapter; import com.intellij.openapi.ui.popup.LightweightWindowEvent; import com.intellij.openapi.util.Disposer; import com.intellij.ui.BalloonImpl; -import com.intellij.ui.Gray; -import com.intellij.ui.JBColor; +import com.intellij.util.ui.UIUtil; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; @@ -41,7 +41,7 @@ public class BalloonPopupBuilderImpl implements BalloonBuilder { private final JComponent myContent; - private Color myBorder = new JBColor(JBColor.GRAY, Gray._200); + private Color myBorder = IdeTooltipManager.getInstance().getBorderColor(true); @Nullable private Insets myBorderInsets = null; private Color myFill = MessageType.INFO.getPopupBackground(); private boolean myHideOnMouseOutside = true; @@ -63,7 +63,7 @@ public class BalloonPopupBuilderImpl implements BalloonBuilder { private boolean myDialogMode; private String myTitle; private Insets myContentInsets = new Insets(2, 2, 2, 2); - private boolean myShadow = false; + private boolean myShadow = UIUtil.isUnderDarcula(); private boolean mySmallVariant = false; private Balloon.Layer myLayer; diff --git a/platform/platform-impl/src/com/intellij/util/PsiErrorElementUtil.java b/platform/platform-impl/src/com/intellij/util/PsiErrorElementUtil.java index 1b5ed7ba7d36..7b7828b3ff32 100644 --- a/platform/platform-impl/src/com/intellij/util/PsiErrorElementUtil.java +++ b/platform/platform-impl/src/com/intellij/util/PsiErrorElementUtil.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2015 JetBrains s.r.o. + * Copyright 2000-2016 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. @@ -25,7 +25,6 @@ import com.intellij.openapi.vfs.VirtualFile; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiErrorElement; import com.intellij.psi.PsiFile; -import com.intellij.psi.PsiManager; import com.intellij.psi.impl.PsiManagerEx; import com.intellij.psi.util.CachedValue; import com.intellij.psi.util.CachedValueProvider; @@ -45,7 +44,7 @@ public class PsiErrorElementUtil { if (project.isDisposed() || !virtualFile.isValid()) { return false; } - PsiManagerEx psiManager = (PsiManagerEx)PsiManager.getInstance(project); + PsiManagerEx psiManager = PsiManagerEx.getInstanceEx(project); PsiFile psiFile = psiManager.getFileManager().findFile(virtualFile); return psiFile != null && hasErrors(psiFile); } diff --git a/platform/platform-impl/src/com/intellij/util/Urls.java b/platform/platform-impl/src/com/intellij/util/Urls.java index 5ae9a7c7117c..2ed214f6114f 100644 --- a/platform/platform-impl/src/com/intellij/util/Urls.java +++ b/platform/platform-impl/src/com/intellij/util/Urls.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2015 JetBrains s.r.o. + * Copyright 2000-2016 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. @@ -77,10 +77,10 @@ public final class Urls { return new UrlImpl(scheme, authority, path); } - @NotNull /** * Url will not be normalized (see {@link VfsUtilCore#toIdeaUrl(String)}), parsed as is */ + @NotNull public static Url newFromIdea(@NotNull CharSequence url) { Url result = parseFromIdea(url); LOG.assertTrue(result != null, url); diff --git a/platform/platform-impl/src/com/intellij/util/ui/CollectionItemEditor.java b/platform/platform-impl/src/com/intellij/util/ui/CollectionItemEditor.java index bf6f91ac5871..c5729a46c2ba 100644 --- a/platform/platform-impl/src/com/intellij/util/ui/CollectionItemEditor.java +++ b/platform/platform-impl/src/com/intellij/util/ui/CollectionItemEditor.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2015 JetBrains s.r.o. + * Copyright 2000-2016 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. @@ -18,10 +18,10 @@ package com.intellij.util.ui; import org.jetbrains.annotations.NotNull; public abstract class CollectionItemEditor { - @NotNull /** * Class must have an empty constructor. */ + @NotNull public abstract Class getItemClass(); /** diff --git a/platform/platform-impl/src/com/intellij/util/ui/CollectionModelEditor.java b/platform/platform-impl/src/com/intellij/util/ui/CollectionModelEditor.java index f1dd95078ec2..f906a2ba7ad3 100644 --- a/platform/platform-impl/src/com/intellij/util/ui/CollectionModelEditor.java +++ b/platform/platform-impl/src/com/intellij/util/ui/CollectionModelEditor.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2015 JetBrains s.r.o. + * Copyright 2000-2016 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. @@ -48,10 +48,10 @@ public abstract class CollectionModelEditor return true; } - @NotNull /** * Mutable internal list of items (must not be exposed to client) */ + @NotNull protected abstract List getItems(); public void reset(@NotNull List originalItems) { diff --git a/platform/platform-impl/src/org/jetbrains/io/LocalFileFinder.java b/platform/platform-impl/src/org/jetbrains/io/LocalFileFinder.java index 2cd8fb403b67..4bf5182c8f8e 100644 --- a/platform/platform-impl/src/org/jetbrains/io/LocalFileFinder.java +++ b/platform/platform-impl/src/org/jetbrains/io/LocalFileFinder.java @@ -1,3 +1,18 @@ +/* + * Copyright 2000-2016 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 org.jetbrains.io; import com.google.common.cache.Cache; @@ -20,13 +35,13 @@ public final class LocalFileFinder { private LocalFileFinder() { } - @Nullable /** Behavior is not predictable and result is not guaranteed: 1) result of check cached, but cache entry invalidated on timeout (5 min after write), not on actual change of drive status. 2) even if drive exists, it could be not used due to 10 ms threshold. Method is not generic and is not suitable for all. */ + @Nullable public static VirtualFile findFile(@NotNull String path) { if (windowsDriveExists(path)) { return LocalFileSystem.getInstance().findFileByPath(path); diff --git a/platform/platform-resources-en/src/messages/ActionsBundle.properties b/platform/platform-resources-en/src/messages/ActionsBundle.properties index ae6d3f2747f7..52e8e9c195cb 100644 --- a/platform/platform-resources-en/src/messages/ActionsBundle.properties +++ b/platform/platform-resources-en/src/messages/ActionsBundle.properties @@ -1228,6 +1228,8 @@ action.ChangesView.CreatePatch.text=Create Patch... action.ChangesView.CreatePatch.description=Create a patch from the selected changes action.ChangesView.ApplyPatch.text=Apply Patch... action.ChangesView.ApplyPatch.description=Apply a patch to the sources of the project +action.ChangesView.ApplyPatchFromClipboard.text=Apply Patch from Clipboard... +action.ChangesView.ApplyPatchFromClipboard.description=Apply a patch to the sources of the project action.ChangesView.Shelve.text=Shelve Changes... action.ChangesView.Shelve.description=Save changes to an external patch file and remove them from the code action.ShelvedChanges.Unshelve.text=Unshelve Changes diff --git a/platform/platform-resources-en/src/messages/DiagnosticBundle.properties b/platform/platform-resources-en/src/messages/DiagnosticBundle.properties index 3f9d30574401..e26b4ae549e3 100644 --- a/platform/platform-resources-en/src/messages/DiagnosticBundle.properties +++ b/platform/platform-resources-en/src/messages/DiagnosticBundle.properties @@ -52,6 +52,8 @@ error.list.disable.plugin=&Disable plugin... error.list.disable.plugin.0=Disable plugin {0} error.notification.tooltip=IDE internal error occurred.
Click to see details and submit a bug report. error.notification.empty.text=No IDE fatal errors +error.new.notification.title=IDE Error Occurred +error.new.notification.link=See Details and Submit Report error.monitor.too.many.errors=Too many IDE fatal errors. Monitoring stopped. error.report.title=Error Report log.monitor.no.files=No log files attached diff --git a/platform/platform-resources-en/src/messages/InspectionsBundle.properties b/platform/platform-resources-en/src/messages/InspectionsBundle.properties index 192eba08e023..996ecead056a 100644 --- a/platform/platform-resources-en/src/messages/InspectionsBundle.properties +++ b/platform/platform-resources-en/src/messages/InspectionsBundle.properties @@ -711,3 +711,4 @@ todo.comment.problem.descriptor=TODO comment #ref #loc long.line.display.name=Line is longer than allowed by code style inspection.default.annotation.param=Default annotation parameter value +preparing.for.apply.fix=Preparing to Apply Fix... diff --git a/platform/platform-resources-en/src/messages/XDebuggerBundle.properties b/platform/platform-resources-en/src/messages/XDebuggerBundle.properties index 0303f726758c..057740356703 100644 --- a/platform/platform-resources-en/src/messages/XDebuggerBundle.properties +++ b/platform/platform-resources-en/src/messages/XDebuggerBundle.properties @@ -56,7 +56,7 @@ xbreakpoint.radio.leave.enabled=Leave enabled xbreakpoint.master.breakpoint.none= xbreakpoint.master.breakpoint.description=Disabled until selected breakpoint is hit: rule.name.group.by.file=Group by file -xbreakpoint.default.display.text=Line {0} in {1} +xbreakpoint.default.display.text={1}:{0} xbreakpoint.label.empty=Select a breakpoint xbreakpoint.reached.text=Breakpoint reached: diff --git a/platform/platform-resources/src/META-INF/PlatformExtensionPoints.xml b/platform/platform-resources/src/META-INF/PlatformExtensionPoints.xml index 58990d478097..002c919fe209 100644 --- a/platform/platform-resources/src/META-INF/PlatformExtensionPoints.xml +++ b/platform/platform-resources/src/META-INF/PlatformExtensionPoints.xml @@ -138,6 +138,8 @@ + + diff --git a/platform/platform-resources/src/META-INF/VcsExtensions.xml b/platform/platform-resources/src/META-INF/VcsExtensions.xml index 2f09f504e87e..5ca713ef160a 100644 --- a/platform/platform-resources/src/META-INF/VcsExtensions.xml +++ b/platform/platform-resources/src/META-INF/VcsExtensions.xml @@ -57,6 +57,7 @@ + diff --git a/platform/platform-resources/src/componentSets/VCS.xml b/platform/platform-resources/src/componentSets/VCS.xml index c761afb2a395..fcd9680acb2e 100644 --- a/platform/platform-resources/src/componentSets/VCS.xml +++ b/platform/platform-resources/src/componentSets/VCS.xml @@ -12,6 +12,9 @@ com.intellij.openapi.vcs.changes.actions.migrate.MigrateDiffApplicationComponent + + com.intellij.openapi.vcs.changes.patch.PatchClipboardTracker + diff --git a/platform/platform-resources/src/idea/PlatformActions.xml b/platform/platform-resources/src/idea/PlatformActions.xml index c60174ab40b7..9b9e0b8cc56d 100644 --- a/platform/platform-resources/src/idea/PlatformActions.xml +++ b/platform/platform-resources/src/idea/PlatformActions.xml @@ -202,7 +202,7 @@ - + diff --git a/platform/platform-resources/src/idea/VcsActions.xml b/platform/platform-resources/src/idea/VcsActions.xml index 4249bc8d4998..4b4790a1a4c1 100644 --- a/platform/platform-resources/src/idea/VcsActions.xml +++ b/platform/platform-resources/src/idea/VcsActions.xml @@ -64,6 +64,7 @@ + @@ -334,6 +335,7 @@ + diff --git a/platform/platform-tests/testSrc/com/intellij/application/options/DocumentChangesCollectorTest.java b/platform/platform-tests/testSrc/com/intellij/application/options/DocumentChangesCollectorTest.java deleted file mode 100644 index de4a35cf2e95..000000000000 --- a/platform/platform-tests/testSrc/com/intellij/application/options/DocumentChangesCollectorTest.java +++ /dev/null @@ -1,190 +0,0 @@ -package com.intellij.application.options; - -import com.intellij.openapi.editor.Document; -import com.intellij.openapi.editor.TextChange; -import com.intellij.openapi.editor.impl.TextChangeImpl; -import com.intellij.openapi.editor.impl.event.DocumentEventImpl; -import org.jmock.Expectations; -import org.jmock.Mockery; -import org.jmock.integration.junit4.JUnit4Mockery; -import org.jmock.lib.legacy.ClassImposteriser; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; - -import java.util.List; - -import static java.util.Arrays.asList; -import static org.junit.Assert.*; -import static org.junit.Assert.assertEquals; - -/** - * @author Denis Zhdanov - * @since 10/12/2010 - */ -public class DocumentChangesCollectorTest { - - private static final String TEXT = "0123456789abcdefghijklmnopqrstuvwxyz"; - - private static long ourCounter; - - private StringBuilder buffer; - private DocumentChangesCollector myCollector; - private Mockery myMockery; - private Document myDocument; - - @Before - public void setUp() { - myCollector = new DocumentChangesCollector(); - buffer = new StringBuilder(TEXT); - myCollector.setCollectChanges(true); - myMockery = new JUnit4Mockery() {{ - setImposteriser(ClassImposteriser.INSTANCE); - }}; - - myDocument = myMockery.mock(Document.class); - - myMockery.checking(new Expectations() {{ - allowing(myDocument).getTextLength(); will(returnValue(TEXT.length())); - }}); - } - - @After - public void checkExpectations() { - myMockery.assertIsSatisfied(); - } - - @Test - public void emptyCollector() { - assertNotNull(myCollector.getChanges()); - } - - @Test - public void scatteredChanges() { - populate(0, 0, "AB"); - populate(5, 5, "CD"); - checkResult(new TextChangeImpl("", 0, 2), new TextChangeImpl("", 5, 7)); - } - - @Test - public void insertAndReplaceAtEnd() { - populate(0, 0, "AB"); - populate(1, 4, "CD"); - checkResult(new TextChangeImpl("01", 0, 3)); - } - - @Test - public void insertAndReplaceAtStart() { - populate(2, 2, "AB"); - populate(1, 3, "CD"); - checkResult(new TextChangeImpl("1", 1, 4)); - } - - @Test - public void removeAndReplace() { - populate(1, 3, ""); - populate(1, 4, "ABC"); - checkResult(new TextChangeImpl("12345", 1, 4)); - } - - @Test - public void removedChangeWithNonStrictBoundaryMatch() { - populate(3, 5, "AB"); - populate(2, 4, ""); - checkResult(new TextChangeImpl("234", 2, 3)); - } - - @Test - public void removedChangeWithStrictBoundaryMatch() { - populate(3, 5, "AB"); - populate(3, 5, ""); - checkResult(new TextChangeImpl("34", 3, 3)); - } - - @Test - public void cutChangeFromEnd() { - populate(3, 3, "ABCD"); - populate(4, 8, ""); - checkResult(new TextChangeImpl("3", 3, 4)); - } - - @Test - public void cutChangeFromStart() { - populate(3, 3, "ABCD"); - populate(2, 4, ""); - checkResult(new TextChangeImpl("2", 2, 5)); - } - - @Test - public void cutInTheMiddleOfInsertedText() { - populate(3, 3, "ABCDEF"); - populate(5, 8, ""); - checkResult(new TextChangeImpl("", 3, 6)); - } - - @Test - public void cutInTheMiddleOfReplacedText() { - populate(3, 9, "ABCDEF"); - populate(5, 8, ""); - checkResult(new TextChangeImpl("345678", 3, 6)); - } - - @Test - public void cutMultipleChanges() { - populate(3, 3, "ABC"); - populate(8, 8, "DEF"); - populate(5, 9, ""); - checkResult(new TextChangeImpl("34", 3, 7)); - } - - @Test - public void mergeChangeFromStart() { - populate(3, 3, "ABC"); - populate(4, 4, "DEF"); - checkResult(new TextChangeImpl("", 3, 9)); - } - - @Test - public void mergeChangeFromEnd() { - populate(3, 3, "AB"); - populate(1, 4, "CDEF"); - checkResult(new TextChangeImpl("12", 1, 6)); - } - - @Test - public void mergeMultipleChangesInOne() { - populate(3, 3, "AB"); - populate(9, 9, "CD"); - populate(5, 9, "EFGH"); - checkResult(new TextChangeImpl("3456", 3, 11)); - } - - @Test - public void mergeChangesSequence() { - populate(1, 1, "AB"); - populate(3, 3, "CD"); - populate(5, 5, "EFGH"); - checkResult(new TextChangeImpl("", 1, 9)); - } - - @Test - public void replaceAndInsertAtEnd() { - populate(4, 8, "ABCD"); - populate(5, 5, "EFGHIJKL"); - checkResult(new TextChangeImpl("4567", 4, 16)); - } - - private void populate(int start, int end, String newText) { - DocumentEventImpl event = new DocumentEventImpl( - myDocument, start, buffer.substring(start, end), newText, ++ourCounter, false - ); - buffer.replace(start, end, newText); - myCollector.beforeDocumentChange(event); - myCollector.documentChanged(event); - } - - private void checkResult(TextChange ... expected) { - List actual = myCollector.getChanges(); - assertEquals(asList(expected), actual); - } -} \ No newline at end of file diff --git a/platform/platform-tests/testSrc/com/intellij/openapi/editor/colors/impl/EditorColorsSchemeImplTest.java b/platform/platform-tests/testSrc/com/intellij/openapi/editor/colors/impl/EditorColorsSchemeImplTest.java index 87f159200272..ba9f9eb8ce54 100644 --- a/platform/platform-tests/testSrc/com/intellij/openapi/editor/colors/impl/EditorColorsSchemeImplTest.java +++ b/platform/platform-tests/testSrc/com/intellij/openapi/editor/colors/impl/EditorColorsSchemeImplTest.java @@ -190,6 +190,7 @@ public class EditorColorsSchemeImplTest extends LightPlatformCodeInsightTestCase Element root = new Element("scheme"); ((AbstractColorsScheme)editorColorsScheme).writeExternal(root); root.removeChildren("option"); // Remove font options + root.removeChildren("metaInfo"); assertXmlOutputEquals("", root); } @@ -200,6 +201,7 @@ public class EditorColorsSchemeImplTest extends LightPlatformCodeInsightTestCase Element root = new Element("scheme"); ((AbstractColorsScheme)editorColorsScheme).writeExternal(root); root.removeChildren("option"); // Remove font options + root.removeChildren("metaInfo"); assertXmlOutputEquals("", root); } diff --git a/platform/platform-tests/testSrc/com/intellij/openapi/fileTypes/impl/FileTypesTest.java b/platform/platform-tests/testSrc/com/intellij/openapi/fileTypes/impl/FileTypesTest.java index 5366e473721b..d841ce8f9ce7 100644 --- a/platform/platform-tests/testSrc/com/intellij/openapi/fileTypes/impl/FileTypesTest.java +++ b/platform/platform-tests/testSrc/com/intellij/openapi/fileTypes/impl/FileTypesTest.java @@ -36,7 +36,10 @@ import com.intellij.openapi.vfs.CharsetToolkit; import com.intellij.openapi.vfs.LocalFileSystem; import com.intellij.openapi.vfs.PersistentFSConstants; import com.intellij.openapi.vfs.VirtualFile; -import com.intellij.psi.*; +import com.intellij.psi.PsiBinaryFile; +import com.intellij.psi.PsiDocumentManager; +import com.intellij.psi.PsiFile; +import com.intellij.psi.PsiPlainTextFile; import com.intellij.psi.impl.PsiManagerEx; import com.intellij.testFramework.PlatformTestCase; import com.intellij.testFramework.PlatformTestUtil; @@ -234,7 +237,7 @@ public class FileTypesTest extends PlatformTestCase { assertEquals(PlainTextFileType.INSTANCE, vFile.getFileType()); // type autodetected during indexing - PsiFile psiFile = ((PsiManagerEx)PsiManager.getInstance(getProject())).getFileManager().findFile(vFile); // autodetect text file if needed + PsiFile psiFile = PsiManagerEx.getInstanceEx(getProject()).getFileManager().findFile(vFile); // autodetect text file if needed assertNotNull(psiFile); assertEquals(PlainTextFileType.INSTANCE, psiFile.getFileType()); } diff --git a/platform/platform-tests/testSrc/com/intellij/util/JdkBundleTest.java b/platform/platform-tests/testSrc/com/intellij/util/JdkBundleTest.java index cee75f9b92ef..a76106b475d9 100644 --- a/platform/platform-tests/testSrc/com/intellij/util/JdkBundleTest.java +++ b/platform/platform-tests/testSrc/com/intellij/util/JdkBundleTest.java @@ -139,7 +139,8 @@ public class JdkBundleTest { assertNotNull(verUpdate); - assertEquals(verStr, verUpdate.first.toString() + "_" + verUpdate.second.toString()); + final String evalVerStr = verUpdate.first.toString() + "_" + verUpdate.second.toString(); + assertTrue(evalVerStr + " is not the same with " + verStr, verStr.contains(evalVerStr)); } @Test @@ -164,6 +165,7 @@ public class JdkBundleTest { assertNotNull(verUpdate); - assertEquals(verStr, verUpdate.first.toString() + "_" + verUpdate.second.toString()); + final String evalVerStr = verUpdate.first.toString() + "_" + verUpdate.second.toString(); + assertTrue(evalVerStr + " is not the same with " + verStr, verStr.contains(evalVerStr)); } } \ No newline at end of file diff --git a/platform/projectModel-api/src/com/intellij/openapi/components/Storage.java b/platform/projectModel-api/src/com/intellij/openapi/components/Storage.java index 0b3921147bf6..a1f9f5d492e4 100644 --- a/platform/projectModel-api/src/com/intellij/openapi/components/Storage.java +++ b/platform/projectModel-api/src/com/intellij/openapi/components/Storage.java @@ -25,10 +25,10 @@ import java.lang.annotation.RetentionPolicy; */ @Retention(RetentionPolicy.RUNTIME) public @interface Storage { - @Deprecated /** * @deprecated Use {@link #value()}. */ + @Deprecated String file() default ""; /** @@ -58,15 +58,15 @@ public @interface Storage { @SuppressWarnings("deprecation") Class stateSplitter() default StateSplitterEx.class; - @Deprecated /** * @deprecated Not required and not used anymore. */ + @Deprecated StorageScheme scheme() default StorageScheme.DEFAULT; - @Deprecated /** * @deprecated Not required and not used anymore. */ + @Deprecated String id() default "default"; } \ No newline at end of file diff --git a/platform/projectModel-api/src/com/intellij/openapi/components/StoragePathMacros.java b/platform/projectModel-api/src/com/intellij/openapi/components/StoragePathMacros.java index 6ffb44e8ef17..bcc771c4ac78 100644 --- a/platform/projectModel-api/src/com/intellij/openapi/components/StoragePathMacros.java +++ b/platform/projectModel-api/src/com/intellij/openapi/components/StoragePathMacros.java @@ -37,25 +37,23 @@ public class StoragePathMacros { /** * Points to the application-level options root directory. + * @deprecated Not required anymore. See {@link State#storages()}. */ @SuppressWarnings("unused") @Deprecated - /** - * @deprecated Not required anymore. See {@link State#storages()}. - */ public static final String APP_CONFIG = "$APP_CONFIG$"; - @Deprecated /** * @deprecated Not required anymore. See {@link State#storages()}. */ + @Deprecated public static final String PROJECT_FILE = "$PROJECT_FILE$"; - @SuppressWarnings("unused") - @Deprecated /** * @deprecated Not required anymore. See {@link State#storages()}. */ + @SuppressWarnings("unused") + @Deprecated public static final String PROJECT_CONFIG_DIR = "$PROJECT_CONFIG_DIR$"; /** diff --git a/platform/projectModel-api/src/com/intellij/openapi/roots/libraries/LibraryUtil.java b/platform/projectModel-api/src/com/intellij/openapi/roots/libraries/LibraryUtil.java index 3025b80ee53d..3dd21fe8ee95 100644 --- a/platform/projectModel-api/src/com/intellij/openapi/roots/libraries/LibraryUtil.java +++ b/platform/projectModel-api/src/com/intellij/openapi/roots/libraries/LibraryUtil.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2009 JetBrains s.r.o. + * Copyright 2000-2016 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. @@ -14,9 +14,6 @@ * limitations under the License. */ -/** - * @author cdr - */ package com.intellij.openapi.roots.libraries; import com.intellij.openapi.module.Module; diff --git a/platform/remote-servers/agent-rt/src/com/intellij/remoteServer/agent/annotation/FinalCall.java b/platform/remote-servers/agent-rt/src/com/intellij/remoteServer/agent/annotation/FinalCall.java index 5b77d5476eee..1a8407ce4255 100644 --- a/platform/remote-servers/agent-rt/src/com/intellij/remoteServer/agent/annotation/FinalCall.java +++ b/platform/remote-servers/agent-rt/src/com/intellij/remoteServer/agent/annotation/FinalCall.java @@ -1,8 +1,19 @@ -package com.intellij.remoteServer.agent.annotation; - -/** - * @author michael.golubev +/* + * Copyright 2000-2016 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.remoteServer.agent.annotation; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; diff --git a/platform/script-debugger/backend/src/org/jetbrains/debugger/Scope.java b/platform/script-debugger/backend/src/org/jetbrains/debugger/Scope.java index d380b07e5002..2e5182186a01 100644 --- a/platform/script-debugger/backend/src/org/jetbrains/debugger/Scope.java +++ b/platform/script-debugger/backend/src/org/jetbrains/debugger/Scope.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2015 JetBrains s.r.o. + * Copyright 2000-2016 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. @@ -36,10 +36,10 @@ public interface Scope { @NotNull Type getType(); - @Nullable /** * Class or function or file name */ + @Nullable String getDescription(); @NotNull diff --git a/platform/structuralsearch/source/META-INF/structuralsearch.xml b/platform/structuralsearch/source/META-INF/structuralsearch.xml index 3ef98f6a2c54..b045255c967f 100644 --- a/platform/structuralsearch/source/META-INF/structuralsearch.xml +++ b/platform/structuralsearch/source/META-INF/structuralsearch.xml @@ -2,8 +2,7 @@ - - diff --git a/platform/testFramework/src/com/intellij/testFramework/FileTreeAccessFilter.java b/platform/testFramework/src/com/intellij/testFramework/FileTreeAccessFilter.java index 06155a9004ef..445f2c73877f 100755 --- a/platform/testFramework/src/com/intellij/testFramework/FileTreeAccessFilter.java +++ b/platform/testFramework/src/com/intellij/testFramework/FileTreeAccessFilter.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2009 JetBrains s.r.o. + * Copyright 2000-2016 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. @@ -30,7 +30,7 @@ import java.util.Set; * @author cdr */ public class FileTreeAccessFilter implements VirtualFileFilter { - protected final Set myAddedClasses = new THashSet(); + private final Set myAddedClasses = new THashSet<>(); private boolean myTreeAccessAllowed; @Override @@ -52,6 +52,6 @@ public class FileTreeAccessFilter implements VirtualFileFilter { } public String toString() { - return "JAVA {allowed=" + myTreeAccessAllowed + " files=" + new ArrayList(myAddedClasses) + "}"; + return "JAVA {allowed=" + myTreeAccessAllowed + " files=" + new ArrayList<>(myAddedClasses) + "}"; } } diff --git a/platform/testFramework/src/com/intellij/testFramework/LightPlatformCodeInsightTestCase.java b/platform/testFramework/src/com/intellij/testFramework/LightPlatformCodeInsightTestCase.java index 5d058fb4ea2b..683566f85eb1 100644 --- a/platform/testFramework/src/com/intellij/testFramework/LightPlatformCodeInsightTestCase.java +++ b/platform/testFramework/src/com/intellij/testFramework/LightPlatformCodeInsightTestCase.java @@ -647,9 +647,6 @@ public abstract class LightPlatformCodeInsightTestCase extends LightPlatformTest /** * file parameterized tests support * @see FileBasedTestCaseHelperEx - */ - - /** * @Parameterized.Parameter fields are injected on parameterized test creation. */ @Parameterized.Parameter(0) 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 589e31dadd95..8f161ae852f7 100644 --- a/platform/testFramework/src/com/intellij/testFramework/fixtures/impl/CodeInsightTestFixtureImpl.java +++ b/platform/testFramework/src/com/intellij/testFramework/fixtures/impl/CodeInsightTestFixtureImpl.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2015 JetBrains s.r.o. + * Copyright 2000-2016 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. @@ -89,6 +89,7 @@ import com.intellij.profile.codeInspection.InspectionProfileManager; import com.intellij.profile.codeInspection.InspectionProjectProfileManager; import com.intellij.psi.*; import com.intellij.psi.impl.DebugUtil; +import com.intellij.psi.impl.PsiManagerEx; import com.intellij.psi.impl.PsiManagerImpl; import com.intellij.psi.impl.PsiModificationTrackerImpl; import com.intellij.psi.impl.cache.CacheManager; @@ -1626,7 +1627,7 @@ public class CodeInsightTestFixtureImpl extends BaseFixture implements CodeInsig final VirtualFileFilter fileTreeAccessFilter = myVirtualFileFilter; Disposable disposable = Disposer.newDisposable(); if (fileTreeAccessFilter != null) { - ((PsiManagerImpl)PsiManager.getInstance(project)).setAssertOnFileLoadingFilter(fileTreeAccessFilter, disposable); + PsiManagerEx.getInstanceEx(project).setAssertOnFileLoadingFilter(fileTreeAccessFilter, disposable); } // ProfilingUtil.startCPUProfiling(); diff --git a/platform/usageView/src/com/intellij/usages/impl/GroupNode.java b/platform/usageView/src/com/intellij/usages/impl/GroupNode.java index 7e8cd1f39f3f..aaf9574ede9e 100644 --- a/platform/usageView/src/com/intellij/usages/impl/GroupNode.java +++ b/platform/usageView/src/com/intellij/usages/impl/GroupNode.java @@ -44,7 +44,7 @@ public class GroupNode extends Node implements Navigatable, Comparable mySubgroupNodes = new THashMap(); private final List myUsageNodes = new SmartList(); @NotNull private final UsageViewTreeModelBuilder myUsageTreeModel; - private volatile int myRecursiveUsageCount = 0; + private volatile int myRecursiveUsageCount; public GroupNode(@Nullable UsageGroup group, int ruleIndex, @NotNull UsageViewTreeModelBuilder treeModel) { super(treeModel); diff --git a/platform/usageView/src/com/intellij/usages/impl/UsageViewImpl.java b/platform/usageView/src/com/intellij/usages/impl/UsageViewImpl.java index e793cada6244..18b18d270ef7 100644 --- a/platform/usageView/src/com/intellij/usages/impl/UsageViewImpl.java +++ b/platform/usageView/src/com/intellij/usages/impl/UsageViewImpl.java @@ -108,7 +108,7 @@ public class UsageViewImpl implements UsageView, UsageModelTracker.UsageModelTra private final ButtonPanel myButtonPanel = new ButtonPanel(); private final JComponent myAdditionalComponent = new JPanel(new BorderLayout()); private volatile boolean isDisposed; - private volatile boolean myChangesDetected = false; + private volatile boolean myChangesDetected; public static final Comparator USAGE_COMPARATOR = new Comparator() { @Override public int compare(final Usage o1, final Usage o2) { diff --git a/platform/util/resources/misc/registry.properties b/platform/util/resources/misc/registry.properties index ee8f4c0695ae..760c19f3e722 100644 --- a/platform/util/resources/misc/registry.properties +++ b/platform/util/resources/misc/registry.properties @@ -438,6 +438,7 @@ search.everywhere.settings=false svn.use.incoming.optimization=false svn.lowest.supported.format.for.command.line=1.7.0 svn.use.svnkit.for.https.server.certificate.check=true +svn.use.sqlite.jdbc=false completion.enable.relevant.method.chain.suggestions=false ide.mac.message.sheets.java.emulation=false diff --git a/platform/util/src/com/intellij/openapi/util/IconLoader.java b/platform/util/src/com/intellij/openapi/util/IconLoader.java index 31c747b25f1d..91d673143021 100644 --- a/platform/util/src/com/intellij/openapi/util/IconLoader.java +++ b/platform/util/src/com/intellij/openapi/util/IconLoader.java @@ -141,11 +141,11 @@ public final class IconLoader { } } - @Nullable /** * Might return null if icon was not found. * Use only if you expected null return value, otherwise see {@link IconLoader#getIcon(String)} */ + @Nullable public static Icon findIcon(@NonNls @NotNull String path) { Class callerClass = ReflectionUtil.getGrandCallerClass(); if (callerClass == null) return null; diff --git a/platform/util/src/com/intellij/openapi/util/JDOMUtil.java b/platform/util/src/com/intellij/openapi/util/JDOMUtil.java index 109de0f62532..333204366ea0 100644 --- a/platform/util/src/com/intellij/openapi/util/JDOMUtil.java +++ b/platform/util/src/com/intellij/openapi/util/JDOMUtil.java @@ -334,10 +334,10 @@ public class JDOMUtil { return loadDocument(new InputStreamReader(stream, CharsetToolkit.UTF8_CHARSET)); } - @Contract("null -> null; !null -> !null") /** * @deprecated Use com.intellij.util.loadElement */ + @Contract("null -> null; !null -> !null") public static Element load(Reader reader) throws JDOMException, IOException { return reader == null ? null : loadDocument(reader).detachRootElement(); } diff --git a/platform/util/src/com/intellij/util/ConcurrencyUtil.java b/platform/util/src/com/intellij/util/ConcurrencyUtil.java index 606cbf229847..37b44edf3914 100644 --- a/platform/util/src/com/intellij/util/ConcurrencyUtil.java +++ b/platform/util/src/com/intellij/util/ConcurrencyUtil.java @@ -137,10 +137,10 @@ public class ConcurrencyUtil { }; } - @TestOnly /** * Awaits for all tasks in the {@code executor} to finish for the specified {@code timeout} */ + @TestOnly public static void awaitQuiescence(@NotNull ThreadPoolExecutor executor, long timeout, @NotNull TimeUnit unit) { executor.setKeepAliveTime(1, TimeUnit.NANOSECONDS); // no need for zombies in tests executor.setCorePoolSize(0); // interrupt idle workers diff --git a/platform/util/src/com/intellij/util/UniqueFileNamesProvider.java b/platform/util/src/com/intellij/util/UniqueFileNamesProvider.java index 2774661843a2..b6390688a4fa 100644 --- a/platform/util/src/com/intellij/util/UniqueFileNamesProvider.java +++ b/platform/util/src/com/intellij/util/UniqueFileNamesProvider.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2015 JetBrains s.r.o. + * Copyright 2000-2016 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. @@ -20,11 +20,11 @@ import com.intellij.openapi.util.io.FileUtil; import java.util.ArrayList; import java.util.List; -@SuppressWarnings("unused") -@Deprecated /** * Use {@link com.intellij.util.text.UniqueNameGenerator} */ +@SuppressWarnings("unused") +@Deprecated public class UniqueFileNamesProvider { private final List myExistingNames; diff --git a/platform/util/src/com/intellij/util/concurrency/AppDelayQueue.java b/platform/util/src/com/intellij/util/concurrency/AppDelayQueue.java index 147161245a4c..8ac0dc9aab1a 100644 --- a/platform/util/src/com/intellij/util/concurrency/AppDelayQueue.java +++ b/platform/util/src/com/intellij/util/concurrency/AppDelayQueue.java @@ -33,7 +33,7 @@ class AppDelayQueue extends DelayQueue private final AtomicBoolean shutdown = new AtomicBoolean(); AppDelayQueue() { - /** this thread takes the ready-to-execute scheduled tasks off the queue and passes them for immediate execution to {@link SchedulingWrapper#backendExecutorService} */ + /* this thread takes the ready-to-execute scheduled tasks off the queue and passes them for immediate execution to {@link SchedulingWrapper#backendExecutorService} */ scheduledToPooledTransferer = new Thread(new Runnable() { @Override public void run() { diff --git a/platform/util/src/com/intellij/util/concurrency/AppScheduledExecutorService.java b/platform/util/src/com/intellij/util/concurrency/AppScheduledExecutorService.java index da5f20e33204..a1a6c8ca4a36 100644 --- a/platform/util/src/com/intellij/util/concurrency/AppScheduledExecutorService.java +++ b/platform/util/src/com/intellij/util/concurrency/AppScheduledExecutorService.java @@ -99,7 +99,7 @@ public class AppScheduledExecutorService extends SchedulingWrapper { public void shutdownAppScheduledExecutorService() { delayQueue.shutdown(); // shutdown delay queue first to avoid rejected execution exceptions in Alarm doShutdown(); - //System.out.println("app threads counter = " + counter); + //System.out.println("app threads created counter = " + counter); } public int getBackendPoolExecutorSize() { @@ -135,11 +135,12 @@ public class AppScheduledExecutorService extends SchedulingWrapper { super.shutdown(); } + @NotNull private List doShutdownNow() { return super.shutdownNow(); } - private void doSetThreadFactory(ThreadFactory threadFactory) { + private void doSetThreadFactory(@NotNull ThreadFactory threadFactory) { super.setThreadFactory(threadFactory); } diff --git a/platform/util/src/com/intellij/util/containers/JBIterable.java b/platform/util/src/com/intellij/util/containers/JBIterable.java index 41577bbded2c..e7df7259c74e 100644 --- a/platform/util/src/com/intellij/util/containers/JBIterable.java +++ b/platform/util/src/com/intellij/util/containers/JBIterable.java @@ -182,6 +182,7 @@ public abstract class JBIterable implements Iterable { }); } + @NotNull public > T typedIterator() { return (T) iterator(); } @@ -190,6 +191,7 @@ public abstract class JBIterable implements Iterable { * Returns a string representation of this iterable up to 50 elements, with the format * {@code (e1, e2, ..., en [, ...] )} for debugging purposes. */ + @NotNull @Override public String toString() { return myIterable == this ? super.toString() : String.valueOf(myIterable); @@ -226,6 +228,7 @@ public abstract class JBIterable implements Iterable { /** * Returns element at index if it is present; otherwise {@code null} */ + @Nullable public final E get(int index) { if (myIterable instanceof List) { return index >= ((List)myIterable).size() ? null : ((List)myIterable).get(index); @@ -240,14 +243,17 @@ public abstract class JBIterable implements Iterable { *

The returned iterable's {@code Iterator} supports {@code remove()} when the corresponding * {@code Iterator} supports it. */ + @NotNull public final JBIterable append(@Nullable Iterable other) { return other == null ? this : this == EMPTY ? from(other) : of(myIterable, other).flatten(Functions., Iterable>identity()); } + @NotNull public final JBIterable append(@Nullable Iterable other, @NotNull Function> fun) { return other == null ? this : this == EMPTY ? from(other).flatten(fun) : append(from(other).flatten(fun)); } + @NotNull public final JBIterable repeat(int count) { Function, JBIterable> fun = Functions.identity(); return generate(this, fun).take(count).flatten(fun); @@ -257,10 +263,12 @@ public abstract class JBIterable implements Iterable { * Returns a {@code JBIterable} whose iterators traverse first the elements of this iterable, * followed by {@code elements}. */ + @NotNull public final JBIterable append(@NotNull E[] elements) { return this == EMPTY ? of(elements) : append(Arrays.asList(elements)); } + @NotNull public final JBIterable append(@Nullable E e) { return e == null ? this : this == EMPTY ? of(e) : append(Collections.singleton(e)); } @@ -268,6 +276,7 @@ public abstract class JBIterable implements Iterable { /** * Returns the elements from this iterable that satisfy a condition. */ + @NotNull public final JBIterable filter(@NotNull final Condition condition) { return intercept(new Function, Iterator>() { @Override @@ -281,6 +290,7 @@ public abstract class JBIterable implements Iterable { * Returns the elements from this iterable that are instances of class {@code type}. * @param type the type of elements desired */ + @NotNull public final JBIterable filter(@NotNull Class type) { return (JBIterable)filter(Conditions.instanceOf(type)); } @@ -426,6 +436,7 @@ public abstract class JBIterable implements Iterable { * Returns an {@code List} containing all of the elements from this iterable in * proper sequence. */ + @NotNull public final List toList() { return Collections.unmodifiableList(ContainerUtil.newArrayList(myIterable)); } @@ -434,6 +445,7 @@ public abstract class JBIterable implements Iterable { * Returns an {@code Set} containing all of the elements from this iterable with * duplicates removed. */ + @NotNull public final Set toSet() { return Collections.unmodifiableSet(ContainerUtil.newLinkedHashSet(myIterable)); } @@ -444,6 +456,7 @@ public abstract class JBIterable implements Iterable { * elements, the returned map will contain each distinct element once in the order it first * appears. */ + @NotNull public final Map toMap(Convertor valueFunction) { return Collections.unmodifiableMap(ContainerUtil.newMapFromKeys(iterator(), valueFunction)); } @@ -455,6 +468,7 @@ public abstract class JBIterable implements Iterable { * @param collection the collection to copy elements to * @return {@code collection}, for convenience */ + @NotNull public final > C addAllTo(@NotNull C collection) { if (myIterable instanceof Collection) { collection.addAll((Collection)myIterable); diff --git a/platform/util/src/com/intellij/util/containers/JBIterator.java b/platform/util/src/com/intellij/util/containers/JBIterator.java index 684481eb2f2a..535c56284966 100644 --- a/platform/util/src/com/intellij/util/containers/JBIterator.java +++ b/platform/util/src/com/intellij/util/containers/JBIterator.java @@ -20,6 +20,7 @@ import com.intellij.openapi.util.text.StringUtil; import com.intellij.util.Function; import com.intellij.util.Functions; import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; import java.util.Collections; import java.util.Iterator; @@ -52,11 +53,13 @@ public abstract class JBIterator implements Iterator { private static final Object STOP = new String("#stop"); private static final Object SKIP = new String("#skip"); + @NotNull public static > JBIterable cursor(@NotNull E iterator) { return JBIterable.generate(iterator, Functions.identity()).takeWhile(ADVANCE); } - public static JBIterator from(final Iterator it) { + @NotNull + public static JBIterator from(@NotNull final Iterator it) { return it instanceof JBIterator ? (JBIterator)it : new JBIterator() { @Override protected E nextImpl() { @@ -84,6 +87,7 @@ public abstract class JBIterator implements Iterator { /** * Notifies the iterator that there's no more elements. */ + @Nullable protected final E stop() { myNext = STOP; return null; @@ -92,6 +96,7 @@ public abstract class JBIterator implements Iterator { /** * Notifies the iterator to skip and re-invoke nextImpl(). */ + @Nullable protected final E skip() { myNext = SKIP; return null; @@ -103,6 +108,7 @@ public abstract class JBIterator implements Iterator { return myNext != STOP; } + @Nullable @Override public final E next() { advance(); @@ -125,6 +131,7 @@ public abstract class JBIterator implements Iterator { /** * Returns the current element if any; otherwise throws exception. */ + @Nullable public final E current() { if (myCurrent == NONE) throw new NoSuchElementException(); return (E)myCurrent; diff --git a/platform/util/src/com/intellij/util/containers/LongStack.java b/platform/util/src/com/intellij/util/containers/LongStack.java index f562d4f56ae3..5b78d626c843 100644 --- a/platform/util/src/com/intellij/util/containers/LongStack.java +++ b/platform/util/src/com/intellij/util/containers/LongStack.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2015 JetBrains s.r.o. + * Copyright 2000-2016 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. @@ -15,9 +15,6 @@ */ package com.intellij.util.containers; -/** - * @author lambdamix - */ import com.intellij.util.ArrayUtil; import java.util.Arrays; diff --git a/platform/util/src/com/intellij/util/containers/MultiMap.java b/platform/util/src/com/intellij/util/containers/MultiMap.java index 908c4cadcf5a..98d115cf8438 100644 --- a/platform/util/src/com/intellij/util/containers/MultiMap.java +++ b/platform/util/src/com/intellij/util/containers/MultiMap.java @@ -300,12 +300,12 @@ public class MultiMap implements Serializable { }; } - @Deprecated - @SuppressWarnings("unused") - @NotNull /** * @deprecated Use {@link #createSmart()} */ + @Deprecated + @SuppressWarnings("unused") + @NotNull public static MultiMap createSmartList() { return createSmart(); } @@ -346,6 +346,11 @@ public class MultiMap implements Serializable { @NotNull public static MultiMap createSet() { + return createSet(TObjectHashingStrategy.CANONICAL); + } + + @NotNull + public static MultiMap createSet(final TObjectHashingStrategy strategy) { return new MultiMap() { @NotNull @Override @@ -362,7 +367,7 @@ public class MultiMap implements Serializable { @NotNull @Override protected Map> createMap() { - return new THashMap>(); + return new THashMap>(strategy); } }; } diff --git a/platform/util/src/com/intellij/util/io/EqualityPolicy.java b/platform/util/src/com/intellij/util/io/EqualityPolicy.java index e1396cdc99e0..f565ee57d18b 100644 --- a/platform/util/src/com/intellij/util/io/EqualityPolicy.java +++ b/platform/util/src/com/intellij/util/io/EqualityPolicy.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2009 JetBrains s.r.o. + * Copyright 2000-2016 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. @@ -16,9 +16,9 @@ package com.intellij.util.io; -@Deprecated /** * Use {@link com.intellij.util.containers.hash.EqualityPolicy} directly */ +@Deprecated public interface EqualityPolicy extends com.intellij.util.containers.hash.EqualityPolicy{ } diff --git a/platform/util/src/com/intellij/util/io/PagedFileStorage.java b/platform/util/src/com/intellij/util/io/PagedFileStorage.java index 5cba7519db1a..405ca070ee1d 100644 --- a/platform/util/src/com/intellij/util/io/PagedFileStorage.java +++ b/platform/util/src/com/intellij/util/io/PagedFileStorage.java @@ -104,7 +104,7 @@ public class PagedFileStorage implements Forceable { private final Object myLastAccessedBufferCacheLock = new Object(); private final byte[] myTypedIOBuffer; - private volatile boolean isDirty = false; + private volatile boolean isDirty; private final File myFile; protected volatile long mySize = -1; protected final int myPageSize; diff --git a/platform/util/src/com/intellij/util/io/RandomAccessDataFile.java b/platform/util/src/com/intellij/util/io/RandomAccessDataFile.java index f035fe04ebfa..dca54a1eac33 100644 --- a/platform/util/src/com/intellij/util/io/RandomAccessDataFile.java +++ b/platform/util/src/com/intellij/util/io/RandomAccessDataFile.java @@ -31,7 +31,7 @@ public class RandomAccessDataFile implements Forceable, Closeable { protected static final Logger LOG = Logger.getInstance("#com.intellij.util.io.RandomAccessDataFile"); private static final OpenChannelsCache ourCache = new OpenChannelsCache(150, "rw"); - private static int ourFilesCount = 0; + private static int ourFilesCount; private final int myCount = ourFilesCount++; private final File myFile; @@ -43,8 +43,8 @@ public class RandomAccessDataFile implements Forceable, Closeable { private final FileWriter log; private volatile long mySize; - private volatile boolean myIsDirty = false; - private volatile boolean myIsDisposed = false; + private volatile boolean myIsDirty; + private volatile boolean myIsDisposed; private static final boolean DEBUG = false; @@ -243,12 +243,12 @@ public class RandomAccessDataFile implements Forceable, Closeable { } } - public static int totalReads = 0; - public static long totalReadBytes = 0; + public static int totalReads; + public static long totalReadBytes; - public static int seekcount = 0; - public static int totalWrites = 0; - public static long totalWriteBytes = 0; + public static int seekcount; + public static int totalWrites; + public static long totalWriteBytes; void loadPage(final Page page) { assertNotDisposed(); diff --git a/platform/util/src/com/intellij/util/ui/ColumnInfo.java b/platform/util/src/com/intellij/util/ui/ColumnInfo.java index 1be6e451deea..77781d23206d 100644 --- a/platform/util/src/com/intellij/util/ui/ColumnInfo.java +++ b/platform/util/src/com/intellij/util/ui/ColumnInfo.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2014 JetBrains s.r.o. + * Copyright 2000-2016 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. @@ -67,11 +67,11 @@ public abstract class ColumnInfo { } - @Nullable /** * @see com.intellij.util.ui.table.IconTableCellRenderer * @see com.intellij.util.ui.LocalPathCellEditor */ + @Nullable public TableCellRenderer getRenderer(Item item) { return null; } @@ -80,10 +80,10 @@ public abstract class ColumnInfo { return renderer; } - @Nullable /** * @see com.intellij.util.ui.table.ComboBoxTableCellEditor */ + @Nullable public TableCellEditor getEditor(Item item) { return null; } diff --git a/platform/util/src/com/intellij/util/ui/ComboBoxTableCellEditor.java b/platform/util/src/com/intellij/util/ui/ComboBoxTableCellEditor.java index 79ae369b6a0c..b2ba22d192ab 100644 --- a/platform/util/src/com/intellij/util/ui/ComboBoxTableCellEditor.java +++ b/platform/util/src/com/intellij/util/ui/ComboBoxTableCellEditor.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2014 JetBrains s.r.o. + * Copyright 2000-2016 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. @@ -23,10 +23,10 @@ import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; -@Deprecated /** * @deprecated Please use {@link com.intellij.util.ui.table.ComboBoxTableCellEditor} */ +@Deprecated public class ComboBoxTableCellEditor extends AbstractTableCellEditor { public static final ComboBoxTableCellEditor INSTANCE = new ComboBoxTableCellEditor(); diff --git a/platform/util/src/com/intellij/util/ui/UIUtil.java b/platform/util/src/com/intellij/util/ui/UIUtil.java index fe47fb4b25df..f1942b61464e 100644 --- a/platform/util/src/com/intellij/util/ui/UIUtil.java +++ b/platform/util/src/com/intellij/util/ui/UIUtil.java @@ -292,7 +292,7 @@ public class UIUtil { } }; - private static volatile Pair ourSystemFontData = null; + private static volatile Pair ourSystemFontData; public static final float DEF_SYSTEM_FONT_SIZE = 12f; // TODO: consider 12 * 1.33 to compensate JDK's 72dpi font scale @@ -354,9 +354,9 @@ public class UIUtil { return isRetina; } - /** - * Could be quite easily implemented with [NSScreen backingScaleFactor] - * and JNA + /* + Could be quite easily implemented with [NSScreen backingScaleFactor] + and JNA */ //private static boolean isAppleRetina (Graphics2D g2d) { // return false; @@ -3503,7 +3503,7 @@ public class UIUtil { return null; } - private static Map ourRealFontFamilies = null; + private static Map ourRealFontFamilies; //Experimental, seems to be reliable under MacOS X only diff --git a/platform/util/src/com/intellij/util/ui/tree/AbstractTreeModel.java b/platform/util/src/com/intellij/util/ui/tree/AbstractTreeModel.java new file mode 100644 index 000000000000..0f7743ab13f5 --- /dev/null +++ b/platform/util/src/com/intellij/util/ui/tree/AbstractTreeModel.java @@ -0,0 +1,97 @@ +/* + * Copyright 2000-2016 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.util.ui.tree; + +import javax.swing.event.TreeModelEvent; +import javax.swing.event.TreeModelListener; +import javax.swing.tree.TreeModel; +import javax.swing.tree.TreePath; + +/** + * @author Sergey.Malenkov + */ +public abstract class AbstractTreeModel implements TreeModel { + private final TreeModelListenerList listeners = new TreeModelListenerList(); + + /** + * Notifies all added listeners that a tree hierarchy was changed. + * + * @param path the path to the parent of the modified items + * @param indices index values of the modified items + * @param children an array containing the inserted, removed, or changed objects + * @see TreeModelListener#treeStructureChanged(TreeModelEvent) + */ + protected void treeStructureChanged(TreePath path, int[] indices, Object[] children) { + if (!listeners.isEmpty()) listeners.treeStructureChanged(new TreeModelEvent(this, path, indices, children)); + } + + /** + * Notifies all added listeners that some nodes were changed. + * + * @param path the path to the parent of the modified items + * @param indices index values of the modified items + * @param children an array containing the inserted, removed, or changed objects + * @see TreeModelListener#treeNodesChanged(TreeModelEvent) + */ + protected void treeNodesChanged(TreePath path, int[] indices, Object[] children) { + if (!listeners.isEmpty()) listeners.treeNodesChanged(new TreeModelEvent(this, path, indices, children)); + } + + /** + * Notifies all added listeners that some nodes were inserted. + * + * @param path the path to the parent of the modified items + * @param indices index values of the modified items + * @param children an array containing the inserted, removed, or changed objects + * @see TreeModelListener#treeNodesInserted(TreeModelEvent) + */ + protected void treeNodesInserted(TreePath path, int[] indices, Object[] children) { + if (!listeners.isEmpty()) listeners.treeNodesInserted(new TreeModelEvent(this, path, indices, children)); + } + + /** + * /** + * Notifies all added listeners that some nodes were removed. + * + * @param path the path to the parent of the modified items + * @param indices index values of the modified items + * @param children an array containing the inserted, removed, or changed objects + * @see TreeModelListener#treeNodesRemoved(TreeModelEvent) + */ + protected void treeNodesRemoved(TreePath path, int[] indices, Object[] children) { + if (!listeners.isEmpty()) listeners.treeNodesRemoved(new TreeModelEvent(this, path, indices, children)); + } + + /** + * Adds a listener for changes in a tree model. + * + * @param listener a listener to add + */ + @Override + public void addTreeModelListener(TreeModelListener listener) { + listeners.add(listener); + } + + /** + * Removes a previously added listener. + * + * @param listener a listener to remove + */ + @Override + public void removeTreeModelListener(TreeModelListener listener) { + listeners.remove(listener); + } +} diff --git a/platform/util/src/com/intellij/util/ui/tree/TreeModelListenerList.java b/platform/util/src/com/intellij/util/ui/tree/TreeModelListenerList.java index fdbfea7a13bd..18f6e74581a6 100644 --- a/platform/util/src/com/intellij/util/ui/tree/TreeModelListenerList.java +++ b/platform/util/src/com/intellij/util/ui/tree/TreeModelListenerList.java @@ -23,7 +23,9 @@ import java.util.ArrayDeque; * @author Sergey.Malenkov */ public final class TreeModelListenerList implements TreeModelListener { + private static final TreeModelListener[] EMPTY_ARRAY = new TreeModelListener[0]; private final ArrayDeque myDeque = new ArrayDeque(); + private volatile boolean myDequeEmpty = true; /** * Adds a listener for changes in a tree model. @@ -35,6 +37,7 @@ public final class TreeModelListenerList implements TreeModelListener { if (listener != null) { synchronized (myDeque) { myDeque.addFirst(listener); + myDequeEmpty = myDeque.isEmpty(); } } } @@ -49,6 +52,7 @@ public final class TreeModelListenerList implements TreeModelListener { if (listener != null) { synchronized (myDeque) { myDeque.remove(listener); + myDequeEmpty = myDeque.isEmpty(); } } } @@ -60,9 +64,7 @@ public final class TreeModelListenerList implements TreeModelListener { * @return {@code true} if no listeners have been added, or {@code false} otherwise */ public boolean isEmpty() { - synchronized (myDeque) { - return myDeque.isEmpty(); - } + return myDequeEmpty; } /** @@ -72,8 +74,9 @@ public final class TreeModelListenerList implements TreeModelListener { * @return all added listeners */ public TreeModelListener[] get() { + if (myDequeEmpty) return EMPTY_ARRAY; synchronized (myDeque) { - return myDeque.toArray(new TreeModelListener[0]); + return myDeque.toArray(EMPTY_ARRAY); } } diff --git a/platform/util/src/com/intellij/util/xmlb/annotations/CollectionBean.java b/platform/util/src/com/intellij/util/xmlb/annotations/CollectionBean.java index da60e05b4ef4..003dc367bc62 100644 --- a/platform/util/src/com/intellij/util/xmlb/annotations/CollectionBean.java +++ b/platform/util/src/com/intellij/util/xmlb/annotations/CollectionBean.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2015 JetBrains s.r.o. + * Copyright 2000-2016 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. @@ -20,13 +20,13 @@ import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; -@Retention(RetentionPolicy.RUNTIME) -@Target({ElementType.FIELD, ElementType.METHOD}) /** * Can read serialized JDOMExternalizableStringList, but in any case will be written in this bean format. * It is useful for application-level config, but for project-level consider to use ConverterProvider. * * Currently, only string element type supported. */ +@Retention(RetentionPolicy.RUNTIME) +@Target({ElementType.FIELD, ElementType.METHOD}) public @interface CollectionBean { } diff --git a/platform/vcs-api/src/com/intellij/openapi/diff/impl/patch/PatchReader.java b/platform/vcs-api/src/com/intellij/openapi/diff/impl/patch/PatchReader.java index c0ccbf4e8cc7..d62c74f14ef6 100644 --- a/platform/vcs-api/src/com/intellij/openapi/diff/impl/patch/PatchReader.java +++ b/platform/vcs-api/src/com/intellij/openapi/diff/impl/patch/PatchReader.java @@ -47,6 +47,9 @@ public class PatchReader { @NonNls private static final String CONTEXT_HUNK_PREFIX = "***************"; @NonNls private static final String CONTEXT_FILE_PREFIX = "*** "; + @NonNls private static final String UNIFIED_BEFORE_HUNK_PREFIX = "--- "; + @NonNls private static final String UNIFIED_AFTER_HUNK_PREFIX = "+++ "; + @NonNls private static final Pattern ourUnifiedHunkStartPattern = Pattern.compile("@@ -(\\d+)(,(\\d+))? \\+(\\d+)(,(\\d+))? @@.*"); @NonNls private static final Pattern ourContextBeforeHunkStartPattern = Pattern.compile("\\*\\*\\* (\\d+),(\\d+) \\*\\*\\*\\*"); @NonNls private static final Pattern ourContextAfterHunkStartPattern = Pattern.compile("--- (\\d+),(\\d+) ----"); @@ -629,4 +632,36 @@ public class PatchReader { return myHunkCount == 1 && myDeleted; } } + + public static boolean isPatchContent(@Nullable String content) { + if (content == null) return false; + List lines = LineTokenizer.tokenizeIntoList(content, false); + final ListIterator iterator = lines.listIterator(); + DiffFormat currentFormat = null; + while (iterator.hasNext()) { + String line = iterator.next(); + if (line.startsWith(CONTEXT_HUNK_PREFIX)) { + currentFormat = DiffFormat.CONTEXT; + } + else if (currentFormat == DiffFormat.CONTEXT && ourContextBeforeHunkStartPattern.matcher(line).matches()) { + break; + } + else if (line.startsWith(UNIFIED_BEFORE_HUNK_PREFIX) && currentFormat == null) { + currentFormat = DiffFormat.UNIFIED; + } + else if (currentFormat == DiffFormat.UNIFIED && line.startsWith(UNIFIED_AFTER_HUNK_PREFIX)) break; + } + if (currentFormat == null) return false; // can't detect format + // check that contains at least one chunk + while (iterator.hasNext()) { + String line = iterator.next(); + if (currentFormat == DiffFormat.CONTEXT) { + if (ourContextAfterHunkStartPattern.matcher(line).matches()) return true; + } + else { + if (ourUnifiedHunkStartPattern.matcher(line).matches()) return true; + } + } + return false; + } } diff --git a/platform/vcs-api/src/com/intellij/openapi/vcs/VcsApplicationSettings.java b/platform/vcs-api/src/com/intellij/openapi/vcs/VcsApplicationSettings.java index 67fc5fa7bad3..322f0d482e03 100644 --- a/platform/vcs-api/src/com/intellij/openapi/vcs/VcsApplicationSettings.java +++ b/platform/vcs-api/src/com/intellij/openapi/vcs/VcsApplicationSettings.java @@ -33,6 +33,7 @@ public class VcsApplicationSettings implements PersistentStateComponent executors, boolean showVcsCommit) { throw new AbstractMethodError(); } diff --git a/platform/vcs-impl/src/com/intellij/openapi/diff/impl/patch/apply/GenericPatchApplier.java b/platform/vcs-impl/src/com/intellij/openapi/diff/impl/patch/apply/GenericPatchApplier.java index 49338c459d83..36f882334901 100644 --- a/platform/vcs-impl/src/com/intellij/openapi/diff/impl/patch/apply/GenericPatchApplier.java +++ b/platform/vcs-impl/src/com/intellij/openapi/diff/impl/patch/apply/GenericPatchApplier.java @@ -34,6 +34,8 @@ import org.jetbrains.annotations.Nullable; import java.util.*; +import static com.intellij.openapi.diff.impl.patch.ApplyPatchStatus.ALREADY_APPLIED; + public class GenericPatchApplier { private static final Logger LOG = Logger.getInstance("#com.intellij.openapi.diff.impl.patch.apply.GenericPatchApplier"); private final static int ourMaxWalk = 1000; @@ -72,7 +74,7 @@ public class GenericPatchApplier { if (! myNotExact.isEmpty()) { return ApplyPatchStatus.FAILURE; } else { - if (myTransformations.isEmpty() && myHadAlreadyAppliedMet) return ApplyPatchStatus.ALREADY_APPLIED; + if (myTransformations.isEmpty() && myHadAlreadyAppliedMet) return ALREADY_APPLIED; boolean haveAlreadyApplied = myHadAlreadyAppliedMet; boolean haveTrue = false; for (MyAppliedData data : myTransformations.values()) { @@ -82,7 +84,7 @@ public class GenericPatchApplier { haveTrue = true; } } - if (haveAlreadyApplied && ! haveTrue) return ApplyPatchStatus.ALREADY_APPLIED; + if (haveAlreadyApplied && ! haveTrue) return ALREADY_APPLIED; if (haveAlreadyApplied) return ApplyPatchStatus.PARTIAL; return ApplyPatchStatus.SUCCESS; } @@ -570,7 +572,8 @@ public class GenericPatchApplier { if (hunk != null) { // +1 to the end because end range is always not included -> [i;j); except add modification; int newStart = lineWithPartContextApplied.getStartOffset() + contextRangeShift.val1; - int newEnd = hunk.isInsertion() ? newStart : lineWithPartContextApplied.getEndOffset() + 1 - contextRangeShift.val2; + int newEnd = hunk.isInsertion() && hunkStatus != AppliedTextPatch.HunkStatus.ALREADY_APPLIED + ? newStart : lineWithPartContextApplied.getEndOffset() + 1 - contextRangeShift.val2; myAppliedInfo.add(new AppliedTextPatch.AppliedSplitPatchHunk(hunk, newStart, newEnd, hunkStatus)); } } diff --git a/platform/vcs-impl/src/com/intellij/openapi/vcs/changes/ChangeListManagerImpl.java b/platform/vcs-impl/src/com/intellij/openapi/vcs/changes/ChangeListManagerImpl.java index df48ba1c74d5..528263c9038d 100644 --- a/platform/vcs-impl/src/com/intellij/openapi/vcs/changes/ChangeListManagerImpl.java +++ b/platform/vcs-impl/src/com/intellij/openapi/vcs/changes/ChangeListManagerImpl.java @@ -1722,11 +1722,9 @@ public class ChangeListManagerImpl extends ChangeListManagerEx implements Projec return true; } myVfsListener.flushDirt(); - final EnsureUpToDateFromNonAWTThread worker = new EnsureUpToDateFromNonAWTThread(myProject); - worker.execute(); myUpdater.waitUntilRefreshed(); waitUpdateAlarm(); - return worker.isDone(); + return true; } @Override diff --git a/platform/vcs-impl/src/com/intellij/openapi/vcs/changes/patch/ApplyPatchAction.java b/platform/vcs-impl/src/com/intellij/openapi/vcs/changes/patch/ApplyPatchAction.java index fe936226ea21..f9bbce641d46 100644 --- a/platform/vcs-impl/src/com/intellij/openapi/vcs/changes/patch/ApplyPatchAction.java +++ b/platform/vcs-impl/src/com/intellij/openapi/vcs/changes/patch/ApplyPatchAction.java @@ -36,7 +36,6 @@ import com.intellij.openapi.extensions.Extensions; import com.intellij.openapi.fileChooser.FileChooser; import com.intellij.openapi.fileChooser.FileChooserDescriptor; import com.intellij.openapi.fileEditor.FileDocumentManager; -import com.intellij.openapi.fileTypes.StdFileTypes; import com.intellij.openapi.project.DumbAwareAction; import com.intellij.openapi.project.Project; import com.intellij.openapi.ui.Messages; @@ -48,15 +47,18 @@ import com.intellij.openapi.util.io.FileUtil; import com.intellij.openapi.util.text.StringUtil; import com.intellij.openapi.vcs.VcsApplicationSettings; import com.intellij.openapi.vcs.VcsBundle; +import com.intellij.openapi.vcs.VcsNotifier; import com.intellij.openapi.vcs.changes.ChangeListManager; import com.intellij.openapi.vcs.changes.CommitContext; import com.intellij.openapi.vfs.LocalFileSystem; +import com.intellij.openapi.vfs.VfsUtil; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.util.Consumer; import com.intellij.util.Function; import com.intellij.util.ObjectUtils; import com.intellij.util.containers.ContainerUtil; import com.intellij.vcsUtil.VcsUtil; +import org.jetbrains.annotations.CalledInAwt; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; @@ -65,6 +67,8 @@ import java.io.IOException; import java.util.Collections; import java.util.List; +import static com.intellij.openapi.vcs.changes.patch.PatchFileType.isPatchFile; + public class ApplyPatchAction extends DumbAwareAction { private static final Logger LOG = Logger.getInstance("#com.intellij.openapi.vcs.changes.patch.ApplyPatchAction"); @@ -81,10 +85,6 @@ public class ApplyPatchAction extends DumbAwareAction { } } - private static boolean isPatchFile(@Nullable VirtualFile vFile) { - return vFile != null && vFile.getFileType() == StdFileTypes.PATCH; - } - public void actionPerformed(AnActionEvent e) { final Project project = e.getRequiredData(CommonDataKeys.PROJECT); if (ChangeListManager.getInstance(project).isFreezedWithNotification("Can not apply patch now")) return; @@ -129,6 +129,25 @@ public class ApplyPatchAction extends DumbAwareAction { dialog.show(); } + @CalledInAwt + public static Boolean showAndGetApplyPatch(@NotNull final Project project, @NotNull final File file) { + VirtualFile vFile = VfsUtil.findFileByIoFile(file, true); + String patchPath = file.getPath(); + if (vFile == null) { + VcsNotifier.getInstance(project).notifyWeakError("Can't find patch file " + patchPath); + return false; + } + if (!isPatchFile(file)) { + VcsNotifier.getInstance(project).notifyWeakError("Selected file " + patchPath + " is not patch type file "); + return false; + } + final ApplyPatchDifferentiatedDialog dialog = new ApplyPatchDifferentiatedDialog(project, new ApplyPatchDefaultExecutor(project), + Collections.emptyList(), + ApplyPatchMode.APPLY_PATCH_IN_MEMORY, vFile); + dialog.setModal(true); + return dialog.showAndGet(); + } + public static void applySkipDirs(final List patches, final int skipDirs) { if (skipDirs < 1) { return; diff --git a/platform/vcs-impl/src/com/intellij/openapi/vcs/changes/patch/ApplyPatchDifferentiatedDialog.java b/platform/vcs-impl/src/com/intellij/openapi/vcs/changes/patch/ApplyPatchDifferentiatedDialog.java index 9d2deb749973..19b10ec559e2 100644 --- a/platform/vcs-impl/src/com/intellij/openapi/vcs/changes/patch/ApplyPatchDifferentiatedDialog.java +++ b/platform/vcs-impl/src/com/intellij/openapi/vcs/changes/patch/ApplyPatchDifferentiatedDialog.java @@ -24,9 +24,9 @@ import com.intellij.diff.chains.DiffRequestProducerException; import com.intellij.diff.requests.DiffRequest; import com.intellij.icons.AllIcons; import com.intellij.ide.util.PropertiesComponent; -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.diff.impl.patch.*; import com.intellij.openapi.fileChooser.FileChooser; import com.intellij.openapi.fileChooser.FileChooserDescriptor; @@ -62,7 +62,6 @@ import com.intellij.ui.SimpleTextAttributes; import com.intellij.ui.UI; import com.intellij.util.Alarm; import com.intellij.util.Consumer; -import com.intellij.util.NullableConsumer; import com.intellij.util.containers.ContainerUtil; import com.intellij.util.containers.Convertor; import com.intellij.util.containers.MultiMap; @@ -99,7 +98,7 @@ public class ApplyPatchDifferentiatedDialog extends DialogWrapper { private JComponent myCenterPanel; protected final Project myProject; - private final AtomicReference myRecentPathFileChange; + private final AtomicReference myRecentPathFileChange; private final ApplyPatchDifferentiatedDialog.MyUpdater myUpdater; private final Runnable myReset; private final ChangeListChooserPanel myChangeListChooser; @@ -153,10 +152,10 @@ public class ApplyPatchDifferentiatedDialog extends DialogWrapper { myProject = project; myPatches = new LinkedList(); - myRecentPathFileChange = new AtomicReference(); + myRecentPathFileChange = new AtomicReference(); myBinaryShelvedPatches = binaryShelvedPatches; myPreselectedChanges = preselectedChanges; - myChangesTreeList = new MyChangeTreeList(project, Collections.emptyList(), + myChangesTreeList = new MyChangeTreeList(project, Collections.emptyList(), new Runnable() { public void run() { final NamedLegendStatuses includedNameStatuses = new NamedLegendStatuses(); @@ -175,15 +174,12 @@ public class ApplyPatchDifferentiatedDialog extends DialogWrapper { updateOkActions(); } }, new MyChangeNodeDecorator()); - myChangesTreeList.setDoubleClickHandler(new Runnable() { - @Override - public void run() { - List selectedChanges = myChangesTreeList.getSelectedChanges(); - if (selectedChanges.size() == 1 && !selectedChanges.get(0).isValid()) { - myChangesTreeList.handleInvalidChangesAndToggle(); - } - new MyShowDiff().showDiff(); + myChangesTreeList.setDoubleClickHandler(() -> { + List selectedChanges = myChangesTreeList.getSelectedChanges(); + if (selectedChanges.size() == 1 && !selectedChanges.get(0).isValid()) { + myChangesTreeList.handleInvalidChangesAndToggle(); } + new MyShowDiff().showDiff(); }); myUpdater = new MyUpdater(); @@ -199,17 +195,11 @@ public class ApplyPatchDifferentiatedDialog extends DialogWrapper { myCommitMessage = externalCommitMessage; myLoadQueue = new ZipperUpdater(500, Alarm.ThreadToUse.POOLED_THREAD, getDisposable()); myCanChangePatchFile = applyPatchMode.isCanChangePatchFile(); - myReset = myCanChangePatchFile ? new Runnable() { - public void run() { - reset(); - } - } : EmptyRunnable.getInstance(); + myReset = myCanChangePatchFile ? this::reset : EmptyRunnable.getInstance(); - myChangeListChooser = new ChangeListChooserPanel(project, new NullableConsumer() { - public void consume(final @Nullable String errorMessage) { - setOKActionEnabled(errorMessage == null); - setErrorText(errorMessage); - } + myChangeListChooser = new ChangeListChooserPanel(project, errorMessage -> { + setOKActionEnabled(errorMessage == null); + setErrorText(errorMessage); }); ChangeListManager changeListManager = ChangeListManager.getInstance(project); myChangeListChooser.setChangeLists(changeListManager.getChangeListsCopy()); @@ -245,20 +235,12 @@ public class ApplyPatchDifferentiatedDialog extends DialogWrapper { myListener = new VirtualFileAdapter() { @Override public void contentsChanged(@NotNull VirtualFileEvent event) { - if (myRecentPathFileChange.get() != null && myRecentPathFileChange.get().getVf() != null && - event.getFile().equals(myRecentPathFileChange.get().getVf())) { - queueRequest(); - } + syncUpdatePatchFileAndScheduleReloadIfNeeded(event.getFile()); } }; final VirtualFileManager fileManager = VirtualFileManager.getInstance(); fileManager.addVirtualFileListener(myListener); - Disposer.register(getDisposable(), new Disposable() { - @Override - public void dispose() { - fileManager.removeVirtualFileListener(myListener); - } - }); + Disposer.register(getDisposable(), () -> fileManager.removeVirtualFileListener(myListener)); } updateOkActions(); } @@ -276,12 +258,10 @@ public class ApplyPatchDifferentiatedDialog extends DialogWrapper { final List matchedPatches = new MatchPatchPaths(myProject).execute(patches, myUseProjectRootAsPredefinedBase); //todo add shelved binary patches - ApplicationManager.getApplication().invokeLater(new Runnable() { - public void run() { - myPatches.clear(); - myPatches.addAll(matchedPatches); - updateTree(true); - } + ApplicationManager.getApplication().invokeLater(() -> { + myPatches.clear(); + myPatches.addAll(matchedPatches); + updateTree(true); }); } @@ -327,7 +307,7 @@ public class ApplyPatchDifferentiatedDialog extends DialogWrapper { patchGroups.putValue(patchInProgress.getBase(), patchInProgress); } final LocalChangeList selected = getSelectedChangeList(); - FilePresentation presentation = myRecentPathFileChange.get(); + FilePresentationModel presentation = myRecentPathFileChange.get(); VirtualFile vf = presentation != null ? presentation.getVf() : null; executor.apply(getOriginalRemaining(), patchGroups, selected, vf == null ? null : vf.getName(), myReader == null ? null : myReader.getAdditionalInfo(ApplyPatchDefaultExecutor.pathsFromGroups(patchGroups))); @@ -356,13 +336,12 @@ public class ApplyPatchDifferentiatedDialog extends DialogWrapper { } private void setPathFileChangeDefault() { - myRecentPathFileChange.set(new FilePresentation(myPatchFile.getText())); + myRecentPathFileChange.set(new FilePresentationModel(myPatchFile.getText())); } - private void init(final VirtualFile patchFile) { + private void init(@NotNull final VirtualFile patchFile) { myPatchFile.setText(patchFile.getPresentableUrl()); - myRecentPathFileChange.set(new FilePresentation(patchFile)); - queueRequest(); + myRecentPathFileChange.set(new FilePresentationModel(patchFile)); } public void setHelpId(String s) { @@ -371,46 +350,35 @@ public class ApplyPatchDifferentiatedDialog extends DialogWrapper { private class MyUpdater implements Runnable { public void run() { - final FilePresentation filePresentation = myRecentPathFileChange.get(); - if ((filePresentation == null) || (filePresentation.getVf() == null)) { - ApplicationManager.getApplication().invokeLater(myReset); + final FilePresentationModel filePresentationModel = myRecentPathFileChange.get(); + final VirtualFile file = filePresentationModel != null ? filePresentationModel.getVf() : null; + if (file == null) { + ApplicationManager.getApplication().invokeLater(myReset, ModalityState.any()); return; } - final VirtualFile file = filePresentation.getVf(); - final PatchReader patchReader = loadPatches(filePresentation); - if (patchReader == null) return; - - List filePatches = ContainerUtil.newArrayList(patchReader.getPatches()); + final PatchReader patchReader = loadPatches(file); + List filePatches = patchReader != null ? ContainerUtil.newArrayList(patchReader.getPatches()) : Collections.emptyList(); if (!ContainerUtil.isEmpty(myBinaryShelvedPatches)) { filePatches.addAll(myBinaryShelvedPatches); } final List matchedPatches = new MatchPatchPaths(myProject).execute(filePatches, myUseProjectRootAsPredefinedBase); - ApplicationManager.getApplication().invokeLater(new Runnable() { - public void run() { - myChangeListChooser - .setDefaultName(myCommitMessage != null ? myCommitMessage : file.getNameWithoutExtension().replace('_', ' ').trim()); - myPatches.clear(); - myPatches.addAll(matchedPatches); - myReader = patchReader; - updateTree(true); - paintBusy(false); - } - }); + ApplicationManager.getApplication().invokeLater(() -> { + myChangeListChooser + .setDefaultName(myCommitMessage != null ? myCommitMessage : file.getNameWithoutExtension().replace('_', ' ').trim()); + myPatches.clear(); + myPatches.addAll(matchedPatches); + myReader = patchReader; + updateTree(true); + paintBusy(false); + }, ModalityState.any()); } } @Nullable - private static PatchReader loadPatches(final FilePresentation filePresentation) { - final VirtualFile patchFile = filePresentation.getVf(); - if (patchFile == null) return null; - patchFile.refresh(false, false); - if (!patchFile.isValid()) { - return null; - } - + private static PatchReader loadPatches(@NotNull VirtualFile patchFile) { PatchReader reader; try { reader = PatchVirtualFileReader.create(patchFile); @@ -428,33 +396,45 @@ public class ApplyPatchDifferentiatedDialog extends DialogWrapper { return reader; } - private static class FilePresentation { - private final VirtualFile myVf; - private final String myPath; + @CalledInAwt + private void syncUpdatePatchFileAndScheduleReloadIfNeeded(@Nullable VirtualFile eventFile) { + // if dialog is modal and refresh called not from dispatch thread then + // fireEvents in RefreshQueueImpl will not be triggered because of wrong modality state inside those thread -> defaultMS == NON_MODAL + final FilePresentationModel filePresentationModel = myRecentPathFileChange.get(); + VirtualFile filePresentationVf = filePresentationModel != null ? filePresentationModel.getVf() : null; + if (filePresentationVf != null && (eventFile == null || filePresentationVf.equals(eventFile))) { + filePresentationVf.refresh(false, false); + queueRequest(); + } + } - private FilePresentation(VirtualFile vf) { - myVf = vf; - myPath = null; + private static class FilePresentationModel { + @NotNull private final String myPath; + @Nullable private VirtualFile myVf; + + private FilePresentationModel(@NotNull String path) { + myPath = path; + myVf = null; // don't try to find vf for each typing; only when requested } - private FilePresentation(String path) { - myPath = path; - myVf = null; + public FilePresentationModel(@NotNull VirtualFile file) { + myPath = file.getPath(); + myVf = file; } @Nullable public VirtualFile getVf() { - if (myVf != null) { - return myVf; + if (myVf == null) { + final VirtualFile file = VfsUtil.findFileByIoFile(new File(myPath), true); + myVf = file != null && !file.isDirectory() ? file : null; } - final VirtualFile file = LocalFileSystem.getInstance().refreshAndFindFileByPath(myPath); - return (file != null) && (!file.isDirectory()) ? file : null; + return myVf; } } private void reset() { myPatches.clear(); - myChangesTreeList.setChangesToDisplay(Collections.emptyList()); + myChangesTreeList.setChangesToDisplay(Collections.emptyList()); myChangesTreeList.repaint(); myContainBasedChanges = false; paintBusy(false); @@ -492,7 +472,7 @@ public class ApplyPatchDifferentiatedDialog extends DialogWrapper { group.add(new AnAction("Refresh", "Refresh", AllIcons.Actions.Refresh) { @Override public void actionPerformed(AnActionEvent e) { - queueRequest(); + syncUpdatePatchFileAndScheduleReloadIfNeeded(null); } }); } @@ -542,21 +522,13 @@ public class ApplyPatchDifferentiatedDialog extends DialogWrapper { ChangeNodeDecorator changeNodeDecorator) { TreeModelBuilder builder = new TreeModelBuilder(myProject, isShowFlatten()); return builder.buildModel(ObjectsConvertor.convert(changes, - new Convertor() { - public Change convert(AbstractFilePatchInProgress.PatchChange o) { - return o; - } - }), changeNodeDecorator); + (Convertor)o -> o), changeNodeDecorator); } @Override protected List getSelectedObjects(ChangesBrowserNode node) { final List under = node.getAllChangesUnder(); - return ObjectsConvertor.convert(under, new Convertor() { - public AbstractFilePatchInProgress.PatchChange convert(Change o) { - return (AbstractFilePatchInProgress.PatchChange)o; - } - }); + return ObjectsConvertor.convert(under, o -> (AbstractFilePatchInProgress.PatchChange)o); } @Override @@ -580,9 +552,7 @@ public class ApplyPatchDifferentiatedDialog extends DialogWrapper { @NotNull private List getOnlyValidChanges(@NotNull Collection changes) { - return ContainerUtil.filter(changes, change -> { - return change.isValid(); - }); + return ContainerUtil.filter(changes, AbstractFilePatchInProgress.PatchChange::isValid); } @Override @@ -681,11 +651,7 @@ public class ApplyPatchDifferentiatedDialog extends DialogWrapper { private List getAllChanges() { return ObjectsConvertor.convert(myPatches, - new Convertor() { - public AbstractFilePatchInProgress.PatchChange convert(AbstractFilePatchInProgress o) { - return o.getChange(); - } - }); + AbstractFilePatchInProgress::getChange); } private static void acceptChange(final NamedLegendStatuses nameStatuses, final AbstractFilePatchInProgress.PatchChange change) { @@ -785,11 +751,7 @@ public class ApplyPatchDifferentiatedDialog extends DialogWrapper { } private static List changes2patches(final List selectedChanges) { - return ObjectsConvertor.convert(selectedChanges, new Convertor() { - public AbstractFilePatchInProgress convert(AbstractFilePatchInProgress.PatchChange o) { - return o.getPatchInProgress(); - } - }); + return ObjectsConvertor.convert(selectedChanges, AbstractFilePatchInProgress.PatchChange::getPatchInProgress); } private class MapPopup extends BaseListPopupStep { @@ -954,7 +916,7 @@ public class ApplyPatchDifferentiatedDialog extends DialogWrapper { if (!patchInProgress.baseExistsOrAdded()) { component.append(" "); component.append("Select missing base", new SimpleTextAttributes(STYLE_PLAIN, UI.getColor("link.foreground")), - (Runnable)() -> myChangesTreeList.handleInvalidChangesAndToggle()); + (Runnable)myChangesTreeList::handleInvalidChangesAndToggle); } else { if (!patchInProgress.getStatus().equals(FilePatchStatus.ADDED) && basePathWasChanged(patchInProgress)) { @@ -993,7 +955,7 @@ public class ApplyPatchDifferentiatedDialog extends DialogWrapper { private Collection getIncluded() { return ObjectsConvertor.convert(myChangesTreeList.getIncludedChanges(), - o -> o.getPatchInProgress()); + AbstractFilePatchInProgress.PatchChange::getPatchInProgress); } @Nullable diff --git a/platform/vcs-impl/src/com/intellij/openapi/vcs/changes/patch/ApplyPatchFromClipboardAction.java b/platform/vcs-impl/src/com/intellij/openapi/vcs/changes/patch/ApplyPatchFromClipboardAction.java new file mode 100644 index 000000000000..701bc013be6c --- /dev/null +++ b/platform/vcs-impl/src/com/intellij/openapi/vcs/changes/patch/ApplyPatchFromClipboardAction.java @@ -0,0 +1,68 @@ +package com.intellij.openapi.vcs.changes.patch; + +import com.intellij.openapi.actionSystem.AnActionEvent; +import com.intellij.openapi.actionSystem.CommonDataKeys; +import com.intellij.openapi.application.ex.ClipboardUtil; +import com.intellij.openapi.fileEditor.FileDocumentManager; +import com.intellij.openapi.project.DumbAwareAction; +import com.intellij.openapi.project.Project; +import com.intellij.openapi.vcs.VcsApplicationSettings; +import com.intellij.openapi.vcs.changes.ChangeListManager; +import com.intellij.testFramework.LightVirtualFile; +import com.intellij.util.ObjectUtils; +import org.jetbrains.annotations.NotNull; + +import javax.swing.*; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.awt.event.KeyEvent; +import java.util.Collections; + +public class ApplyPatchFromClipboardAction extends DumbAwareAction { + + @Override + public void update(AnActionEvent e) { + Project project = e.getData(CommonDataKeys.PROJECT); + String text = ClipboardUtil.getTextInClipboard(); + // allow to apply from clipboard even if we do not detect it as a patch, because during applying we parse content more precisely + e.getPresentation().setEnabled(project != null && text != null && ChangeListManager.getInstance(project).isFreezed() == null); + } + + public void actionPerformed(AnActionEvent e) { + final Project project = e.getRequiredData(CommonDataKeys.PROJECT); + if (ChangeListManager.getInstance(project).isFreezedWithNotification("Can not apply patch now")) return; + FileDocumentManager.getInstance().saveAllDocuments(); + + String clipboardText = ClipboardUtil.getTextInClipboard(); + assert clipboardText != null; + new MyApplyPatchFromClipboardDialog(project, clipboardText).show(); + } + + public static class MyApplyPatchFromClipboardDialog extends ApplyPatchDifferentiatedDialog { + private static final JCheckBox FLY_OPTION_PANEL = createAnalyzeOnTheFlyOptionPanel(); + + public MyApplyPatchFromClipboardDialog(@NotNull Project project, @NotNull String clipboardText) { + super(project, new ApplyPatchDefaultExecutor(project), Collections.emptyList(), ApplyPatchMode.APPLY_PATCH_IN_MEMORY, + new LightVirtualFile("clipboardPatchFile", clipboardText)); + } + + @Override + protected JComponent createSouthPanel() { + return addDoNotShowCheckBox(ObjectUtils.assertNotNull(super.createSouthPanel()), FLY_OPTION_PANEL); + } + + @NotNull + private static JCheckBox createAnalyzeOnTheFlyOptionPanel() { + final JCheckBox removeOptionCheckBox = new JCheckBox("Analyze and Apply Patch from Clipboard on the Fly"); + removeOptionCheckBox.setMnemonic(KeyEvent.VK_L); + removeOptionCheckBox.setSelected(VcsApplicationSettings.getInstance().DETECT_PATCH_ON_THE_FLY); + removeOptionCheckBox.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + VcsApplicationSettings.getInstance().DETECT_PATCH_ON_THE_FLY = removeOptionCheckBox.isSelected(); + } + }); + return removeOptionCheckBox; + } + } +} diff --git a/platform/vcs-impl/src/com/intellij/openapi/vcs/changes/patch/PatchClipboardTracker.java b/platform/vcs-impl/src/com/intellij/openapi/vcs/changes/patch/PatchClipboardTracker.java new file mode 100644 index 000000000000..eeac82f9942b --- /dev/null +++ b/platform/vcs-impl/src/com/intellij/openapi/vcs/changes/patch/PatchClipboardTracker.java @@ -0,0 +1,57 @@ +/* + * Copyright 2000-2016 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.vcs.changes.patch; + +import com.intellij.openapi.application.ApplicationActivationListener; +import com.intellij.openapi.application.ClipboardAnalyzeListener; +import com.intellij.openapi.application.ex.ApplicationManagerEx; +import com.intellij.openapi.components.ApplicationComponent; +import com.intellij.openapi.diff.impl.patch.PatchReader; +import com.intellij.openapi.project.Project; +import com.intellij.openapi.vcs.VcsApplicationSettings; +import com.intellij.util.messages.MessageBusConnection; +import org.jetbrains.annotations.NotNull; + + +public class PatchClipboardTracker extends ApplicationComponent.Adapter { + private static final PatchClipboardListener LISTENER = new PatchClipboardListener(); + private MessageBusConnection myConnection; + + @Override + public void initComponent() { + myConnection = ApplicationManagerEx.getApplicationEx().getMessageBus().connect(); + myConnection.subscribe(ApplicationActivationListener.TOPIC, LISTENER); + } + + @Override + public void disposeComponent() { + myConnection.disconnect(); + myConnection = null; + } + + private static class PatchClipboardListener extends ClipboardAnalyzeListener { + @Override + protected void handle(@NotNull Project project, @NotNull String value) { + new ApplyPatchFromClipboardAction.MyApplyPatchFromClipboardDialog(project, value).show(); + } + + @Override + public boolean canHandle(@NotNull String value) { + if (!VcsApplicationSettings.getInstance().DETECT_PATCH_ON_THE_FLY) return false; + return PatchReader.isPatchContent(value); + } + } +} diff --git a/platform/vcs-impl/src/com/intellij/openapi/vcs/changes/patch/PatchFileDropHandler.java b/platform/vcs-impl/src/com/intellij/openapi/vcs/changes/patch/PatchFileDropHandler.java new file mode 100644 index 000000000000..fef76c02835a --- /dev/null +++ b/platform/vcs-impl/src/com/intellij/openapi/vcs/changes/patch/PatchFileDropHandler.java @@ -0,0 +1,42 @@ +/* + * Copyright 2000-2016 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.vcs.changes.patch; + +import com.intellij.ide.dnd.FileCopyPasteUtil; +import com.intellij.openapi.editor.CustomFileDropHandler; +import com.intellij.openapi.project.Project; +import org.jetbrains.annotations.NotNull; + +import java.awt.datatransfer.Transferable; +import java.io.File; +import java.util.List; + +public class PatchFileDropHandler extends CustomFileDropHandler { + + @Override + public boolean canHandle(@NotNull Transferable t) { + List list = FileCopyPasteUtil.getFileList(t); + if (list == null || list.size() != 1) return false; + return PatchFileType.isPatchFile(list.get(0)); + } + + @Override + public boolean handleDrop(@NotNull Transferable t, @NotNull final Project project) { + List list = FileCopyPasteUtil.getFileList(t); + if (list == null || list.size() != 1) return false; + return ApplyPatchAction.showAndGetApplyPatch(project, list.get(0)); + } +} diff --git a/platform/vcs-impl/src/com/intellij/openapi/vcs/changes/patch/PatchFileType.java b/platform/vcs-impl/src/com/intellij/openapi/vcs/changes/patch/PatchFileType.java index a1ee6520d223..22c5c6a16740 100644 --- a/platform/vcs-impl/src/com/intellij/openapi/vcs/changes/patch/PatchFileType.java +++ b/platform/vcs-impl/src/com/intellij/openapi/vcs/changes/patch/PatchFileType.java @@ -25,15 +25,18 @@ package com.intellij.openapi.vcs.changes.patch; import com.intellij.icons.AllIcons; import com.intellij.ide.structureView.StructureViewBuilder; import com.intellij.openapi.fileTypes.FileType; +import com.intellij.openapi.fileTypes.StdFileTypes; import com.intellij.openapi.fileTypes.SyntaxHighlighter; import com.intellij.openapi.project.Project; import com.intellij.openapi.vcs.VcsBundle; +import com.intellij.openapi.vfs.VfsUtil; import com.intellij.openapi.vfs.VirtualFile; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.swing.*; +import java.io.File; public class PatchFileType implements FileType { public static final String NAME = "PATCH"; @@ -83,4 +86,12 @@ public class PatchFileType implements FileType { public StructureViewBuilder getStructureViewBuilder(@NotNull VirtualFile file, @NotNull Project project) { return null; } + + public static boolean isPatchFile(@Nullable VirtualFile vFile) { + return vFile != null && vFile.getFileType() == StdFileTypes.PATCH; + } + + public static boolean isPatchFile(@NotNull File file) { + return isPatchFile(VfsUtil.findFileByIoFile(file, true)); + } } diff --git a/platform/vcs-impl/src/com/intellij/openapi/vcs/ex/RollbackLineStatusAction.java b/platform/vcs-impl/src/com/intellij/openapi/vcs/ex/RollbackLineStatusAction.java index 559cb91c14bb..531c6c042489 100644 --- a/platform/vcs-impl/src/com/intellij/openapi/vcs/ex/RollbackLineStatusAction.java +++ b/platform/vcs-impl/src/com/intellij/openapi/vcs/ex/RollbackLineStatusAction.java @@ -12,11 +12,11 @@ */ package com.intellij.openapi.vcs.ex; +import com.intellij.diff.util.DiffUtil; import com.intellij.openapi.actionSystem.AnActionEvent; import com.intellij.openapi.actionSystem.CommonDataKeys; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.command.CommandProcessor; -import com.intellij.openapi.diff.impl.DiffUtil; import com.intellij.openapi.editor.Caret; import com.intellij.openapi.editor.Document; import com.intellij.openapi.editor.Editor; @@ -88,10 +88,6 @@ public class RollbackLineStatusAction extends DumbAwareAction { } Document document = editor.getDocument(); - int totalLines = getLineCount(document); - - BitSet lines = new BitSet(totalLines + 1); - List carets = editor.getCaretModel().getAllCarets(); if (carets.size() == 1) { @@ -102,20 +98,7 @@ public class RollbackLineStatusAction extends DumbAwareAction { } } - for (Caret caret : carets) { - if (caret.hasSelection()) { - int line1 = editor.offsetToLogicalPosition(caret.getSelectionStart()).line; - int line2 = editor.offsetToLogicalPosition(caret.getSelectionEnd()).line; - lines.set(line1, line2 + 1); - if (caret.getSelectionEnd() == document.getTextLength()) lines.set(totalLines); - } - else { - lines.set(caret.getLogicalPosition().line); - if (caret.getOffset() == document.getTextLength()) lines.set(totalLines); - } - } - - doRollback(tracker, lines); + doRollback(tracker, DiffUtil.getSelectedLines(editor)); } private static void doRollback(@NotNull final LineStatusTracker tracker, @NotNull final Range range) { @@ -161,8 +144,4 @@ public class RollbackLineStatusAction extends DumbAwareAction { } }, VcsBundle.message("command.name.rollback.change"), null); } - - private static int getLineCount(@NotNull Document document) { - return Math.max(document.getLineCount(), 1); - } } diff --git a/platform/vcs-log/graph/src/com/intellij/vcs/log/graph/utils/impl/SmartDeltaCompressor.java b/platform/vcs-log/graph/src/com/intellij/vcs/log/graph/utils/impl/SmartDeltaCompressor.java index 772e8dc5c746..8a505ba604f1 100644 --- a/platform/vcs-log/graph/src/com/intellij/vcs/log/graph/utils/impl/SmartDeltaCompressor.java +++ b/platform/vcs-log/graph/src/com/intellij/vcs/log/graph/utils/impl/SmartDeltaCompressor.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2015 JetBrains s.r.o. + * Copyright 2000-2016 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. @@ -47,11 +47,11 @@ public class SmartDeltaCompressor implements IntList { writeDelta(offset, deltaList.get(index), sizeOf, deltas); long mask = 1L << rem; - /** - * 4 -> 11 - * 3 -> 10 - * 2 -> 01 - * 1 -> 00 + /* + 4 -> 11 + 3 -> 10 + 2 -> 01 + 1 -> 00 */ if (sizeOf == 3 || sizeOf == 4) majorBits[main] |= mask; if (sizeOf == 2 || sizeOf == 4) minorBits[main] |= mask; diff --git a/platform/vcs-log/impl/src/com/intellij/vcs/log/impl/VcsLogContentProvider.java b/platform/vcs-log/impl/src/com/intellij/vcs/log/impl/VcsLogContentProvider.java index e19c1d2c0cff..c69930978957 100644 --- a/platform/vcs-log/impl/src/com/intellij/vcs/log/impl/VcsLogContentProvider.java +++ b/platform/vcs-log/impl/src/com/intellij/vcs/log/impl/VcsLogContentProvider.java @@ -17,6 +17,7 @@ package com.intellij.vcs.log.impl; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.project.Project; +import com.intellij.openapi.util.Condition; import com.intellij.openapi.vcs.ProjectLevelVcsManager; import com.intellij.openapi.vcs.VcsListener; import com.intellij.openapi.vcs.changes.ui.ChangesViewContentProvider; @@ -24,9 +25,11 @@ import com.intellij.openapi.wm.ToolWindow; import com.intellij.openapi.wm.ToolWindowId; import com.intellij.openapi.wm.ToolWindowManager; import com.intellij.ui.components.JBPanel; +import com.intellij.ui.content.Content; import com.intellij.ui.content.TabbedContent; import com.intellij.util.ContentUtilEx; import com.intellij.util.NotNullFunction; +import com.intellij.util.containers.ContainerUtil; import com.intellij.util.messages.MessageBusConnection; import com.intellij.vcs.log.ui.VcsLogUiImpl; import org.jetbrains.annotations.NotNull; @@ -34,6 +37,7 @@ import org.jetbrains.annotations.NotNull; import javax.swing.*; import java.awt.*; import java.util.Arrays; +import java.util.List; /** * Provides the Content tab to the ChangesView log toolwindow. @@ -52,11 +56,11 @@ public class VcsLogContentProvider implements ChangesViewContentProvider { myProject = project; myLogManager = logManager; myLogManager.setRecreateMainLogHandler(new Runnable() { - @Override - public void run() { - recreateLog(); - } - }); + @Override + public void run() { + recreateLog(); + } + }); } @Override @@ -83,12 +87,28 @@ public class VcsLogContentProvider implements ChangesViewContentProvider { VcsLogManager logManager = VcsLogManager.getInstance(project); ToolWindow toolWindow = ToolWindowManager.getInstance(project).getToolWindow(ToolWindowId.VCS); - TabbedContent tabbedContent = ContentUtilEx.findTabbedContent(toolWindow.getContentManager(), TAB_NAME); - String shortName = String.valueOf(tabbedContent == null ? 1 : tabbedContent.getTabs().size() + 1); + String shortName = generateShortName(toolWindow); VcsLogUiImpl logUi = logManager.createLog(ContentUtilEx.getFullName(TAB_NAME, shortName)); addLogTab(logManager, toolWindow, logUi, shortName); } + @NotNull + private static String generateShortName(ToolWindow toolWindow) { + TabbedContent tabbedContent = ContentUtilEx.findTabbedContent(toolWindow.getContentManager(), TAB_NAME); + if (tabbedContent != null) { + return String.valueOf(tabbedContent.getTabs().size() + 1); + } + else { + List contents = ContainerUtil.filter(toolWindow.getContentManager().getContents(), new Condition() { + @Override + public boolean value(Content content) { + return TAB_NAME.equals(content.getUserData(Content.TAB_GROUP_NAME_KEY)); + } + }); + return String.valueOf(contents.size() + 1); + } + } + private static void addLogTab(@NotNull VcsLogManager logManager, @NotNull ToolWindow toolWindow, @NotNull VcsLogUiImpl logUi, diff --git a/platform/xdebugger-api/src/com/intellij/xdebugger/XDebugProcess.java b/platform/xdebugger-api/src/com/intellij/xdebugger/XDebugProcess.java index 9323a7b67adc..87844d448f8d 100644 --- a/platform/xdebugger-api/src/com/intellij/xdebugger/XDebugProcess.java +++ b/platform/xdebugger-api/src/com/intellij/xdebugger/XDebugProcess.java @@ -88,10 +88,10 @@ public abstract class XDebugProcess { public void startPausing() { } - @Deprecated /** * @deprecated Use {@link #startStepOver(XSuspendContext)} instead */ + @Deprecated public void startStepOver() { throw new AbstractMethodError(); } @@ -106,10 +106,10 @@ public abstract class XDebugProcess { startStepOver(); } - @Deprecated /** * @deprecated Use {@link #startForceStepInto(XSuspendContext)} instead */ + @Deprecated public void startForceStepInto(){ //noinspection deprecation startStepInto(); @@ -127,10 +127,10 @@ public abstract class XDebugProcess { startForceStepInto(); } - @Deprecated /** * @deprecated Use {@link #startStepInto(XSuspendContext)} instead */ + @Deprecated public void startStepInto() { throw new AbstractMethodError(); } @@ -145,10 +145,10 @@ public abstract class XDebugProcess { startStepInto(); } - @Deprecated /** * @deprecated Use {@link #startStepOut(XSuspendContext)} instead */ + @Deprecated public void startStepOut() { throw new AbstractMethodError(); } @@ -186,10 +186,10 @@ public abstract class XDebugProcess { return Promise.DONE; } - @Deprecated /** * @deprecated Use {@link #resume(XSuspendContext)} instead */ + @Deprecated public void resume() { throw new AbstractMethodError(); } @@ -203,10 +203,10 @@ public abstract class XDebugProcess { resume(); } - @Deprecated /** * @deprecated Use {@link #runToPosition(XSuspendContext)} instead */ + @Deprecated public void runToPosition(@NotNull XSourcePosition position) { throw new AbstractMethodError(); } diff --git a/platform/xdebugger-api/src/com/intellij/xdebugger/XDebugSessionAdapter.java b/platform/xdebugger-api/src/com/intellij/xdebugger/XDebugSessionAdapter.java index 7ff22392ad46..8af7b0453f96 100644 --- a/platform/xdebugger-api/src/com/intellij/xdebugger/XDebugSessionAdapter.java +++ b/platform/xdebugger-api/src/com/intellij/xdebugger/XDebugSessionAdapter.java @@ -15,9 +15,9 @@ */ package com.intellij.xdebugger; -@Deprecated /** * Is not required since Java 1.8 */ +@Deprecated public abstract class XDebugSessionAdapter implements XDebugSessionListener { } diff --git a/platform/xdebugger-api/src/com/intellij/xdebugger/settings/XDebuggerSettings.java b/platform/xdebugger-api/src/com/intellij/xdebugger/settings/XDebuggerSettings.java index 367601db12aa..62e2cb1aa22f 100644 --- a/platform/xdebugger-api/src/com/intellij/xdebugger/settings/XDebuggerSettings.java +++ b/platform/xdebugger-api/src/com/intellij/xdebugger/settings/XDebuggerSettings.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2014 JetBrains s.r.o. + * Copyright 2000-2016 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. @@ -53,11 +53,11 @@ public abstract class XDebuggerSettings implements PersistentStateComponent { myChildren.clear(); } + public void computeWatches() { + myChildren.forEach(WatchNodeImpl::computePresentationIfNeeded); + } + /** * @deprecated Use {@link #addWatchExpression(XStackFrame, XExpression, int, boolean)} */ diff --git a/plugins/InspectionGadgets/InspectionGadgetsAnalysis/src/com/siyeh/ig/bugs/IgnoreResultOfCallInspectionBase.java b/plugins/InspectionGadgets/InspectionGadgetsAnalysis/src/com/siyeh/ig/bugs/IgnoreResultOfCallInspectionBase.java index 2881c458dd87..90ec54d62cc7 100644 --- a/plugins/InspectionGadgets/InspectionGadgetsAnalysis/src/com/siyeh/ig/bugs/IgnoreResultOfCallInspectionBase.java +++ b/plugins/InspectionGadgets/InspectionGadgetsAnalysis/src/com/siyeh/ig/bugs/IgnoreResultOfCallInspectionBase.java @@ -31,6 +31,7 @@ import org.jdom.Element; import org.jetbrains.annotations.NotNull; import java.util.Collections; +import java.util.Set; public class IgnoreResultOfCallInspectionBase extends BaseInspection { @@ -148,29 +149,37 @@ public class IgnoreResultOfCallInspectionBase extends BaseInspection { registerMethodCallError(call, aClass); return; } - if (!myMethodMatcher.matches(method) && findAnnotationInTree(method, "javax.annotation.CheckReturnValue") == null) { + if (!myMethodMatcher.matches(method) && + findAnnotationInTree(method, Collections.singleton("javax.annotation.CheckReturnValue")) == null) { return; } registerMethodCallError(call, aClass); } - private PsiAnnotation findAnnotationInTree(PsiMethod method, String fqAnnotationName) { - final PsiAnnotation methodAnnotation = - AnnotationUtil.findAnnotationInHierarchy(method, Collections.singleton(fqAnnotationName)); - if (methodAnnotation != null) { - return methodAnnotation; + private PsiAnnotation findAnnotationInTree(PsiElement element, Set fqAnnotationNames) { + while (element != null) { + if (element instanceof PsiModifierListOwner) { + final PsiModifierListOwner modifierListOwner = (PsiModifierListOwner)element; + final PsiAnnotation annotation = + AnnotationUtil.findAnnotationInHierarchy(modifierListOwner, fqAnnotationNames); + if (annotation != null) { + return annotation; + } + } + + if (element instanceof PsiClassOwner) { + final PsiClassOwner classOwner = (PsiClassOwner)element; + final String packageName = classOwner.getPackageName(); + final PsiPackage aPackage = JavaPsiFacade.getInstance(element.getProject()).findPackage(packageName); + if (aPackage == null) { + return null; + } + return AnnotationUtil.findAnnotation(aPackage, fqAnnotationNames); + } + + element = element.getContext(); } - final PsiClass aClass = method.getContainingClass(); - if (aClass == null) { - return null; - } - final PsiAnnotation classAnnotation = AnnotationUtil.findAnnotation(aClass, fqAnnotationName); - if (classAnnotation != null) { - return classAnnotation; - } - final PsiDirectory directory = aClass.getContainingFile().getContainingDirectory(); - final PsiPackage aPackage = JavaDirectoryService.getInstance().getPackage(directory); - return AnnotationUtil.findAnnotation(aPackage, fqAnnotationName); + return null; } } } diff --git a/plugins/InspectionGadgets/InspectionGadgetsAnalysis/src/com/siyeh/ig/psiutils/MethodMatcher.java b/plugins/InspectionGadgets/InspectionGadgetsAnalysis/src/com/siyeh/ig/psiutils/MethodMatcher.java index 40c7c7a2f6b7..002c3e19f126 100644 --- a/plugins/InspectionGadgets/InspectionGadgetsAnalysis/src/com/siyeh/ig/psiutils/MethodMatcher.java +++ b/plugins/InspectionGadgets/InspectionGadgetsAnalysis/src/com/siyeh/ig/psiutils/MethodMatcher.java @@ -17,15 +17,16 @@ package com.siyeh.ig.psiutils; import com.intellij.openapi.util.InvalidDataException; import com.intellij.openapi.util.WriteExternalException; +import com.intellij.psi.PsiCall; import com.intellij.psi.PsiClass; import com.intellij.psi.PsiMethod; import com.intellij.psi.PsiMethodCallExpression; -import com.intellij.psi.PsiReferenceExpression; import com.intellij.psi.util.InheritanceUtil; import com.intellij.util.containers.ContainerUtil; import com.siyeh.ig.BaseInspection; import org.jdom.Element; import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; import java.util.List; import java.util.Map; @@ -111,7 +112,10 @@ public class MethodMatcher { return myClassNames; } - public boolean matches(PsiMethod method) { + public boolean matches(@Nullable PsiMethod method) { + if (method == null) { + return false; + } final String methodName = method.getName(); final PsiClass aClass = method.getContainingClass(); if (aClass == null) { @@ -130,31 +134,8 @@ public class MethodMatcher { return false; } - public boolean matches(PsiMethodCallExpression methodCallExpression) { - final PsiReferenceExpression methodExpression = methodCallExpression.getMethodExpression(); - final String methodName = methodExpression.getReferenceName(); - if (methodName == null) { - return false; - } - PsiClass aClass = null; - for (int i = 0, size = myMethodNamePatterns.size(); i < size; i++) { - final Pattern pattern = getPattern(i); - if (pattern == null || !pattern.matcher(methodName).matches()) { - continue; - } - if (aClass == null) { - final PsiMethod method = methodCallExpression.resolveMethod(); - if (method == null || method.isConstructor()) { - return false; - } - aClass = method.getContainingClass(); - } - final String className = myClassNames.get(i); - if (InheritanceUtil.isInheritor(aClass, className)) { - return true; - } - } - return false; + public boolean matches(PsiCall call) { + return matches(call.resolveMethod()); } private Pattern getPattern(int i) { diff --git a/plugins/InspectionGadgets/InspectionGadgetsAnalysis/src/com/siyeh/ig/threading/SharedThreadLocalRandomInspection.java b/plugins/InspectionGadgets/InspectionGadgetsAnalysis/src/com/siyeh/ig/threading/SharedThreadLocalRandomInspectionBase.java similarity index 70% rename from plugins/InspectionGadgets/InspectionGadgetsAnalysis/src/com/siyeh/ig/threading/SharedThreadLocalRandomInspection.java rename to plugins/InspectionGadgets/InspectionGadgetsAnalysis/src/com/siyeh/ig/threading/SharedThreadLocalRandomInspectionBase.java index 97adc033c5b1..1ad40a066096 100644 --- a/plugins/InspectionGadgets/InspectionGadgetsAnalysis/src/com/siyeh/ig/threading/SharedThreadLocalRandomInspection.java +++ b/plugins/InspectionGadgets/InspectionGadgetsAnalysis/src/com/siyeh/ig/threading/SharedThreadLocalRandomInspectionBase.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2014 JetBrains s.r.o. + * Copyright 2000-2016 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. @@ -15,14 +15,18 @@ */ package com.siyeh.ig.threading; +import com.intellij.openapi.util.InvalidDataException; +import com.intellij.openapi.util.WriteExternalException; import com.intellij.psi.*; import com.intellij.psi.util.InheritanceUtil; import com.intellij.psi.util.PsiTreeUtil; import com.siyeh.InspectionGadgetsBundle; import com.siyeh.ig.BaseInspection; import com.siyeh.ig.BaseInspectionVisitor; +import com.siyeh.ig.psiutils.MethodMatcher; import com.siyeh.ig.psiutils.ParenthesesUtils; import com.siyeh.ig.psiutils.VariableAccessUtils; +import org.jdom.Element; import org.jetbrains.annotations.Nls; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; @@ -30,7 +34,16 @@ import org.jetbrains.annotations.NotNull; /** * @author Bas Leijdekkers */ -public class SharedThreadLocalRandomInspection extends BaseInspection { +public class SharedThreadLocalRandomInspectionBase extends BaseInspection { + + protected final MethodMatcher myMethodMatcher; + + public SharedThreadLocalRandomInspectionBase() { + myMethodMatcher = new MethodMatcher(true, "ignoreArgumentToMethods") + .add("java.math.BigInteger", ".*") + .add("java.util.Collections", "shuffle"); + } + @Nls @NotNull @Override @@ -44,12 +57,24 @@ public class SharedThreadLocalRandomInspection extends BaseInspection { return InspectionGadgetsBundle.message("shared.thread.local.random.problem.descriptor"); } + @Override + public void readSettings(@NotNull Element element) throws InvalidDataException { + super.readSettings(element); + myMethodMatcher.readSettings(element); + } + + @Override + public void writeSettings(@NotNull Element element) throws WriteExternalException { + super.writeSettings(element); + myMethodMatcher.writeSettings(element); + } + @Override public BaseInspectionVisitor buildVisitor() { return new SharedThreadLocalRandomVisitor(); } - private static class SharedThreadLocalRandomVisitor extends BaseInspectionVisitor { + private class SharedThreadLocalRandomVisitor extends BaseInspectionVisitor { @Override public void visitMethodCallExpression(PsiMethodCallExpression expression) { @@ -77,24 +102,28 @@ public class SharedThreadLocalRandomInspection extends BaseInspection { } else if (variable instanceof PsiLocalVariable) { final PsiCodeBlock context = PsiTreeUtil.getParentOfType(variable, PsiCodeBlock.class); - if (VariableAccessUtils.variableIsPassedAsMethodArgument(variable, context) || - VariableAccessUtils.variableIsUsedInInnerClass(variable, context)) { + final boolean passed = VariableAccessUtils.variableIsPassedAsMethodArgument(variable, context, myMethodMatcher::matches); + if (passed || VariableAccessUtils.variableIsUsedInInnerClass(variable, context)) { registerMethodCallError(expression); } } } } - private static boolean isArgumentToMethodCall(PsiExpression expression) { + private boolean isArgumentToMethodCall(PsiExpression expression) { final PsiElement parent = ParenthesesUtils.getParentSkipParentheses(expression); if (!(parent instanceof PsiExpressionList)) { return false; } final PsiElement grandParent = parent.getParent(); - return grandParent instanceof PsiMethodCallExpression; + if (!(grandParent instanceof PsiMethodCallExpression)) { + return false; + } + final PsiMethodCallExpression methodCallExpression = (PsiMethodCallExpression)grandParent; + return !myMethodMatcher.matches(methodCallExpression); } - private static PsiVariable assignedToVariable(PsiMethodCallExpression expression) { + private PsiVariable assignedToVariable(PsiMethodCallExpression expression) { final PsiElement parent = PsiTreeUtil.skipParentsOfType(expression, PsiParenthesizedExpression.class); if (parent instanceof PsiVariable) { return (PsiVariable)parent; diff --git a/plugins/InspectionGadgets/src/com/siyeh/ig/threading/SharedThreadLocalRandomInspection.java b/plugins/InspectionGadgets/src/com/siyeh/ig/threading/SharedThreadLocalRandomInspection.java new file mode 100644 index 000000000000..409bfb5275ea --- /dev/null +++ b/plugins/InspectionGadgets/src/com/siyeh/ig/threading/SharedThreadLocalRandomInspection.java @@ -0,0 +1,44 @@ +/* + * Copyright 2000-2016 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. + */ + +/** + * (c) 2016 Silent Forest AB + * created: 28 April 2016 + */ +package com.siyeh.ig.threading; + +import com.intellij.codeInspection.ui.ListTable; +import com.intellij.codeInspection.ui.ListWrappingTableModel; +import com.siyeh.InspectionGadgetsBundle; +import com.siyeh.ig.ui.UiUtils; + +import javax.swing.*; +import java.util.Arrays; + +/** + * @author Bas Leijdekkers + */ +public class SharedThreadLocalRandomInspection extends SharedThreadLocalRandomInspectionBase { + + @Override + public JComponent createOptionsPanel() { + final ListTable table = new ListTable(new ListWrappingTableModel( + Arrays.asList(myMethodMatcher.getClassNames(), myMethodMatcher.getMethodNamePatterns()), + InspectionGadgetsBundle.message("result.of.method.call.ignored.class.column.title"), + InspectionGadgetsBundle.message("result.of.method.call.ignored.method.column.title"))); + return UiUtils.createAddRemoveTreeClassChooserPanel(table, "Choose class"); + } +} diff --git a/plugins/InspectionGadgets/src/inspectionDescriptions/SharedThreadLocalRandom.html b/plugins/InspectionGadgets/src/inspectionDescriptions/SharedThreadLocalRandom.html index 88be483c39bf..c3bbd92b40b7 100644 --- a/plugins/InspectionGadgets/src/inspectionDescriptions/SharedThreadLocalRandom.html +++ b/plugins/InspectionGadgets/src/inspectionDescriptions/SharedThreadLocalRandom.html @@ -10,5 +10,7 @@ Usages of ThreadLocalRandom should typically look like ThreadLocalRand When all usages are in this form, ThreadLocalRandom instances can not be used accidentally by multiple threads.

+Use the table below to specify methods that are safe to pass a ThreadLocalRandom to, as an argument. +

\ No newline at end of file diff --git a/plugins/InspectionGadgets/testsrc/com/siyeh/ig/IGInspectionTestCase.java b/plugins/InspectionGadgets/testsrc/com/siyeh/ig/IGInspectionTestCase.java index 82f315a392b2..827d1ce15235 100644 --- a/plugins/InspectionGadgets/testsrc/com/siyeh/ig/IGInspectionTestCase.java +++ b/plugins/InspectionGadgets/testsrc/com/siyeh/ig/IGInspectionTestCase.java @@ -1,17 +1,17 @@ /* - * Copyright 2000-2011 JetBrains s.r.o. + * Copyright 2000-2016 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 + * 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 + * 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. + * 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.siyeh.ig; @@ -20,6 +20,7 @@ import com.intellij.codeInspection.ex.LocalInspectionToolWrapper; import com.intellij.openapi.application.PluginPathManager; import com.intellij.testFramework.InspectionTestCase; import org.jetbrains.annotations.NonNls; +import org.jetbrains.annotations.NotNull; /** * @author Alexey @@ -31,7 +32,7 @@ public abstract class IGInspectionTestCase extends InspectionTestCase { } @Override - public void doTest(@NonNls final String folderName, final LocalInspectionTool tool) { + public void doTest(@NotNull @NonNls final String folderName, @NotNull final LocalInspectionTool tool) { super.doTest(folderName, new LocalInspectionToolWrapper(tool), "java 1.5"); } } diff --git a/plugins/InspectionGadgets/testsrc/com/siyeh/ig/bugs/IgnoreResultOfCallInspectionTest.groovy b/plugins/InspectionGadgets/testsrc/com/siyeh/ig/bugs/IgnoreResultOfCallInspectionTest.groovy index 4bda75f16080..1ad5af5df95c 100644 --- a/plugins/InspectionGadgets/testsrc/com/siyeh/ig/bugs/IgnoreResultOfCallInspectionTest.groovy +++ b/plugins/InspectionGadgets/testsrc/com/siyeh/ig/bugs/IgnoreResultOfCallInspectionTest.groovy @@ -95,6 +95,21 @@ public class IgnoreResultOfCallInspectionTest extends LightInspectionTestCase { "}"); } + public void testJSR305Annotation3() { + doTest("import javax.annotation.CheckReturnValue;" + + "@CheckReturnValue " + + "class Parent {" + + " class A {" + + " Object a() {" + + " return null;" + + " }" + + " void b() {" + + " /*Result of 'A.a()' is ignored*/a/**/();" + + " }" + + " }" + + "}"); + } + public void testPureMethod() { doTest """ import org.jetbrains.annotations.Contract; diff --git a/plugins/InspectionGadgets/testsrc/com/siyeh/ig/threading/SharedThreadLocalRandomInspectionTest.java b/plugins/InspectionGadgets/testsrc/com/siyeh/ig/threading/SharedThreadLocalRandomInspectionTest.java index b15bc350fd6b..505cbb1ab18f 100644 --- a/plugins/InspectionGadgets/testsrc/com/siyeh/ig/threading/SharedThreadLocalRandomInspectionTest.java +++ b/plugins/InspectionGadgets/testsrc/com/siyeh/ig/threading/SharedThreadLocalRandomInspectionTest.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2014 JetBrains s.r.o. + * Copyright 2000-2016 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. @@ -74,4 +74,15 @@ public class SharedThreadLocalRandomInspectionTest extends LightInspectionTestCa " }" + "}"); } + + public void testCollectionsShuffle() { + doStatementTest("java.util.Collections.shuffle(new java.util.ArrayList(), java.util.concurrent.ThreadLocalRandom.current());"); + } + + public void testCollectionsShuffle2() { + doMemberTest("void f(java.util.List l) {" + + " java.util.Random r = java.util.concurrent.ThreadLocalRandom.current();" + + " java.util.Collections.shuffle(l, r);" + + "}"); + } } diff --git a/plugins/devkit/resources/META-INF/plugin.xml b/plugins/devkit/resources/META-INF/plugin.xml index 6c7412fbfab8..e63a7be8d79a 100644 --- a/plugins/devkit/resources/META-INF/plugin.xml +++ b/plugins/devkit/resources/META-INF/plugin.xml @@ -54,7 +54,7 @@ - - - extends GroovyPsiElementImpl implements GrReferenceElement { - private volatile String myCachedQName = null; + private volatile String myCachedQName; private volatile String myCachedTextSkipWhiteSpaceAndComments; public GrReferenceElementImpl(@NotNull ASTNode node) { diff --git a/plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/psi/impl/GroovyFileBaseImpl.java b/plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/psi/impl/GroovyFileBaseImpl.java index f748390722b2..57c5b5484891 100644 --- a/plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/psi/impl/GroovyFileBaseImpl.java +++ b/plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/psi/impl/GroovyFileBaseImpl.java @@ -57,7 +57,7 @@ import java.util.List; */ public abstract class GroovyFileBaseImpl extends PsiFileBase implements GroovyFileBase, GrControlFlowOwner { - private GrMethod[] myMethods = null; + private GrMethod[] myMethods; @Override public void subtreeChanged() { @@ -220,7 +220,7 @@ public abstract class GroovyFileBaseImpl extends PsiFileBase implements GroovyFi myControlFlow = null; } - private volatile SoftReference myControlFlow = null; + private volatile SoftReference myControlFlow; @Override public Instruction[] getControlFlow() { diff --git a/plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/psi/impl/GroovyFileImpl.java b/plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/psi/impl/GroovyFileImpl.java index 844c0d5efd3a..0f449da4ac71 100644 --- a/plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/psi/impl/GroovyFileImpl.java +++ b/plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/psi/impl/GroovyFileImpl.java @@ -79,7 +79,7 @@ public class GroovyFileImpl extends GroovyFileBaseImpl implements GroovyFile { private volatile Boolean myScript; private volatile GroovyScriptClass myScriptClass; - private volatile GrParameter mySyntheticArgsParameter = null; + private volatile GrParameter mySyntheticArgsParameter; private volatile PsiElement myContext; public GroovyFileImpl(FileViewProvider viewProvider) { diff --git a/plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/psi/impl/GroovyPsiManager.java b/plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/psi/impl/GroovyPsiManager.java index a2b367459739..2cca3e3422fd 100644 --- a/plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/psi/impl/GroovyPsiManager.java +++ b/plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/psi/impl/GroovyPsiManager.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2014 JetBrains s.r.o. + * Copyright 2000-2016 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. @@ -68,7 +68,7 @@ public class GroovyPsiManager { public GroovyPsiManager(Project project) { myProject = project; - ((PsiManagerEx)PsiManager.getInstance(myProject)).registerRunnableToRunOnAnyChange(new Runnable() { + PsiManagerEx.getInstanceEx(myProject).registerRunnableToRunOnAnyChange(new Runnable() { @Override public void run() { dropTypesCache(); diff --git a/plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/psi/impl/auxiliary/GrListOrMapImpl.java b/plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/psi/impl/auxiliary/GrListOrMapImpl.java index 9ca2f9b7261c..49cec6ec1e66 100644 --- a/plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/psi/impl/auxiliary/GrListOrMapImpl.java +++ b/plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/psi/impl/auxiliary/GrListOrMapImpl.java @@ -55,8 +55,8 @@ public class GrListOrMapImpl extends GrExpressionImpl implements GrListOrMap { private static final Function TYPES_CALCULATOR = new MyTypesCalculator(); private final PsiReference myLiteralReference = new LiteralConstructorReference(this); - private volatile GrExpression[] myInitializers = null; - private volatile GrNamedArgument[] myNamedArguments = null; + private volatile GrExpression[] myInitializers; + private volatile GrNamedArgument[] myNamedArguments; public GrListOrMapImpl(@NotNull ASTNode node) { super(node); diff --git a/plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/psi/impl/statements/expressions/TypesUtil.java b/plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/psi/impl/statements/expressions/TypesUtil.java index 5689142a08cc..6e6623834918 100644 --- a/plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/psi/impl/statements/expressions/TypesUtil.java +++ b/plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/psi/impl/statements/expressions/TypesUtil.java @@ -612,15 +612,15 @@ public class TypesUtil { } @NotNull - public static PsiType getLeastUpperBound(PsiClass[] classes, PsiManager manager) { + public static PsiType getLeastUpperBound(PsiType[] classes, PsiManager manager) { PsiElementFactory factory = JavaPsiFacade.getElementFactory(manager.getProject()); if (classes.length == 0) return factory.createTypeByFQClassName(CommonClassNames.JAVA_LANG_OBJECT); - PsiType type = factory.createType(classes[0]); + PsiType type = classes[0]; for (int i = 1; i < classes.length; i++) { - PsiType t = getLeastUpperBound(type, factory.createType(classes[i]), manager); + PsiType t = getLeastUpperBound(type, classes[i], manager); if (t != null) { type = t; } diff --git a/plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/psi/impl/synthetic/GrLightParameter.java b/plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/psi/impl/synthetic/GrLightParameter.java index 20f0d6f3badd..d1c72d1158ea 100644 --- a/plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/psi/impl/synthetic/GrLightParameter.java +++ b/plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/psi/impl/synthetic/GrLightParameter.java @@ -38,7 +38,7 @@ public class GrLightParameter extends LightVariableBuilder imp public static final GrLightParameter[] EMPTY_ARRAY = new GrLightParameter[0]; private volatile boolean myOptional; private volatile GrModifierList myModifierList; - private volatile GrExpression myInitializer = null; + private volatile GrExpression myInitializer; private final PsiElement myScope; private final GrTypeElement myTypeElement; private final PsiType myTypeGroovy; diff --git a/plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/psi/impl/synthetic/GroovyScriptClass.java b/plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/psi/impl/synthetic/GroovyScriptClass.java index 530398d35c86..6e848d24033b 100644 --- a/plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/psi/impl/synthetic/GroovyScriptClass.java +++ b/plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/psi/impl/synthetic/GroovyScriptClass.java @@ -54,10 +54,10 @@ import java.util.List; */ public class GroovyScriptClass extends LightElement implements PsiClass, SyntheticElement { private final GroovyFile myFile; - private volatile PsiMethod myMainMethod = null; - private volatile PsiMethod myRunMethod = null; + private volatile PsiMethod myMainMethod; + private volatile PsiMethod myRunMethod; - private volatile boolean myInitialized = false; + private volatile boolean myInitialized; private final LightModifierList myModifierList; diff --git a/plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/psi/impl/types/GrDisjunctionTypeElementImpl.java b/plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/psi/impl/types/GrDisjunctionTypeElementImpl.java index 23c33953a836..c25648a4a993 100644 --- a/plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/psi/impl/types/GrDisjunctionTypeElementImpl.java +++ b/plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/psi/impl/types/GrDisjunctionTypeElementImpl.java @@ -33,7 +33,7 @@ import java.util.ArrayList; * @author Max Medvedev */ public class GrDisjunctionTypeElementImpl extends GroovyPsiElementImpl implements GrDisjunctionTypeElement { - private volatile PsiType myCachedType = null; + private volatile PsiType myCachedType; public GrDisjunctionTypeElementImpl(@NotNull ASTNode node) { super(node); diff --git a/plugins/groovy/src/org/jetbrains/plugins/groovy/refactoring/changeSignature/GrChangeInfoImpl.java b/plugins/groovy/src/org/jetbrains/plugins/groovy/refactoring/changeSignature/GrChangeInfoImpl.java index e8e1fe8f2d75..e03aacb073a7 100644 --- a/plugins/groovy/src/org/jetbrains/plugins/groovy/refactoring/changeSignature/GrChangeInfoImpl.java +++ b/plugins/groovy/src/org/jetbrains/plugins/groovy/refactoring/changeSignature/GrChangeInfoImpl.java @@ -87,7 +87,7 @@ public class GrChangeInfoImpl implements JavaChangeInfo { oldReturnType = method.getReturnType(); } try { - PsiType newReturnType = returnType == null ? null : returnType.getType(method, getMethod().getManager()); + PsiType newReturnType = returnType == null ? null : returnType.getType(method); if ((oldReturnType == null && newReturnType != null) || (oldReturnType != null && !oldReturnType.equals(newReturnType))) { myIsReturnTypeChanged = true; } @@ -122,7 +122,7 @@ public class GrChangeInfoImpl implements JavaChangeInfo { myIsParameterNamesChanged = true; } try { - PsiType type = parameter.createType(method, method.getManager()); + PsiType type = parameter.createType(method); PsiType oldType = params[i].getType(); if (!oldType.equals(type)) { myIsParameterTypesChanged = true; diff --git a/plugins/groovy/src/org/jetbrains/plugins/groovy/refactoring/changeSignature/GrChangeSignatureUsageProcessor.java b/plugins/groovy/src/org/jetbrains/plugins/groovy/refactoring/changeSignature/GrChangeSignatureUsageProcessor.java index 312a53febdeb..b4de21c48d1f 100644 --- a/plugins/groovy/src/org/jetbrains/plugins/groovy/refactoring/changeSignature/GrChangeSignatureUsageProcessor.java +++ b/plugins/groovy/src/org/jetbrains/plugins/groovy/refactoring/changeSignature/GrChangeSignatureUsageProcessor.java @@ -155,7 +155,7 @@ public class GrChangeSignatureUsageProcessor implements ChangeSignatureUsageProc if (defaultValue == null && parameter.getOldIndex() == -1) { ((ParameterInfoImpl)parameter).setDefaultValue(""); if (!ApplicationManager.getApplication().isUnitTestMode()) { - final PsiType type = ((ParameterInfoImpl)parameter).getTypeWrapper().getType(element, element.getManager()); + final PsiType type = ((ParameterInfoImpl)parameter).getTypeWrapper().getType(element); final DefaultValueChooser chooser = new DefaultValueChooser(project, parameter.getName(), PsiTypesUtil.getDefaultValueOfType(type)); if (chooser.showAndGet()) { diff --git a/plugins/groovy/src/org/jetbrains/plugins/groovy/refactoring/introduce/variable/GrInplaceVariableIntroducer.java b/plugins/groovy/src/org/jetbrains/plugins/groovy/refactoring/introduce/variable/GrInplaceVariableIntroducer.java index 837ddf5f6a68..ef4fa4cd7683 100644 --- a/plugins/groovy/src/org/jetbrains/plugins/groovy/refactoring/introduce/variable/GrInplaceVariableIntroducer.java +++ b/plugins/groovy/src/org/jetbrains/plugins/groovy/refactoring/introduce/variable/GrInplaceVariableIntroducer.java @@ -156,7 +156,7 @@ public abstract class GrInplaceVariableIntroducer extends GrAbstractInplaceIntro @Nullable @Override public PsiType getSelectedType() { - return myType != null ? myType.getType(context.getPlace(), context.getPlace().getManager()) : null; + return myType != null ? myType.getType(context.getPlace()) : null; } }; } diff --git a/plugins/groovy/src/org/jetbrains/plugins/groovy/refactoring/introduceParameterObject/GroovyIntroduceObjectClassDescriptor.java b/plugins/groovy/src/org/jetbrains/plugins/groovy/refactoring/introduceParameterObject/GroovyIntroduceObjectClassDescriptor.java index a5f3aa771c2f..0f0759ba0dfc 100644 --- a/plugins/groovy/src/org/jetbrains/plugins/groovy/refactoring/introduceParameterObject/GroovyIntroduceObjectClassDescriptor.java +++ b/plugins/groovy/src/org/jetbrains/plugins/groovy/refactoring/introduceParameterObject/GroovyIntroduceObjectClassDescriptor.java @@ -15,9 +15,10 @@ */ package org.jetbrains.plugins.groovy.refactoring.introduceParameterObject; +import com.intellij.codeInsight.highlighting.ReadWriteAccessDetector; import com.intellij.psi.PsiElement; import com.intellij.refactoring.introduceParameterObject.IntroduceParameterObjectClassDescriptor; -import com.intellij.refactoring.introduceParameterObject.IntroduceParameterObjectDelegate; +import org.jetbrains.annotations.NotNull; import org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.members.GrMethod; import org.jetbrains.plugins.groovy.refactoring.changeSignature.GrParameterInfo; @@ -33,22 +34,22 @@ public class GroovyIntroduceObjectClassDescriptor extends IntroduceParameterObje } @Override - public String getSetterName(GrParameterInfo paramInfo, PsiElement context) { + public String getSetterName(GrParameterInfo paramInfo, @NotNull PsiElement context) { throw new UnsupportedOperationException(); } @Override - public String getGetterName(GrParameterInfo paramInfo, PsiElement context) { + public String getGetterName(GrParameterInfo paramInfo, @NotNull PsiElement context) { throw new UnsupportedOperationException(); } @Override - public void initExistingClass(GrMethod method) { + public GrMethod findCompatibleConstructorInExistingClass(GrMethod method) { throw new UnsupportedOperationException(); } @Override - public PsiElement createClass(GrMethod method, IntroduceParameterObjectDelegate.Accessor[] accessors) { + public PsiElement createClass(GrMethod method, ReadWriteAccessDetector.Access[] accessors) { throw new UnsupportedOperationException(); } } diff --git a/plugins/groovy/src/org/jetbrains/plugins/groovy/refactoring/introduceParameterObject/GroovyIntroduceParameterObjectDelegate.java b/plugins/groovy/src/org/jetbrains/plugins/groovy/refactoring/introduceParameterObject/GroovyIntroduceParameterObjectDelegate.java index 3985d2d2aa3f..b5365f22bc0b 100644 --- a/plugins/groovy/src/org/jetbrains/plugins/groovy/refactoring/introduceParameterObject/GroovyIntroduceParameterObjectDelegate.java +++ b/plugins/groovy/src/org/jetbrains/plugins/groovy/refactoring/introduceParameterObject/GroovyIntroduceParameterObjectDelegate.java @@ -15,10 +15,10 @@ */ package org.jetbrains.plugins.groovy.refactoring.introduceParameterObject; +import com.intellij.codeInsight.highlighting.ReadWriteAccessDetector; import com.intellij.openapi.util.text.StringUtil; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiNamedElement; -import com.intellij.psi.PsiReference; import com.intellij.psi.PsiType; import com.intellij.psi.search.LocalSearchScope; import com.intellij.psi.search.searches.ReferencesSearch; @@ -31,7 +31,6 @@ import com.intellij.refactoring.introduceparameterobject.JavaIntroduceParameterO import com.intellij.refactoring.util.CanonicalTypes; import com.intellij.refactoring.util.FixableUsageInfo; import com.intellij.usageView.UsageInfo; -import com.intellij.util.Processor; import com.intellij.util.VisibilityUtil; import com.intellij.util.containers.MultiMap; import org.jetbrains.annotations.Nullable; @@ -120,36 +119,40 @@ public class GroovyIntroduceParameterObjectDelegate } @Override - public Accessor collectInternalUsages(Collection usages, - GrMethod overridingMethod, - IntroduceParameterObjectClassDescriptor classDescriptor, - P1 parameterInfo, - String mergedParamName) { + public ReadWriteAccessDetector.Access collectInternalUsages(Collection usages, + GrMethod overridingMethod, + IntroduceParameterObjectClassDescriptor classDescriptor, + P1 parameterInfo, + String mergedParamName) { final int oldIndex = parameterInfo.getOldIndex(); final GrParameter parameter = overridingMethod.getParameterList().getParameters()[oldIndex]; - final Accessor[] accessors = new Accessor[1]; + final ReadWriteAccessDetector.Access[] accessors = new ReadWriteAccessDetector.Access[1]; final String setter = classDescriptor.getSetterName(parameterInfo, overridingMethod); final String getter = classDescriptor.getGetterName(parameterInfo, overridingMethod); - ReferencesSearch.search(parameter, new LocalSearchScope(overridingMethod)).forEach(new Processor() { - @Override - public boolean process(PsiReference reference) { - final PsiElement element = reference.getElement(); - if (element instanceof GrReferenceExpression) { - accessors[0] = Accessor.Getter; - //todo proceed with write access - usages.add(new GrReplaceParameterReferenceWithCall(element, getter, mergedParamName)); - } - return true; + ReferencesSearch.search(parameter, new LocalSearchScope(overridingMethod)).forEach(reference -> { + final PsiElement element = reference.getElement(); + if (element instanceof GrReferenceExpression) { + accessors[0] = ReadWriteAccessDetector.Access.Read; + //todo proceed with write access + usages.add(new GrReplaceParameterReferenceWithCall(element, getter, mergedParamName)); } + return true; }); return accessors[0]; } @Override - public void collectAccessibilityUsages(Collection usages, - GrMethod method, - GroovyIntroduceObjectClassDescriptor descriptor, - Accessor[] accessors) { + public void collectUsagesToGenerateMissedFieldAccessors(Collection usages, + GrMethod method, + GroovyIntroduceObjectClassDescriptor descriptor, + ReadWriteAccessDetector.Access[] accessors) { + throw new UnsupportedOperationException(); + } + + @Override + public void collectAdditionalFixes(Collection usages, + GrMethod method, + GroovyIntroduceObjectClassDescriptor descriptor) { throw new UnsupportedOperationException(); } diff --git a/plugins/hg4idea/src/org/zmlx/hg4idea/HgProjectSettings.java b/plugins/hg4idea/src/org/zmlx/hg4idea/HgProjectSettings.java index c9e8d75657bc..29810853e7d8 100644 --- a/plugins/hg4idea/src/org/zmlx/hg4idea/HgProjectSettings.java +++ b/plugins/hg4idea/src/org/zmlx/hg4idea/HgProjectSettings.java @@ -74,7 +74,10 @@ public class HgProjectSettings implements PersistentStateComponent + diff --git a/plugins/javaFX/src/org/jetbrains/plugins/javaFX/fxml/JavaFxPsiUtil.java b/plugins/javaFX/src/org/jetbrains/plugins/javaFX/fxml/JavaFxPsiUtil.java index 3c0ef9b52c44..0817e30ab30c 100644 --- a/plugins/javaFX/src/org/jetbrains/plugins/javaFX/fxml/JavaFxPsiUtil.java +++ b/plugins/javaFX/src/org/jetbrains/plugins/javaFX/fxml/JavaFxPsiUtil.java @@ -219,7 +219,9 @@ public class JavaFxPsiUtil { return null; } - public static PsiMethod findStaticPropertySetter(String attributeName, PsiClass classWithStaticProperty) { + @Nullable + public static PsiMethod findStaticPropertySetter(@NotNull String attributeName, @Nullable PsiClass classWithStaticProperty) { + if (classWithStaticProperty == null) return null; final String setterName = PropertyUtil.suggestSetterName(StringUtil.getShortName(attributeName)); final PsiMethod[] setters = classWithStaticProperty.findMethodsByName(setterName, true); for (PsiMethod setter : setters) { @@ -232,7 +234,8 @@ public class JavaFxPsiUtil { return null; } - public static PsiMethod findPropertyGetter(@NotNull PsiClass psiClass, @NotNull String propertyName) { + public static PsiMethod findPropertyGetter(@NotNull PsiClass psiClass, @Nullable String propertyName) { + if (StringUtil.isEmpty(propertyName)) return null; PsiMethod getter = findPropertyGetter(psiClass, propertyName, null); if (getter != null) { return getter; @@ -253,7 +256,8 @@ public class JavaFxPsiUtil { return null; } - public static PsiMethod findObservablePropertyGetter(@NotNull PsiClass psiClass, @NotNull String propertyName) { + public static PsiMethod findObservablePropertyGetter(@NotNull PsiClass psiClass, @Nullable String propertyName) { + if (StringUtil.isEmpty(propertyName)) return null; final PsiMethod[] getters = psiClass.findMethodsByName(propertyName + JavaFxCommonNames.PROPERTY_METHOD_SUFFIX, true); for (PsiMethod getter : getters) { if (getter.hasModifierProperty(PsiModifier.PUBLIC) && @@ -957,7 +961,8 @@ public class JavaFxPsiUtil { } @Nullable - public static PsiMethod findInstancePropertySetter(@NotNull PsiClass psiClass, @NotNull String propertyName) { + public static PsiMethod findInstancePropertySetter(@NotNull PsiClass psiClass, @Nullable String propertyName) { + if (StringUtil.isEmpty(propertyName)) return null; final String suggestedSetterName = PropertyUtil.suggestSetterName(propertyName); final PsiMethod[] setters = psiClass.findMethodsByName(suggestedSetterName, true); for (PsiMethod setter : setters) { diff --git a/plugins/javaFX/src/org/jetbrains/plugins/javaFX/fxml/refs/FxmlReferencesContributor.java b/plugins/javaFX/src/org/jetbrains/plugins/javaFX/fxml/refs/FxmlReferencesContributor.java index f5ef7a919337..fd630b9a5a5b 100644 --- a/plugins/javaFX/src/org/jetbrains/plugins/javaFX/fxml/refs/FxmlReferencesContributor.java +++ b/plugins/javaFX/src/org/jetbrains/plugins/javaFX/fxml/refs/FxmlReferencesContributor.java @@ -125,6 +125,10 @@ public class FxmlReferencesContributor extends PsiReferenceContributor { .withParent(XmlPatterns.xmlTag().withParent(XmlPatterns.xmlTag().withName(FxmlConstants.STYLESHEETS)))) .and(attributeValueInFxml), new JavaFxLocationReferenceProvider(true, "css")); + + registrar.registerReferenceProvider(XmlPatterns.xmlAttribute().withLocalName(string().contains(".")) + .inVirtualFile(virtualFile().withExtension(JavaFxFileTypeFactory.FXML_EXTENSION)), + new JavaFxStaticPropertyReferenceProvider()); } private static class MyJavaClassReferenceProvider extends JavaClassReferenceProvider { diff --git a/plugins/javaFX/src/org/jetbrains/plugins/javaFX/fxml/refs/JavaFxComponentIdReferenceProvider.java b/plugins/javaFX/src/org/jetbrains/plugins/javaFX/fxml/refs/JavaFxComponentIdReferenceProvider.java index 789a8203c262..fe8d81f915ed 100644 --- a/plugins/javaFX/src/org/jetbrains/plugins/javaFX/fxml/refs/JavaFxComponentIdReferenceProvider.java +++ b/plugins/javaFX/src/org/jetbrains/plugins/javaFX/fxml/refs/JavaFxComponentIdReferenceProvider.java @@ -43,7 +43,7 @@ import java.util.stream.Collectors; /** * User: anna */ -class JavaFxComponentIdReferenceProvider extends PsiReferenceProvider { +public class JavaFxComponentIdReferenceProvider extends PsiReferenceProvider { @NotNull @Override @@ -190,7 +190,7 @@ class JavaFxComponentIdReferenceProvider extends PsiReferenceProvider { } } - private static class JavaFxIdReferenceBase extends PsiReferenceBase implements JavaFxIdAttributeReference { + public static class JavaFxIdReferenceBase extends PsiReferenceBase { private final Map myFileIds; private final Set myAcceptableIds; private final Map myTypeMatches; @@ -232,26 +232,23 @@ class JavaFxComponentIdReferenceProvider extends PsiReferenceProvider { .toArray(LookupElement[]::new); } - @Override public boolean isBuiltIn() { return FxmlConstants.CONTROLLER.equals(myReferencesId) || myReferencesId.endsWith(FxmlConstants.CONTROLLER_SUFFIX); } } - private static class JavaFxExpressionReferenceBase extends PsiReferenceBase implements JavaFxPropertyReference { - private final PsiClass myTagClass; + private static class JavaFxExpressionReferenceBase extends JavaFxPropertyReference { private final String myFieldName; - public JavaFxExpressionReferenceBase(XmlAttributeValue xmlAttributeValue, PsiClass tagClass, String fieldName) { - super(xmlAttributeValue); - myTagClass = tagClass; + public JavaFxExpressionReferenceBase(@NotNull XmlAttributeValue xmlAttributeValue, PsiClass tagClass, @NotNull String fieldName) { + super(xmlAttributeValue, tagClass); myFieldName = fieldName; } @Nullable @Override public PsiElement resolve() { - return JavaFxPsiUtil.collectReadableProperties(myTagClass).get(myFieldName); + return JavaFxPsiUtil.collectReadableProperties(myPsiClass).get(myFieldName); } @NotNull @@ -259,7 +256,7 @@ class JavaFxComponentIdReferenceProvider extends PsiReferenceProvider { public Object[] getVariants() { final XmlAttributeValue xmlAttributeValue = getElement(); final PsiElement declaration = JavaFxPsiUtil.getAttributeDeclaration(xmlAttributeValue); - final PsiType propertyType = JavaFxPsiUtil.getWritablePropertyType(myTagClass, declaration); + final PsiType propertyType = JavaFxPsiUtil.getWritablePropertyType(myPsiClass, declaration); if (propertyType != null) { return collectProperties(propertyType, xmlAttributeValue.getProject()); } @@ -269,7 +266,7 @@ class JavaFxComponentIdReferenceProvider extends PsiReferenceProvider { private Object[] collectProperties(@NotNull PsiType propertyType, @NotNull Project project) { final PsiType resolvedType = JavaFxPsiUtil.getWritablePropertyType(propertyType, project); final List objs = new ArrayList<>(); - final Collection readableProperties = JavaFxPsiUtil.collectReadableProperties(myTagClass).values(); + final Collection readableProperties = JavaFxPsiUtil.collectReadableProperties(myPsiClass).values(); for (PsiMember readableMember : readableProperties) { final PsiType readableType = JavaFxPsiUtil.getReadablePropertyType(readableMember); if (readableType == null) continue; @@ -284,34 +281,10 @@ class JavaFxComponentIdReferenceProvider extends PsiReferenceProvider { return ArrayUtil.toObjectArray(objs); } - @Nullable + @NotNull @Override - public PsiMethod getGetter() { - return JavaFxPropertyReference.getGetter(myTagClass, myFieldName); - } - - @Nullable - @Override - public PsiMethod getSetter() { - return JavaFxPropertyReference.getSetter(myTagClass, myFieldName); - } - - @Nullable - @Override - public PsiField getField() { - return JavaFxPropertyReference.getField(myTagClass, myFieldName); - } - - @Nullable - @Override - public PsiMethod getObservableGetter() { - return JavaFxPropertyReference.getObservableGetter(myTagClass, myFieldName); - } - - @Nullable - @Override - public PsiType getType() { - return JavaFxPsiUtil.getReadablePropertyType(resolve()); + public String getPropertyName() { + return myFieldName; } @Override diff --git a/plugins/javaFX/src/org/jetbrains/plugins/javaFX/fxml/refs/JavaFxFieldIdReferenceProvider.java b/plugins/javaFX/src/org/jetbrains/plugins/javaFX/fxml/refs/JavaFxFieldIdReferenceProvider.java index 183312b70fec..29ddef78527d 100644 --- a/plugins/javaFX/src/org/jetbrains/plugins/javaFX/fxml/refs/JavaFxFieldIdReferenceProvider.java +++ b/plugins/javaFX/src/org/jetbrains/plugins/javaFX/fxml/refs/JavaFxFieldIdReferenceProvider.java @@ -55,13 +55,13 @@ public class JavaFxFieldIdReferenceProvider extends JavaFxControllerBasedReferen return new PsiReference[]{new JavaFxControllerFieldRef(xmlAttributeValue, fieldOrGetterMethod, aClass)}; } - public static class JavaFxControllerFieldRef extends PsiReferenceBase implements JavaFxPropertyReference { + public static class JavaFxControllerFieldRef extends JavaFxPropertyReference { private final XmlAttributeValue myXmlAttributeValue; private final PsiMember myFieldOrMethod; private final PsiClass myAClass; public JavaFxControllerFieldRef(XmlAttributeValue xmlAttributeValue, PsiMember fieldOrMethod, PsiClass aClass) { - super(xmlAttributeValue, true); + super(xmlAttributeValue, aClass, true); myXmlAttributeValue = xmlAttributeValue; myFieldOrMethod = fieldOrMethod; myAClass = aClass; @@ -127,7 +127,7 @@ public class JavaFxFieldIdReferenceProvider extends JavaFxControllerBasedReferen if (myFieldOrMethod instanceof PsiMethod && PropertyUtil.isSimplePropertyGetter((PsiMethod)myFieldOrMethod)) { return (PsiMethod)myFieldOrMethod; } - return JavaFxPropertyReference.getGetter(myAClass, PropertyUtil.getPropertyName(myFieldOrMethod)); + return super.getGetter(); } @Nullable @@ -136,7 +136,7 @@ public class JavaFxFieldIdReferenceProvider extends JavaFxControllerBasedReferen if (myFieldOrMethod instanceof PsiMethod && PropertyUtil.isSimplePropertySetter((PsiMethod)myFieldOrMethod)) { return (PsiMethod)myFieldOrMethod; } - return JavaFxPropertyReference.getSetter(myAClass, PropertyUtil.getPropertyName(myFieldOrMethod)); + return super.getSetter(); } @Nullable @@ -145,19 +145,13 @@ public class JavaFxFieldIdReferenceProvider extends JavaFxControllerBasedReferen if (myFieldOrMethod instanceof PsiField) { return (PsiField)myFieldOrMethod; } - return JavaFxPropertyReference.getField(myAClass, PropertyUtil.getPropertyName(myFieldOrMethod)); + return super.getField(); } @Nullable @Override - public PsiMethod getObservableGetter() { - return JavaFxPropertyReference.getObservableGetter(myAClass, PropertyUtil.getPropertyName(myFieldOrMethod)); - } - - @Nullable - @Override - public PsiType getType() { - return JavaFxPsiUtil.getReadablePropertyType(myFieldOrMethod); + public String getPropertyName() { + return PropertyUtil.getPropertyName(myFieldOrMethod); } @Override diff --git a/plugins/javaFX/src/org/jetbrains/plugins/javaFX/fxml/refs/JavaFxIdAttributeReference.java b/plugins/javaFX/src/org/jetbrains/plugins/javaFX/fxml/refs/JavaFxIdAttributeReference.java deleted file mode 100644 index b5c08610b18d..000000000000 --- a/plugins/javaFX/src/org/jetbrains/plugins/javaFX/fxml/refs/JavaFxIdAttributeReference.java +++ /dev/null @@ -1,10 +0,0 @@ -package org.jetbrains.plugins.javaFX.fxml.refs; - -import com.intellij.psi.PsiReference; - -/** - * @author Pavel.Dolgov - */ -public interface JavaFxIdAttributeReference extends PsiReference { - boolean isBuiltIn(); -} diff --git a/plugins/javaFX/src/org/jetbrains/plugins/javaFX/fxml/refs/JavaFxMethodSearcher.java b/plugins/javaFX/src/org/jetbrains/plugins/javaFX/fxml/refs/JavaFxMethodSearcher.java new file mode 100644 index 000000000000..532744d5e7c5 --- /dev/null +++ b/plugins/javaFX/src/org/jetbrains/plugins/javaFX/fxml/refs/JavaFxMethodSearcher.java @@ -0,0 +1,130 @@ +/* + * Copyright 2000-2013 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 org.jetbrains.plugins.javaFX.fxml.refs; + +import com.intellij.openapi.application.ApplicationManager; +import com.intellij.openapi.project.Project; +import com.intellij.openapi.util.Computable; +import com.intellij.openapi.vfs.VirtualFile; +import com.intellij.psi.*; +import com.intellij.psi.impl.cache.CacheManager; +import com.intellij.psi.search.GlobalSearchScope; +import com.intellij.psi.search.LocalSearchScope; +import com.intellij.psi.search.SearchScope; +import com.intellij.psi.search.UsageSearchContext; +import com.intellij.psi.search.searches.ReferencesSearch; +import com.intellij.psi.util.PropertyUtil; +import com.intellij.psi.util.PsiUtilCore; +import com.intellij.psi.xml.XmlAttribute; +import com.intellij.util.ArrayUtil; +import com.intellij.util.Processor; +import com.intellij.util.QueryExecutor; +import com.intellij.util.containers.ContainerUtil; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.plugins.javaFX.fxml.JavaFxFileTypeFactory; +import org.jetbrains.plugins.javaFX.refactoring.JavaFxPropertyElement; + +/** + * @author Pavel.Dolgov + */ +public class JavaFxMethodSearcher implements QueryExecutor { + @Override + public boolean execute(@NotNull final ReferencesSearch.SearchParameters queryParameters, + @NotNull final Processor consumer) { + final PsiElement elementToSearch = queryParameters.getElementToSearch(); + if (elementToSearch instanceof PsiMethod) { + searchMethod((PsiMethod)elementToSearch, queryParameters, consumer); + } + if (elementToSearch instanceof JavaFxPropertyElement) { + final JavaFxPropertyElement propertyElement = (JavaFxPropertyElement)elementToSearch; + final JavaFxPropertyReference propertyReference = propertyElement.getPropertyReference(); + final PsiMethod staticSetter = propertyReference.getStaticSetter(); + if (staticSetter != null) { + searchMethod(staticSetter, queryParameters, consumer); + } + } + return true; + } + + private static void searchMethod(@NotNull PsiMethod psiMethod, @NotNull ReferencesSearch.SearchParameters queryParameters, + @NotNull Processor consumer) { + final Project project = PsiUtilCore.getProjectInReadAction(psiMethod); + final SearchScope scope = + ApplicationManager.getApplication().runReadAction((Computable)queryParameters::getEffectiveSearchScope); + if (scope instanceof LocalSearchScope) { + final VirtualFile[] vFiles = ((LocalSearchScope)scope).getVirtualFiles(); + for (VirtualFile vFile : vFiles) { + if (JavaFxFileTypeFactory.isFxml(vFile)) { + final PsiFile psiFile = PsiManager.getInstance(project).findFile(vFile); + if (psiFile != null) { + final Boolean goOn = ApplicationManager.getApplication().runReadAction( + (Computable)() -> searchMethodInFile(psiMethod, psiFile, consumer)); + if (!goOn) break; + } + } + } + } + else if (scope instanceof GlobalSearchScope) { + final String propertyName = ApplicationManager.getApplication().runReadAction( + (Computable)() -> PropertyUtil.getPropertyName(psiMethod.getName())); + if (propertyName == null) return; + + final String className = ApplicationManager.getApplication().runReadAction( + (Computable)() -> { + final PsiClass psiClass = psiMethod.getContainingClass(); + return psiClass != null ? psiClass.getName() : null; + }); + if (className == null) return; + + final GlobalSearchScope fxmlScope = new JavaFxScopeEnlarger.GlobalFxmlSearchScope((GlobalSearchScope)scope); + final VirtualFile[] filteredFiles = ApplicationManager.getApplication().runReadAction((Computable)() -> + CacheManager.SERVICE.getInstance(project).getVirtualFilesWithWord(className, UsageSearchContext.IN_PLAIN_TEXT, fxmlScope, true)); + if (ArrayUtil.isEmpty(filteredFiles)) return; + + final GlobalSearchScope filteredScope = GlobalSearchScope.filesScope(project, ContainerUtil.newHashSet(filteredFiles)); + ApplicationManager.getApplication().runReadAction( + (Runnable)() -> CacheManager.SERVICE.getInstance(project).processFilesWithWord( + file -> searchMethodInFile(psiMethod, file, consumer), propertyName, UsageSearchContext.IN_PLAIN_TEXT, filteredScope, true)); + } + } + + private static boolean searchMethodInFile(@NotNull PsiMethod psiMethod, + @NotNull PsiFile file, + @NotNull Processor consumer) { + class StopException extends RuntimeException { + } + try { + file.accept(new XmlRecursiveElementVisitor() { + @Override + public void visitXmlAttribute(XmlAttribute attribute) { + final PsiReference[] references = attribute.getReferences(); + for (PsiReference reference : references) { + if ((reference instanceof JavaFxStaticPropertyReference || reference instanceof JavaFxEventHandlerReference) && + reference.isReferenceTo(psiMethod)) { + if (!consumer.process(reference)) { + throw new StopException(); + } + } + } + } + }); + return true; + } + catch (StopException unused) { + return false; + } + } +} diff --git a/plugins/javaFX/src/org/jetbrains/plugins/javaFX/fxml/refs/JavaFxPropertyReference.java b/plugins/javaFX/src/org/jetbrains/plugins/javaFX/fxml/refs/JavaFxPropertyReference.java index 98274817738a..95d6d09ae84d 100644 --- a/plugins/javaFX/src/org/jetbrains/plugins/javaFX/fxml/refs/JavaFxPropertyReference.java +++ b/plugins/javaFX/src/org/jetbrains/plugins/javaFX/fxml/refs/JavaFxPropertyReference.java @@ -1,51 +1,60 @@ package org.jetbrains.plugins.javaFX.fxml.refs; import com.intellij.psi.*; -import com.intellij.psi.util.PropertyUtil; -import gnu.trove.THashMap; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; -import org.jetbrains.plugins.javaFX.fxml.JavaFxCommonNames; import org.jetbrains.plugins.javaFX.fxml.JavaFxPsiUtil; -import java.util.Map; - /** * @author Pavel.Dolgov */ -public interface JavaFxPropertyReference extends PsiReference { - @Nullable - PsiMethod getGetter(); +public abstract class JavaFxPropertyReference extends PsiReferenceBase { + protected final PsiClass myPsiClass; - @Nullable - PsiMethod getSetter(); - - @Nullable - PsiField getField(); - - @Nullable - PsiMethod getObservableGetter(); - - @Nullable - PsiType getType(); - - static PsiMethod getGetter(PsiClass psiClass, String propertyName) { - if (psiClass == null || propertyName == null) return null; - return JavaFxPsiUtil.findPropertyGetter(psiClass, propertyName); + public JavaFxPropertyReference(@NotNull T element, PsiClass aClass, boolean soft) { + super(element, soft); + myPsiClass = aClass; } - static PsiMethod getSetter(PsiClass psiClass, String propertyName) { - if (psiClass == null || propertyName == null) return null; - return JavaFxPsiUtil.findInstancePropertySetter(psiClass, propertyName); + public JavaFxPropertyReference(@NotNull T element, PsiClass aClass) { + super(element); + myPsiClass = aClass; } - static PsiField getField(PsiClass psiClass, String propertyName) { - if (psiClass == null || propertyName == null) return null; - return psiClass.findFieldByName(propertyName, true); + @Nullable + public PsiMethod getGetter() { + if (myPsiClass == null) return null; + return JavaFxPsiUtil.findPropertyGetter(myPsiClass, getPropertyName()); } - static PsiMethod getObservableGetter(PsiClass psiClass, String propertyName) { - if (psiClass == null || propertyName == null) return null; - return JavaFxPsiUtil.findObservablePropertyGetter(psiClass, propertyName); + @Nullable + public PsiMethod getSetter() { + if (myPsiClass == null) return null; + return JavaFxPsiUtil.findInstancePropertySetter(myPsiClass, getPropertyName()); } + + @Nullable + public PsiField getField() { + if (myPsiClass == null) return null; + return myPsiClass.findFieldByName(getPropertyName(), true); + } + + @Nullable + public PsiMethod getObservableGetter() { + if (myPsiClass == null) return null; + return JavaFxPsiUtil.findObservablePropertyGetter(myPsiClass, getPropertyName()); + } + + @Nullable + public PsiMethod getStaticSetter() { + return null; + } + + @Nullable + public PsiType getType() { + return JavaFxPsiUtil.getReadablePropertyType(resolve()); + } + + @Nullable + public abstract String getPropertyName(); } diff --git a/plugins/javaFX/src/org/jetbrains/plugins/javaFX/fxml/refs/JavaFxScopeEnlarger.java b/plugins/javaFX/src/org/jetbrains/plugins/javaFX/fxml/refs/JavaFxScopeEnlarger.java index 51ac310bcaa6..76c055b79901 100644 --- a/plugins/javaFX/src/org/jetbrains/plugins/javaFX/fxml/refs/JavaFxScopeEnlarger.java +++ b/plugins/javaFX/src/org/jetbrains/plugins/javaFX/fxml/refs/JavaFxScopeEnlarger.java @@ -16,13 +16,16 @@ package org.jetbrains.plugins.javaFX.fxml.refs; import com.intellij.codeInsight.AnnotationUtil; +import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.project.Project; +import com.intellij.openapi.util.Computable; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.psi.*; import com.intellij.psi.search.DelegatingGlobalSearchScope; import com.intellij.psi.search.GlobalSearchScope; import com.intellij.psi.search.SearchScope; import com.intellij.psi.search.UseScopeEnlarger; +import com.intellij.psi.util.InheritanceUtil; import com.intellij.psi.util.PropertyUtil; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; @@ -41,6 +44,9 @@ public class JavaFxScopeEnlarger extends UseScopeEnlarger { if (element instanceof PsiField) { containingClass = ((PsiField)element).getContainingClass(); } + else if (element instanceof PsiMethod) { + containingClass = ((PsiMethod)element).getContainingClass(); + } else if (element instanceof PsiParameter) { final PsiElement declarationScope = ((PsiParameter)element).getDeclarationScope(); if (declarationScope instanceof PsiMethod && PropertyUtil.isSimplePropertySetter((PsiMethod)declarationScope)) { @@ -49,23 +55,42 @@ public class JavaFxScopeEnlarger extends UseScopeEnlarger { } if (containingClass != null) { - if (element instanceof PsiField && - !((PsiField)element).hasModifierProperty(PsiModifier.PUBLIC) && - AnnotationUtil.isAnnotated((PsiField)element, JavaFxCommonNames.JAVAFX_FXML_ANNOTATION, false) || element instanceof PsiParameter) { + if (element instanceof PsiField && needToEnlargeScope((PsiField)element) || + element instanceof PsiMethod && needToEnlargeScope((PsiMethod)element) || + element instanceof PsiParameter) { final Project project = element.getProject(); final String qualifiedName = containingClass.getQualifiedName(); - if (qualifiedName != null && !JavaFxControllerClassIndex.findFxmlWithController(project, qualifiedName).isEmpty()) { + if (qualifiedName != null && !JavaFxControllerClassIndex.findFxmlWithController(project, qualifiedName).isEmpty() || + InheritanceUtil.isInheritor(containingClass, JavaFxCommonNames.JAVAFX_SCENE_NODE)) { final GlobalSearchScope projectScope = GlobalSearchScope.projectScope(project); - return new DelegatingGlobalSearchScope(projectScope){ - @Override - public boolean contains(@NotNull VirtualFile file) { - return super.contains(file) && JavaFxFileTypeFactory.isFxml(file); - } - }; + return new GlobalFxmlSearchScope(projectScope); } } - } + } return null; } + + private static boolean needToEnlargeScope(PsiField field) { + return !field.hasModifierProperty(PsiModifier.PUBLIC) && + AnnotationUtil.isAnnotated(field, JavaFxCommonNames.JAVAFX_FXML_ANNOTATION, false); + } + + private static boolean needToEnlargeScope(PsiMethod method) { + final boolean isStatic = method.hasModifierProperty(PsiModifier.STATIC); + return isStatic && method.getParameterList().getParametersCount() == 2 || + !isStatic && !method.hasModifierProperty(PsiModifier.PUBLIC) && + AnnotationUtil.isAnnotated(method, JavaFxCommonNames.JAVAFX_FXML_ANNOTATION, false); + } + + static class GlobalFxmlSearchScope extends DelegatingGlobalSearchScope { + public GlobalFxmlSearchScope(GlobalSearchScope baseScope) { + super(baseScope); + } + + @Override + public boolean contains(@NotNull VirtualFile file) { + return super.contains(file) && JavaFxFileTypeFactory.isFxml(file); + } + } } diff --git a/plugins/javaFX/src/org/jetbrains/plugins/javaFX/fxml/refs/JavaFxStaticPropertyReference.java b/plugins/javaFX/src/org/jetbrains/plugins/javaFX/fxml/refs/JavaFxStaticPropertyReference.java new file mode 100644 index 000000000000..0b84f3708756 --- /dev/null +++ b/plugins/javaFX/src/org/jetbrains/plugins/javaFX/fxml/refs/JavaFxStaticPropertyReference.java @@ -0,0 +1,89 @@ +package org.jetbrains.plugins.javaFX.fxml.refs; + +import com.intellij.psi.*; +import com.intellij.psi.xml.XmlAttribute; +import com.intellij.util.ArrayUtil; +import com.intellij.util.IncorrectOperationException; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; +import org.jetbrains.plugins.javaFX.fxml.JavaFxPsiUtil; + +/** + * @author Pavel.Dolgov + */ +public class JavaFxStaticPropertyReference extends JavaFxPropertyReference { + private String myPropertyName; + private PsiMethod myStaticMethod; + + public JavaFxStaticPropertyReference(@NotNull XmlAttribute xmlAttribute, + @Nullable PsiClass psiClass, + @NotNull String propertyName) { + super(xmlAttribute, psiClass); + myPropertyName = propertyName; + myStaticMethod = JavaFxPsiUtil.findStaticPropertySetter(propertyName, psiClass); + } + + @Nullable + @Override + public PsiElement resolve() { + return myStaticMethod; + } + + @Nullable + @Override + public PsiMethod getGetter() { + return null; + } + + @Nullable + @Override + public PsiMethod getSetter() { + return null; + } + + @Nullable + @Override + public PsiField getField() { + return null; + } + + @Nullable + @Override + public PsiMethod getObservableGetter() { + return null; + } + + @Nullable + @Override + public PsiMethod getStaticSetter() { + return myStaticMethod; + } + + @Override + public PsiType getType() { + if (myStaticMethod != null) { + final PsiParameter[] parameters = myStaticMethod.getParameterList().getParameters(); + if (parameters.length == 2) { + return parameters[1].getType(); + } + } + return null; + } + + @Override + public String getPropertyName() { + return myPropertyName; + } + + @NotNull + @Override + public Object[] getVariants() { + return ArrayUtil.EMPTY_OBJECT_ARRAY; + } + + @Override + public PsiElement handleElementRename(String newElementName) throws IncorrectOperationException { + final String newPropertyName = JavaFxPsiUtil.getPropertyName(newElementName, true); + return super.handleElementRename(newPropertyName); + } +} diff --git a/plugins/javaFX/src/org/jetbrains/plugins/javaFX/fxml/refs/JavaFxStaticPropertyReferenceProvider.java b/plugins/javaFX/src/org/jetbrains/plugins/javaFX/fxml/refs/JavaFxStaticPropertyReferenceProvider.java new file mode 100644 index 000000000000..071522742b44 --- /dev/null +++ b/plugins/javaFX/src/org/jetbrains/plugins/javaFX/fxml/refs/JavaFxStaticPropertyReferenceProvider.java @@ -0,0 +1,64 @@ +package org.jetbrains.plugins.javaFX.fxml.refs; + +import com.intellij.openapi.util.TextRange; +import com.intellij.psi.*; +import com.intellij.psi.xml.XmlAttribute; +import com.intellij.util.ArrayUtil; +import com.intellij.util.ProcessingContext; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; +import org.jetbrains.plugins.javaFX.fxml.JavaFxFileTypeFactory; +import org.jetbrains.plugins.javaFX.fxml.JavaFxPsiUtil; + +/** + * @author Pavel.Dolgov + */ +public class JavaFxStaticPropertyReferenceProvider extends PsiReferenceProvider { + @NotNull + @Override + public PsiReference[] getReferencesByElement(@NotNull PsiElement element, @NotNull ProcessingContext context) { + if (!(element instanceof XmlAttribute) || !JavaFxFileTypeFactory.isFxml(element.getContainingFile())) return PsiReference.EMPTY_ARRAY; + + final XmlAttribute xmlAttribute = (XmlAttribute)element; + final String name = xmlAttribute.getName(); + final int dotIndex = name.indexOf('.'); + if (dotIndex <= 0 || name.indexOf('.', dotIndex + 1) >= 0) return PsiReference.EMPTY_ARRAY; + final String className = name.substring(0, dotIndex); + final JavaFxStaticPropertyClassReference classReference = new JavaFxStaticPropertyClassReference(xmlAttribute, className); + classReference.setRangeInElement(new TextRange(0, dotIndex)); + if (dotIndex + 1 == name.length()) { + return new PsiReference[]{classReference}; + } + final String propertyName = name.substring(dotIndex + 1); + final JavaFxStaticPropertyReference methodReference = + new JavaFxStaticPropertyReference(xmlAttribute, classReference.getPsiClass(), propertyName); + methodReference.setRangeInElement(new TextRange(dotIndex + 1, name.length())); + + return new PsiReference[]{classReference, methodReference}; + } + + private static class JavaFxStaticPropertyClassReference extends PsiReferenceBase { + private PsiClass myPsiClass; + + public JavaFxStaticPropertyClassReference(@NotNull XmlAttribute xmlAttribute, @NotNull String className) { + super(xmlAttribute); + myPsiClass = JavaFxPsiUtil.findPsiClass(className, xmlAttribute); + } + + public PsiClass getPsiClass() { + return myPsiClass; + } + + @Nullable + @Override + public PsiElement resolve() { + return myPsiClass; + } + + @NotNull + @Override + public Object[] getVariants() { + return ArrayUtil.EMPTY_OBJECT_ARRAY; + } + } +} diff --git a/plugins/javaFX/src/org/jetbrains/plugins/javaFX/refactoring/JavaFxPropertyElement.java b/plugins/javaFX/src/org/jetbrains/plugins/javaFX/refactoring/JavaFxPropertyElement.java index 7f497cf6b02d..fb7331e4c6e4 100644 --- a/plugins/javaFX/src/org/jetbrains/plugins/javaFX/refactoring/JavaFxPropertyElement.java +++ b/plugins/javaFX/src/org/jetbrains/plugins/javaFX/refactoring/JavaFxPropertyElement.java @@ -5,7 +5,6 @@ import com.intellij.psi.PsiField; import com.intellij.psi.PsiMethod; import com.intellij.psi.PsiType; import com.intellij.psi.impl.beanProperties.BeanPropertyElement; -import com.intellij.psi.util.PropertyUtil; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.jetbrains.plugins.javaFX.fxml.refs.JavaFxPropertyReference; @@ -13,10 +12,10 @@ import org.jetbrains.plugins.javaFX.fxml.refs.JavaFxPropertyReference; /** * @author Pavel.Dolgov */ -class JavaFxPropertyElement extends BeanPropertyElement { +public class JavaFxPropertyElement extends BeanPropertyElement { private final JavaFxPropertyReference myPropertyReference; - private JavaFxPropertyElement(JavaFxPropertyReference propertyReference, String propertyName, PsiMethod method) { + private JavaFxPropertyElement(PsiMethod method, String propertyName, JavaFxPropertyReference propertyReference) { super(method, propertyName); myPropertyReference = propertyReference; } @@ -32,14 +31,18 @@ class JavaFxPropertyElement extends BeanPropertyElement { return "property"; } + @NotNull + public JavaFxPropertyReference getPropertyReference() { + return myPropertyReference; + } + @Nullable static PsiElement fromReference(@NotNull final JavaFxPropertyReference propertyReference) { final PsiElement element = propertyReference.resolve(); if (element instanceof PsiMethod) { - final PsiMethod method = (PsiMethod)element; - final String propertyName = PropertyUtil.getPropertyName(method); + final String propertyName = propertyReference.getPropertyName(); if (propertyName != null) { - return new JavaFxPropertyElement(propertyReference, propertyName, method); + return new JavaFxPropertyElement((PsiMethod)element, propertyName, propertyReference); } } if (element instanceof PsiField) { diff --git a/plugins/javaFX/src/org/jetbrains/plugins/javaFX/refactoring/JavaFxPropertyRenameHandler.java b/plugins/javaFX/src/org/jetbrains/plugins/javaFX/refactoring/JavaFxPropertyRenameHandler.java index ebe58dc31060..6e7b0a972de6 100644 --- a/plugins/javaFX/src/org/jetbrains/plugins/javaFX/refactoring/JavaFxPropertyRenameHandler.java +++ b/plugins/javaFX/src/org/jetbrains/plugins/javaFX/refactoring/JavaFxPropertyRenameHandler.java @@ -10,6 +10,7 @@ import com.intellij.psi.PsiDocumentManager; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiFile; import com.intellij.psi.PsiReference; +import com.intellij.psi.impl.source.resolve.reference.impl.PsiMultiReference; import com.intellij.psi.util.PropertyUtil; import com.intellij.psi.xml.XmlFile; import com.intellij.refactoring.RenameRefactoring; @@ -18,13 +19,13 @@ import com.intellij.refactoring.rename.PsiElementRenameHandler; import com.intellij.refactoring.rename.RenameDialog; import com.intellij.refactoring.rename.RenameHandler; import com.intellij.refactoring.util.CommonRefactoringUtil; -import com.intellij.util.containers.ContainerUtil; +import com.intellij.util.NotNullProducer; import gnu.trove.THashMap; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.jetbrains.plugins.javaFX.fxml.JavaFxCommonNames; import org.jetbrains.plugins.javaFX.fxml.JavaFxFileTypeFactory; -import org.jetbrains.plugins.javaFX.fxml.refs.JavaFxIdAttributeReference; +import org.jetbrains.plugins.javaFX.fxml.refs.JavaFxComponentIdReferenceProvider; import org.jetbrains.plugins.javaFX.fxml.refs.JavaFxPropertyReference; import java.util.Map; @@ -36,9 +37,7 @@ public class JavaFxPropertyRenameHandler implements RenameHandler { @Override public boolean isAvailableOnDataContext(DataContext dataContext) { final PsiReference reference = getReference(dataContext); - if (reference instanceof JavaFxPropertyReference) return true; - if (reference instanceof JavaFxIdAttributeReference) return ((JavaFxIdAttributeReference)reference).isBuiltIn(); - return false; + return reference != null; } @Override @@ -57,24 +56,28 @@ public class JavaFxPropertyRenameHandler implements RenameHandler { } private static void performInvoke(@NotNull Project project, @Nullable Editor editor, DataContext dataContext) { - final PsiReference reference = getReference(dataContext); + PsiReference reference = getReference(dataContext); if (reference == null) return; - if (reference instanceof JavaFxIdAttributeReference && ((JavaFxIdAttributeReference)reference).isBuiltIn()) { + if (reference instanceof JavaFxComponentIdReferenceProvider.JavaFxIdReferenceBase && + ((JavaFxComponentIdReferenceProvider.JavaFxIdReferenceBase)reference).isBuiltIn()) { CommonRefactoringUtil.showErrorHint(project, editor, "Cannot rename built-in property", null, null); return; } - if ((reference instanceof JavaFxPropertyReference) && reference.resolve() != null) { + if (reference instanceof JavaFxPropertyReference && reference.resolve() != null) { final JavaFxPropertyReference propertyReference = (JavaFxPropertyReference)reference; + final Map elementsToRename = getElementsToRename(propertyReference, "a"); + final boolean cannotRename = !elementsToRename.isEmpty() && + elementsToRename.keySet().stream() + .anyMatch(element -> !PsiElementRenameHandler.canRename(project, editor, element)); + if (cannotRename) { + return; + } if (ApplicationManager.getApplication().isUnitTestMode()) { final String newName = PsiElementRenameHandler.DEFAULT_NAME.getData(dataContext); assert newName != null : "Rename property"; doRename(propertyReference, newName, false, false); return; } - final Map elementsToRename = getElementsToRename(propertyReference, "a"); - for (PsiElement element : elementsToRename.values()) { - if (!PsiElementRenameHandler.canRename(project, editor, element)) return; - } final PsiElement psiElement = JavaFxPropertyElement.fromReference(propertyReference); if (psiElement != null) { new PropertyRenameDialog(propertyReference, psiElement, project, editor).show(); @@ -88,13 +91,12 @@ public class JavaFxPropertyRenameHandler implements RenameHandler { final RenameRefactoring rename = new JavaRenameRefactoringImpl(psiElement.getProject(), psiElement, newName, searchInComments, false); rename.setPreviewUsages(isPreview); - final Map elementsToRename = getElementsToRename(reference, newName); - for (Map.Entry entry : elementsToRename.entrySet()) { - rename.addElement(entry.getValue(), entry.getKey()); - } + final Map elementsToRename = getElementsToRename(reference, newName); + elementsToRename.forEach(rename::addElement); rename.run(); } + @Nullable private static PsiReference getReference(DataContext dataContext) { final Editor editor = CommonDataKeys.EDITOR.getData(dataContext); @@ -109,23 +111,46 @@ public class JavaFxPropertyRenameHandler implements RenameHandler { if (editor != null && file instanceof XmlFile && JavaFxFileTypeFactory.isFxml(file)) { final int offset = editor.getCaretModel().getOffset(); - return file.findReferenceAt(offset); + final PsiReference reference = file.findReferenceAt(offset); + + if (reference instanceof PsiMultiReference) { + final PsiReference[] references = ((PsiMultiReference)reference).getReferences(); + for (PsiReference ref : references) { + if (isKnown(ref)) { + return ref; + } + } + } + if (isKnown(reference)) return reference; } return null; } + private static boolean isKnown(PsiReference reference) { + if (reference instanceof JavaFxPropertyReference) return true; + if (reference instanceof JavaFxComponentIdReferenceProvider.JavaFxIdReferenceBase) { + return ((JavaFxComponentIdReferenceProvider.JavaFxIdReferenceBase)reference).isBuiltIn(); + } + return false; + } + @NotNull - private static Map getElementsToRename(@NotNull JavaFxPropertyReference reference, @NotNull String newPropertyName) { - final Map rename = new THashMap<>(); - ContainerUtil.putIfNotNull(newPropertyName, reference.getField(), rename); - ContainerUtil.putIfNotNull(PropertyUtil.suggestGetterName(newPropertyName, reference.getType()), reference.getGetter(), rename); - ContainerUtil.putIfNotNull(PropertyUtil.suggestSetterName(newPropertyName), reference.getSetter(), rename); - ContainerUtil.putIfNotNull(newPropertyName + JavaFxCommonNames.PROPERTY_METHOD_SUFFIX, reference.getObservableGetter(), rename); + private static Map getElementsToRename(@NotNull JavaFxPropertyReference reference, @NotNull String newPropertyName) { + final Map rename = new THashMap<>(); + putIfKeyNotNull(rename, reference.getGetter(), () -> PropertyUtil.suggestGetterName(newPropertyName, reference.getType())); + putIfKeyNotNull(rename, reference.getField(), () -> newPropertyName); + putIfKeyNotNull(rename, reference.getSetter(), () -> PropertyUtil.suggestSetterName(newPropertyName)); + putIfKeyNotNull(rename, reference.getObservableGetter(), () -> newPropertyName + JavaFxCommonNames.PROPERTY_METHOD_SUFFIX); + putIfKeyNotNull(rename, reference.getStaticSetter(), () -> PropertyUtil.suggestSetterName(newPropertyName)); //TODO add "name" parameter of the observable property constructor (like new SimpleObjectProperty(this, "name", null); return rename; } + private static void putIfKeyNotNull(Map map, K key, NotNullProducer valueProducer) { + if (key != null) map.put(key, valueProducer.produce()); + } + private static class PropertyRenameDialog extends RenameDialog { private final JavaFxPropertyReference myPropertyReference; diff --git a/plugins/javaFX/testData/rename/StaticPropertyFromLibrary.java b/plugins/javaFX/testData/rename/StaticPropertyFromLibrary.java new file mode 100644 index 000000000000..8ca65ac0c6a9 --- /dev/null +++ b/plugins/javaFX/testData/rename/StaticPropertyFromLibrary.java @@ -0,0 +1 @@ +class StaticPropertyFromLibrary {} \ No newline at end of file diff --git a/plugins/javaFX/testData/rename/container/MyCustomContainer.java b/plugins/javaFX/testData/rename/container/MyCustomContainer.java new file mode 100644 index 000000000000..a7c288a3ac3d --- /dev/null +++ b/plugins/javaFX/testData/rename/container/MyCustomContainer.java @@ -0,0 +1,8 @@ +package container; + +import javafx.scene.Node; +import javafx.scene.layout.HBox; + +public class MyCustomContainer extends HBox { + public static void setStaticProp(Node node, String staticProp) { } +} \ No newline at end of file diff --git a/plugins/javaFX/testData/rename/propertyRenameHandlerPresentForStatic.fxml b/plugins/javaFX/testData/rename/propertyRenameHandlerPresentForStatic.fxml new file mode 100644 index 000000000000..c3841828f98e --- /dev/null +++ b/plugins/javaFX/testData/rename/propertyRenameHandlerPresentForStatic.fxml @@ -0,0 +1,5 @@ + + + +