Skip to content

Commit 3f9f609

Browse files
committed
Give the imports IntelliJ IDEA inserts open-java-format's layout
Auto-import, Alt+Enter and completion insert imports through the IDE's ImportHelper, by the Java code style settings, and no import optimizer sees them: by default five classes from one package become an import on demand, which open-java-format keeps. A CodeStyleSettingsModifier now gives Java files open-java-format's import settings while the plugin is enabled: single-class imports up to 999 from a package, no packages always imported on demand, and the static imports, a blank line, then the others. The Code Style page then says that open-java-format may override its settings, and its Disable link switches the plugin off for the project, as unticking it on the plugin's page does. Switching the plugin on or off there refreshes the code style of open files, which the IDE caches for each file. The platform applies only the first modifier that changes a file's settings, and EditorConfig's is registered first: in a project whose .editorconfig sets code style properties for Java files, these settings do not apply.
1 parent 9d5ece4 commit 3f9f609

6 files changed

Lines changed: 301 additions & 8 deletions

File tree

Original file line numberDiff line numberDiff line change
@@ -0,0 +1,88 @@
1+
/*
2+
* Licensed under the Apache License, Version 2.0 (the "License");
3+
* you may not use this file except in compliance with the License.
4+
* You may obtain a copy of the License at
5+
*
6+
* http://www.apache.org/licenses/LICENSE-2.0
7+
*
8+
* Unless required by applicable law or agreed to in writing, software
9+
* distributed under the License is distributed on an "AS IS" BASIS,
10+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11+
* See the License for the specific language governing permissions and
12+
* limitations under the License.
13+
*/
14+
15+
package com.palantir.javaformat.intellij;
16+
17+
import com.intellij.ide.highlighter.JavaFileType;
18+
import com.intellij.openapi.project.Project;
19+
import com.intellij.psi.PsiFile;
20+
import com.intellij.psi.codeStyle.CodeStyleSettings;
21+
import com.intellij.psi.codeStyle.JavaCodeStyleSettings;
22+
import com.intellij.psi.codeStyle.PackageEntry;
23+
import com.intellij.psi.codeStyle.PackageEntryTable;
24+
import com.intellij.psi.codeStyle.modifier.CodeStyleSettingsModifier;
25+
import com.intellij.psi.codeStyle.modifier.CodeStyleStatusBarUIContributor;
26+
import com.intellij.psi.codeStyle.modifier.TransientCodeStyleSettings;
27+
import java.util.function.Consumer;
28+
import org.jspecify.annotations.Nullable;
29+
30+
/**
31+
* Gives the Java files the plugin formats the import settings that open-java-format writes by. The IDE inserts imports
32+
* through auto-import, Alt+Enter and completion by these settings, and no import optimizer sees them: with the IDE's
33+
* defaults, five classes from one package become {@code import java.util.*;}, which open-java-format keeps.
34+
*
35+
* <p>The platform applies only the first modifier that changes a file's settings, and EditorConfig's is registered
36+
* first: in a project whose {@code .editorconfig} sets code style properties for Java files, these settings do not
37+
* apply, and its {@code ij_java_*} properties can set them there instead.
38+
*/
39+
final class PalantirJavaFormatCodeStyleSettingsModifier implements CodeStyleSettingsModifier {
40+
// More names than a file imports from one package, so that an import on demand is never written.
41+
private static final int NEVER_IMPORT_ON_DEMAND = 999;
42+
43+
@Override
44+
public boolean modifySettings(TransientCodeStyleSettings settings, PsiFile file) {
45+
if (!JavaFileType.INSTANCE.equals(file.getFileType())
46+
|| !PalantirJavaFormatSettings.getInstance(file.getProject()).isEnabled()) {
47+
return false;
48+
}
49+
var javaSettings = settings.getCustomSettings(JavaCodeStyleSettings.class);
50+
javaSettings.USE_SINGLE_CLASS_IMPORTS = true;
51+
javaSettings.CLASS_COUNT_TO_USE_IMPORT_ON_DEMAND = NEVER_IMPORT_ON_DEMAND;
52+
javaSettings.NAMES_COUNT_TO_USE_IMPORT_ON_DEMAND = NEVER_IMPORT_ON_DEMAND;
53+
javaSettings.PACKAGES_TO_USE_IMPORT_ON_DEMAND.copyFrom(new PackageEntryTable());
54+
// Static imports, a blank line, then the others, each group in the order of its names: ImportOrderer's.
55+
javaSettings.LAYOUT_STATIC_IMPORTS_SEPARATELY = true;
56+
var importLayout = new PackageEntryTable();
57+
importLayout.addEntry(PackageEntry.ALL_OTHER_STATIC_IMPORTS_ENTRY);
58+
importLayout.addEntry(PackageEntry.BLANK_LINE_ENTRY);
59+
importLayout.addEntry(PackageEntry.ALL_OTHER_IMPORTS_ENTRY);
60+
javaSettings.IMPORT_LAYOUT_TABLE.copyFrom(importLayout);
61+
return true;
62+
}
63+
64+
// The Code Style page then says that its settings may be overridden by open-java-format.
65+
@Override
66+
public boolean mayOverrideSettingsOf(Project project) {
67+
return PalantirJavaFormatSettings.getInstance(project).isEnabled();
68+
}
69+
70+
@Override
71+
public String getName() {
72+
return "open-java-format";
73+
}
74+
75+
@Override
76+
@Nullable
77+
public CodeStyleStatusBarUIContributor getStatusBarUiContributor(TransientCodeStyleSettings transientSettings) {
78+
return null;
79+
}
80+
81+
// What the Disable link next to that message runs: these settings come with the plugin, so it switches the plugin
82+
// off for the project, as unticking it on the plugin's settings page does.
83+
@Override
84+
public Consumer<CodeStyleSettings> getDisablingFunction(Project project) {
85+
return settings -> PalantirJavaFormatSettings.getInstance(project)
86+
.setEnabled(PalantirJavaFormatSettings.disabledState(project));
87+
}
88+
}

‎open-java-format-idea-plugin/src/main/java/com/palantir/javaformat/intellij/PalantirJavaFormatConfigurable.java‎

Lines changed: 9 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,7 @@
2525
import com.intellij.openapi.ui.TextBrowseFolderListener;
2626
import com.intellij.openapi.ui.TextFieldWithBrowseButton;
2727
import com.intellij.openapi.util.Disposer;
28+
import com.intellij.psi.codeStyle.CodeStyleSettingsManager;
2829
import com.intellij.ui.DocumentAdapter;
2930
import com.intellij.ui.components.ActionLink;
3031
import com.intellij.ui.components.JBTextArea;
@@ -174,16 +175,16 @@ public void apply() throws ConfigurationException {
174175
throw new ConfigurationException("Download the embedded version or choose a binary");
175176
}
176177
}
177-
settings.setEnabled(enable.isSelected() ? EnabledState.ENABLED : getDisabledState());
178+
var wasEnabled = settings.isEnabled();
179+
settings.setEnabled(
180+
enable.isSelected() ? EnabledState.ENABLED : PalantirJavaFormatSettings.disabledState(project));
178181
settings.setUseNativeImage(useNativeImage.isSelected());
179182
settings.setNativeImagePath(path);
180-
}
181-
182-
private EnabledState getDisabledState() {
183-
// The default settings (inherited by new projects) are either 'enabled' or
184-
// 'show notification'. There's no way to default new projects to disabled. If someone wants
185-
// that, we can add another checkbox, I suppose.
186-
return project.isDefault() ? EnabledState.UNKNOWN : EnabledState.DISABLED;
183+
if (settings.isEnabled() != wasEnabled) {
184+
// The Java import settings of each file are cached, and PalantirJavaFormatCodeStyleSettingsModifier sets
185+
// them while the plugin is enabled.
186+
CodeStyleSettingsManager.getInstance(project).notifyCodeStyleSettingsChanged();
187+
}
187188
}
188189

189190
@Override

‎open-java-format-idea-plugin/src/main/java/com/palantir/javaformat/intellij/PalantirJavaFormatSettings.java‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -67,6 +67,15 @@ void setEnabled(EnabledState enabled) {
6767
state.enabled = enabled;
6868
}
6969

70+
/**
71+
* The state that switches the plugin off. The default settings (inherited by new projects) are either 'enabled' or
72+
* 'show notification'. There's no way to default new projects to disabled. If someone wants that, we can add
73+
* another checkbox, I suppose.
74+
*/
75+
static EnabledState disabledState(Project project) {
76+
return project.isDefault() ? EnabledState.UNKNOWN : EnabledState.DISABLED;
77+
}
78+
7079
boolean isUninitialized() {
7180
return state.enabled.equals(EnabledState.UNKNOWN);
7281
}

‎open-java-format-idea-plugin/src/main/resources/META-INF/plugin.xml‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,8 @@
2222
<extensions defaultExtensionNs="com.intellij">
2323
<formattingService
2424
implementation="com.palantir.javaformat.intellij.PalantirJavaFormatFormattingService"/>
25+
<codeStyleSettingsModifier
26+
implementation="com.palantir.javaformat.intellij.PalantirJavaFormatCodeStyleSettingsModifier"/>
2527
<projectConfigurable parentId="tools"
2628
instance="com.palantir.javaformat.intellij.PalantirJavaFormatConfigurable"
2729
id="open-java-format.settings"
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,174 @@
1+
/*
2+
* Licensed under the Apache License, Version 2.0 (the "License");
3+
* you may not use this file except in compliance with the License.
4+
* You may obtain a copy of the License at
5+
*
6+
* http://www.apache.org/licenses/LICENSE-2.0
7+
*
8+
* Unless required by applicable law or agreed to in writing, software
9+
* distributed under the License is distributed on an "AS IS" BASIS,
10+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11+
* See the License for the specific language governing permissions and
12+
* limitations under the License.
13+
*/
14+
15+
package com.palantir.javaformat.intellij;
16+
17+
import static java.util.Objects.requireNonNull;
18+
import static org.assertj.core.api.Assertions.assertThat;
19+
20+
import com.intellij.application.options.CodeStyle;
21+
import com.intellij.openapi.command.WriteCommandAction;
22+
import com.intellij.psi.PsiFile;
23+
import com.intellij.psi.PsiJavaFile;
24+
import com.intellij.psi.codeStyle.CodeStyleSettings;
25+
import com.intellij.psi.codeStyle.JavaCodeStyleManager;
26+
import com.intellij.psi.codeStyle.JavaCodeStyleSettings;
27+
import com.intellij.psi.codeStyle.PackageEntry;
28+
import com.intellij.psi.codeStyle.modifier.CodeStyleSettingsModifier;
29+
import com.intellij.psi.codeStyle.modifier.TransientCodeStyleSettings;
30+
import com.intellij.testFramework.fixtures.DefaultLightProjectDescriptor;
31+
import com.intellij.testFramework.fixtures.IdeaProjectTestFixture;
32+
import com.intellij.testFramework.fixtures.IdeaTestFixtureFactory;
33+
import com.intellij.testFramework.fixtures.JavaCodeInsightTestFixture;
34+
import com.intellij.testFramework.fixtures.JavaTestFixtureFactory;
35+
import com.intellij.testFramework.fixtures.TestFixtureBuilder;
36+
import com.intellij.testFramework.fixtures.impl.LightTempDirTestFixtureImpl;
37+
import com.palantir.javaformat.intellij.PalantirJavaFormatSettings.StoredSettings;
38+
import java.util.List;
39+
import org.junit.jupiter.api.AfterEach;
40+
import org.junit.jupiter.api.BeforeEach;
41+
import org.junit.jupiter.api.Test;
42+
43+
final class PalantirJavaFormatCodeStyleSettingsModifierTest {
44+
private final PalantirJavaFormatCodeStyleSettingsModifier modifier =
45+
new PalantirJavaFormatCodeStyleSettingsModifier();
46+
47+
private JavaCodeInsightTestFixture fixture;
48+
private PalantirJavaFormatSettings settings;
49+
50+
@BeforeEach
51+
void setUp() throws Exception {
52+
TestFixtureBuilder<IdeaProjectTestFixture> projectBuilder = IdeaTestFixtureFactory.getFixtureFactory()
53+
.createLightFixtureBuilder(
54+
new DefaultLightProjectDescriptor(), getClass().getName());
55+
// Files in the light project's source root, so that the imports between them resolve.
56+
fixture = JavaTestFixtureFactory.getFixtureFactory()
57+
.createCodeInsightFixture(projectBuilder.getFixture(), new LightTempDirTestFixtureImpl(true));
58+
fixture.setUp();
59+
settings = PalantirJavaFormatSettings.getInstance(fixture.getProject());
60+
var resetState = new StoredSettings();
61+
resetState.setEnabled("true");
62+
settings.loadState(resetState);
63+
}
64+
65+
@AfterEach
66+
void tearDown() throws Exception {
67+
fixture.tearDown();
68+
}
69+
70+
@Test
71+
void java_files_get_the_import_settings_that_open_java_format_writes_by() {
72+
var transientSettings = transientSettings(fixture.configureByText("A.java", "class A {}"));
73+
74+
assertThat(modifier.modifySettings(transientSettings, fixture.getFile()))
75+
.isTrue();
76+
77+
var javaSettings = transientSettings.getCustomSettings(JavaCodeStyleSettings.class);
78+
assertThat(javaSettings.USE_SINGLE_CLASS_IMPORTS).isTrue();
79+
assertThat(javaSettings.CLASS_COUNT_TO_USE_IMPORT_ON_DEMAND).isEqualTo(999);
80+
assertThat(javaSettings.NAMES_COUNT_TO_USE_IMPORT_ON_DEMAND).isEqualTo(999);
81+
assertThat(javaSettings.PACKAGES_TO_USE_IMPORT_ON_DEMAND.getEntries()).isEmpty();
82+
assertThat(javaSettings.LAYOUT_STATIC_IMPORTS_SEPARATELY).isTrue();
83+
assertThat(javaSettings.IMPORT_LAYOUT_TABLE.getEntries())
84+
.containsExactly(
85+
PackageEntry.ALL_OTHER_STATIC_IMPORTS_ENTRY,
86+
PackageEntry.BLANK_LINE_ENTRY,
87+
PackageEntry.ALL_OTHER_IMPORTS_ENTRY);
88+
// The project's own settings stay as they were.
89+
assertThat(JavaCodeStyleSettings.getInstance(fixture.getProject()).CLASS_COUNT_TO_USE_IMPORT_ON_DEMAND)
90+
.isEqualTo(5);
91+
}
92+
93+
@Test
94+
void the_settings_stay_as_they_are_with_the_plugin_disabled() {
95+
settings.setEnabled(false);
96+
var transientSettings = transientSettings(fixture.configureByText("A.java", "class A {}"));
97+
98+
assertThat(modifier.modifySettings(transientSettings, fixture.getFile()))
99+
.isFalse();
100+
assertThat(modifier.mayOverrideSettingsOf(fixture.getProject())).isFalse();
101+
}
102+
103+
@Test
104+
void files_of_other_languages_keep_their_settings() {
105+
var transientSettings = transientSettings(fixture.configureByText("a.txt", "text"));
106+
107+
assertThat(modifier.modifySettings(transientSettings, fixture.getFile()))
108+
.isFalse();
109+
assertThat(modifier.mayOverrideSettingsOf(fixture.getProject())).isTrue();
110+
}
111+
112+
@Test
113+
void the_disable_link_of_the_code_style_page_switches_the_plugin_off() {
114+
requireNonNull(modifier.getDisablingFunction(fixture.getProject()))
115+
.accept(CodeStyle.getSettings(fixture.getProject()));
116+
117+
assertThat(settings.isEnabled()).isFalse();
118+
}
119+
120+
@Test
121+
void an_import_the_ide_adds_is_a_single_class_import_however_many_come_from_its_package() {
122+
assertThat(CodeStyleSettingsModifier.EP_NAME.getExtensionList())
123+
.hasAtLeastOneElementOfType(PalantirJavaFormatCodeStyleSettingsModifier.class);
124+
125+
assertThat(addFifthImportFromOnePackage()).isEqualTo("""
126+
import p.A;
127+
import p.B;
128+
import p.C;
129+
import p.D;
130+
import p.E;
131+
132+
class Main {}
133+
""");
134+
}
135+
136+
@Test
137+
void with_the_plugin_disabled_the_ide_imports_a_fifth_class_from_a_package_on_demand() {
138+
settings.setEnabled(false);
139+
140+
assertThat(addFifthImportFromOnePackage()).isEqualTo("""
141+
import p.*;
142+
143+
class Main {}
144+
""");
145+
}
146+
147+
/** Adds an import as auto-import, Alt+Enter and completion do, through the IDE's ImportHelper. */
148+
private String addFifthImportFromOnePackage() {
149+
// The test fixture gives every file the same temporary settings, which no modifier sees.
150+
CodeStyle.dropTemporarySettings(fixture.getProject());
151+
for (var name : List.of("A", "B", "C", "D")) {
152+
fixture.addClass("package p; public class " + name + " {}");
153+
}
154+
var fifth = fixture.addClass("package p; public class E {}");
155+
var file = (PsiJavaFile) fixture.configureByText("Main.java", """
156+
import p.A;
157+
import p.B;
158+
import p.C;
159+
import p.D;
160+
161+
class Main {}
162+
""");
163+
164+
WriteCommandAction.runWriteCommandAction(fixture.getProject(), () -> {
165+
JavaCodeStyleManager.getInstance(fixture.getProject()).addImport(file, fifth);
166+
});
167+
return file.getText();
168+
}
169+
170+
private TransientCodeStyleSettings transientSettings(PsiFile file) {
171+
CodeStyleSettings projectSettings = CodeStyle.getSettings(fixture.getProject());
172+
return new TransientCodeStyleSettings(file.getVirtualFile(), fixture.getProject(), projectSettings);
173+
}
174+
}

‎open-java-format-idea-plugin/src/test/java/com/palantir/javaformat/intellij/PalantirJavaFormatConfigurableTest.java‎

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@
1919
import static com.google.common.collect.MoreCollectors.onlyElement;
2020
import static org.assertj.core.api.Assertions.assertThatThrownBy;
2121

22+
import com.intellij.application.options.CodeStyle;
2223
import com.intellij.openapi.options.Configurable;
2324
import com.intellij.openapi.options.ConfigurationException;
2425
import com.intellij.openapi.ui.ComboBox;
@@ -123,6 +124,24 @@ void readsAndWritesTheEnabledSetting() throws Throwable {
123124
assertThat(settings.isEnabled()).isTrue();
124125
}
125126

127+
@Test
128+
void refreshesTheCodeStyleOfOpenFilesWhenOpenJavaFormatIsSwitchedOnOrOff() throws Throwable {
129+
// The import settings of each file are cached, and the plugin sets them while it is on.
130+
var tracker = CodeStyle.getSettings(fixture.getProject()).getModificationTracker();
131+
var countBefore = tracker.getModificationCount();
132+
133+
EdtTestUtil.runInEdtAndWait(() -> {
134+
configurable.reset();
135+
configurable.apply();
136+
assertThat(tracker.getModificationCount()).isEqualTo(countBefore);
137+
138+
findCheckBox("Enable open-java-format").setSelected(false);
139+
configurable.apply();
140+
});
141+
142+
assertThat(tracker.getModificationCount()).isGreaterThan(countBefore);
143+
}
144+
126145
@Test
127146
void sitsUnderTools() {
128147
var page = Configurable.PROJECT_CONFIGURABLE.getExtensions(fixture.getProject()).stream()

0 commit comments

Comments
 (0)