@NotNull for RunConfigurationExtension.updateJavaParameters()

GitOrigin-RevId: 5c472044f340aeaf67f3a81695814e70e3a125f0
This commit is contained in:
Dmitry Jemerov
2019-06-13 03:31:49 +03:00
committed by intellij-monorepo-bot
parent 8f41ae3227
commit 7afa5ca0ac
279 changed files with 3786 additions and 2440 deletions
+2
View File
@@ -571,6 +571,7 @@
<module fileurl="file://$PROJECT_DIR$/platform/external-system-api/intellij.platform.externalSystem.iml" filepath="$PROJECT_DIR$/platform/external-system-api/intellij.platform.externalSystem.iml" />
<module fileurl="file://$PROJECT_DIR$/platform/external-system-impl/intellij.platform.externalSystem.impl.iml" filepath="$PROJECT_DIR$/platform/external-system-impl/intellij.platform.externalSystem.impl.iml" />
<module fileurl="file://$PROJECT_DIR$/platform/external-system-rt/intellij.platform.externalSystem.rt.iml" filepath="$PROJECT_DIR$/platform/external-system-rt/intellij.platform.externalSystem.rt.iml" />
<module fileurl="file://$PROJECT_DIR$/platform/external-system-impl/intellij.platform.externalSystem.tests.iml" filepath="$PROJECT_DIR$/platform/external-system-impl/intellij.platform.externalSystem.tests.iml" />
<module fileurl="file://$PROJECT_DIR$/platform/icons/intellij.platform.icons.iml" filepath="$PROJECT_DIR$/platform/icons/intellij.platform.icons.iml" />
<module fileurl="file://$PROJECT_DIR$/platform/platform-api/intellij.platform.ide.iml" filepath="$PROJECT_DIR$/platform/platform-api/intellij.platform.ide.iml" />
<module fileurl="file://$PROJECT_DIR$/platform/platform-impl/intellij.platform.ide.impl.iml" filepath="$PROJECT_DIR$/platform/platform-impl/intellij.platform.ide.impl.iml" />
@@ -663,6 +664,7 @@
<module fileurl="file://$PROJECT_DIR$/python/python-community-configure/intellij.python.configure.iml" filepath="$PROJECT_DIR$/python/python-community-configure/intellij.python.configure.iml" />
<module fileurl="file://$PROJECT_DIR$/python/python-copyright/intellij.python.copyright.iml" filepath="$PROJECT_DIR$/python/python-copyright/intellij.python.copyright.iml" />
<module fileurl="file://$PROJECT_DIR$/python/intellij.python.helpers.iml" filepath="$PROJECT_DIR$/python/intellij.python.helpers.iml" />
<module fileurl="file://$PROJECT_DIR$/python/helpers/tests/intellij.python.helpers.tests.iml" filepath="$PROJECT_DIR$/python/helpers/tests/intellij.python.helpers.tests.iml" />
<module fileurl="file://$PROJECT_DIR$/python/IntelliLang-python/intellij.python.langInjection.iml" filepath="$PROJECT_DIR$/python/IntelliLang-python/intellij.python.langInjection.iml" />
<module fileurl="file://$PROJECT_DIR$/python/psi-api/intellij.python.psi.iml" filepath="$PROJECT_DIR$/python/psi-api/intellij.python.psi.iml" />
<module fileurl="file://$PROJECT_DIR$/python/intellij.python.pydev.iml" filepath="$PROJECT_DIR$/python/intellij.python.pydev.iml" />
+1 -1
View File
@@ -1 +1 @@
192.SNAPSHOT
193.SNAPSHOT
+2 -3
View File
@@ -2,8 +2,7 @@
# kotlinPluginBuild format: <plugin-version>[:<channel>], e.g. 1.3.20-release-IJ2018.3-1 or 1.3.20-eap-100-IJ2018.3-1:EAP
kotlinPluginBuild=1.3.31-release-IJ2019.2-1
jetSignBuild=42.30
secondJreVersion=11
secondJreBuild=11_0_3b304.2
jdkBuild=11_0_3b304.2
bundledMavenVersion=3.6.1
jdkBuild=u212b1586.4
secondJreBuild=u212b1586.4
gradleApiVersion=5.2.1
+2 -3
View File
@@ -5,15 +5,14 @@ import java.util.concurrent.TimeUnit
task setupJbre()
def targetOs = System.getProperty("intellij.build.target.os", "all")
def jreVersion = System.getProperty("intellij.build.bundled.jre.version", "8").toInteger()
def jreVersion = System.getProperty("intellij.build.bundled.jre.version", "11").toInteger()
def jreBuild = System.getProperty("intellij.build.bundled.jre.build", jdkBuild)
def jrePrefix = System.getProperty("intellij.build.bundled.jre.prefix")
createJbreTasks(jreBuild, jreVersion, targetOs, jrePrefix)
if (System.getProperty('intellij.build.bundle.second.jre', 'false').toBoolean()) {
def secondJreBuild = System.getProperty("intellij.build.bundled.second.jre.build", secondJreBuild)
def secondJreVersion = System.getProperty("intellij.build.bundled.second.jre.version", secondJreVersion).toInteger()
createJbreTasks(secondJreBuild, secondJreVersion, targetOs)
createJbreTasks(secondJreBuild, 8, targetOs)
}
/**
+1 -1
View File
@@ -11,7 +11,7 @@ cleanSetupJdks.dependsOn('cleanSetupJdk', 'cleanSetupJdk16', 'cleanDownloadJdk')
project.ext.jdkRepo = 'https://cache-redirector.jetbrains.com/intellij-jbr'
project.ext.jdkVersion = System.getProperty('intellij.build.jdk.version', '8').toInteger()
def isModular = jdkVersion > 8
project.ext.build = isModular ? secondJreBuild : jdkBuild
project.ext.build = isModular ? jdkBuild : secondJreBuild
def setupJbrSdk = System.getProperty('intellij.build.jbr.setupSdk', 'false').toBoolean()
project.ext.jdkArtifactPrefix = isModular && !setupJbrSdk ? 'jbr-' : 'jbrsdk-'
@@ -97,9 +97,13 @@ abstract class BaseIdeaProperties extends ProductProperties {
//for compatibility with generated Ant build.xml files which refer to this file
productLayout.additionalPlatformJars.
putAll("javac2.jar", ["intellij.java.compiler.antTasks", "intellij.java.guiForms.compiler", "intellij.java.guiForms.rt", "intellij.java.compiler.instrumentationUtil", "intellij.java.compiler.instrumentationUtil.java8", "intellij.java.jps.javacRefScanner8"])
putAll("javac2.jar",
["intellij.java.compiler.antTasks", "intellij.java.guiForms.compiler", "intellij.java.guiForms.rt",
"intellij.java.compiler.instrumentationUtil", "intellij.java.compiler.instrumentationUtil.java8",
"intellij.java.jps.javacRefScanner8"])
productLayout.additionalPlatformJars.put("resources.jar", "intellij.java.ide.resources")
productLayout.additionalPlatformJars.put("external-system-rt.jar", "intellij.platform.externalSystem.rt")
productLayout.platformLayoutCustomizer = { PlatformLayout layout ->
layout.customize {
@@ -139,4 +143,4 @@ abstract class BaseIdeaProperties extends ProductProperties {
//for compatibility with users projects which refer to IDEA_HOME/lib/annotations.jar
context.ant.move(file: "$targetDirectory/lib/annotations-java5.jar", tofile: "$targetDirectory/lib/annotations.jar")
}
}
}
@@ -1,7 +1,7 @@
<component xmlns="http://jetbrains.org/intellij/schema/application-info"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://jetbrains.org/intellij/schema/application-info http://jetbrains.org/intellij/schema/ApplicationInfo.xsd">
<version major="2019" minor="2" eap="true" suffix="Snapshot"/>
<version major="2019" minor="3" eap="true" suffix="Snapshot"/>
<company name="JetBrains s.r.o." url="https://www.jetbrains.com"/>
<build number="IC-__BUILD__" date="__BUILD_DATE__"/>
<logo url="/idea_community_logo.png" textcolor="ffffff" progressColor="ffffff" progressX="117" progressY="280" progressHeight="3" />
@@ -30,6 +30,7 @@
<orderEntry type="library" name="protobuf" level="project" />
<orderEntry type="library" name="netty-codec-http" level="project" />
<orderEntry type="module" module-name="intellij.platform.vcs.impl" />
<orderEntry type="module" module-name="intellij.platform.externalSystem" />
</component>
<component name="copyright">
<Base>
@@ -1,10 +1,11 @@
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.openapi.externalSystem.service.project.settings
import com.intellij.execution.BeforeRunTask
import com.intellij.execution.BeforeRunTaskProvider
import com.intellij.execution.configurations.RunConfiguration
import com.intellij.openapi.externalSystem.model.project.settings.ConfigurationData
import com.intellij.openapi.externalSystem.project.PackagingModifiableModel
import com.intellij.openapi.externalSystem.service.project.IdeModifiableModelsProvider
import com.intellij.openapi.module.Module
import com.intellij.openapi.module.ModuleManager
@@ -30,7 +31,8 @@ class ArtifactsImporter: ConfigurationHandler {
return
}
val modifiableModel = modelsProvider.modifiableArtifactModel
val packagingModifiableModel = modelsProvider.getModifiableModel(PackagingModifiableModel::class.java)
val modifiableModel = packagingModifiableModel.modifiableArtifactModel
val postponedOps: MutableList<(ModifiableArtifactModel) -> Unit> = mutableListOf()
artifacts.forEach { value ->
@@ -11,6 +11,7 @@
<orderEntry type="module" module-name="intellij.platform.projectModel.impl" />
<orderEntry type="library" name="JDOM" level="project" />
<orderEntry type="module" module-name="intellij.platform.util.ui" />
<orderEntry type="module" module-name="intellij.platform.externalSystem" />
</component>
<component name="copyright">
<Base>
@@ -1,19 +1,5 @@
/*
* Copyright 2000-2015 JetBrains s.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.externalSystem.service.project;
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.openapi.externalSystem.project;
import com.intellij.packaging.artifacts.Artifact;
import com.intellij.packaging.artifacts.ModifiableArtifactModel;
@@ -0,0 +1,17 @@
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.openapi.externalSystem.project;
import com.intellij.openapi.externalSystem.service.project.ModifiableModel;
import com.intellij.packaging.artifacts.ModifiableArtifactModel;
import com.intellij.packaging.elements.PackagingElementResolvingContext;
import org.jetbrains.annotations.NotNull;
public interface PackagingModifiableModel extends ModifiableModel {
@NotNull
ModifiableArtifactModel getModifiableArtifactModel();
@NotNull
PackagingElementResolvingContext getPackagingElementResolvingContext();
ArtifactExternalDependenciesImporter getArtifactExternalDependenciesImporter();
}
@@ -22,6 +22,7 @@
<orderEntry type="library" name="intellij-test-discovery" level="project" />
<orderEntry type="library" scope="RUNTIME" name="precompiled_jshell-frontend" level="project" />
<orderEntry type="module" module-name="intellij.platform.externalSystem" />
<orderEntry type="module" module-name="intellij.platform.externalSystem.impl" />
<orderEntry type="library" name="gson" level="project" />
<orderEntry type="library" name="jackson" level="project" />
<orderEntry type="library" name="miglayout-swing" level="project" />
@@ -0,0 +1,77 @@
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.execution;
import com.intellij.execution.configurations.*;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.externalSystem.service.execution.ExternalSystemProcessHandler;
import com.intellij.openapi.externalSystem.service.execution.ExternalSystemRunConfiguration;
import com.intellij.openapi.externalSystem.service.execution.ExternalSystemRunConfigurationExtension;
import com.intellij.openapi.options.SettingsEditorGroup;
import org.jdom.Element;
import org.jetbrains.annotations.ApiStatus;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
@ApiStatus.Experimental
public class ExternalSystemRunConfigurationJavaExtension implements ExternalSystemRunConfigurationExtension {
private static final Logger LOG = Logger.getInstance(ExternalSystemRunConfigurationJavaExtension.class);
@Override
public void readExternal(@NotNull ExternalSystemRunConfiguration configuration, @NotNull Element element) {
JavaRunConfigurationExtensionManager javaRunConfigurationExtensionManager = JavaRunConfigurationExtensionManager.getInstanceOrNull();
if (javaRunConfigurationExtensionManager != null) {
javaRunConfigurationExtensionManager.readExternal(configuration, element);
}
}
@Override
public void writeExternal(@NotNull ExternalSystemRunConfiguration configuration, @NotNull Element element) {
JavaRunConfigurationExtensionManager javaRunConfigurationExtensionManager = JavaRunConfigurationExtensionManager.getInstanceOrNull();
if (javaRunConfigurationExtensionManager != null) {
javaRunConfigurationExtensionManager.writeExternal(configuration, element);
}
}
@Override
public void appendEditors(@NotNull ExternalSystemRunConfiguration configuration,
@NotNull SettingsEditorGroup<ExternalSystemRunConfiguration> group) {
JavaRunConfigurationExtensionManager javaRunConfigurationExtensionManager = JavaRunConfigurationExtensionManager.getInstanceOrNull();
if (javaRunConfigurationExtensionManager != null) {
javaRunConfigurationExtensionManager.appendEditors(configuration, group);
}
}
@Override
public void attachToProcess(@NotNull ExternalSystemRunConfiguration configuration,
@NotNull ExternalSystemProcessHandler processHandler,
@Nullable RunnerSettings settings) {
JavaRunConfigurationExtensionManager javaRunConfigurationExtensionManager = JavaRunConfigurationExtensionManager.getInstanceOrNull();
if (javaRunConfigurationExtensionManager != null) {
javaRunConfigurationExtensionManager.attachExtensionsToProcess(configuration, processHandler, settings);
}
}
@Override
public void updateVMParameters(@NotNull ExternalSystemRunConfiguration configuration,
@NotNull SimpleJavaParameters javaParameters,
@Nullable RunnerSettings settings,
@NotNull Executor executor) {
final JavaParameters extensionsJP = new JavaParameters();
for (RunConfigurationExtension ext : RunConfigurationExtension.EP_NAME.getExtensionList()) {
try {
ext.updateJavaParameters(configuration, extensionsJP, settings, executor);
}
catch (ExecutionException e) {
LOG.error(e);
}
}
copy(extensionsJP.getVMParametersList(), javaParameters.getVMParametersList());
}
private static void copy(@NotNull ParametersList from, @NotNull ParametersList to) {
to.addAll(from.getParameters());
for (ParamsGroup group : from.getParamsGroups()) {
to.addParamsGroup(group);
}
}
}
@@ -19,14 +19,15 @@ public abstract class RunConfigurationExtension extends RunConfigurationExtensio
new ExtensionPointName<>("com.intellij.runConfigurationExtension");
@ApiStatus.Experimental
public <T extends RunConfigurationBase> void updateJavaParameters(final T configuration,
final JavaParameters params,
public <T extends RunConfigurationBase> void updateJavaParameters(@NotNull final T configuration,
@NotNull final JavaParameters params,
RunnerSettings runnerSettings,
@NotNull final Executor executor) throws ExecutionException {
updateJavaParameters(configuration,params,runnerSettings);
updateJavaParameters(configuration, params, runnerSettings);
}
public abstract <T extends RunConfigurationBase> void updateJavaParameters(final T configuration, final JavaParameters params, RunnerSettings runnerSettings) throws ExecutionException;
public abstract <T extends RunConfigurationBase> void updateJavaParameters(@NotNull final T configuration,
@NotNull final JavaParameters params, RunnerSettings runnerSettings) throws ExecutionException;
@Override
protected void patchCommandLine(@NotNull RunConfigurationBase configuration,
@@ -18,14 +18,14 @@ import org.jetbrains.annotations.NotNull;
* @author nik
*/
public abstract class BaseJavaApplicationCommandLineState<T extends RunConfigurationBase&CommonJavaRunConfigurationParameters> extends JavaCommandLineState {
protected final T myConfiguration;
@NotNull protected final T myConfiguration;
public BaseJavaApplicationCommandLineState(ExecutionEnvironment environment, @NotNull final T configuration) {
super(environment);
myConfiguration = configuration;
}
protected void setupJavaParameters(JavaParameters params) throws ExecutionException {
protected void setupJavaParameters(@NotNull JavaParameters params) throws ExecutionException {
JavaParametersUtil.configureConfiguration(params, myConfiguration);
for (RunConfigurationExtension ext : RunConfigurationExtension.EP_NAME.getExtensionList()) {
@@ -53,6 +53,7 @@ public abstract class BaseJavaApplicationCommandLineState<T extends RunConfigura
return super.createCommandLine().withInput(InputRedirectAware.getInputFile(myConfiguration));
}
@NotNull
protected T getConfiguration() {
return myConfiguration;
}
@@ -81,7 +81,7 @@ public class JavaScratchConfiguration extends ApplicationConfiguration {
}
@Override
protected void setupJavaParameters(JavaParameters params) throws ExecutionException {
protected void setupJavaParameters(@NotNull JavaParameters params) throws ExecutionException {
super.setupJavaParameters(params);
final File scrachesOutput = JavaScratchCompilationSupport.getScratchOutputDirectory(getProject());
if (scrachesOutput != null) {
@@ -75,7 +75,7 @@ public class TestDiscoveryExtension extends RunConfigurationExtension {
}
@Override
public void updateJavaParameters(RunConfigurationBase configuration, JavaParameters params, RunnerSettings runnerSettings) {
public void updateJavaParameters(@NotNull RunConfigurationBase configuration, @NotNull JavaParameters params, RunnerSettings runnerSettings) {
if (runnerSettings != null || !isApplicableFor(configuration)) {
return;
}
@@ -45,16 +45,6 @@
</xi:include>
<xi:include href="/META-INF/coverage-common-plugin.xml" xpointer="xpointer(/idea-plugin/*)"/>
<module value="com.intellij.modules.externalSystem"/>
<xi:include href="/componentSets/ExternalSystemComponents.xml" xpointer="xpointer(/idea-plugin/*)"/>
<extensionPoints>
<xi:include href="/META-INF/ExternalSystemExtensionPoints.xml" xpointer="xpointer(/idea-plugin/extensionPoints/*)"/>
</extensionPoints>
<extensions defaultExtensionNs="com.intellij">
<xi:include href="/META-INF/ExternalSystemExtensions.xml" xpointer="xpointer(/idea-plugin/extensions/*)"/>
</extensions>
<xi:include href="/idea/ExternalSystemActions.xml" xpointer="xpointer(/idea-plugin/*)"/>
<extensions defaultExtensionNs="com.intellij">
<applicationInitializedListener implementation="com.intellij.internal.statistic.updater.StatisticsJobsScheduler"/>
@@ -161,5 +151,10 @@
<action id="ConsoleView.FoldLinesLikeThis" class="com.intellij.execution.console.FoldLinesLikeThis" text="Fold Lines Like This">
<add-to-group group-id="ConsoleEditorPopupMenu" anchor="after" relative-to-action="$SearchWeb"/>
</action>
<action id="ExternalSystem.AttachProject"
class="com.intellij.openapi.externalSystem.action.AttachExternalProjectAction">
<add-to-group group-id="ExternalSystemView.ActionsToolbar.LeftPanel" anchor="after" relative-to-action="ExternalSystem.RefreshAllProjects"/>
</action>
</actions>
</idea-plugin>
+2
View File
@@ -16,5 +16,7 @@
<orderEntry type="module" module-name="intellij.platform.vcs.impl" />
<orderEntry type="library" name="Guava" level="project" />
<orderEntry type="library" name="jna" level="project" />
<orderEntry type="module" module-name="intellij.platform.externalSystem" />
<orderEntry type="module" module-name="intellij.platform.externalSystem.impl" />
</component>
</module>
@@ -31,12 +31,6 @@ public class AttachExternalProjectAction extends AnAction {
@Override
public void update(@NotNull AnActionEvent e) {
Presentation presentation = e.getPresentation();
// todo [Vlad, IDEA-187835]: provide java subsystem independent implementation
if (!ExternalSystemApiUtil.isJavaCompatibleIde()) {
presentation.setEnabledAndVisible(false);
return;
}
ProjectSystemId externalSystemId = e.getData(ExternalSystemDataKeys.EXTERNAL_SYSTEM_ID);
if (externalSystemId != null) {
String name = externalSystemId.getReadableName();
@@ -15,6 +15,7 @@
*/
package com.intellij.openapi.externalSystem.service.project;
import com.intellij.openapi.externalSystem.project.ArtifactExternalDependenciesImporter;
import com.intellij.openapi.roots.ui.configuration.artifacts.ManifestFilesInfo;
import com.intellij.openapi.util.Pair;
import com.intellij.packaging.artifacts.Artifact;
@@ -1,25 +1,12 @@
/*
* Copyright 2000-2017 JetBrains s.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.externalSystem.service.project.manage;
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.openapi.externalSystem.service.project;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.externalSystem.ExternalSystemManager;
import com.intellij.openapi.externalSystem.ExternalSystemModulePropertyManager;
import com.intellij.openapi.externalSystem.model.ProjectSystemId;
import com.intellij.openapi.externalSystem.service.project.manage.ExternalProjectsManagerImpl;
import com.intellij.openapi.externalSystem.settings.AbstractExternalSystemSettings;
import com.intellij.openapi.externalSystem.settings.ExternalProjectSettings;
import com.intellij.openapi.externalSystem.util.ExternalSystemApiUtil;
@@ -46,7 +33,6 @@ import java.util.Map;
public class ExternalModuleStructureExtension extends ModuleStructureExtension {
private static final Logger LOG = Logger.getInstance(ExternalModuleStructureExtension.class);
@SuppressWarnings("StatefulEp")
@Nullable
private Project myProject;
private boolean isExternalSystemsInvolved;
@@ -1,22 +1,9 @@
/*
* Copyright 2000-2009 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.openapi.externalSystem.service.project;
import com.intellij.facet.ModifiableFacetModel;
import com.intellij.openapi.application.ModalityState;
import com.intellij.openapi.externalSystem.service.project.manage.ProjectStructureUIModifiableModelsProvider;
import com.intellij.openapi.module.ModifiableModuleModel;
import com.intellij.openapi.module.Module;
import com.intellij.openapi.project.Project;
@@ -29,7 +16,8 @@ import com.intellij.openapi.roots.ui.configuration.projectRoot.ProjectLibrariesC
import com.intellij.packaging.artifacts.ModifiableArtifactModel;
import org.jetbrains.annotations.NotNull;
public class IdeUIModifiableModelsProvider extends AbstractIdeModifiableModelsProvider {
public class IdeUIModifiableModelsProvider extends AbstractIdeModifiableModelsProvider implements
ProjectStructureUIModifiableModelsProvider {
private final ModifiableModuleModel myModel;
private final ModulesConfigurator myModulesConfigurator;
private final ModifiableArtifactModel myModifiableArtifactModel;
@@ -54,8 +42,7 @@ public class IdeUIModifiableModelsProvider extends AbstractIdeModifiableModelsPr
return myLibrariesModel;
}
@Override
protected ModifiableArtifactModel doGetModifiableArtifactModel() {
public ModifiableArtifactModel getModifiableArtifactModel() {
return myModifiableArtifactModel;
}
@@ -81,7 +68,6 @@ public class IdeUIModifiableModelsProvider extends AbstractIdeModifiableModelsPr
@Override
public void commit() {
processExternalArtifactDependencies();
}
@Override
@@ -0,0 +1,276 @@
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.openapi.externalSystem.service.project;
import com.intellij.facet.Facet;
import com.intellij.facet.FacetModel;
import com.intellij.facet.FacetTypeId;
import com.intellij.openapi.application.ReadAction;
import com.intellij.openapi.externalSystem.project.ArtifactExternalDependenciesImporter;
import com.intellij.openapi.externalSystem.project.PackagingModifiableModel;
import com.intellij.openapi.module.Module;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.roots.ModuleRootModel;
import com.intellij.openapi.roots.ProjectModelExternalSource;
import com.intellij.openapi.roots.libraries.Library;
import com.intellij.openapi.roots.libraries.LibraryTable;
import com.intellij.openapi.roots.libraries.LibraryTablesRegistrar;
import com.intellij.openapi.roots.ui.configuration.FacetsProvider;
import com.intellij.openapi.roots.ui.configuration.ModulesProvider;
import com.intellij.packaging.artifacts.*;
import com.intellij.packaging.elements.CompositePackagingElement;
import com.intellij.packaging.elements.ManifestFileProvider;
import com.intellij.packaging.elements.PackagingElementResolvingContext;
import com.intellij.packaging.impl.artifacts.DefaultManifestFileProvider;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.Collection;
import java.util.List;
public class PackagingModifiableModelImpl implements PackagingModifiableModel {
private final Project myProject;
private final IdeModifiableModelsProvider myModelsProvider;
private ModifiableArtifactModel myModifiableArtifactModel;
private MyPackagingElementResolvingContext myPackagingElementResolvingContext;
private final ArtifactExternalDependenciesImporter myArtifactExternalDependenciesImporter;
public PackagingModifiableModelImpl(@NotNull Project project, @NotNull IdeModifiableModelsProvider modifiableModelsProvider) {
myProject = project;
myModelsProvider = modifiableModelsProvider;
myArtifactExternalDependenciesImporter = new ArtifactExternalDependenciesImporterImpl();
}
@Override
@NotNull
public ModifiableArtifactModel getModifiableArtifactModel() {
if (myModifiableArtifactModel == null) {
myModifiableArtifactModel = myModelsProvider instanceof IdeUIModifiableModelsProvider
?
((IdeUIModifiableModelsProvider)myModelsProvider).getModifiableArtifactModel()
: doGetModifiableArtifactModel();
}
return myModifiableArtifactModel;
}
private ModifiableArtifactModel doGetModifiableArtifactModel() {
return ReadAction.compute(() -> {
ArtifactManager artifactManager = ArtifactManager.getInstance(myProject);
return artifactManager != null ? artifactManager.createModifiableModel() : new DummyArtifactModel();
});
}
@NotNull
@Override
public PackagingElementResolvingContext getPackagingElementResolvingContext() {
if (myPackagingElementResolvingContext == null) {
myPackagingElementResolvingContext = new MyPackagingElementResolvingContext();
}
return myPackagingElementResolvingContext;
}
@Override
public ArtifactExternalDependenciesImporter getArtifactExternalDependenciesImporter() {
return myArtifactExternalDependenciesImporter;
}
@Override
public void commit() {
myArtifactExternalDependenciesImporter.applyChanges(getModifiableArtifactModel(), getPackagingElementResolvingContext());
if (myModifiableArtifactModel != null) {
myModifiableArtifactModel.commit();
}
}
@Override
public void dispose() {
if (myModifiableArtifactModel != null) {
myModifiableArtifactModel.dispose();
}
}
private class MyPackagingElementResolvingContext implements PackagingElementResolvingContext {
private final ModulesProvider myModulesProvider = new MyModulesProvider();
private final MyFacetsProvider myFacetsProvider = new MyFacetsProvider();
private final ManifestFileProvider myManifestFileProvider = new DefaultManifestFileProvider(this);
@Override
@NotNull
public Project getProject() {
return myProject;
}
@Override
@NotNull
public ArtifactModel getArtifactModel() {
return PackagingModifiableModelImpl.this.getModifiableArtifactModel();
}
@Override
@NotNull
public ModulesProvider getModulesProvider() {
return myModulesProvider;
}
@Override
@NotNull
public FacetsProvider getFacetsProvider() {
return myFacetsProvider;
}
@Override
public Library findLibrary(@NotNull String level, @NotNull String libraryName) {
if (level.equals(LibraryTablesRegistrar.PROJECT_LEVEL)) {
return myModelsProvider.getLibraryByName(libraryName);
}
final LibraryTable table = LibraryTablesRegistrar.getInstance().getLibraryTableByLevel(level, myProject);
return table != null ? table.getLibraryByName(libraryName) : null;
}
@NotNull
@Override
public ManifestFileProvider getManifestFileProvider() {
return myManifestFileProvider;
}
}
private class MyModulesProvider implements ModulesProvider {
@Override
@NotNull
public Module[] getModules() {
return myModelsProvider.getModules();
}
@Override
public Module getModule(@NotNull String name) {
return myModelsProvider.findIdeModule(name);
}
@Override
public ModuleRootModel getRootModel(@NotNull Module module) {
return myModelsProvider.getModifiableRootModel(module);
}
@NotNull
@Override
public FacetModel getFacetModel(@NotNull Module module) {
return myModelsProvider.getModifiableFacetModel(module);
}
}
private class MyFacetsProvider implements FacetsProvider {
@Override
@NotNull
public Facet[] getAllFacets(Module module) {
return myModelsProvider.getModifiableFacetModel(module).getAllFacets();
}
@Override
@NotNull
public <F extends Facet> Collection<F> getFacetsByType(Module module, FacetTypeId<F> type) {
return myModelsProvider.getModifiableFacetModel(module).getFacetsByType(type);
}
@Override
public <F extends Facet> F findFacet(Module module, FacetTypeId<F> type, String name) {
return myModelsProvider.getModifiableFacetModel(module).findFacet(type, name);
}
}
private static class DummyArtifactModel implements ModifiableArtifactModel {
@NotNull
@Override
public ModifiableArtifact addArtifact(@NotNull String name, @NotNull ArtifactType artifactType) {
throw new UnsupportedOperationException();
}
@NotNull
@Override
public ModifiableArtifact addArtifact(@NotNull String name,
@NotNull ArtifactType artifactType,
CompositePackagingElement<?> rootElement) {
throw new UnsupportedOperationException();
}
@NotNull
@Override
public ModifiableArtifact addArtifact(@NotNull String name,
@NotNull ArtifactType artifactType,
CompositePackagingElement<?> rootElement,
@Nullable ProjectModelExternalSource externalSource) {
throw new UnsupportedOperationException();
}
@Override
public void removeArtifact(@NotNull Artifact artifact) {
}
@NotNull
@Override
public ModifiableArtifact getOrCreateModifiableArtifact(@NotNull Artifact artifact) {
throw new UnsupportedOperationException();
}
@Nullable
@Override
public Artifact getModifiableCopy(Artifact artifact) {
return null;
}
@Override
public void addListener(@NotNull ArtifactListener listener) {
}
@Override
public void removeListener(@NotNull ArtifactListener listener) {
}
@Override
public boolean isModified() {
return false;
}
@Override
public void commit() {
}
@Override
public void dispose() {
}
@NotNull
@Override
public Artifact[] getArtifacts() {
return new Artifact[0];
}
@Nullable
@Override
public Artifact findArtifact(@NotNull String name) {
return null;
}
@NotNull
@Override
public Artifact getArtifactByOriginal(@NotNull Artifact artifact) {
throw new UnsupportedOperationException();
}
@NotNull
@Override
public Artifact getOriginalArtifact(@NotNull Artifact artifact) {
throw new UnsupportedOperationException();
}
@NotNull
@Override
public Collection<? extends Artifact> getArtifactsByType(@NotNull ArtifactType type) {
throw new UnsupportedOperationException();
}
@Override
public List<? extends Artifact> getAllArtifactsIncludingInvalid() {
throw new UnsupportedOperationException();
}
}
}
@@ -0,0 +1,19 @@
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.openapi.externalSystem.service.project;
import com.intellij.openapi.externalSystem.project.PackagingModifiableModel;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.Pair;
import org.jetbrains.annotations.ApiStatus;
import org.jetbrains.annotations.NotNull;
@ApiStatus.Experimental
public class PackagingModifiableModelProvider implements ModifiableModelsProviderExtension<PackagingModifiableModel> {
@NotNull
@Override
public Pair<Class<PackagingModifiableModel>, PackagingModifiableModel> create(@NotNull Project project,
@NotNull IdeModifiableModelsProvider modelsProvider) {
return Pair.create(PackagingModifiableModel.class, new PackagingModifiableModelImpl(project, modelsProvider));
}
}
@@ -47,8 +47,16 @@ public class TestOnlyInspection extends AbstractBaseJavaLocalInspectionTool {
public PsiElementVisitor buildVisitor(@NotNull final ProblemsHolder h, boolean isOnTheFly) {
return new JavaElementVisitor() {
@Override
public void visitCallExpression(PsiCallExpression e) {
validate(e, e.resolveMethod(), h);
public void visitMethodCallExpression(PsiMethodCallExpression expression) {
validate(expression.getMethodExpression(), expression.resolveMethod(), h);
}
@Override
public void visitNewExpression(PsiNewExpression expression) {
PsiJavaCodeReferenceElement reference = expression.getClassOrAnonymousClassReference();
if (reference != null) {
validate(reference, expression.resolveMethod(), h);
}
}
@Override
@@ -80,12 +88,12 @@ public class TestOnlyInspection extends AbstractBaseJavaLocalInspectionTool {
};
}
private static void validate(@NotNull PsiElement reference, @Nullable PsiMember member, ProblemsHolder h) {
private static void validate(@NotNull PsiElement place, @Nullable PsiMember member, ProblemsHolder h) {
if (member == null || !isAnnotatedAsTestOnly(member)) return;
if (isInsideTestOnlyMethod(reference)) return;
if (isInsideTestOnlyField(reference)) return;
if (isInsideTestClass(reference)) return;
if (isUnderTestSources(reference)) return;
if (isInsideTestOnlyMethod(place)) return;
if (isInsideTestOnlyField(place)) return;
if (isInsideTestClass(place)) return;
if (isUnderTestSources(place)) return;
PsiAnnotation anno = findVisibleForTestingAnnotation(member);
if (anno != null) {
@@ -95,12 +103,12 @@ public class TestOnlyInspection extends AbstractBaseJavaLocalInspectionTool {
}
LightModifierList modList = new LightModifierList(member.getManager(), JavaLanguage.INSTANCE, modifier);
if (JavaResolveUtil.isAccessible(member, member.getContainingClass(), modList, reference, null, null)) {
if (JavaResolveUtil.isAccessible(member, member.getContainingClass(), modList, place, null, null)) {
return;
}
}
reportProblem(reference, member, h);
reportProblem(place, member, h);
}
private static final List<String> ourModifiersDescending =
@@ -199,7 +199,7 @@ make.final.family=Make Final
make.final.text=Make {0} final
make.final.copy.to.temp=Copy ''{0}'' to {1} temp variable
make.final.transform.to.one.element.array=Transform {0} into final one element array
fix.variable.type.family=Fix Variable Type
fix.variable.type.family=Fix variable type
fix.variable.type.text=Change {0} ''{1}'' type to ''{2}''
# Sample: Boolean b = "true"; -> Boolean b = Boolean.valueOf("true");
+1
View File
@@ -62,6 +62,7 @@
<orderEntry type="library" name="javax.activation" level="project" />
<orderEntry type="library" scope="RUNTIME" name="jaxb-runtime" level="project" />
<orderEntry type="module" module-name="intellij.platform.objectSerializer.annotations" />
<orderEntry type="module" module-name="intellij.platform.externalSystem.impl" />
</component>
<component name="copyright">
<Base>
@@ -547,6 +547,15 @@
<stepsBeforeRunProvider implementation="com.intellij.packaging.impl.run.BuildArtifactsBeforeRunTaskProvider"
order="after compileBeforeRunNoErrorCheck"/>
<externalSystem.beforeRunTaskImporter implementation="com.intellij.compiler.options.CompileStepBeforeRunImporter"/>
<externalSystemConfigurationHandler
implementation="com.intellij.openapi.externalSystem.service.project.settings.CompilerConfigurationHandler"/>
<externalSystemConfigurationHandler implementation="com.intellij.openapi.externalSystem.service.project.settings.ArtifactsImporter"/>
<externalSystem.moduleDataServiceExtension implementation="com.intellij.openapi.externalSystem.service.project.ModuleDataServiceJavaExtension"/>
<externalSystem.runConfigurationExtension implementation="com.intellij.execution.ExternalSystemRunConfigurationJavaExtension"/>
<applicationService serviceInterface="com.intellij.openapi.externalSystem.service.execution.ExternalSystemJdkProvider"
serviceImplementation="com.intellij.openapi.externalSystem.service.execution.ExternalSystemJavaSdkProvider"
overrides="true"/>
<programRunner implementation="com.intellij.openapi.externalSystem.service.execution.ExternalSystemTaskDebugRunner"/>
<programRunner id="defaultRunRunner" implementation="com.intellij.execution.impl.DefaultJavaProgramRunner"/>
@@ -657,6 +666,9 @@
<externalSystem.runConfigurationImporter implementation="com.intellij.execution.application.JavaApplicationRunConfigurationImporter"/>
<externalSystem.runConfigurationImporter implementation="com.intellij.execution.remote.JavaRemoteDebugRunConfigurationImporter"/>
<externalSystem.modifiableModelsProvider implementation="com.intellij.openapi.externalSystem.service.project.PackagingModifiableModelProvider"/>
<configuration.ModuleStructureExtension
implementation="com.intellij.openapi.externalSystem.service.project.ExternalModuleStructureExtension"/>
<runLineMarkerContributor language="JVM"
order="before applicationRunLineMarkerProvider"
@@ -16,6 +16,7 @@ import com.intellij.psi.search.GlobalSearchScope;
import com.intellij.psi.util.CachedValueProvider;
import com.intellij.psi.util.CachedValuesManager;
import com.intellij.psi.util.PsiModificationTracker;
import com.intellij.psi.util.PsiUtilCore;
import com.intellij.util.containers.ContainerUtil;
import gnu.trove.THashSet;
import org.jdom.Element;
@@ -238,14 +239,15 @@ public class NullableNotNullManagerImpl extends NullableNotNullManager implement
if (modifierList == null) return null;
for (PsiAnnotation annotation : modifierList.getAnnotations()) {
if (container instanceof PsiPackage) {
PsiFile file = annotation.getContainingFile();
ProjectFileIndex index = ProjectRootManager.getInstance(file.getProject()).getFileIndex();
VirtualFile annotationFile = file.getVirtualFile();
VirtualFile annotationRoot = annotationFile == null ? null : index.getClassRootForFile(annotationFile);
VirtualFile ownerFile = owner.getContainingFile().getVirtualFile();
VirtualFile ownerRoot = ownerFile == null ? null : index.getClassRootForFile(ownerFile);
if (ownerRoot != null && !ownerRoot.equals(annotationRoot)) {
continue;
VirtualFile annotationFile = PsiUtilCore.getVirtualFile(annotation);
VirtualFile ownerFile = PsiUtilCore.getVirtualFile(owner);
if (annotationFile != null && ownerFile != null && !annotationFile.equals(ownerFile)) {
ProjectFileIndex index = ProjectRootManager.getInstance(container.getProject()).getFileIndex();
VirtualFile annotationRoot = index.getClassRootForFile(annotationFile);
VirtualFile ownerRoot = index.getClassRootForFile(ownerFile);
if (ownerRoot != null && !ownerRoot.equals(annotationRoot)) {
continue;
}
}
}
NullabilityAnnotationInfo result = checkNullityDefault(annotation, placeTargetTypes, superPackage);
@@ -39,7 +39,7 @@ public class IterateOverIterableIntention implements IntentionAction {
@Override
public boolean isAvailable(@NotNull Project project, Editor editor, PsiFile file) {
final TemplateImpl template = getTemplate();
final TemplateImpl template = file instanceof PsiJavaFile ? getTemplate() : null;
if (template != null) {
int offset = editor.getCaretModel().getOffset();
int startOffset = offset;
@@ -46,7 +46,7 @@ public class VariableTypeFix extends LocalQuickFixAndIntentionActionOnPsiElement
private final PsiType myReturnType;
protected final String myName;
public VariableTypeFix(@NotNull PsiVariable variable, PsiType toReturn) {
public VariableTypeFix(@NotNull PsiVariable variable, @NotNull PsiType toReturn) {
super(variable);
myReturnType = GenericsUtil.getVariableTypeByExpressionType(toReturn);
myName = variable.getName();
@@ -15,9 +15,15 @@
*/
package com.intellij.codeInsight.editorActions;
import com.intellij.codeInsight.CodeInsightBundle;
import com.intellij.codeInsight.CodeInsightSettings;
import com.intellij.codeInsight.daemon.impl.CollectHighlightsUtil;
import com.intellij.codeInsight.hint.HintManager;
import com.intellij.codeInsight.hint.HintManagerImpl;
import com.intellij.codeInsight.hint.HintUtil;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.application.ModalityState;
import com.intellij.openapi.command.WriteCommandAction;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.editor.Document;
import com.intellij.openapi.editor.Editor;
@@ -29,18 +35,19 @@ import com.intellij.openapi.util.Ref;
import com.intellij.openapi.util.TextRange;
import com.intellij.psi.*;
import com.intellij.psi.util.PsiUtilCore;
import com.intellij.ui.LightweightHint;
import com.intellij.util.ArrayUtil;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import javax.swing.event.HyperlinkEvent;
import javax.swing.event.HyperlinkListener;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.Transferable;
import java.awt.datatransfer.UnsupportedFlavorException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.*;
import java.util.stream.Collectors;
public abstract class CopyPasteReferenceProcessor<TRef extends PsiElement> extends CopyPastePostProcessor<ReferenceTransferableData> {
private static final Logger LOG = Logger.getInstance("#com.intellij.codeInsight.editorActions.CopyPasteReferenceProcessor");
@@ -121,7 +128,35 @@ public abstract class CopyPasteReferenceProcessor<TRef extends PsiElement> exten
askReferencesToRestore(project, refs, referenceData);
}
PsiDocumentManager.getInstance(project).commitAllDocuments();
ApplicationManager.getApplication().runWriteAction(() -> restoreReferences(referenceData, refs));
ApplicationManager.getApplication().runWriteAction(() -> {
Set<String> imported = new TreeSet<>();
restoreReferences(referenceData, refs, imported);
if (CodeInsightSettings.getInstance().ADD_IMPORTS_ON_PASTE == CodeInsightSettings.YES && !imported.isEmpty()) {
String notificationText = CodeInsightBundle.message("copy.paste.reference.notification", imported.size());
ApplicationManager.getApplication().invokeLater(
() -> showHint(editor, notificationText, e -> {
if (e.getEventType() == HyperlinkEvent.EventType.ACTIVATED) {
reviewImports(project, file, imported);
}
}), ModalityState.NON_MODAL);
}
});
}
protected abstract void removeImports(PsiFile file, Set<String> imports);
private void reviewImports(Project project, PsiFile file, Set<String> importedClasses) {
RestoreReferencesDialog dialog = new RestoreReferencesDialog(project, ArrayUtil.toObjectArray(importedClasses), false);
dialog.setTitle(CodeInsightBundle.message("dialog.import.on.paste.title3"));
dialog.setExplanation(CodeInsightBundle.message("dialog.paste.on.import.text3"));
if (dialog.showAndGet()) {
Object[] selectedElements = dialog.getSelectedElements();
if (selectedElements.length > 0) {
WriteCommandAction.runWriteCommandAction(project, "", null, () -> {
removeImports(file, Arrays.stream(selectedElements).map(o -> (String)o).collect(Collectors.toSet()));
});
}
}
}
protected static void addReferenceData(final PsiElement element,
@@ -138,8 +173,8 @@ public abstract class CopyPasteReferenceProcessor<TRef extends PsiElement> exten
@NotNull
protected abstract TRef[] findReferencesToRestore(PsiFile file,
RangeMarker bounds,
ReferenceData[] referenceData);
RangeMarker bounds,
ReferenceData[] referenceData);
protected PsiElement resolveReferenceIgnoreOverriding(PsiPolyVariantReference reference) {
PsiElement referent = reference.resolve();
@@ -153,7 +188,8 @@ public abstract class CopyPasteReferenceProcessor<TRef extends PsiElement> exten
}
protected abstract void restoreReferences(ReferenceData[] referenceData,
TRef[] refs);
TRef[] refs,
Set<String> imported);
private static void askReferencesToRestore(Project project, @NotNull PsiElement[] refs,
ReferenceData[] referenceData) {
@@ -209,6 +245,14 @@ public abstract class CopyPasteReferenceProcessor<TRef extends PsiElement> exten
}
}
private static void showHint(@NotNull Editor editor, @NotNull String info, HyperlinkListener hyperlinkListener) {
if (ApplicationManager.getApplication().isUnitTestMode()) return;
LightweightHint hint = new LightweightHint(HintUtil.createInformationLabel(info, hyperlinkListener, null, null));
int flags = HintManager.HIDE_BY_ANY_KEY | HintManager.HIDE_BY_TEXT_CHANGE;
HintManagerImpl.getInstanceImpl().showEditorHint(hint, editor, HintManager.UNDER, flags, 0, false);
}
private static String getFQName(Object element) {
return element instanceof PsiClass ? ((PsiClass)element).getQualifiedName() : (String)element;
}
@@ -20,12 +20,17 @@ import com.intellij.codeInsight.daemon.impl.quickfix.ImportClassFixBase;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.editor.RangeMarker;
import com.intellij.openapi.util.TextRange;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.psi.*;
import com.intellij.psi.codeStyle.JavaCodeStyleSettings;
import com.intellij.psi.impl.source.codeStyle.ImportHelper;
import com.intellij.util.IncorrectOperationException;
import com.intellij.util.ObjectUtils;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.ArrayList;
import java.util.Set;
/**
* @author peter
@@ -59,6 +64,25 @@ public class JavaCopyPasteReferenceProcessor extends CopyPasteReferenceProcessor
}
}
@Override
protected void removeImports(PsiFile file, Set<String> imports) {
removeImports((PsiJavaFile)file, imports);
}
/**
* Remove imports on {@code imports} (including static imports in format Class_Name.Member_Name)
* To ensure that on-demand import expands when one of the import inside was deleted, let's do optimize imports.
*
* This may change some unrelated imports
*/
public static void removeImports(PsiJavaFile javaFile, Set<String> imports) {
PsiImportList importList = new ImportHelper(JavaCodeStyleSettings.getInstance(javaFile))
.prepareOptimizeImportsResult(javaFile, pair -> !imports.contains(pair.first));
if (importList != null) {
ObjectUtils.notNull(javaFile.getImportList()).replace(importList);
}
}
@NotNull
@Override
@@ -124,7 +148,8 @@ public class JavaCopyPasteReferenceProcessor extends CopyPasteReferenceProcessor
@Override
protected void restoreReferences(ReferenceData[] referenceData,
PsiJavaCodeReferenceElement[] refs) {
PsiJavaCodeReferenceElement[] refs,
Set<String> imported) {
for (int i = 0; i < refs.length; i++) {
PsiJavaCodeReferenceElement reference = refs[i];
if (reference == null || !reference.isValid()) continue;
@@ -135,10 +160,12 @@ public class JavaCopyPasteReferenceProcessor extends CopyPasteReferenceProcessor
if (refClass != null) {
if (refData.staticMemberName == null) {
reference.bindToElement(refClass);
imported.add(refData.qClassName);
}
else {
LOG.assertTrue(reference instanceof PsiReferenceExpression);
((PsiReferenceExpression)reference).bindToElementViaStaticImport(refClass);
imported.add(StringUtil.getQualifiedName(refData.qClassName, refData.staticMemberName));
}
}
}
@@ -1,4 +1,4 @@
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.codeInsight.editorActions;
import com.intellij.openapi.editor.Editor;
@@ -14,22 +14,23 @@ import org.jetbrains.annotations.Nullable;
* @author peter
*/
public class JavaQuoteHandler extends SimpleTokenSetQuoteHandler implements JavaLikeQuoteHandler, MultiCharQuoteHandler {
private final TokenSet concatenatableStrings;
private final TokenSet myConcatenableStrings = TokenSet.create(JavaTokenType.STRING_LITERAL);
private final TokenSet myAppropriateElementTypeForLiteral = TokenSet.orSet(
ElementType.JAVA_COMMENT_OR_WHITESPACE_BIT_SET,
TokenSet.create(JavaTokenType.CHARACTER_LITERAL, JavaTokenType.STRING_LITERAL, JavaTokenType.RAW_STRING_LITERAL,
JavaTokenType.SEMICOLON, JavaTokenType.COMMA, JavaTokenType.RPARENTH, JavaTokenType.RBRACKET, JavaTokenType.RBRACE));
public JavaQuoteHandler() {
super(JavaTokenType.STRING_LITERAL, JavaTokenType.CHARACTER_LITERAL, JavaTokenType.RAW_STRING_LITERAL);
concatenatableStrings = TokenSet.create(JavaTokenType.STRING_LITERAL);
}
@Override
public boolean isOpeningQuote(HighlighterIterator iterator, int offset) {
boolean openingQuote = super.isOpeningQuote(iterator, offset);
if (openingQuote) {
// check escape next
if (!iterator.atEnd()) {
iterator.retreat();
if (!iterator.atEnd() && StringEscapesTokenTypes.STRING_LITERAL_ESCAPES.contains(iterator.getTokenType())) {
openingQuote = false;
}
@@ -42,12 +43,10 @@ public class JavaQuoteHandler extends SimpleTokenSetQuoteHandler implements Java
@Override
public boolean isClosingQuote(HighlighterIterator iterator, int offset) {
boolean closingQuote = super.isClosingQuote(iterator, offset);
if (closingQuote) {
// check escape next
if (!iterator.atEnd()) {
iterator.advance();
if (!iterator.atEnd() && StringEscapesTokenTypes.STRING_LITERAL_ESCAPES.contains(iterator.getTokenType())) {
closingQuote = false;
}
@@ -58,8 +57,9 @@ public class JavaQuoteHandler extends SimpleTokenSetQuoteHandler implements Java
}
@Override
@SuppressWarnings("SpellCheckingInspection")
public TokenSet getConcatenatableStringTokenTypes() {
return concatenatableStrings;
return myConcatenableStrings;
}
@Override
@@ -73,12 +73,12 @@ public class JavaQuoteHandler extends SimpleTokenSetQuoteHandler implements Java
}
@Override
public boolean isAppropriateElementTypeForLiteral(final @NotNull IElementType tokenType) {
return isAppropriateElementTypeForLiteralStatic(tokenType);
public boolean isAppropriateElementTypeForLiteral(@NotNull IElementType tokenType) {
return myAppropriateElementTypeForLiteral.contains(tokenType);
}
@Override
public boolean needParenthesesAroundConcatenation(final PsiElement element) {
public boolean needParenthesesAroundConcatenation(PsiElement element) {
// example code: "some string".length() must become ("some" + " string").length()
return element.getParent() instanceof PsiLiteralExpression && element.getParent().getParent() instanceof PsiReferenceExpression;
}
@@ -104,16 +104,4 @@ public class JavaQuoteHandler extends SimpleTokenSetQuoteHandler implements Java
editor.getDocument().insertString(offset, " " + closingQuote);
editor.getSelectionModel().setSelection(offset, offset + 1);
}
public static boolean isAppropriateElementTypeForLiteralStatic(final IElementType tokenType) {
return ElementType.JAVA_COMMENT_OR_WHITESPACE_BIT_SET.contains(tokenType)
|| tokenType == JavaTokenType.SEMICOLON
|| tokenType == JavaTokenType.COMMA
|| tokenType == JavaTokenType.RPARENTH
|| tokenType == JavaTokenType.RBRACKET
|| tokenType == JavaTokenType.RBRACE
|| tokenType == JavaTokenType.STRING_LITERAL
|| tokenType == JavaTokenType.CHARACTER_LITERAL
|| tokenType == JavaTokenType.RAW_STRING_LITERAL;
}
}
}
@@ -40,8 +40,13 @@ class RestoreReferencesDialog extends DialogWrapper {
private JList myList;
private Object[] mySelectedElements = PsiClass.EMPTY_ARRAY;
private boolean myContainsClassesOnly = true;
private JBLabel myExplanationLabel;
RestoreReferencesDialog(final Project project, final Object[] elements) {
this(project, elements, true);
}
RestoreReferencesDialog(final Project project, final Object[] elements, boolean preselect) {
super(project, true);
myNamedElements = elements;
for (Object element : elements) {
@@ -58,7 +63,9 @@ class RestoreReferencesDialog extends DialogWrapper {
}
init();
myList.setSelectionInterval(0, myNamedElements.length - 1);
if (preselect) {
myList.setSelectionInterval(0, myNamedElements.length - 1);
}
}
@Override
@@ -76,9 +83,10 @@ class RestoreReferencesDialog extends DialogWrapper {
myList.setCellRenderer(new FQNameCellRenderer());
panel.add(ScrollPaneFactory.createScrollPane(myList), BorderLayout.CENTER);
panel.add(new JBLabel(myContainsClassesOnly ?
CodeInsightBundle.message("dialog.paste.on.import.text") :
CodeInsightBundle.message("dialog.paste.on.import.text2"), SMALL, BRIGHTER), BorderLayout.NORTH);
myExplanationLabel = new JBLabel(myContainsClassesOnly ?
CodeInsightBundle.message("dialog.paste.on.import.text") :
CodeInsightBundle.message("dialog.paste.on.import.text2"), SMALL, BRIGHTER);
panel.add(myExplanationLabel, BorderLayout.NORTH);
final JPanel buttonPanel = new JPanel(new VerticalFlowLayout());
final JButton okButton = new JButton(CommonBundle.getOkButtonText());
@@ -92,6 +100,9 @@ class RestoreReferencesDialog extends DialogWrapper {
return panel;
}
public void setExplanation(String explanation) {
myExplanationLabel.setText(explanation);
}
@Override
protected String getDimensionServiceKey(){
@@ -57,7 +57,7 @@ public class DeannotateIntentionAction implements IntentionAction, LowPriorityAc
@Override
public boolean isAvailable(@NotNull Project project, Editor editor, PsiFile file) {
myAnnotationName = null;
PsiModifierListOwner listOwner = AddAnnotationPsiFix.getContainer(file, editor.getCaretModel().getOffset());
PsiModifierListOwner listOwner = AddAnnotationPsiFix.getContainer(file, editor.getCaretModel().getOffset(), true);
if (listOwner != null) {
final ExternalAnnotationsManager externalAnnotationsManager = ExternalAnnotationsManager.getInstance(project);
final PsiAnnotation[] annotations = externalAnnotationsManager.findExternalAnnotations(listOwner);
@@ -76,7 +76,7 @@ public class DeannotateIntentionAction implements IntentionAction, LowPriorityAc
@Override
public void invoke(@NotNull final Project project, Editor editor, final PsiFile file) throws IncorrectOperationException {
final PsiModifierListOwner listOwner = AddAnnotationPsiFix.getContainer(file, editor.getCaretModel().getOffset());
final PsiModifierListOwner listOwner = AddAnnotationPsiFix.getContainer(file, editor.getCaretModel().getOffset(), true);
LOG.assertTrue(listOwner != null);
final ExternalAnnotationsManager annotationsManager = ExternalAnnotationsManager.getInstance(project);
final PsiAnnotation[] externalAnnotations = annotationsManager.findExternalAnnotations(listOwner);
@@ -74,6 +74,8 @@ public class AnnotationDocGenerator {
boolean red = type == null && !myResolveNotPossible && !isInferred() && !isExternal();
boolean highlightNonCodeAnnotations = format == AnnotationFormat.ToolTip && (isInferred() || isExternal());
if (highlightNonCodeAnnotations) buffer.append("<b>");
if (isInferred()) buffer.append("<i>");
if (red) buffer.append("<font color=red>");
@@ -91,6 +93,7 @@ public class AnnotationDocGenerator {
generateAnnotationAttributes(buffer, generateLink);
if (isInferred()) buffer.append("</i>");
if (highlightNonCodeAnnotations) buffer.append("</b>");
}
private void generateAnnotationAttributes(StringBuilder buffer, boolean generateLink) {
@@ -1031,15 +1031,15 @@ public class JavaDocInfoGenerator {
}
private static void generateMethodSignature(StringBuilder buffer, PsiMethod method, SignaturePlace place) {
boolean useShortNames = place == SignaturePlace.ToolTip;
boolean isTooltip = place == SignaturePlace.ToolTip;
boolean generateLink = place == SignaturePlace.Javadoc;
generateAnnotations(buffer, method, place, true);
int modLength = generateModifiers(buffer, method, true);
int modLength = isTooltip ? 0 : generateModifiers(buffer, method, true);
int indent = modLength == 0 ? 0 : modLength + 1;
String typeParamsString = generateTypeParameters(method, useShortNames);
String typeParamsString = generateTypeParameters(method, isTooltip);
indent += StringUtil.unescapeXmlEntities(StringUtil.stripHtml(typeParamsString, true)).length();
if (!typeParamsString.isEmpty()) {
buffer.append(typeParamsString);
@@ -1048,7 +1048,7 @@ public class JavaDocInfoGenerator {
}
if (method.getReturnType() != null) {
indent += generateType(buffer, method.getReturnType(), method, generateLink, useShortNames);
indent += generateType(buffer, method.getReturnType(), method, generateLink, isTooltip);
buffer.append(NBSP);
indent++;
}
@@ -1063,9 +1063,9 @@ public class JavaDocInfoGenerator {
for (int i = 0; i < parameters.length; i++) {
PsiParameter parm = parameters[i];
generateAnnotations(buffer, parm, place, false);
generateType(buffer, parm.getType(), method, generateLink, useShortNames);
buffer.append(NBSP);
if (parm.getName() != null) {
generateType(buffer, parm.getType(), method, generateLink, isTooltip);
if (parm.getName() != null && !isTooltip) {
buffer.append(NBSP);
buffer.append(parm.getName());
}
if (i < parameters.length - 1) {
@@ -1081,7 +1081,7 @@ public class JavaDocInfoGenerator {
buffer.append(THROWS_KEYWORD);
buffer.append(NBSP);
for (int i = 0; i < refs.length; i++) {
generateLink(buffer, useShortNames ? refs[i].getPresentableText() : refs[i].getCanonicalText(), null, method, false);
generateLink(buffer, isTooltip ? refs[i].getPresentableText() : refs[i].getCanonicalText(), null, method, false);
if (i < refs.length - 1) {
buffer.append(',').append(NBSP);
}
@@ -0,0 +1,32 @@
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.openapi.externalSystem.service.execution;
import com.intellij.openapi.projectRoots.JavaSdk;
import com.intellij.openapi.projectRoots.JdkUtil;
import com.intellij.openapi.projectRoots.Sdk;
import com.intellij.openapi.projectRoots.SdkType;
import com.intellij.openapi.projectRoots.impl.JavaAwareProjectJdkTableImpl;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
public class ExternalSystemJavaSdkProvider implements ExternalSystemJdkProvider {
@NotNull
@Override
public SdkType getJavaSdkType() {
return JavaSdk.getInstance();
}
@NotNull
@Override
public Sdk getInternalJdk() {
return JavaAwareProjectJdkTableImpl.getInstanceEx().getInternalJdk();
}
@NotNull
@Override
public Sdk createJdk(@Nullable String jdkName, @NotNull String homePath) {
SdkType javaSdk = getJavaSdkType();
String sdkName = jdkName != null ? jdkName : javaSdk.suggestSdkName(null, homePath);
return ((JavaSdk)javaSdk).createJdk(sdkName, homePath, !JdkUtil.checkForJdk(homePath));
}
}
@@ -0,0 +1,49 @@
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.openapi.externalSystem.service.project;
import com.intellij.compiler.CompilerConfiguration;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.externalSystem.model.project.ModuleData;
import com.intellij.openapi.externalSystem.service.project.manage.ModuleDataServiceExtension;
import com.intellij.openapi.module.Module;
import com.intellij.openapi.module.ModuleTypeId;
import com.intellij.openapi.roots.LanguageLevelModuleExtension;
import com.intellij.openapi.roots.ModifiableRootModel;
import com.intellij.pom.java.LanguageLevel;
import org.jetbrains.annotations.ApiStatus;
import org.jetbrains.annotations.NotNull;
@ApiStatus.Experimental
public class ModuleDataServiceJavaExtension implements ModuleDataServiceExtension {
private static final Logger LOG = Logger.getInstance(ModuleDataServiceJavaExtension.class);
@Override
public void importModule(@NotNull IdeModifiableModelsProvider modelsProvider, @NotNull Module module, @NotNull ModuleData data) {
if (ModuleTypeId.JAVA_MODULE.equals(module.getModuleTypeName())) {
ModifiableRootModel modifiableRootModel = modelsProvider.getModifiableRootModel(module);
setLanguageLevel(modifiableRootModel, data);
setBytecodeTargetLevel(module, data);
}
}
private static void setLanguageLevel(@NotNull ModifiableRootModel modifiableRootModel, ModuleData data) {
LanguageLevel level = LanguageLevel.parse(data.getSourceCompatibility());
if (level != null) {
try {
modifiableRootModel.getModuleExtension(LanguageLevelModuleExtension.class).setLanguageLevel(level);
}
catch (IllegalArgumentException e) {
LOG.debug(e);
}
}
}
private static void setBytecodeTargetLevel(@NotNull Module module, @NotNull ModuleData data) {
String targetLevel = data.getTargetCompatibility();
if (targetLevel != null) {
CompilerConfiguration configuration = CompilerConfiguration.getInstance(module.getProject());
configuration.setBytecodeTargetLevel(module, targetLevel);
}
}
}
@@ -44,6 +44,8 @@ import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.*;
import java.util.function.Predicate;
import java.util.stream.Collectors;
import static java.util.stream.Collectors.toSet;
@@ -67,7 +69,15 @@ public class ImportHelper{
}
@Nullable("null means no need to replace the import list because they are the same")
PsiImportList prepareOptimizeImportsResult(@NotNull final PsiJavaFile file) {
public PsiImportList prepareOptimizeImportsResult(@NotNull final PsiJavaFile file) {
return prepareOptimizeImportsResult(file, pair -> true);
}
/**
* @param filter pretend some references do not exist so the corresponding imports may be deleted
*/
@Nullable("null means no need to replace the import list because they are the same")
public PsiImportList prepareOptimizeImportsResult(@NotNull final PsiJavaFile file, Predicate<? super Pair<String, Boolean>> filter) {
PsiImportList oldList = file.getImportList();
if (oldList == null) return null;
@@ -78,8 +88,12 @@ public class ImportHelper{
// We want to preserve those comments then.
List<PsiElement> nonImports = new NotNullList<>();
// Note: this array may contain "<packageOrClassName>.*" for unresolved imports!
List<Pair<String, Boolean>> names = new ArrayList<>(collectNamesToImport(file, nonImports));
Collections.sort(names, Comparator.comparing(o -> o.getFirst()));
List<Pair<String, Boolean>> names =
collectNamesToImport(file, nonImports)
.stream()
.filter(filter)
.sorted(Comparator.comparing(o -> o.getFirst()))
.collect(Collectors.toList());
List<Pair<String, Boolean>> resultList = sortItemsAccordingToSettings(names, mySettings);
@@ -216,7 +216,7 @@ public class IntroduceParameterDialog extends RefactoringDialog {
final PsiAnonymousClass anonymClass = myExpression instanceof PsiNewExpression ? ((PsiNewExpression)myExpression).getAnonymousClass()
: null;
myCbCollapseToLambda.setVisible(anonymClass != null && AnonymousCanBeLambdaInspection.isLambdaForm(anonymClass, false, Collections.emptySet()));
myCbCollapseToLambda.setSelected(PropertiesComponent.getInstance(myProject).getBoolean(INTRODUCE_PARAMETER_LAMBDA));
myCbCollapseToLambda.setSelected(PropertiesComponent.getInstance(myProject).getBoolean(INTRODUCE_PARAMETER_LAMBDA, true));
gbConstraints.gridy++;
panel.add(myCbCollapseToLambda, gbConstraints);
@@ -86,11 +86,8 @@ public class JavaNullMethodArgumentIndex extends ScalarIndexExtension<JavaNullMe
}
private static boolean containsStopSymbol(int startIndex, @NotNull CharSequence text, boolean leftDirection) {
int i = startIndex;
int i = leftDirection ? startIndex - 1 : startIndex + 1;
while (true) {
if (leftDirection) i--; else i++;
if (leftDirection) {
if (i < 0) return false;
} else {
@@ -102,6 +99,8 @@ public class JavaNullMethodArgumentIndex extends ScalarIndexExtension<JavaNullMe
if (!Lazy.WHITE_SPACE_OR_EOL_SYMBOLS.contains(c) && !Character.isWhitespace(c)) {
return false;
}
if (leftDirection) i--; else i++;
}
}
@@ -27,7 +27,6 @@ import com.intellij.psi.util.TypeConversionUtil;
import com.intellij.util.containers.ContainerUtil;
import org.jetbrains.annotations.Nullable;
import java.util.Arrays;
import java.util.List;
public class PsiMethodReferenceCompatibilityConstraint implements ConstraintFormula {
@@ -170,17 +169,20 @@ public class PsiMethodReferenceCompatibilityConstraint implements ConstraintForm
//if i) the method reference elides NonWildTypeArguments,
// ii) the compile-time declaration is a generic method, and
// iii) the return type of the compile-time declaration mentions at least one of the method's type parameters;
if (typeParameters.length == 0 && method.getTypeParameters().length > 0) {
final PsiClass interfaceClass = classResolveResult.getElement();
LOG.assertTrue(interfaceClass != null);
if (PsiTypesUtil.mentionsTypeParameters(referencedMethodReturnType,
ContainerUtil.newHashSet(method.getTypeParameters()))) {
session.initBounds(myExpression, psiSubstitutor, method.getTypeParameters());
//the constraint reduces to the bound set B3 which would be used to determine the method reference's invocation type
//when targeting the return type of the function type, as defined in 18.5.2.
session.collectApplicabilityConstraints(myExpression, ((MethodCandidateInfo)resolve), groundTargetType);
session.registerReturnTypeConstraints(psiSubstitutor.substitute(referencedMethodReturnType), returnType, myExpression);
return true;
if (typeParameters.length == 0) {
PsiTypeParameter[] methodTypeParameters = method.isConstructor() ? containingClass.getTypeParameters() : method.getTypeParameters();
if (methodTypeParameters.length > 0) {
final PsiClass interfaceClass = classResolveResult.getElement();
LOG.assertTrue(interfaceClass != null);
if (PsiTypesUtil.mentionsTypeParameters(referencedMethodReturnType,
ContainerUtil.newHashSet(methodTypeParameters))) {
session.initBounds(myExpression, psiSubstitutor, methodTypeParameters);
//the constraint reduces to the bound set B3 which would be used to determine the method reference's invocation type
//when targeting the return type of the function type, as defined in 18.5.2.
session.collectApplicabilityConstraints(myExpression, ((MethodCandidateInfo)resolve), groundTargetType);
session.registerReturnTypeConstraints(psiSubstitutor.substitute(referencedMethodReturnType), returnType, myExpression);
return true;
}
}
}
@@ -230,30 +232,6 @@ public class PsiMethodReferenceCompatibilityConstraint implements ConstraintForm
final PsiType pType = PsiUtil.captureToplevelWildcards(parameterization, methodReferenceExpression);
psiSubstitutor = TypeConversionUtil.getSuperClassSubstitutor(qContainingClass, (PsiClassType)pType);
}
else if (member instanceof PsiMethod && ((PsiMethod)member).isConstructor() || member instanceof PsiClass) {
//15.13.1
//If ClassType is a raw type, but is not a non-static member type of a raw type,
//the candidate notional member methods are those specified in p15.9.3 for a class instance creation expression that uses <>
//to elide the type arguments to a class.
final PsiResolveHelper helper = JavaPsiFacade.getInstance(methodReferenceExpression.getProject()).getResolveHelper();
final PsiType[] paramTypes =
member instanceof PsiMethod ? ((PsiMethod)member).getSignature(PsiSubstitutor.EMPTY).getParameterTypes() : PsiType.EMPTY_ARRAY;
if (paramTypes.length != signature.getParameterTypes().length && !(member instanceof PsiMethod && ((PsiMethod)member).isVarArgs())) {
//inapplicable method reference
return PsiSubstitutor.EMPTY;
}
if (Arrays.deepEquals(signature.getParameterTypes(), paramTypes)) {
return PsiSubstitutor.EMPTY;
}
if (paramTypes.length == signature.getParameterTypes().length) {
psiSubstitutor = helper.inferTypeArguments(PsiTypesUtil.filterUnusedTypeParameters(qContainingClass.getTypeParameters(), paramTypes),
paramTypes,
signature.getParameterTypes(),
PsiUtil.getLanguageLevel(methodReferenceExpression));
}
}
else {
psiSubstitutor = PsiSubstitutor.EMPTY;
}
@@ -117,8 +117,11 @@ public class MethodReferenceResolver implements ResolveCache.PolyVariantContextR
}
if (includeReturnConstraint && !PsiType.VOID.equals(interfaceMethodReturnType) && interfaceMethodReturnType != null) {
PsiSubstitutor subst = PsiMethodReferenceCompatibilityConstraint.getSubstitutor(signature, qualifierResolveResult, method, containingClass, reference);
final PsiType returnType = method.isConstructor() ? composeReturnType(containingClass, subst) : subst.substitute(method.getReturnType());
final PsiType returnType = method.isConstructor()
? composeReturnType(containingClass, substitutor)
: PsiMethodReferenceCompatibilityConstraint
.getSubstitutor(signature, qualifierResolveResult, method, containingClass, reference)
.substitute(method.getReturnType());
if (returnType != null) {
session.registerReturnTypeConstraints(returnType, interfaceMethodReturnType, reference);
}
@@ -0,0 +1,27 @@
import java.util.function.Function;
class MyTest {
{
Function<B, Try<A>> aNew = Try::new;
Try<B> bTry = new Try<>(new B());
Try<A> aTry = bTry.flatMap(Try::new);
}
private static class A { }
private static class B extends A { }
private static class Try<T> {
public Try(T t) {
}
public Try(Exception e) {
}
public <U> Try<U> flatMap(Function<? super T, Try<U>> mapper) {
return null;
}
}
}
@@ -0,0 +1,17 @@
// "Extract common part from 'if'" "INFORMATION"
class X {
void foo() {
if (true) {
another(1);
}
else {
another(2);
}
bar();
}
void another(int i) {}
void bar() {}
}
@@ -0,0 +1,18 @@
// "Extract common part from 'if'" "INFORMATION"
class X {
void foo() {
if<caret> (true) {
another(1);
bar();
}
else {
another(2);
bar();
}
}
void another(int i) {}
void bar() {}
}
@@ -5,6 +5,6 @@ import java.util.stream.*;
class Test {
public static void test(List<String> s) {
new TreeSet<? extends String>(s).contains("abc");
new TreeSet<>(s).contains("abc");
}
}
@@ -191,6 +191,7 @@ public class NewMethodRefHighlightingTest extends LightDaemonAnalyzerTestCase {
public void testSkipInferenceForInapplicableMethodReference() { doTest(); }
public void testRegisterVariablesForNonFoundParameterizations() { doTest(); }
public void testConstructorReferenceOnRawTypeWithInferredSubtypes() { doTest(); }
public void testPreferErrorOnTopLevelToFailedSubstitutorOnNestedLevel() { doTest(); }
public void testDontIgnoreIncompatibilitiesDuringFirstApplicabilityCheck() { doTest(); }
public void testCaptureOnDedicatedParameterOfSecondSearch() { doTest(); }
@@ -96,15 +96,15 @@ public class BytecodeAnalysisIntegrationTest extends LightCodeInsightFixtureTest
public void testInferredAnnoGutter() {
checkHasGutter("org.apache.velocity.util.ExceptionUtils",
"<html><i>Inferred</i> annotations available. Full signature:<p>\n" +
"<i>@Contract('null,_,_->null')</i> \n" +
"public static Throwable <b>createWithCause</b>(Class clazz,\n String message,\n Throwable cause)</html>");
"<b><i>@Contract('null,_,_->null')</i></b> \n" +
"Throwable <b>createWithCause</b>(Class,\n String,\n Throwable)</html>");
}
public void testExternalAnnoGutter() {
checkHasGutter("java.lang.String",
"<html>External and <i>inferred</i> annotations available. Full signature:<p>\n" +
"<i>@Contract(pure = true)</i> \n" +
"public <b>String</b>(@NotNull String var1)</html>");
"<b><i>@Contract(pure = true)</i></b> \n" +
"<b>String</b>(<b>@NotNull</b> String)</html>");
}
private void checkHasGutter(String className, String expectedText) {
@@ -60,7 +60,9 @@ import com.intellij.util.indexing.*
import com.intellij.util.indexing.impl.MapIndexStorage
import com.intellij.util.indexing.impl.MapReduceIndex
import com.intellij.util.indexing.impl.UpdatableValueContainer
import com.intellij.util.io.*
import com.intellij.util.io.CaseInsensitiveEnumeratorStringDescriptor
import com.intellij.util.io.EnumeratorStringDescriptor
import com.intellij.util.io.PersistentHashMap
import com.intellij.util.ref.GCUtil
import com.intellij.util.ref.GCWatcher
import com.siyeh.ig.JavaOverridingMethodUtil
@@ -771,7 +773,6 @@ class IndexTest extends JavaCodeInsightFixtureTestCase {
}
class RecordingVfsListener extends IndexedFilesListener {
def vfsEventMerger = new VfsEventsMerger()
@Override
protected void iterateIndexableFiles(@NotNull VirtualFile file, @NotNull ContentIterator iterator) {
@@ -784,18 +785,9 @@ class IndexTest extends JavaCodeInsightFixtureTestCase {
})
}
protected void doInvalidateIndicesForFile(@NotNull VirtualFile file, boolean contentChange) {
vfsEventMerger.recordBeforeFileEvent(((VirtualFileWithId)file).id, file, contentChange)
}
@Override
protected void buildIndicesForFile(@NotNull VirtualFile file, boolean contentChange) {
vfsEventMerger.recordFileEvent(((VirtualFileWithId)file).id, file, contentChange)
}
String indexingOperation(VirtualFile file) {
Ref<String> operation = new Ref<>()
vfsEventMerger.processChanges(new VfsEventsMerger.VfsEventProcessor() {
eventMerger.processChanges(new VfsEventsMerger.VfsEventProcessor() {
@Override
boolean process(@NotNull VfsEventsMerger.ChangeInfo info) {
operation.set(info.toString())
@@ -810,10 +802,7 @@ class IndexTest extends JavaCodeInsightFixtureTestCase {
void testIndexedFilesListener() throws Throwable {
def listener = new RecordingVfsListener()
ApplicationManager.getApplication().getMessageBus().connect(myFixture.getTestRootDisposable()).subscribe(
VirtualFileManager.VFS_CHANGES,
listener
)
VirtualFileManager.instance.addAsyncFileListener(listener, myFixture.testRootDisposable)
def fileName = "test.txt"
final VirtualFile testFile = myFixture.addFileToProject(fileName, "test").getVirtualFile()
@@ -922,7 +911,7 @@ class IndexTest extends JavaCodeInsightFixtureTestCase {
}
@CompileStatic
void "test Vfs Events Processing Performance"() {
void "test Vfs Event Processing Performance"() {
def filename = 'A.java'
myFixture.addFileToProject('foo/bar/' + filename, 'class A {}')
@@ -944,9 +933,9 @@ class IndexTest extends JavaCodeInsightFixtureTestCase {
eventList.add(new VFileCreateEvent(null, file.parent, filename, false, null, null, true, null))
}
IndexedFilesListener indexedFilesListener = ((FileBasedIndexImpl)FileBasedIndex.instance).changedFilesCollector
indexedFilesListener.before(eventList)
indexedFilesListener.after(eventList)
def applier = ((FileBasedIndexImpl)FileBasedIndex.instance).changedFilesCollector.prepareChange(eventList)
applier.beforeVfsChange()
applier.afterVfsChange()
files = FilenameIndex.getFilesByName(project, filename, GlobalSearchScope.moduleScope(module))
assert files?.length == 1
@@ -0,0 +1,84 @@
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.java.index;
import com.intellij.openapi.util.Disposer;
import com.intellij.openapi.util.io.BufferExposingByteArrayOutputStream;
import com.intellij.openapi.vfs.VfsUtilCore;
import com.intellij.psi.PsiFile;
import com.intellij.psi.impl.DebugUtil;
import com.intellij.psi.impl.source.PsiFileWithStubSupport;
import com.intellij.psi.stubs.*;
import com.intellij.testFramework.fixtures.JavaCodeInsightFixtureTestCase;
import com.intellij.util.io.PersistentStringEnumerator;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.util.Arrays;
public class StubReSerializationTest extends JavaCodeInsightFixtureTestCase {
public void testReSerializationWithDifferentSerializerEnumeration() throws Exception {
SerializationManagerEx serializationManager = SerializationManagerEx.getInstanceEx();
serializationManager.flushNameStorage();
File externalStubEnumerator =
VfsUtilCore.virtualToIoFile(myFixture.getTempDirFixture().createFile("external_stub_serializer_enumerator/serializer.names"));
// ensure we have different serializer's enumeration
try (PersistentStringEnumerator enumerator = new PersistentStringEnumerator(externalStubEnumerator)) {
for (int i = 0; i < 10000; i++) {
enumerator.enumerate("garbage value " + i);
}
}
SerializationManagerImpl externalSerializationManager = new SerializationManagerImpl(externalStubEnumerator, false);
try {
PsiFileStub stub = createStub();
BufferExposingByteArrayOutputStream out = new BufferExposingByteArrayOutputStream();
serializationManager.serialize(stub, out);
byte[] serialized = out.toByteArray();
BufferExposingByteArrayOutputStream externallySerializedOut = new BufferExposingByteArrayOutputStream();
serializationManager.reSerialize(new ByteArrayInputStream(serialized), externallySerializedOut, externalSerializationManager);
byte[] externalStub = externallySerializedOut.toByteArray();
assertFalse(Arrays.equals(serialized, externalStub));
Stub stubFromExternSerializationManager = externalSerializationManager.deserialize(new ByteArrayInputStream(externalStub));
assertEquals(DebugUtil.stubTreeToString(stub), DebugUtil.stubTreeToString(stubFromExternSerializationManager));
BufferExposingByteArrayOutputStream initialOut = new BufferExposingByteArrayOutputStream();
externalSerializationManager.reSerialize(new ByteArrayInputStream(externalStub), initialOut, serializationManager);
byte[] initialSerializedStub = initialOut.toByteArray();
assertOrderedEquals(serialized, initialSerializedStub);
} finally {
Disposer.dispose(externalSerializationManager);
}
}
public void testIdenticalReSerialization() throws Exception {
SerializationManagerEx serializationManager = SerializationManagerEx.getInstanceEx();
PsiFileStub stub = createStub();
BufferExposingByteArrayOutputStream out = new BufferExposingByteArrayOutputStream();
serializationManager.serialize(stub, out);
byte[] serialized = out.toByteArray();
BufferExposingByteArrayOutputStream reSerializedOut = new BufferExposingByteArrayOutputStream();
serializationManager.reSerialize(new ByteArrayInputStream(serialized), reSerializedOut, serializationManager);
byte[] reSerialized = reSerializedOut.toByteArray();
assertOrderedEquals(serialized, reSerialized);
BufferExposingByteArrayOutputStream reSerializedOut2 = new BufferExposingByteArrayOutputStream();
serializationManager.reSerialize(new ByteArrayInputStream(reSerialized), reSerializedOut2, serializationManager);
byte[] reSerialized2 = reSerializedOut.toByteArray();
assertOrderedEquals(serialized, reSerialized2);
}
private PsiFileStub createStub() {
PsiFile f = myFixture.addFileToProject("A.java", "class A { int j = 123; void m () { Runnable r = () -> {}; }}");
return ((PsiFileWithStubSupport)f).getStubTree().getRoot();
}
}
@@ -677,20 +677,23 @@ public class SmartPsiElementPointersTest extends CodeInsightTestCase {
}
public void testLargeFileWithManyChangesPerformance() throws Exception {
PsiFile file = createFile("a.txt", StringUtil.repeat("foo foo \n", 50000));
String text = StringUtil.repeat("foo foo \n", 50000);
PsiFile file = createFile("a.txt", text);
final TextRange range = TextRange.from(10, 10);
final SmartPsiFileRange pointer = getPointerManager().createSmartPsiFileRangePointer(file, range);
final Document document = file.getViewProvider().getDocument();
assertNotNull(document);
WriteAction.run(() -> PlatformTestUtil.startPerformanceTest("smart pointer range update", 11_000, () -> {
document.setText(StringUtil.repeat("foo foo \n", 50000));
WriteAction.run(() -> PlatformTestUtil.startPerformanceTest("smart pointer range update", 10_000, () -> {
for (int i = 0; i < 10000; i++) {
document.insertString(i * 20 + 100, "x\n");
assertFalse(PsiDocumentManager.getInstance(myProject).isCommitted(document));
assertEquals(range, pointer.getRange());
}
}).setup(() -> {
document.setText(text);
assertEquals(range, pointer.getRange());
}).attempts(10).assertTiming());
PsiDocumentManager.getInstance(myProject).commitAllDocuments();
@@ -1,18 +1,4 @@
/*
* Copyright 2000-2017 JetBrains s.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.
*/
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.roots
import com.intellij.openapi.application.ex.PathManagerEx
@@ -24,6 +10,7 @@ import com.intellij.openapi.project.impl.ProjectManagerImpl
import com.intellij.openapi.roots.ModuleRootManager
import com.intellij.openapi.roots.ModuleRootModificationUtil
import com.intellij.openapi.util.io.FileUtil
import com.intellij.openapi.util.io.FileUtilRt
import com.intellij.openapi.vfs.VfsUtilCore
import com.intellij.testFramework.ModuleTestCase
import java.io.File
@@ -33,7 +20,7 @@ import java.io.File
*/
class UnloadedModulesConfigurationTest : ModuleTestCase() {
fun `test load project`() {
val projectPath = File(PathManagerEx.getTestDataPath(), "moduleRootManager/unloadedModules").absolutePath
val projectPath = FileUtilRt.toSystemIndependentName(File(PathManagerEx.getTestDataPath(), "moduleRootManager/unloadedModules").absolutePath)
val project = getProjectManager().loadAndOpenProject(projectPath)!!
try {
val moduleManager = ModuleManager.getInstance(project)
@@ -41,7 +28,7 @@ class UnloadedModulesConfigurationTest : ModuleTestCase() {
assertEquals(2, moduleManager.unloadedModuleDescriptions.size)
val util = moduleManager.unloadedModuleDescriptions.find { it.name == "util" }!!
val projectDirUrl = VfsUtilCore.pathToUrl(FileUtil.toSystemIndependentName(projectPath))
val projectDirUrl = VfsUtilCore.pathToUrl(projectPath)
assertEquals("$projectDirUrl/util", assertOneElement(util.contentRoots).url)
assertEmpty(util.dependencyModuleNames)
+4 -3
View File
@@ -1,16 +1,16 @@
<idea-plugin xmlns:xi="http://www.w3.org/2001/XInclude" use-idea-classloader="true">
<!-- we need to use the platform classloader to make the plugin compatible with CLion until IDEA-187832 is fixed,
see cidr-external-system/resources/META-INF/plugin.xml for details -->
<id>com.intellij.java</id>
<name>Java</name>
<description>Java language support.</description>
<vendor>JetBrains</vendor>
<resource-bundle>messages.ActionsBundle</resource-bundle>
<depends>com.intellij.modules.platform</depends>
<depends>com.intellij.modules.lang</depends>
<depends>com.intellij.modules.vcs</depends>
<depends>com.intellij.modules.xdebugger</depends>
<depends>com.intellij.modules.xml</depends>
<xi:include href="/META-INF/JavaPlugin.xml" xpointer="xpointer(/idea-plugin/*)"/>
<!-- todo: these files are present in Java plugin for IDEA Ultimate only, they should be extract to a different plugin.xml -->
@@ -27,7 +27,8 @@
<depends optional="true" config-file="profiler-java.xml">com.intellij.modules.profiler</depends>
<depends optional="true" config-file="structuralsearch-java.xml">com.intellij.modules.structuralsearch</depends>
<depends optional="true" config-file="RemoteServersJava.xml">com.intellij.modules.remoteServers</depends>
<depends optional="true" config-file="JavaCMakeActionPatcher.xml">com.intellij.modules.clion.cmake</depends> <!-- this is a workaround for IDEA-209728 -->
<depends optional="true" config-file="JavaCMakeActionPatcher.xml">com.intellij.modules.clion.cmake</depends> <!-- a workaround for IDEA-209728 -->
<extensions defaultExtensionNs="com.intellij">
<moduleType id="JAVA_MODULE" classpathProvider="true" implementationClass="com.intellij.openapi.module.JavaModuleType"/>
</extensions>
@@ -11,6 +11,7 @@ import com.intellij.ide.highlighter.JavaFileType;
import com.intellij.lang.Language;
import com.intellij.lang.annotation.HighlightSeverity;
import com.intellij.lang.java.JavaLanguage;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.fileTypes.LanguageFileType;
import com.intellij.openapi.fileTypes.StdFileTypes;
import com.intellij.openapi.project.Project;
@@ -18,8 +19,6 @@ import com.intellij.openapi.util.registry.Registry;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.psi.*;
import com.intellij.psi.impl.source.JavaDummyHolder;
import com.intellij.psi.impl.source.PsiCodeFragmentImpl;
import com.intellij.psi.impl.source.tree.JavaElementType;
import com.intellij.psi.javadoc.PsiDocComment;
import com.intellij.psi.javadoc.PsiDocToken;
import com.intellij.psi.util.PsiTreeUtil;
@@ -484,7 +483,10 @@ public class JavaStructuralSearchProfile extends StructuralSearchProfile {
}
@Override
public boolean shouldShowProblem(HighlightInfo highlightInfo, PsiFile file) {
public boolean shouldShowProblem(HighlightInfo highlightInfo, PsiFile file, PatternContext context) {
if (!Registry.is("ssr.in.editor.problem.highlighting")) {
return false;
}
if (highlightInfo.getSeverity() != HighlightSeverity.ERROR && highlightInfo.getSeverity() != HighlightSeverity.INFORMATION) {
return false;
}
@@ -511,7 +513,7 @@ public class JavaStructuralSearchProfile extends StructuralSearchProfile {
return false;
}
final List<PsiStatement> children = PsiTreeUtil.getChildrenOfTypeAsList(file, PsiStatement.class);
if (children.size() == 1 && ((PsiCodeFragmentImpl)file).getContentElementType() == JavaElementType.STATEMENTS) {
if (children.size() == 1 && context == DEFAULT_CONTEXT) {
final PsiStatement child = children.get(0);
if (child == parent && (child instanceof PsiExpressionStatement || child instanceof PsiDeclarationStatement)) {
// search for expression, type, annotation or symbol
@@ -572,6 +574,10 @@ public class JavaStructuralSearchProfile extends StructuralSearchProfile {
public void checkSearchPattern(CompiledPattern pattern) {
final ValidatingVisitor visitor = new ValidatingVisitor();
final NodeIterator nodes = pattern.getNodes();
if (pattern.getNodeCount() == 1 && (
nodes.current() instanceof PsiExpressionStatement || nodes.current() instanceof PsiDeclarationStatement)) {
visitor.setCurrent(nodes.current());
}
while (nodes.hasNext()) {
nodes.current().accept(visitor);
nodes.advance();
@@ -593,6 +599,9 @@ public class JavaStructuralSearchProfile extends StructuralSearchProfile {
final boolean replaceIsExpression = statements2.length == 1 && statements2[0].getLastChild() instanceof PsiErrorElement;
final ValidatingVisitor visitor = new ValidatingVisitor();
if (statements2.length == 1 && (statements2[0] instanceof PsiExpressionStatement || statements2[0] instanceof PsiDeclarationStatement)) {
visitor.setCurrent(statements2[0]);
}
for (PsiElement statement : statements2) {
statement.accept(visitor);
}
@@ -617,6 +626,7 @@ public class JavaStructuralSearchProfile extends StructuralSearchProfile {
}
static class ValidatingVisitor extends JavaRecursiveElementWalkingVisitor {
private PsiElement myCurrent;
@Override public void visitAnnotation(PsiAnnotation annotation) {
super.visitAnnotation(annotation);
@@ -642,6 +652,45 @@ public class JavaStructuralSearchProfile extends StructuralSearchProfile {
throw new MalformedPatternException(SSRBundle.message("invalid.modifier.type",name));
}
}
@Override
public void visitErrorElement(PsiErrorElement element) {
super.visitErrorElement(element);
if (Registry.is("ssr.in.editor.problem.highlighting") && Registry.is("ssr.use.new.search.dialog") &&
!ApplicationManager.getApplication().isUnitTestMode()) {
return;
}
final PsiElement parent = element.getParent();
final String errorDescription = element.getErrorDescription();
if (parent instanceof PsiClass && "Identifier expected".equals(errorDescription)) {
// other class content variable.
return;
}
if (parent instanceof PsiTryStatement && "'catch' or 'finally' expected".equals(errorDescription)) {
// searching for naked try allowed
return;
}
if (parent == myCurrent) {
// search for expression, type, annotation or symbol
if ("';' expected".equals(errorDescription) && element.getNextSibling() == null) {
// expression
return;
}
if ("Identifier or type expected".equals(errorDescription)) {
// annotation
return;
}
if ("Identifier expected".equals(errorDescription)) {
// type
return;
}
}
throw new MalformedPatternException(errorDescription);
}
void setCurrent(PsiElement current) {
myCurrent = current;
}
}
@Override
@@ -6,8 +6,9 @@ import org.jetbrains.annotations.NotNull;
/**
* @author Mikhail Golubev
*
* @deprecated use &lt;fileType&gt; extension point instead
*/
@Deprecated
public class JsonFileTypeFactory extends FileTypeFactory {
@Override
public void createFileTypes(@NotNull FileTypeConsumer consumer) {
@@ -55,10 +55,10 @@ import java.util.stream.Collectors;
* @author Irina.Chernushina on 10/1/2015.
*/
public class JsonSchemaCompletionContributor extends CompletionContributor {
private static final String BUILTIN_USAGE_KEY = "json.schema.builtin.completion";
private static final String SCHEMA_USAGE_KEY = "json.schema.schema.completion";
private static final String USER_USAGE_KEY = "json.schema.user.completion";
private static final String REMOTE_USAGE_KEY = "json.schema.remote.completion";
private static final String BUILTIN_USAGE_KEY = "builtin";
private static final String SCHEMA_USAGE_KEY = "schema";
private static final String USER_USAGE_KEY = "user";
private static final String REMOTE_USAGE_KEY = "remote";
@Override
public void fillCompletionVariants(@NotNull CompletionParameters parameters, @NotNull CompletionResultSet result) {
@@ -1,11 +1,12 @@
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.jetbrains.jsonSchema.impl;
import com.intellij.internal.statistic.eventLog.FeatureUsageData;
import com.intellij.internal.statistic.service.fus.collectors.FUCounterUsageLogger;
public class JsonSchemaUsageTriggerCollector {
public static void trigger(String feature) {
FUCounterUsageLogger.getInstance().logEvent("json.schema", feature);
FUCounterUsageLogger.getInstance().logEvent("json.schema", "completion.by.schema.invoked",
new FeatureUsageData().addData("schemaKind", feature));
}
}
+9
View File
@@ -94,6 +94,15 @@
<replaceregexp file="${idea.project.home}/plugins/NodeJS/src/com/jetbrains/nodejs/packageJson/packageJsonSchema.json"
match="&quot;publishConfig&quot;"
replace="&quot;jscsConfig&quot; : {&quot;$ref&quot;: &quot;http://json.schemastore.org/jscsrc#&quot;},${line.separator} &quot;publishConfig&quot;" />
<replaceregexp file="${idea.project.home}/plugins/NodeJS/src/com/jetbrains/nodejs/packageJson/packageJsonSchema.json"
match="&quot;publishConfig&quot;"
replace="&quot;nodemonConfig&quot; : {&quot;$ref&quot;: &quot;http://json.schemastore.org/nodemon#&quot;},${line.separator} &quot;publishConfig&quot;" />
<replaceregexp file="${idea.project.home}/plugins/NodeJS/src/com/jetbrains/nodejs/packageJson/packageJsonSchema.json"
match="&quot;publishConfig&quot;"
replace="&quot;husky&quot; : {&quot;$ref&quot;: &quot;http://json.schemastore.org/huskyrc#&quot;},${line.separator} &quot;publishConfig&quot;" />
<replaceregexp file="${idea.project.home}/plugins/NodeJS/src/com/jetbrains/nodejs/packageJson/packageJsonSchema.json"
match="&quot;publishConfig&quot;"
replace="&quot;renovate&quot; : {&quot;$ref&quot;: &quot;http://json.schemastore.org/renovate#&quot;},${line.separator} &quot;publishConfig&quot;" />
<replaceregexp file="${idea.project.home}/plugins/NodeJS/src/com/jetbrains/nodejs/packageJson/packageJsonSchema.json"
match="&quot;publishConfig&quot;"
replace="&quot;browserslist&quot; : {&quot;oneOf&quot;: [{&quot;type&quot;: &quot;array&quot;, &quot;items&quot;: {&quot;type&quot;: &quot;string&quot;}}, {&quot;type&quot;: &quot;object&quot;, &quot;additionalProperties&quot;: {&quot;type&quot;: &quot;array&quot;, &quot;items&quot;: {&quot;type&quot;: &quot;string&quot;}}}] , &quot;description&quot;: &quot;List of Browserslist queries&quot;},${line.separator} &quot;publishConfig&quot;" />
@@ -1,52 +0,0 @@
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.ide;
import com.intellij.util.lang.UrlClassLoader;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.security.ProtectionDomain;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
public class BootstrapClassLoader extends UrlClassLoader {
public interface Transformer {
byte[] transform(ClassLoader loader, String className, @Nullable ProtectionDomain protectionDomain, byte[] classBytes);
}
private final List<Transformer> myTransformers = new CopyOnWriteArrayList<>();
public BootstrapClassLoader(@NotNull Builder<BootstrapClassLoader> builder) {
super(builder);
}
public void addTransformer(Transformer transformer) {
myTransformers.add(transformer);
}
public boolean removeTransformer(Transformer transformer) {
return myTransformers.remove(transformer);
}
@Override
protected Class _defineClass(String name, byte[] b) {
return super._defineClass(name, doTransform(name, null, b));
}
@Override
protected Class _defineClass(String name, byte[] b, @Nullable ProtectionDomain protectionDomain) {
return super._defineClass(name, doTransform(name, protectionDomain, b), protectionDomain);
}
private byte[] doTransform(String name, ProtectionDomain protectionDomain, byte[] bytes) {
byte[] b = bytes;
for (Transformer transformer : myTransformers) {
final byte[] result = transformer.transform(this, name, protectionDomain, b);
if (result != null) {
b = result;
}
}
return b;
}
}
@@ -1,14 +1,17 @@
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.ide;
import com.intellij.idea.Main;
import com.intellij.openapi.application.PathManager;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.util.ClassLoaderUtil;
import com.intellij.openapi.util.SystemInfo;
import com.intellij.openapi.util.io.FileUtilRt;
import com.intellij.util.SmartList;
import com.intellij.util.lang.UrlClassLoader;
import com.intellij.util.text.StringTokenizer;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.io.File;
import java.io.IOException;
@@ -20,18 +23,20 @@ import java.net.URLClassLoader;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.security.ProtectionDomain;
import java.util.*;
import java.util.regex.Pattern;
/**
* @author max
*/
public class BootstrapClassLoaderUtil extends ClassUtilCore {
private static final Logger LOG = Logger.getInstance("#com.intellij.ide.BootstrapClassLoaderUtil");
public class BootstrapClassLoaderUtil {
public static final String CLASSPATH_ORDER_FILE = "classpath-order.txt";
private static final String PROPERTY_IGNORE_CLASSPATH = "ignore.classpath";
private static final String PROPERTY_ALLOW_BOOTSTRAP_RESOURCES = "idea.allow.bootstrap.resources";
private static final String PROPERTY_ADDITIONAL_CLASSPATH = "idea.additional.classpath";
public static final String CLASSPATH_ORDER_FILE = "classpath-order.txt";
private static final String MARKETPLACE_PLUGIN_DIR = "marketplace";
private BootstrapClassLoaderUtil() { }
@@ -49,13 +54,16 @@ public class BootstrapClassLoaderUtil extends ClassUtilCore {
addAdditionalClassPath(classpath);
addParentClasspath(classpath, true);
final File mpBoot = new File(PathManager.getPluginsPath(), "marketplace/lib/boot/marketplace-bootstrap.jar");
final boolean installMarketplace = mpBoot.exists();
File mpBoot = new File(PathManager.getPluginsPath(), MARKETPLACE_PLUGIN_DIR + "/lib/boot/marketplace-bootstrap.jar");
boolean installMarketplace = mpBoot.exists();
if (installMarketplace) {
classpath.add(new File(PathManager.getPluginsPath(), "marketplace/lib/boot/marketplace-impl.jar").toURI().toURL());
File marketplaceImpl = new File(PathManager.getPluginsPath(), MARKETPLACE_PLUGIN_DIR + "/lib/boot/marketplace-impl.jar");
if (marketplaceImpl.exists()) {
classpath.add(marketplaceImpl.toURI().toURL());
}
}
UrlClassLoader.Builder<BootstrapClassLoader> builder = UrlClassLoader.build(BootstrapClassLoader.class)
UrlClassLoader.Builder builder = UrlClassLoader.build()
.urls(filterClassPath(new ArrayList<>(classpath)))
.allowLock()
.usePersistentClasspathIndexForLocalClassDirectories()
@@ -67,21 +75,26 @@ public class BootstrapClassLoaderUtil extends ClassUtilCore {
ClassLoaderUtil.addPlatformLoaderParentIfOnJdk9(builder);
final BootstrapClassLoader loader = builder.get();
if (installMarketplace) {
try {
final UrlClassLoader mpBootloader = UrlClassLoader.build().urls(mpBoot.toURI().toURL()).parent(BootstrapClassLoaderUtil.class.getClassLoader()).get();
for (BootstrapClassLoader.Transformer transformer : ServiceLoader.load(BootstrapClassLoader.Transformer.class, mpBootloader)) {
loader.addTransformer(transformer);
List<BytecodeTransformer> transformers = new SmartList<>();
UrlClassLoader spiLoader = UrlClassLoader.build().urls(mpBoot.toURI().toURL()).parent(BootstrapClassLoaderUtil.class.getClassLoader()).get();
for (BytecodeTransformer transformer : ServiceLoader.load(BytecodeTransformer.class, spiLoader)) {
transformers.add(transformer);
}
if (!transformers.isEmpty()) {
return new TransformingLoader(builder, transformers);
}
}
catch (Throwable e) {
LOG.info("Marketplace boot error: ", e);
// at this point logging is not initialized yet, so reporting the error directly
String path = new File(PathManager.getPluginsPath(), MARKETPLACE_PLUGIN_DIR).getAbsolutePath();
String message = "As a workaround, you may uninstall or update JetBrains Marketplace Support plugin at " + path;
Main.showMessage("JetBrains Marketplace boot failure", new Exception(message, e));
}
}
return loader;
return builder.get();
}
/**
@@ -243,4 +256,34 @@ public class BootstrapClassLoaderUtil extends ClassUtilCore {
}
return classpath;
}
private static class TransformingLoader extends UrlClassLoader {
private final List<BytecodeTransformer> myTransformers;
TransformingLoader(@NotNull Builder builder, List<BytecodeTransformer> transformers) {
super(builder);
myTransformers = Collections.unmodifiableList(transformers);
}
@Override
protected Class _defineClass(String name, byte[] b) {
return super._defineClass(name, doTransform(name, null, b));
}
@Override
protected Class _defineClass(String name, byte[] b, @Nullable ProtectionDomain protectionDomain) {
return super._defineClass(name, doTransform(name, protectionDomain, b), protectionDomain);
}
private byte[] doTransform(String name, ProtectionDomain protectionDomain, byte[] bytes) {
byte[] b = bytes;
for (BytecodeTransformer transformer : myTransformers) {
byte[] result = transformer.transform(this, name, protectionDomain, b);
if (result != null) {
b = result;
}
}
return b;
}
}
}
@@ -0,0 +1,10 @@
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.ide;
import org.jetbrains.annotations.Nullable;
import java.security.ProtectionDomain;
public interface BytecodeTransformer {
byte[] transform(ClassLoader loader, String className, @Nullable ProtectionDomain protectionDomain, byte[] classBytes);
}
@@ -189,7 +189,7 @@ public final class Main {
JOptionPane.showMessageDialog(JOptionPane.getRootFrame(), scrollPane, title, type);
}
catch (Throwable t) {
stream.println("\nAlso, an UI exception occurred on attempt to show above message:");
stream.println("\nAlso, a UI exception occurred on an attempt to show the above message:");
t.printStackTrace(stream);
}
}
@@ -123,9 +123,9 @@ class BuildOptions {
System.getProperty("teamcity.buildType.id") == null)
/**
* Specifies JRE version to be bundled with distributions, 8 by default.
* Specifies JRE version to be bundled with distributions, 11 by default.
*/
int bundledJreVersion = System.getProperty("intellij.build.bundled.jre.version", "8").toInteger()
int bundledJreVersion = System.getProperty("intellij.build.bundled.jre.version", "11").toInteger()
/**
* Specifies JRE build to be bundled with distributions. If {@code null} then jdkBuild from gradle.properties will be used.
@@ -60,6 +60,7 @@ class CommunityRepositoryModules {
"intellij.platform.lvcs.impl",
"intellij.platform.ide.impl",
"intellij.platform.projectModel.impl",
"intellij.platform.externalSystem.impl",
"intellij.platform.scriptDebugger.protocolReaderRuntime",
"intellij.regexp",
"intellij.platform.remoteServers.impl",
@@ -282,6 +283,9 @@ class CommunityRepositoryModules {
withModule("intellij.android.adt.ui.model", "adt-ui.jar")
withModule("intellij.android.layoutlib", "layoutlib-loader.jar")
withModule("android.sdktools.instant-run-client", "sdk-tools.jar")
withModule("android.sdktools.instant-run-common", "sdk-tools.jar")
withModule("intellij.android.jps", "jps/android-jps-plugin.jar", null)
withProjectLibrary("freemarker") //todo[nik] move to module libraries
@@ -331,6 +335,9 @@ class CommunityRepositoryModules {
withProjectLibrary("com.android.tools.build:builder-test-api")
withProjectLibrary("com.android.tools.pixelprobe:pixelprobe")
withProjectLibrary("org.jetbrains.intellij.deps.android.tools:perflib")
withProjectLibrary("org.jetbrains.intellij.deps.android.tools:layoutInspector")
additionalModulesToJars.entrySet().each {
withModule(it.key, it.value)
}
@@ -17,7 +17,12 @@ class JavaPluginLayout {
withModule("intellij.java.resources", "resources.jar")
withModule("intellij.java.resources.en", "resources.jar")
["intellij.java.compiler.antTasks", "intellij.java.guiForms.compiler", "intellij.java.guiForms.rt", "intellij.java.compiler.instrumentationUtil", "intellij.java.compiler.instrumentationUtil.java8", "intellij.java.jps.javacRefScanner8"].
["intellij.java.compiler.antTasks",
"intellij.java.guiForms.compiler",
"intellij.java.guiForms.rt",
"intellij.java.compiler.instrumentationUtil",
"intellij.java.compiler.instrumentationUtil.java8",
"intellij.java.jps.javacRefScanner8"].
each {
withModule(it, "javac2.jar")
}
@@ -38,6 +43,7 @@ class JavaPluginLayout {
].each {
withModule(it, "java-api.jar", "java_resources_en.jar")
}
[
"intellij.java.compiler.impl",
"intellij.java.debugger.impl",
@@ -61,11 +67,6 @@ class JavaPluginLayout {
withModule(it, "java-impl.jar", "java_resources_en.jar")
}
// externalSystem API is coupled with `java` modules and therefore must be included into the same plugin
// TODO[Vlad, IDEA-187832] remove this from Java plugin distribution as soon as the externalSystem API become java subsystem independent platform API
withModule("intellij.platform.externalSystem.impl")
withModule("intellij.platform.externalSystem.rt")
withArtifact("debugger-agent", "rt")
withArtifact("debugger-agent-storage", "rt")
withProjectLibrary("Eclipse")
@@ -86,4 +87,4 @@ class JavaPluginLayout {
addition()
}
}
}
}
@@ -438,8 +438,7 @@ idea.fatal.error.notification=disabled
}
[
'intellij.build.bundle.second.jre',
'intellij.build.bundled.second.jre.build',
'intellij.build.bundled.second.jre.version'
'intellij.build.bundled.second.jre.build'
].each { prop ->
System.getProperty(prop)?.with {
args += "-D$prop=$it"
@@ -28,55 +28,42 @@ class BundledJreManager {
* Extract JRE for Linux distribution of the product
* @return path to the directory containing 'jre' subdirectory with extracted JRE
*/
String extractLinuxJre() {
return extractJre("linux")
String extractSecondBundledJreForLinux() {
return extractSecondBundledJre("linux")
}
private static boolean doBundleSecondJre() {
boolean doBundleSecondJre() {
return System.getProperty('intellij.build.bundle.second.jre', 'false').toBoolean()
}
String getSecondJreBuild() {
if (!doBundleSecondJre()) return null
def build = System.getProperty("intellij.build.bundled.second.jre.build")
if (build == null) {
loadDependencyVersions()
build = dependencyVersions.get('secondJreBuild')
}
return build
private String getJreBuild(String osName) {
loadDependencyVersions()
return dependencyVersions.get("jreBuild_${osName}" as String, buildContext.options.bundledJreBuild ?: dependencyVersions.get("jdkBuild", ""))
}
String getSecondJreVersion() {
if (!doBundleSecondJre()) return null
def version = System.getProperty("intellij.build.bundled.second.jre.version")
if (version == null) {
loadDependencyVersions()
version = dependencyVersions.get('secondJreVersion')
}
return version
private int getJreVersion() {
return buildContext.options.bundledJreVersion
}
String extractSecondJre(String osName, String secondJreBuild) {
private int getSecondBundledJreVersion() {
return 8
}
String extractJre(String osName) {
String targetDir = "$baseDirectoryForJre/secondJre.${osName}_${JvmArchitecture.x64}"
if (new File(targetDir).exists()) {
buildContext.messages.info("JRE is already extracted to $targetDir")
return targetDir
}
def jreArchive = "jbr-${jreArchiveSuffix(secondJreBuild, getSecondJreVersion(), JvmArchitecture.x64, osName)}"
File archive = new File(jreDir(), jreArchive)
if (!archive.file || !archive.exists()) {
def errorMessage = "Cannot extract $osName JRE: file $jreArchive is not found"
buildContext.messages.warning(errorMessage)
}
File archive = findArchive(osName, getJreBuild(osName), getJreVersion(), null, JvmArchitecture.x64, JreVendor.JetBrains)
if (archive == null) {
return null
}
buildContext.messages.block("Extract $archive.absolutePath JRE") {
String destination = "$targetDir/jbr"
def destinationDir = new File(destination)
if (destinationDir.exists()) destinationDir.deleteDir()
untar(archive, destination, isSecondBundledJreModular())
untar(archive, destination, isBundledJreModular())
}
return targetDir
}
@@ -85,37 +72,41 @@ class BundledJreManager {
* Extract JRE for Windows distribution of the product
* @return path to the directory containing 'jre' subdirectory with extracted JRE
*/
String extractWinJre(JvmArchitecture arch) {
return extractJre("windows", arch)
String extractSecondBundledJreForWin(JvmArchitecture arch) {
return extractSecondBundledJre("windows", arch)
}
/**
* Extract Oracle JRE for Windows distribution of the product
* @return path to the directory containing 'jre' subdirectory with extracted JRE
*/
String extractOracleWinJre(JvmArchitecture arch) {
return extractJre("windows", arch, JreVendor.Oracle)
String extractSecondBundledOracleJreForWin(JvmArchitecture arch) {
return extractSecondBundledJre("windows", arch, JreVendor.Oracle)
}
/**
* Return path to a .tar.gz archive containing distribution of JRE for macOS which will be bundled with the product
*/
String findMacJreArchive() {
return findJreArchive("osx")?.absolutePath
String findSecondBundledJreArchiveForMac() {
return findSecondBundledJreArchive("osx")?.absolutePath
}
/**
* Return a .tar.gz archive containing distribution of JRE for Win OS which will be bundled with the product
*/
File findWinJreArchive(JvmArchitecture arch) {
return findJreArchive("windows", arch)
File findSecondBundledJreArchiveForWin(JvmArchitecture arch) {
return findSecondBundledJreArchive("windows", arch)
}
File findJreArchive(String osName, JvmArchitecture arch = JvmArchitecture.x64) {
return findArchive(osName, getJreBuild(osName), getJreVersion(), null, arch, JreVendor.JetBrains)
}
String archiveNameJre(BuildContext buildContext) {
return "jre-for-${buildContext.buildNumber}.tar.gz"
}
private String extractJre(String osName, JvmArchitecture arch = JvmArchitecture.x64, JreVendor vendor = JreVendor.JetBrains) {
private String extractSecondBundledJre(String osName, JvmArchitecture arch = JvmArchitecture.x64, JreVendor vendor = JreVendor.JetBrains) {
String vendorSuffix = vendor == JreVendor.Oracle ? ".oracle" : ""
String targetDir = arch == JvmArchitecture.x64 ?
"$baseDirectoryForJre/jre.$osName$arch.fileSuffix$vendorSuffix" :
@@ -125,7 +116,7 @@ class BundledJreManager {
return targetDir
}
File archive = findJreArchive(osName, arch, vendor)
File archive = findSecondBundledJreArchive(osName, arch, vendor)
if (archive == null) {
return null
}
@@ -135,7 +126,7 @@ class BundledJreManager {
destination = "$targetDir/jre32"
}
buildContext.messages.progress("Extracting JRE from '$archive.name' archive")
untar(archive, destination, isBundledJreModular())
untar(archive, destination, isSecondBundledJreModular())
}
return targetDir
}
@@ -186,7 +177,7 @@ class BundledJreManager {
* `build/dependencies/setupJbre.gradle`
* `build/dependencies/setupJdk.gradle`
*/
static String jreArchiveSuffix(String jreBuild, String version, JvmArchitecture arch, String osName) {
private String jreArchiveSuffix(String jreBuild, int version, JvmArchitecture arch, String osName) {
String update, build
def split = jreBuild.split('b')
if (split.length > 2) {
@@ -196,29 +187,33 @@ class BundledJreManager {
}
if (split.length == 2) {
update = split[0]
if (update.startsWith(version)) update -= version
if (update.startsWith(version.toString())) update -= version
// [11_0_2, b140] or [8u202, b1483.24]
(update, build) = ["$version$update", "b${split[1]}"]
}
else {
// [11, b96]
(update, build) = [version, jreBuild]
(update, build) = [version.toString(), jreBuild]
}
"${update}-${osName}-${arch == JvmArchitecture.x32 ? 'i586' : 'x64'}-${build}.tar.gz"
}
private File findJreArchive(String osName, JvmArchitecture arch = JvmArchitecture.x64, JreVendor vendor = JreVendor.JetBrains) {
def jreDir = jreDir()
def jreBuild = getExpectedJreBuild(osName)
private File findSecondBundledJreArchive(String osName, JvmArchitecture arch = JvmArchitecture.x64, JreVendor vendor = JreVendor.JetBrains) {
return findArchive(osName, secondBundledJreBuild, secondBundledJreVersion,
System.getProperty("intellij.build.bundled.jre.prefix"),
arch, vendor)
}
String suffix = jreArchiveSuffix(jreBuild, buildContext.options.bundledJreVersion.toString(), arch, osName)
String prefix = System.getProperty("intellij.build.bundled.jre.prefix")
if (prefix == null) {
prefix = isBundledJreModular() ? vendor.jreNamePrefix :
private File findArchive(String osName, String jreBuild,
int jreVersion, String jrePrefix,
JvmArchitecture arch, JreVendor vendor) {
def jreDir = jreDir()
String suffix = jreArchiveSuffix(jreBuild, jreVersion, arch, osName)
if (jrePrefix == null) {
jrePrefix = jreVersion >= 9 ? vendor.jreNamePrefix :
buildContext.productProperties.toolsJarRequired ? vendor.jreWithToolsJarNamePrefix : vendor.jreNamePrefix
}
def jreArchive = new File(jreDir, "$prefix$suffix")
def jreArchive = new File(jreDir, "$jrePrefix$suffix")
if (!jreArchive.file || !jreArchive.exists()) {
def errorMessage = "Cannot extract $osName JRE: file $jreArchive is not found (${jreDir.listFiles()})"
if (buildContext.options.isInDevelopmentMode) {
@@ -249,9 +244,16 @@ class BundledJreManager {
}
}
private String getExpectedJreBuild(String osName) {
loadDependencyVersions()
return dependencyVersions.get("jreBuild_${osName}" as String, buildContext.options.bundledJreBuild ?: dependencyVersions.get("jdkBuild", ""))
private String getSecondBundledJreBuild() {
if (!doBundleSecondJre()) {
throw new IllegalArgumentException("Second JBR won't be bundled, unable to determine build")
}
def build = System.getProperty("intellij.build.bundled.second.jre.build")
if (build == null) {
loadDependencyVersions()
build = dependencyVersions.get('secondJreBuild')
}
return build
}
private enum JreVendor {
@@ -267,12 +269,8 @@ class BundledJreManager {
}
}
String jreSuffix() {
isBundledJreModular() ? "" : "-jbr8"
}
boolean is32bitArchSupported() {
!isBundledJreModular()
String secondJreSuffix() {
return "-jbr8"
}
/**
@@ -286,7 +284,7 @@ class BundledJreManager {
* If {@code true} then second bundled JRE version is 9+
*/
boolean isSecondBundledJreModular() {
return secondJreVersion.toInteger() >= 9
return secondBundledJreVersion.toInteger() >= 9
}
private final Map<File, Boolean> jbrArchiveInspectionCache = new ConcurrentHashMap<>()
@@ -57,29 +57,21 @@ class LinuxDistributionBuilder extends OsSpecificDistributionBuilder {
buildTarGz(null, osSpecificDistPath, "-no-jbr")
}
}
String jreDirectoryPath = buildContext.bundledJreManager.extractLinuxJre()
String modularJreDirectoryPath // Used for Snap packages
if (buildContext.bundledJreManager.doBundleSecondJre()) {
String jreDirectoryPath = buildContext.bundledJreManager.extractSecondBundledJreForLinux()
if (jreDirectoryPath != null) {
buildTarGz(jreDirectoryPath, osSpecificDistPath, buildContext.bundledJreManager.secondJreSuffix())
}
else {
buildContext.messages.info("Skipping building Linux distribution with bundled JRE because JRE archive is missing")
}
}
// Used for Snap packages
String jreDirectoryPath = buildContext.bundledJreManager.extractJre("linux")
buildTarGz(jreDirectoryPath, osSpecificDistPath, "")
if (jreDirectoryPath != null) {
buildTarGz(jreDirectoryPath, osSpecificDistPath, buildContext.bundledJreManager.jreSuffix())
if (buildContext.bundledJreManager.bundledJreModular) {
modularJreDirectoryPath = jreDirectoryPath
}
}
else {
buildContext.messages.info("Skipping building Linux distribution with bundled JRE because JRE archive is missing")
}
String secondJreBuild = buildContext.bundledJreManager.getSecondJreBuild()
if (secondJreBuild != null) {
String secondJreDirectoryPath = buildContext.bundledJreManager.extractSecondJre("linux", secondJreBuild)
buildTarGz(secondJreDirectoryPath, osSpecificDistPath, "")
if (buildContext.bundledJreManager.secondBundledJreModular) {
modularJreDirectoryPath = secondJreDirectoryPath
}
}
if (modularJreDirectoryPath != null) {
buildSnapPackage(modularJreDirectoryPath, osSpecificDistPath)
buildSnapPackage(jreDirectoryPath, osSpecificDistPath)
}
else {
buildContext.messages.info("Skipping building Snap packages because no modular JRE are available")
@@ -107,21 +107,20 @@ class MacDistributionBuilder extends OsSpecificDistributionBuilder {
void buildArtifacts(String osSpecificDistPath) {
buildContext.executeStep("Build macOS artifacts", BuildOptions.MAC_ARTIFACTS_STEP) {
def macZipPath = buildMacZip(osSpecificDistPath)
def secondJreBuild = buildContext.bundledJreManager.getSecondJreBuild()
if (buildContext.proprietaryBuildTools.macHostProperties == null) {
buildContext.messages.info("A macOS build agent isn't configured - .dmg artifact won't be produced")
buildContext.notifyArtifactBuilt(macZipPath)
}
else {
buildContext.executeStep("Build .dmg artifact for macOS", BuildOptions.MAC_DMG_STEP) {
MacDmgBuilder.signAndBuildDmg(buildContext, customizer, buildContext.proprietaryBuildTools.macHostProperties, macZipPath)
if (secondJreBuild != null) {
def secondJreVersion = buildContext.bundledJreManager.getSecondJreVersion()
def jreArchive = "jbr-${buildContext.bundledJreManager.jreArchiveSuffix(secondJreBuild, secondJreVersion, JvmArchitecture.x64, 'osx')}"
File archive = new File(buildContext.bundledJreManager.jreDir(), jreArchive)
if (archive.file) {
MacDmgBuilder.signAndBuildDmg(buildContext, customizer, buildContext.proprietaryBuildTools.macHostProperties, macZipPath, archive.absolutePath)
}
if (buildContext.bundledJreManager.doBundleSecondJre()) {
MacDmgBuilder.signAndBuildDmg(buildContext, customizer, buildContext.proprietaryBuildTools.macHostProperties,
macZipPath, buildContext.bundledJreManager.findSecondBundledJreArchiveForMac(), true)
}
File jreArchive = buildContext.bundledJreManager.findJreArchive('osx')
if (jreArchive.file) {
MacDmgBuilder.signAndBuildDmg(buildContext, customizer, buildContext.proprietaryBuildTools.macHostProperties,
macZipPath, jreArchive.absolutePath, false)
}
buildContext.ant.delete(file: macZipPath)
}
@@ -270,9 +269,8 @@ class MacDistributionBuilder extends OsSpecificDistributionBuilder {
def extraBins = customizer.extraExecutables
def allPaths = [buildContext.paths.distAll, macDistPath]
def zipRoot = getZipRoot(buildContext, customizer)
def suffix = buildContext.bundledJreManager.jreSuffix()
def baseName = buildContext.productProperties.getBaseArtifactName(buildContext.applicationInfo, buildContext.buildNumber)
def targetPath = "${buildContext.paths.artifacts}/${baseName}${suffix}.mac.zip"
def targetPath = "${buildContext.paths.artifacts}/${baseName}.mac.zip"
buildContext.messages.progress("Building zip archive for macOS")
def productJsonDir = new File(buildContext.paths.temp, "mac.dist.product-info.json.zip").absolutePath
@@ -35,17 +35,18 @@ class MacDmgBuilder {
dmgBuilder.doSignBinaryFiles(macDistPath)
}
static void signAndBuildDmg(BuildContext buildContext, MacDistributionCustomizer customizer, MacHostProperties macHostProperties, String macZipPath, String secondJreArchive = null) {
static void signAndBuildDmg(BuildContext buildContext, MacDistributionCustomizer customizer,
MacHostProperties macHostProperties, String macZipPath,
String jreArchivePath, boolean isSecondJre) {
MacDmgBuilder dmgBuilder = createInstance(buildContext, customizer, macHostProperties)
def jreArchivePath = (secondJreArchive == null) ? buildContext.bundledJreManager.findMacJreArchive() : secondJreArchive
if (jreArchivePath != null) {
dmgBuilder.doSignAndBuildDmg(macZipPath, jreArchivePath, secondJreArchive)
dmgBuilder.doSignAndBuildDmg(macZipPath, jreArchivePath, isSecondJre)
}
else {
buildContext.messages.info("Skipping building macOS distribution with bundled JRE because JRE archive is missing")
}
if (buildContext.options.buildDmgWithoutBundledJre) {
dmgBuilder.doSignAndBuildDmg(macZipPath, null)
dmgBuilder.doSignAndBuildDmg(macZipPath, null, false)
}
}
@@ -105,16 +106,16 @@ class MacDmgBuilder {
return "../${topLevelDir}/Contents/Home/${isModular ? '' : 'jre/'}bin/java"
}
private void doSignAndBuildDmg(String macZipPath, String jreArchivePath, String secondJreArchive = null) {
private void doSignAndBuildDmg(String macZipPath, String jreArchivePath, boolean isSecondJre) {
def zipRoot = MacDistributionBuilder.getZipRoot(buildContext, customizer)
def jreManager = buildContext.bundledJreManager
String suffix = "-no-jdk", javaExePath = null
if (secondJreArchive != null) {
suffix = ""
javaExePath = getJavaExePath(secondJreArchive, jreManager.isSecondBundledJreModular())
if (isSecondJre) {
suffix = jreManager.secondJreSuffix()
javaExePath = getJavaExePath(jreArchivePath, jreManager.isSecondBundledJreModular())
}
else if (jreArchivePath != null) {
suffix = jreManager.jreSuffix()
suffix = ""
javaExePath = getJavaExePath(jreArchivePath, jreManager.isBundledJreModular())
}
def productJsonDir = new File(buildContext.paths.temp, "mac.dist.product-info.json.dmg$suffix").absolutePath
@@ -61,7 +61,7 @@ class WinExeInstallerBuilder {
customizer.fileAssociations.collect { !it.startsWith(".") ? ".$it" : it}
}
void buildInstaller(String winDistPath, String additionalDirectoryToInclude, String secondJreSuffix = null, boolean jre32BitVersionSupported) {
void buildInstaller(String winDistPath, String additionalDirectoryToInclude, String suffix, boolean jre32BitVersionSupported) {
if (!SystemInfo.isWindows && !SystemInfo.isLinux) {
buildContext.messages.warning("Windows installer can be built only under Windows or Linux")
@@ -69,7 +69,6 @@ class WinExeInstallerBuilder {
}
String communityHome = buildContext.paths.communityHome
def suffix = secondJreSuffix != null ? secondJreSuffix : buildContext.bundledJreManager.jreSuffix()
String outFileName = buildContext.productProperties.getBaseArtifactName(buildContext.applicationInfo, buildContext.buildNumber) + suffix
buildContext.messages.progress("Building Windows installer $outFileName")
@@ -108,8 +107,8 @@ class WinExeInstallerBuilder {
generator.generateInstallerFile(new File(box, "nsiconf/idea_win.nsh"))
if (buildContext.bundledJreManager.is32bitArchSupported()) {
String jre32Dir = buildContext.bundledJreManager.extractWinJre(JvmArchitecture.x32)
if (buildContext.bundledJreManager.doBundleSecondJre()) {
String jre32Dir = buildContext.bundledJreManager.extractSecondBundledJreForWin(JvmArchitecture.x32)
if (jre32Dir != null) {
generator.addDirectory(jre32Dir)
}
@@ -72,56 +72,60 @@ class WindowsDistributionBuilder extends OsSpecificDistributionBuilder {
@Override
void buildArtifacts(String winDistPath) {
def arch = customizer.bundledJreArchitecture
def jreSuffix = buildContext.bundledJreManager.secondJreSuffix()
String jreDirectoryPath64 = null
//do not include win32 launcher into winzip with 9+ jbr bundled
List<String> excludeList = ["bin/${buildContext.productProperties.baseFileName}.exe", "bin/${buildContext.productProperties.baseFileName}.exe.vmoptions"]
String jreDirectoryPath64 = arch != null ? buildContext.bundledJreManager.extractWinJre(arch) : null
List<String> jreDirectoryPaths = [jreDirectoryPath64]
if (buildContext.bundledJreManager.doBundleSecondJre()) {
jreDirectoryPath64 = arch != null ? buildContext.bundledJreManager.extractSecondBundledJreForWin(arch) : null
List<String> jreDirectoryPaths = [jreDirectoryPath64]
if (customizer.getBaseDownloadUrlForJre() != null && arch != JvmArchitecture.x32 && buildContext.bundledJreManager.is32bitArchSupported()) {
File archive = buildContext.bundledJreManager.findWinJreArchive(JvmArchitecture.x32)
if (archive != null && archive.exists()) {
//prepare folder with jre x86 for win archive
def jreDirectoryPath = buildContext.bundledJreManager.extractWinJre(JvmArchitecture.x32)
buildContext.ant.tar(tarfile: "${buildContext.paths.artifacts}/${buildContext.bundledJreManager.archiveNameJre(buildContext)}", longfile: "gnu", compression: "gzip") {
tarfileset(dir: "${jreDirectoryPath}/jre32") {
include(name: "**/**")
if (customizer.getBaseDownloadUrlForJre() != null && arch != JvmArchitecture.x32) {
File archive = buildContext.bundledJreManager.findSecondBundledJreArchiveForWin(JvmArchitecture.x32)
if (archive != null && archive.exists()) {
//prepare folder with jre x86 for win archive
def jreDirectoryPath = buildContext.bundledJreManager.extractSecondBundledJreForWin(JvmArchitecture.x32)
buildContext.ant.tar(tarfile: "${buildContext.paths.artifacts}/${buildContext.bundledJreManager.archiveNameJre(buildContext)}", longfile: "gnu", compression: "gzip") {
tarfileset(dir: "${jreDirectoryPath}/jre32") {
include(name: "**/**")
}
}
jreDirectoryPaths = [jreDirectoryPath64, jreDirectoryPath]
}
}
if (customizer.buildZipArchive) {
buildWinZip(jreDirectoryPaths.findAll { it != null }, "${jreSuffix}.win", winDistPath, [])
}
if (arch != null && customizer.buildZipWithBundledOracleJre && arch != JvmArchitecture.x32) {
String oracleJrePath = buildContext.bundledJreManager.extractSecondBundledOracleJreForWin(arch)
if (oracleJrePath != null) {
buildWinZip([oracleJrePath], "${jreSuffix}-oracle-win", winDistPath)
}
else {
buildContext.messages.warning("Skipping building Windows zip archive with bundled Oracle JRE because JRE archive is missing")
}
jreDirectoryPaths = [jreDirectoryPath64, jreDirectoryPath]
}
}
def jreSuffix = buildContext.bundledJreManager.jreSuffix()
def secondJreBuild = buildContext.bundledJreManager.getSecondJreBuild()
def secondJreDirectoryPath = (secondJreBuild != null) ? buildContext.bundledJreManager.extractSecondJre("windows", secondJreBuild) : null
def jreDirectoryPath = buildContext.bundledJreManager.extractJre("windows")
if (customizer.buildZipArchive) {
buildWinZip(jreDirectoryPaths.findAll { it != null }, "${jreSuffix}.win", winDistPath, !buildContext.bundledJreManager.is32bitArchSupported() ? excludeList : [])
if (secondJreDirectoryPath != null) {
buildWinZip([secondJreDirectoryPath], ".win", winDistPath, excludeList)
}
}
if (arch != null && customizer.buildZipWithBundledOracleJre &&
(arch != JvmArchitecture.x32 || buildContext.bundledJreManager.is32bitArchSupported())) {
String oracleJrePath = buildContext.bundledJreManager.extractOracleWinJre(arch)
if (oracleJrePath != null) {
buildWinZip([oracleJrePath], "${jreSuffix}-oracle-win", winDistPath)
}
else {
buildContext.messages.warning("Skipping building Windows zip archive with bundled Oracle JRE because JRE archive is missing")
}
buildWinZip([jreDirectoryPath], ".win", winDistPath, excludeList)
}
buildContext.executeStep("Build Windows Exe Installer", BuildOptions.WINDOWS_EXE_INSTALLER_STEP) {
def productJsonDir = new File(buildContext.paths.temp, "win.dist.product-info.json.exe").absolutePath
generateProductJson(productJsonDir, jreDirectoryPath64 != null)
new ProductInfoValidator(buildContext).validateInDirectory(productJsonDir, "", [winDistPath, jreDirectoryPath64], [])
new WinExeInstallerBuilder(buildContext, customizer, jreDirectoryPath64).buildInstaller(winDistPath, productJsonDir, null, buildContext.bundledJreManager.is32bitArchSupported())
if (secondJreDirectoryPath != null) {
generateProductJson(productJsonDir, secondJreDirectoryPath != null)
new ProductInfoValidator(buildContext).validateInDirectory(productJsonDir, "", [winDistPath, secondJreDirectoryPath], [])
new WinExeInstallerBuilder(buildContext, customizer, secondJreDirectoryPath).buildInstaller(winDistPath, productJsonDir, "", buildContext.bundledJreManager.getSecondJreVersion().toInteger() == 8)
if (buildContext.bundledJreManager.doBundleSecondJre()) {
generateProductJson(productJsonDir, jreDirectoryPath64 != null)
new ProductInfoValidator(buildContext).validateInDirectory(productJsonDir, "", [winDistPath, jreDirectoryPath64], [])
new WinExeInstallerBuilder(buildContext, customizer, jreDirectoryPath64)
.buildInstaller(winDistPath, productJsonDir,
buildContext.bundledJreManager.secondJreSuffix(),
buildContext.bundledJreManager.secondBundledJreModular)
}
generateProductJson(productJsonDir, jreDirectoryPath != null)
new ProductInfoValidator(buildContext).validateInDirectory(productJsonDir, "", [winDistPath, jreDirectoryPath], [])
new WinExeInstallerBuilder(buildContext, customizer, jreDirectoryPath)
.buildInstaller(winDistPath, productJsonDir, '', buildContext.bundledJreManager.bundledJreModular)
}
}
@@ -43,7 +43,7 @@ internal fun checkIcons(context: Context = Context(), loggerImpl: Consumer<Strin
}
catch (e: Throwable) {
val investigator = Investigator(DEFAULT_INVESTIGATOR)
assignInvestigation(investigator, emptyList())
assignInvestigation(investigator)
if (context.notifySlack) callSafely {
notifySlackChannel(investigator, context)
}
@@ -52,8 +52,6 @@ internal fun checkIcons(context: Context = Context(), loggerImpl: Consumer<Strin
if (context.doSyncDevRepo || context.iconsCommitHashesToSync.isNotEmpty()) {
createReviewForDev(context)?.also {
context.createdReviews = listOf(it)
assignInvestigation(Investigator(triggeredBy().email),
context.createdReviews.map(Review::url))
}
}
}
@@ -29,11 +29,8 @@ internal val DEFAULT_INVESTIGATOR by lazy {
internal class Investigator(val email: String, var isAssigned: Boolean = false)
internal fun assignInvestigation(investigator: Investigator, reviews: List<String>): Investigator {
val report = if (reviews.isNotEmpty()) {
"Please review and cherry-pick ${reviews.joinToString()}."
}
else "Unexpected error, please investigate."
internal fun assignInvestigation(investigator: Investigator): Investigator {
val report = "Unexpected error, please investigate."
assignInvestigation(investigator, report)
if (!investigator.isAssigned) {
var nextAttempts = guessEmail(investigator.email)
@@ -52,8 +52,17 @@ class ApplicationStoreImpl(private val application: Application, pathMacroManage
override fun toString() = "app"
}
internal val appFileBasedStorageConfiguration = object: FileBasedStorageConfiguration {
override val isUseVfsForRead: Boolean
get() = false
override val isUseVfsForWrite: Boolean
get() = false
}
class ApplicationStorageManager(application: Application?, pathMacroManager: PathMacroManager? = null)
: StateStorageManagerImpl("application", pathMacroManager?.createTrackingSubstitutor(), application) {
override fun getFileBasedStorageConfiguration(fileSpec: String) = appFileBasedStorageConfiguration
override fun getOldStorageSpec(component: Any, componentName: String, operation: StateStorageOperation): String? {
return when (component) {
@@ -72,9 +81,6 @@ class ApplicationStorageManager(application: Application?, pathMacroManager: Pat
override val isUseXmlProlog: Boolean
get() = false
override val isUseVfsForWrite: Boolean
get() = false
override fun providerDataStateChanged(storage: FileBasedStorage, writer: DataWriter?, type: DataStateChanged) {
// IDEA-144052 When "Settings repository" is enabled changes in 'Path Variables' aren't saved to default path.macros.xml file causing errors in build process
if (storage.fileSpec == "path.macros.xml" || storage.fileSpec == "applicationLibraries.xml") {
@@ -231,7 +231,7 @@ abstract class ComponentStoreImpl : IComponentStore {
@CalledInAwt
override fun saveComponent(component: PersistentStateComponent<*>) {
val stateSpec = getStateSpec(component)
LOG.info("saveComponent is called for ${stateSpec.name}")
LOG.debug { "saveComponent is called for ${stateSpec.name}" }
val saveManager = createSaveSessionProducerManager()
commitComponent(saveManager, ComponentInfoImpl(component, stateSpec), null)
val absolutePath = Paths.get(storageManager.expandMacros(findNonDeprecated(stateSpec.storages).path)).toAbsolutePath().toString()
@@ -242,8 +242,7 @@ abstract class ComponentStoreImpl : IComponentStore {
val saveResult = saveManager.save()
saveResult.throwIfErrored()
val isSomethingChanged = saveResult.isChanged
if (!isSomethingChanged) {
if (!saveResult.isChanged) {
LOG.info("saveApplicationComponent is called for ${stateSpec.name} but nothing to save")
}
}
@@ -46,7 +46,8 @@ open class FileBasedStorage(file: Path,
var file = file
private set
protected open val configuration: FileBasedStorageConfiguration = defaultFileBasedStorageConfiguration
protected open val configuration: FileBasedStorageConfiguration
get() = defaultFileBasedStorageConfiguration
init {
val app = ApplicationManager.getApplication()
@@ -57,7 +58,7 @@ open class FileBasedStorage(file: Path,
protected open val isUseXmlProlog = false
override val isUseVfsForWrite: Boolean
final override val isUseVfsForWrite: Boolean
get() = configuration.isUseVfsForWrite
private val isUseUnixLineSeparator: Boolean
@@ -9,17 +9,13 @@ interface FileBasedStorageConfiguration {
val isUseVfsForWrite: Boolean
fun resolveVirtualFile(path: String): VirtualFile?
fun resolveVirtualFile(path: String): VirtualFile? = LocalFileSystem.getInstance().findFileByPath(path)
}
internal val defaultFileBasedStorageConfiguration: FileBasedStorageConfiguration = object: FileBasedStorageConfiguration {
internal val defaultFileBasedStorageConfiguration: FileBasedStorageConfiguration = object : FileBasedStorageConfiguration {
override val isUseVfsForRead: Boolean
get() = false
override val isUseVfsForWrite: Boolean
get() = true
override fun resolveVirtualFile(path: String): VirtualFile? {
return LocalFileSystem.getInstance().findFileByPath(path)
}
}
@@ -65,12 +65,11 @@ internal class ModuleStateStorageManager(macroSubstitutor: TrackingPathMacroSubs
override val isExternalSystemStorageEnabled: Boolean
get() = (componentManager as Module).project.isExternalStorageEnabled
override fun createFileBasedStorage(path: String, collapsedPath: String, roamingType: RoamingType, rootTagName: String?): StateStorage
= ModuleFileStorage(this, Paths.get(path), collapsedPath, rootTagName, roamingType, getMacroSubstitutor(collapsedPath), if (roamingType == RoamingType.DISABLED) null else compoundStreamProvider)
override fun createFileBasedStorage(path: String, collapsedPath: String, roamingType: RoamingType, rootTagName: String?): StateStorage {
return ModuleFileStorage(this, Paths.get(path), collapsedPath, rootTagName, roamingType, getMacroSubstitutor(collapsedPath), if (roamingType == RoamingType.DISABLED) null else compoundStreamProvider)
}
// use VFS to load module file because it is refreshed and loaded into VFS in any case
override val isUseVfsForRead: Boolean
get() = true
override fun getFileBasedStorageConfiguration(fileSpec: String) = moduleFileBasedStorageConfiguration
private class ModuleFileStorage(storageManager: ModuleStateStorageManager,
file: Path,
@@ -85,4 +84,13 @@ internal class ModuleStateStorageManager(macroSubstitutor: TrackingPathMacroSubs
}
}
}
}
}
private val moduleFileBasedStorageConfiguration = object : FileBasedStorageConfiguration {
override val isUseVfsForWrite: Boolean
get() = true
// use VFS to load module file because it is refreshed and loaded into VFS in any case
override val isUseVfsForRead: Boolean
get() = true
}
@@ -21,6 +21,28 @@ open class ProjectStateStorageManager(macroSubstitutor: PathMacroSubstitutor,
const val ROOT_TAG_NAME = "project"
}
private val fileBasedStorageConfiguration = object : FileBasedStorageConfiguration {
override val isUseVfsForWrite: Boolean
get() = true
override val isUseVfsForRead: Boolean
get() = project is VirtualFileResolver
override fun resolveVirtualFile(path: String): VirtualFile? {
return when (project) {
is VirtualFileResolver -> project.resolveVirtualFile(path)
else -> super.resolveVirtualFile(path)
}
}
}
override fun getFileBasedStorageConfiguration(fileSpec: String): FileBasedStorageConfiguration {
return when {
isSpecialStorage(fileSpec) -> appFileBasedStorageConfiguration
else -> fileBasedStorageConfiguration
}
}
override fun normalizeFileSpec(fileSpec: String) = removeMacroIfStartsWith(super.normalizeFileSpec(fileSpec), PROJECT_CONFIG_DIR)
override fun expandMacros(path: String): String {
@@ -46,16 +68,6 @@ open class ProjectStateStorageManager(macroSubstitutor: PathMacroSubstitutor,
override val isExternalSystemStorageEnabled: Boolean
get() = project.isExternalStorageEnabled
override val isUseVfsForRead: Boolean
get() = project is VirtualFileResolver
override fun resolveVirtualFile(path: String): VirtualFile? {
return when (project) {
is VirtualFileResolver -> project.resolveVirtualFile(path)
else -> super.resolveVirtualFile(path)
}
}
}
// for upsource
@@ -1,7 +1,6 @@
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.configurationStore
import com.intellij.ide.SaveAndSyncHandler
import com.intellij.ide.highlighter.ProjectFileType
import com.intellij.ide.highlighter.WorkspaceFileType
import com.intellij.openapi.application.ApplicationManager
@@ -105,8 +104,7 @@ abstract class ProjectStoreBase(final override val project: Project) : Component
}
}
// used in upsource
protected suspend fun setPath(filePath: String, isRefreshVfs: Boolean) {
override fun setPath(filePath: String, isRefreshVfsNeeded: Boolean) {
val storageManager = storageManager
val fs = LocalFileSystem.getInstance()
val isUnitTestMode = ApplicationManager.getApplication().isUnitTestMode
@@ -118,10 +116,8 @@ abstract class ProjectStoreBase(final override val project: Project) : Component
val workspacePath = composeFileBasedProjectWorkSpacePath(filePath)
storageManager.addMacro(StoragePathMacros.WORKSPACE_FILE, workspacePath)
if (isRefreshVfs) {
withEdtContext {
VfsUtil.markDirtyAndRefresh(false, true, false, fs.refreshAndFindFileByPath(filePath), fs.refreshAndFindFileByPath(workspacePath))
}
if (isRefreshVfsNeeded) {
VfsUtil.markDirtyAndRefresh(false, true, false, fs.refreshAndFindFileByPath(filePath), fs.refreshAndFindFileByPath(workspacePath))
}
if (isUnitTestMode) {
@@ -142,10 +138,8 @@ abstract class ProjectStoreBase(final override val project: Project) : Component
isOptimiseTestLoadSpeed = !Paths.get(filePath).exists()
}
if (isRefreshVfs) {
withEdtContext {
VfsUtil.markDirtyAndRefresh(false, true, true, fs.refreshAndFindFileByPath(configDir))
}
if (isRefreshVfsNeeded) {
VfsUtil.markDirtyAndRefresh(false, true, true, fs.refreshAndFindFileByPath(configDir))
}
}
@@ -174,8 +168,6 @@ abstract class ProjectStoreBase(final override val project: Project) : Component
catch (e: Exception) {
LOG.error(e)
}
SaveAndSyncHandler.getInstance().scheduleSave(SaveAndSyncHandler.SaveTask(project, saveDocuments = false, forceSavingAllSettings = true))
}
storageManager.addMacro(StoragePathMacros.PRODUCT_WORKSPACE_FILE, "$productSpecificWorkspaceParentDir/$projectId.xml")
@@ -23,7 +23,6 @@ import com.intellij.util.containers.computeIfAny
import com.intellij.util.io.*
import kotlinx.coroutines.coroutineScope
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking
import org.jetbrains.annotations.ApiStatus
import org.jetbrains.annotations.CalledInAny
import java.nio.file.AccessDeniedException
@@ -46,9 +45,7 @@ open class ProjectStoreImpl(project: Project) : ProjectStoreBase(project) {
override val storageManager = ProjectStateStorageManager(TrackingPathMacroSubstitutorImpl(PathMacroManager.getInstance(project)), project)
override fun setPath(path: String) {
runBlocking {
setPath(path, true)
}
setPath(path, true)
}
override fun getProjectName(): String {
@@ -36,8 +36,7 @@ private val MACRO_PATTERN = Pattern.compile("(\\$[^$]*\\$)")
open class StateStorageManagerImpl(private val rootTagName: String,
final override val macroSubstitutor: PathMacroSubstitutor? = null,
override val componentManager: ComponentManager? = null,
private val virtualFileTracker: StorageVirtualFileTracker? = createDefaultVirtualTracker(componentManager)) : StateStorageManager,
FileBasedStorageConfiguration by defaultFileBasedStorageConfiguration {
private val virtualFileTracker: StorageVirtualFileTracker? = createDefaultVirtualTracker(componentManager)) : StateStorageManager {
private val macros: MutableList<Macro> = ContainerUtil.createLockFreeCopyOnWriteList()
private val storageLock = ReentrantReadWriteLock()
private val storages = THashMap<String, StateStorage>()
@@ -62,14 +61,16 @@ open class StateStorageManagerImpl(private val rootTagName: String,
// access under storageLock
@Suppress("LeakingThis")
private var isUseVfsListener = if (componentManager == null || !isUseVfsForWrite) ThreeState.NO else ThreeState.UNSURE // unsure because depends on stream provider state
private var isUseVfsListener = when {
componentManager == null || componentManager is Application -> ThreeState.NO
else -> ThreeState.UNSURE // unsure because depends on stream provider state
}
open fun getFileBasedStorageConfiguration(fileSpec: String): FileBasedStorageConfiguration = defaultFileBasedStorageConfiguration
protected open val isUseXmlProlog: Boolean
get() = true
override val isUseVfsForWrite: Boolean
get() = true
companion object {
private fun createDefaultVirtualTracker(componentManager: ComponentManager?): StorageVirtualFileTracker? {
return when (componentManager) {
@@ -307,11 +308,8 @@ open class StateStorageManagerImpl(private val rootTagName: String,
override val isUseXmlProlog: Boolean
get() = rootElementName != null && storageManager.isUseXmlProlog && !isSpecialStorage(fileSpec)
override val isUseVfsForWrite: Boolean
get() = super.isUseVfsForWrite && !isSpecialStorage(fileSpec)
override val configuration: FileBasedStorageConfiguration
get() = storageManager
get() = storageManager.getFileBasedStorageConfiguration(fileSpec)
override fun beforeElementSaved(elements: MutableList<Element>, rootAttributes: MutableMap<String, String>) {
if (rootElementName != null) {
@@ -169,9 +169,9 @@ internal class ComponentStoreModificationTrackerTest {
private class MyComponentStore(testAppConfigPath: Path) : ChildlessComponentStore() {
private class MyStorageManager(private val rootDir: Path) : StateStorageManagerImpl("application") {
override val isUseXmlProlog = false
override fun getFileBasedStorageConfiguration(fileSpec: String) = appFileBasedStorageConfiguration
override val isUseVfsForWrite = false
override val isUseXmlProlog = false
override fun normalizeFileSpec(fileSpec: String) = removeMacroIfStartsWith(super.normalizeFileSpec(fileSpec), APP_CONFIG)
@@ -20,10 +20,13 @@
package com.intellij.openapi.fileTypes;
import com.intellij.openapi.util.KeyedExtensionCollector;
import com.intellij.util.KeyedLazyInstance;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class FileTypeExtension<T> extends KeyedExtensionCollector<T, FileType> {
public FileTypeExtension(@NonNls final String epName) {
@@ -45,4 +48,13 @@ public class FileTypeExtension<T> extends KeyedExtensionCollector<T, FileType> {
final List<T> all = allForFileType(t);
return all.isEmpty() ? null : all.get(0);
}
public Map<FileType, T> getAllRegisteredExtensions() {
List<KeyedLazyInstance<T>> extensions = getExtensions();
Map<FileType, T> result = new HashMap<>();
for (KeyedLazyInstance<T> extension : extensions) {
result.put(FileTypeRegistry.getInstance().findFileTypeByName(extension.getKey()), extension.getInstance());
}
return result;
}
}
@@ -34,7 +34,8 @@ public abstract class FileTypeRegistry {
public abstract boolean isFileOfType(@NotNull VirtualFile file, @NotNull FileType type);
public LanguageFileType findFileTypeByLanguage(Language language) {
@Nullable
public LanguageFileType findFileTypeByLanguage(@NotNull Language language) {
return language.findMyFileType(getRegisteredFileTypes());
}
@@ -32,9 +32,14 @@ public interface StartupActivity {
ExtensionPointName<StartupActivity> POST_STARTUP_ACTIVITY = ExtensionPointName.create("com.intellij.postStartupActivity");
/**
* Executed some time after startup on a background thread with no progress indicator. Such activities may produce notifications
* but should not be used for any work that needs to be otherwise visible to users. Such activities are run regardless
* of the current indexing mode and should not be used for any work that requires access to indices.
* Executed some time after startup on a background thread with no visible progress indicator. Such activities may produce
* notifications but should not be used for any work that needs to be otherwise visible to users (including work that consumes
* CPU over a noticeable period of time).
*
* Such activities are run regardless of the current indexing mode and should not be used for any work that requires access
* to indices. The current project may get disposed while the activity is running, and the activity may not be interrupted
* immediately when this happens, so if you need to access other components, you're responsible for doing this in a
* thread-safe way (e.g. by taking a read action to collect all the state you need).
*/
ExtensionPointName<StartupActivity> BACKGROUND_POST_STARTUP_ACTIVITY = ExtensionPointName.create("com.intellij.backgroundPostStartupActivity");

Some files were not shown because too many files have changed in this diff Show More