Skip to content
Open
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,10 @@ static String parsingErrorMessage(String filename) {
return "open-java-format failed. Does " + filename + " have syntax errors?";
}

static String untrustedProjectMessage() {
return "open-java-format requires a trusted project to load the external formatter classpath.";
}

Comment thread
abashev marked this conversation as resolved.
Resolved
static String formatterFailedMessage(String filename) {
return "open-java-format could not run the formatter on " + filename + ". The details are in idea.log.";
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
/*
* 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.palantir.javaformat.intellij;

import com.intellij.ide.highlighter.JavaFileType;
import com.intellij.openapi.project.Project;
import com.intellij.psi.PsiFile;
import com.intellij.psi.codeStyle.CodeStyleSettings;
import com.intellij.psi.codeStyle.JavaCodeStyleSettings;
import com.intellij.psi.codeStyle.PackageEntry;
import com.intellij.psi.codeStyle.PackageEntryTable;
import com.intellij.psi.codeStyle.modifier.CodeStyleSettingsModifier;
import com.intellij.psi.codeStyle.modifier.CodeStyleStatusBarUIContributor;
import com.intellij.psi.codeStyle.modifier.TransientCodeStyleSettings;
import java.util.function.Consumer;
import org.jspecify.annotations.Nullable;

/**
* Gives the Java files the plugin formats the import settings that open-java-format writes by. The IDE inserts imports
* through auto-import, Alt+Enter and completion by these settings, and no import optimizer sees them: with the IDE's
* defaults, five classes from one package become {@code import java.util.*;}, which open-java-format keeps.
*
* <p>The platform applies only the first modifier that changes a file's settings, and EditorConfig's is registered
* first: in a project whose {@code .editorconfig} sets code style properties for Java files, these settings do not
* apply, and its {@code ij_java_*} properties can set them there instead.
*/
final class PalantirJavaFormatCodeStyleSettingsModifier implements CodeStyleSettingsModifier {
// More names than a file imports from one package, so that an import on demand is never written.
private static final int NEVER_IMPORT_ON_DEMAND = 999;

@Override
public boolean modifySettings(TransientCodeStyleSettings settings, PsiFile file) {
if (!JavaFileType.INSTANCE.equals(file.getFileType())
|| !PalantirJavaFormatSettings.getInstance(file.getProject()).isEnabled()) {
return false;
}
var javaSettings = settings.getCustomSettings(JavaCodeStyleSettings.class);
javaSettings.USE_SINGLE_CLASS_IMPORTS = true;
javaSettings.CLASS_COUNT_TO_USE_IMPORT_ON_DEMAND = NEVER_IMPORT_ON_DEMAND;
javaSettings.NAMES_COUNT_TO_USE_IMPORT_ON_DEMAND = NEVER_IMPORT_ON_DEMAND;
javaSettings.PACKAGES_TO_USE_IMPORT_ON_DEMAND.copyFrom(new PackageEntryTable());
// Static imports, a blank line, then the others, each group in the order of its names: ImportOrderer's.
javaSettings.LAYOUT_STATIC_IMPORTS_SEPARATELY = true;
var importLayout = new PackageEntryTable();
importLayout.addEntry(PackageEntry.ALL_OTHER_STATIC_IMPORTS_ENTRY);
importLayout.addEntry(PackageEntry.BLANK_LINE_ENTRY);
importLayout.addEntry(PackageEntry.ALL_OTHER_IMPORTS_ENTRY);
javaSettings.IMPORT_LAYOUT_TABLE.copyFrom(importLayout);
return true;
}

// The Code Style page then says that its settings may be overridden by open-java-format.
@Override
public boolean mayOverrideSettingsOf(Project project) {
return PalantirJavaFormatSettings.getInstance(project).isEnabled();
}

@Override
public String getName() {
return "open-java-format";
}

@Override
@Nullable
public CodeStyleStatusBarUIContributor getStatusBarUiContributor(TransientCodeStyleSettings transientSettings) {
return null;
}

// What the Disable link next to that message runs: these settings come with the plugin, so it switches the plugin
// off for the project, as unticking it on the plugin's settings page does.
@Override
public Consumer<CodeStyleSettings> getDisablingFunction(Project project) {
return settings -> PalantirJavaFormatSettings.getInstance(project)
.setEnabled(PalantirJavaFormatSettings.disabledState(project));
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@
import com.intellij.openapi.ui.TextBrowseFolderListener;
import com.intellij.openapi.ui.TextFieldWithBrowseButton;
import com.intellij.openapi.util.Disposer;
import com.intellij.psi.codeStyle.CodeStyleSettingsManager;
import com.intellij.ui.DocumentAdapter;
import com.intellij.ui.components.ActionLink;
import com.intellij.ui.components.JBTextArea;
Expand Down Expand Up @@ -174,16 +175,16 @@ public void apply() throws ConfigurationException {
throw new ConfigurationException("Download the embedded version or choose a binary");
}
}
settings.setEnabled(enable.isSelected() ? EnabledState.ENABLED : getDisabledState());
var wasEnabled = settings.isEnabled();
settings.setEnabled(
enable.isSelected() ? EnabledState.ENABLED : PalantirJavaFormatSettings.disabledState(project));
settings.setUseNativeImage(useNativeImage.isSelected());
settings.setNativeImagePath(path);
}

private EnabledState getDisabledState() {
// The default settings (inherited by new projects) are either 'enabled' or
// 'show notification'. There's no way to default new projects to disabled. If someone wants
// that, we can add another checkbox, I suppose.
return project.isDefault() ? EnabledState.UNKNOWN : EnabledState.DISABLED;
if (settings.isEnabled() != wasEnabled) {
// The Java import settings of each file are cached, and PalantirJavaFormatCodeStyleSettingsModifier sets
// them while the plugin is enabled.
CodeStyleSettingsManager.getInstance(project).notifyCodeStyleSettingsChanged();
}
}

@Override
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,13 +24,20 @@
import com.intellij.formatting.service.AsyncFormattingRequest;
import com.intellij.ide.highlighter.JavaFileType;
import com.intellij.ide.impl.TrustedProjects;
import com.intellij.lang.ImportOptimizer;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.editor.Document;
import com.intellij.openapi.editor.event.DocumentEvent;
import com.intellij.openapi.editor.event.DocumentListener;
import com.intellij.openapi.extensions.PluginAware;
import com.intellij.openapi.extensions.PluginDescriptor;
import com.intellij.openapi.progress.ProcessCanceledException;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.Disposer;
import com.intellij.openapi.util.Key;
import com.intellij.openapi.util.NlsSafe;
import com.intellij.openapi.util.TextRange;
import com.intellij.psi.PsiDocumentManager;
import com.intellij.psi.PsiFile;
import com.palantir.javaformat.java.FormatterException;
import com.palantir.javaformat.java.FormatterService;
Expand All @@ -40,12 +47,14 @@
import java.util.List;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.atomic.AtomicReference;
import org.jspecify.annotations.Nullable;

class PalantirJavaFormatFormattingService extends AsyncDocumentFormattingService implements PluginAware {
private static final Logger logger = Logger.getInstance(PalantirJavaFormatFormattingService.class);

Check warning on line 54 in open-java-format-idea-plugin/src/main/java/com/palantir/javaformat/intellij/PalantirJavaFormatFormattingService.java

View workflow job for this annotation

GitHub Actions / build

[ConstantNaming] Constant variables should adhere to the `UPPER_SNAKE_CASE` naming convention
private final FormatterProvider formatterProvider =
new FormatterProvider(() -> EmbeddedNativeImage.getInstance().installedPath());
private final ImportOptimizer importOptimizer = new PalantirJavaFormatImportOptimizer(this);

// The platform sets this right after creating the service from plugin.xml: the descriptor of the plugin that
// declared it, which is how the plugin learns its own path and version (see FormatterProvider.getPluginDescriptor).
Expand All @@ -66,19 +75,27 @@
@Nullable
protected FormattingTask createFormattingTask(AsyncFormattingRequest request) {
Project project = request.getContext().getProject();
// The marketplace verifier reports this class as experimental, and newer IDEs also deprecate it. It stays:
// its replacement, com.intellij.ide.trustedProjects.TrustedProjects, is @ApiStatus.Internal — a worse thing
// for a plugin to call.
if (!TrustedProjects.isTrusted(project)) {
if (!isTrusted(project)) {
logger.warn("open-java-format: skipping formatting for untrusted project: " + project.getName());
request.onError(
Notifications.GENERIC_ERROR_NOTIFICATION_GROUP,
"open-java-format requires a trusted project to load the external formatter classpath.");
request.onError(Notifications.GENERIC_ERROR_NOTIFICATION_GROUP, Notifications.untrustedProjectMessage());
return null;
}
PalantirJavaFormatSettings settings = PalantirJavaFormatSettings.getInstance(project);
Optional<FormatterService> formatter = formatterProvider.get(project, settings);
return new PalantirJavaFormatFormattingTask(request, formatter);
PendingFormat pendingFormat = PendingFormat.start(
project,
PsiDocumentManager.getInstance(project)
.getDocument(request.getContext().getContainingFile()));
return new PalantirJavaFormatFormattingTask(request, getFormatter(project), pendingFormat);
}

static boolean isTrusted(Project project) {
// The marketplace verifier reports this class as experimental, and newer IDEs also deprecate it. It stays:
// its replacement, com.intellij.ide.trustedProjects.TrustedProjects, is @ApiStatus.Internal — a worse thing
// for a plugin to call.
Comment thread
abashev marked this conversation as resolved.
Resolved
return TrustedProjects.isTrusted(project);
}

Optional<FormatterService> getFormatter(Project project) {
return formatterProvider.get(project, PalantirJavaFormatSettings.getInstance(project));
}

@Override
Expand All @@ -91,9 +108,17 @@
return "open-java-format";
}

// OPTIMIZE_IMPORTS: every way the IDE optimizes imports asks the first formatting service that has this feature and
// can format the file for its optimizers (FormattingServiceUtil.findImportsOptimizingService), and so takes ours
// instead of its own JavaImportOptimizer.
@Override
public Set<Feature> getFeatures() {
return Set.of(Feature.FORMAT_FRAGMENTS);
return Set.of(Feature.FORMAT_FRAGMENTS, Feature.OPTIMIZE_IMPORTS);
}

@Override
public Set<ImportOptimizer> getImportOptimizers(PsiFile file) {
return Set.of(importOptimizer);
}

@Override
Expand All @@ -102,22 +127,120 @@
&& PalantirJavaFormatSettings.getInstance(file.getProject()).isEnabled();
}

/**
* A formatting request of this service whose text is not in its document yet, kept on the document.
*
* <p>The formatter runs in the background, and the platform applies its text later, only if the document has not
* changed since the request started: IntelliJ IDEA registers no {@code DocumentMerger} to do anything else.
* Reformat with "Optimize imports" starts the formatter and the import optimizer on the same document without
* waiting for the first, so whichever wrote second would lose: the formatted text, or the imports. While a request
* is formatting, the optimizer hands its work over to it, and the request fixes the imports of the text it
* formatted, as the command line does. Once the request has its text, the optimizer leaves the document alone
* until the text is applied.
*/
static final class PendingFormat {
private static final Key<PendingFormat> KEY = Key.create("open-java-format.pendingFormat");

private enum State {
FORMATTING,
FORMATTING_AND_FIXING_IMPORTS,
// Until the document next changes: with the text, or with an edit that makes the platform drop it.
UNAPPLIED,
DONE
}

private final AtomicReference<State> state = new AtomicReference<>(State.FORMATTING);
private final Project project;

@Nullable
private final Document document;

private PendingFormat(Project project, @Nullable Document document) {
this.project = project;
this.document = document;
}

static PendingFormat start(Project project, @Nullable Document document) {
var pendingFormat = new PendingFormat(project, document);
if (document != null) {
document.putUserData(KEY, pendingFormat);
}
return pendingFormat;
}

@Nullable
static PendingFormat of(Document document) {
return document.getUserData(KEY);
}

/** Asks the request to fix the imports too: false if it has finished formatting already. */
boolean handOverImports() {
return state.compareAndSet(State.FORMATTING, State.FORMATTING_AND_FIXING_IMPORTS);
}

boolean isUnapplied() {
return state.get() == State.UNAPPLIED;
}

/** Ends the formatting, and says whether the imports were handed over meanwhile. */
private boolean finishFormatting() {
return state.getAndSet(State.UNAPPLIED) == State.FORMATTING_AND_FIXING_IMPORTS;
}

private void finish(boolean changesDocument) {
if (!changesDocument || document == null) {
state.set(State.DONE);
return;
}
var untilChanged = Disposer.newDisposable("open-java-format: until the formatted text is applied");
if (!Disposer.tryRegister(project, untilChanged)) {
state.set(State.DONE);
return;
}
// Registered before the platform applies the text, which it does only once the task has returned.
document.addDocumentListener(
new DocumentListener() {
@Override
public void documentChanged(DocumentEvent event) {
state.set(State.DONE);
Disposer.dispose(untilChanged);
}
},
untilChanged);
}
}

private static final class PalantirJavaFormatFormattingTask implements FormattingTask {
private final AsyncFormattingRequest request;
private final Optional<FormatterService> formatterService;
private final PendingFormat pendingFormat;

PalantirJavaFormatFormattingTask(AsyncFormattingRequest request, Optional<FormatterService> formatterService) {
PalantirJavaFormatFormattingTask(
AsyncFormattingRequest request,
Optional<FormatterService> formatterService,
PendingFormat pendingFormat) {
this.request = request;
this.formatterService = formatterService;
this.pendingFormat = pendingFormat;
}

@Override
public void run() {
var changesDocument = false;
try {
changesDocument = format();
} finally {
pendingFormat.finish(changesDocument);
}
}

/** Formats, and says whether the text it gave back changes the document. */
private boolean format() {
if (formatterService.isEmpty()) {
request.onError(
Notifications.GENERIC_ERROR_NOTIFICATION_GROUP,
"Failed to format file because formatterService is not configured");
return;
return false;
}

String preFormatText = request.getDocumentText();
Expand All @@ -138,14 +261,18 @@
// returns a change. Thus we must perform a content aware diff / branching.
String formattedText = applyReplacements(
preFormatText, formatterService.get().getFormatReplacements(preFormatText, toRanges(request)));
if (pendingFormat.finishFormatting()) {
formattedText = formatterService.get().fixImports(formattedText);
}

// The Javadoc of this API says that you should set it to null when the document is unchanged
// We should not be trying to format a document that is already formatted
if (preFormatText.equals(formattedText)) {
request.onTextReady(null);
} else {
request.onTextReady(formattedText);
return false;
}
request.onTextReady(formattedText);
return true;
} catch (FormatterException e) {
// A syntax error in the file, not a fault of the plugin: an error would go to its error reports.
logger.warn(
Expand All @@ -169,6 +296,7 @@
Notifications.formatterFailedMessage(
request.getContext().getContainingFile().getName()));
}
return false;
}

static String applyReplacements(String input, Collection<Replacement> replacementsCollection) {
Expand Down
Loading
Loading