• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright 2016 Google Inc. All Rights Reserved.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *     http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 package com.google.googlejavaformat.intellij;
18 
19 import static com.google.common.base.Preconditions.checkState;
20 
21 import com.intellij.ide.plugins.IdeaPluginDescriptor;
22 import com.intellij.ide.plugins.PluginManagerCore;
23 import com.intellij.openapi.extensions.PluginId;
24 import com.intellij.openapi.project.Project;
25 import com.intellij.openapi.project.ProjectManagerListener;
26 import com.intellij.psi.codeStyle.CodeStyleManager;
27 import com.intellij.serviceContainer.ComponentManagerImpl;
28 import org.jetbrains.annotations.NotNull;
29 
30 /**
31  * A component that replaces the default IntelliJ {@link CodeStyleManager} with one that formats via
32  * google-java-format.
33  */
34 final class GoogleJavaFormatInstaller implements ProjectManagerListener {
35 
36   @Override
projectOpened(@otNull Project project)37   public void projectOpened(@NotNull Project project) {
38     installFormatter(project);
39   }
40 
installFormatter(Project project)41   private static void installFormatter(Project project) {
42     CodeStyleManager currentManager = CodeStyleManager.getInstance(project);
43 
44     if (currentManager instanceof GoogleJavaFormatCodeStyleManager) {
45       currentManager = ((GoogleJavaFormatCodeStyleManager) currentManager).getDelegate();
46     }
47 
48     setManager(project, new GoogleJavaFormatCodeStyleManager(currentManager));
49   }
50 
setManager(Project project, CodeStyleManager newManager)51   private static void setManager(Project project, CodeStyleManager newManager) {
52     ComponentManagerImpl platformComponentManager = (ComponentManagerImpl) project;
53     IdeaPluginDescriptor plugin = PluginManagerCore.getPlugin(PluginId.getId("google-java-format"));
54     checkState(plugin != null, "Couldn't locate our own PluginDescriptor.");
55     platformComponentManager.registerServiceInstance(CodeStyleManager.class, newManager, plugin);
56   }
57 }
58