summaryrefslogtreecommitdiff
path: root/plugins/InspectionGadgets/InspectionGadgetsAnalysis/src/com/siyeh/ig/inheritance/StaticInheritanceFix.java
blob: 1289bbdbe6947531b5c3ab53b95524b7627a83c0 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
/*
 * Copyright 2000-2013 JetBrains s.r.o.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.siyeh.ig.inheritance;

import com.intellij.codeInsight.FileModificationService;
import com.intellij.codeInsight.intention.IntentionAction;
import com.intellij.codeInsight.intention.QuickFixFactory;
import com.intellij.codeInspection.ProblemDescriptor;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.application.ModalityState;
import com.intellij.openapi.application.Result;
import com.intellij.openapi.command.WriteCommandAction;
import com.intellij.openapi.progress.ProgressIndicator;
import com.intellij.openapi.progress.ProgressManager;
import com.intellij.openapi.progress.Task;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.Computable;
import com.intellij.psi.*;
import com.intellij.psi.impl.DebugUtil;
import com.intellij.psi.search.searches.ReferencesSearch;
import com.intellij.psi.util.InheritanceUtil;
import com.intellij.psi.util.PsiTreeUtil;
import com.intellij.util.IncorrectOperationException;
import com.intellij.util.Query;
import com.intellij.util.ui.UIUtil;
import com.siyeh.InspectionGadgetsBundle;
import com.siyeh.ig.InspectionGadgetsFix;
import com.siyeh.ig.psiutils.ClassUtils;
import org.jetbrains.annotations.NotNull;

/**
 * User: cdr
 */
class StaticInheritanceFix extends InspectionGadgetsFix {
  private final boolean myReplaceInWholeProject;

  StaticInheritanceFix(boolean replaceInWholeProject) {
    myReplaceInWholeProject = replaceInWholeProject;
  }

  @Override
  @NotNull
  public String getName() {
    String scope =
      myReplaceInWholeProject ? InspectionGadgetsBundle.message("the.whole.project") : InspectionGadgetsBundle.message("this.class");
    return InspectionGadgetsBundle.message("static.inheritance.replace.quickfix", scope);
  }

  @NotNull
  @Override
  public String getFamilyName() {
    return "Replace inheritance with qualified reference";
  }

  @Override
  public void doFix(final Project project, final ProblemDescriptor descriptor) throws IncorrectOperationException {
    ApplicationManager.getApplication().invokeLater(new Runnable() {
      @Override
      public void run() {
        dodoFix(project, descriptor);
      }
    }, ModalityState.NON_MODAL, project.getDisposed());
  }

  private void dodoFix(final Project project, ProblemDescriptor descriptor) throws IncorrectOperationException {
    final PsiJavaCodeReferenceElement referenceElement = (PsiJavaCodeReferenceElement)descriptor.getPsiElement();
    final PsiClass iface = (PsiClass)referenceElement.resolve();
    assert iface != null;
    final PsiField[] allFields = iface.getAllFields();

    final PsiClass implementingClass = ClassUtils.getContainingClass(referenceElement);
    final PsiManager manager = referenceElement.getManager();
    assert implementingClass != null;
    final PsiFile file = implementingClass.getContainingFile();

    ProgressManager.getInstance().run(new Task.Modal(project, "Replacing usages of " + iface.getName(), false) {

      @Override
      public void run(@NotNull ProgressIndicator indicator) {
        for (final PsiField field : allFields) {
          final Query<PsiReference> search = ReferencesSearch.search(field, implementingClass.getUseScope(), false);
          for (PsiReference reference : search) {
            if (!(reference instanceof PsiReferenceExpression)) {
              continue;
            }
            final PsiReferenceExpression referenceExpression = (PsiReferenceExpression)reference;
            if (!myReplaceInWholeProject) {
              boolean isInheritor =
              ApplicationManager.getApplication().runReadAction(new Computable<Boolean>() {
                @Override
                public Boolean compute() {
                  boolean isInheritor = false;
                  PsiClass aClass = PsiTreeUtil.getParentOfType(referenceExpression, PsiClass.class);
                  while (aClass != null) {
                    isInheritor = InheritanceUtil.isInheritorOrSelf(aClass, implementingClass, true);
                    if (isInheritor) break;
                    aClass = PsiTreeUtil.getParentOfType(aClass, PsiClass.class);
                  }
                  return isInheritor;
                }
              });
              if (!isInheritor) continue;
            }
            final Runnable runnable = new Runnable() {
              @Override
              public void run() {
                if (!FileModificationService.getInstance().preparePsiElementsForWrite(referenceExpression)) {
                  return;
                }
                final PsiElementFactory elementFactory = JavaPsiFacade.getInstance(manager.getProject()).getElementFactory();
                final PsiReferenceExpression qualified =
                  (PsiReferenceExpression)elementFactory
                    .createExpressionFromText("xxx." + referenceExpression.getText(), referenceExpression);
                final PsiReferenceExpression newReference = (PsiReferenceExpression)referenceExpression.replace(qualified);
                final PsiReferenceExpression qualifier = (PsiReferenceExpression)newReference.getQualifierExpression();
                assert qualifier != null : DebugUtil.psiToString(newReference, false);
                final PsiClass containingClass = field.getContainingClass();
                qualifier.bindToElement(containingClass);
              }
            };
            invokeWriteAction(runnable, file);
          }
        }
        final Runnable runnable = new Runnable() {
          @Override
          public void run() {
            PsiClassType classType = JavaPsiFacade.getInstance(project).getElementFactory().createType(iface);
            IntentionAction fix = QuickFixFactory.getInstance().createExtendsListFix(implementingClass, classType, false);
            fix.invoke(project, null, file);
          }
        };
        invokeWriteAction(runnable, file);
      }
    });
  }

  private static void invokeWriteAction(final Runnable runnable, final PsiFile file) {
    UIUtil.invokeLaterIfNeeded(new Runnable() {
      @Override
      public void run() {
        new WriteCommandAction(file.getProject(), file) {
          @Override
          protected void run(Result result) throws Throwable {
            runnable.run();
          }
        }.execute();
      }
    });
  }
}