3aee7c9f9d21a8d3026b5ad29095491fd7c389e9
[idea/community.git] / platform / lang-impl / src / com / intellij / codeInsight / actions / FormatChangedTextUtil.java
1 /*
2  * Copyright 2000-2011 JetBrains s.r.o.
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 package com.intellij.codeInsight.actions;
17
18 import com.intellij.openapi.application.ApplicationManager;
19 import com.intellij.openapi.application.ReadAction;
20 import com.intellij.openapi.application.Result;
21 import com.intellij.openapi.diagnostic.Logger;
22 import com.intellij.openapi.editor.Document;
23 import com.intellij.openapi.editor.EditorFactory;
24 import com.intellij.openapi.editor.impl.EditorFactoryImpl;
25 import com.intellij.openapi.editor.markup.RangeHighlighter;
26 import com.intellij.openapi.module.ModifiableModuleModel;
27 import com.intellij.openapi.module.Module;
28 import com.intellij.openapi.module.ModuleManager;
29 import com.intellij.openapi.project.Project;
30 import com.intellij.openapi.roots.ModuleRootManager;
31 import com.intellij.openapi.util.Key;
32 import com.intellij.openapi.util.TextRange;
33 import com.intellij.openapi.vcs.VcsException;
34 import com.intellij.openapi.vcs.changes.Change;
35 import com.intellij.openapi.vcs.changes.ChangeListManager;
36 import com.intellij.openapi.vcs.changes.ContentRevision;
37 import com.intellij.openapi.vcs.ex.LineStatusTracker;
38 import com.intellij.openapi.vcs.ex.Range;
39 import com.intellij.openapi.vcs.ex.RangesBuilder;
40 import com.intellij.openapi.vcs.impl.LineStatusTrackerManager;
41 import com.intellij.openapi.vcs.impl.LineStatusTrackerManagerI;
42 import com.intellij.openapi.vfs.VirtualFile;
43 import com.intellij.psi.PsiDirectory;
44 import com.intellij.psi.PsiDocumentManager;
45 import com.intellij.psi.PsiFile;
46 import com.intellij.psi.PsiManager;
47 import com.intellij.util.Function;
48 import com.intellij.util.containers.ContainerUtil;
49 import com.intellij.util.containers.ContainerUtilRt;
50 import com.intellij.util.diff.FilesTooBigForDiffException;
51 import org.jetbrains.annotations.NotNull;
52 import org.jetbrains.annotations.Nullable;
53
54 import java.util.*;
55
56 public class FormatChangedTextUtil {
57   private static final Logger LOG = Logger.getInstance("#com.intellij.codeInsight.actions.FormatChangedTextUtil");
58   protected static final Key<List<TextRange>> CHANGED_RANGES = Key.create("changed.ranges.since.last.revision");
59
60   private FormatChangedTextUtil() {
61   }
62
63   /**
64    * Allows to answer if given file has changes in comparison with VCS.
65    * 
66    * @param file  target file
67    * @return      <code>true</code> if given file has changes; <code>false</code> otherwise
68    */
69   public static boolean hasChanges(@NotNull PsiFile file) {
70     final Project project = file.getProject();
71     final VirtualFile virtualFile = file.getVirtualFile();
72     if (virtualFile != null) {
73       final Change change = ChangeListManager.getInstance(project).getChange(virtualFile);
74       return change != null;
75     }
76     return false;
77   }
78
79   /**
80    * Allows to answer if any file below the given directory (any level of nesting) has changes in comparison with VCS.
81    * 
82    * @param directory  target directory to check
83    * @return           <code>true</code> if any file below the given directory has changes in comparison with VCS;
84    *                   <code>false</code> otherwise
85    */
86   public static boolean hasChanges(@NotNull PsiDirectory directory) {
87     return hasChanges(directory.getVirtualFile(), directory.getProject());
88   }
89
90   /**
91    * Allows to answer if given file or any file below the given directory (any level of nesting) has changes in comparison with VCS.
92    * 
93    * @param file     target directory to check
94    * @param project  target project
95    * @return         <code>true</code> if given file or any file below the given directory has changes in comparison with VCS;
96    *                 <code>false</code> otherwise
97    */
98   public static boolean hasChanges(@NotNull VirtualFile file, @NotNull Project project) {
99     final Collection<Change> changes = ChangeListManager.getInstance(project).getChangesIn(file);
100     for (Change change : changes) {
101       if (change.getType() == Change.Type.NEW || change.getType() == Change.Type.MODIFICATION) {
102         return true;
103       }
104     }
105     return false;
106   }
107
108   public static boolean hasChanges(@NotNull VirtualFile[] files, @NotNull Project project) {
109     for (VirtualFile file : files) {
110       if (hasChanges(file, project))
111         return true;
112     }
113     return false;
114   }
115
116   /**
117    * Allows to answer if any file that belongs to the given module has changes in comparison with VCS.
118    * 
119    * @param module  target module to check
120    * @return        <code>true</code> if any file that belongs to the given module has changes in comparison with VCS
121    *                <code>false</code> otherwise
122    */
123   public static boolean hasChanges(@NotNull Module module) {
124     final ModuleRootManager rootManager = ModuleRootManager.getInstance(module);
125     for (VirtualFile root : rootManager.getSourceRoots()) {
126       if (hasChanges(root, module.getProject())) {
127         return true;
128       }
129     }
130     return false;
131   }
132
133   /**
134    * Allows to answer if any file that belongs to the given project has changes in comparison with VCS.
135    * 
136    * @param project  target project to check
137    * @return         <code>true</code> if any file that belongs to the given project has changes in comparison with VCS
138    *                 <code>false</code> otherwise
139    */
140   public static boolean hasChanges(@NotNull final Project project) {
141     final ModifiableModuleModel moduleModel = new ReadAction<ModifiableModuleModel>() {
142       @Override
143       protected void run(Result<ModifiableModuleModel> result) throws Throwable {
144         result.setResult(ModuleManager.getInstance(project).getModifiableModel());
145       }
146     }.execute().getResultObject();
147     try {
148       for (Module module : moduleModel.getModules()) {
149         if (hasChanges(module)) {
150           return true;
151         }
152       }
153       return false;
154     }
155     finally {
156       moduleModel.dispose();
157     }
158   }
159
160   /**
161    * Allows to ask for the changed text of the given file (in comparison with VCS).
162    * 
163    * @param file  target file
164    * @return      collection of changed regions for the given file
165    */
166   @NotNull
167   public static Collection<TextRange> getChanges(@NotNull PsiFile file) {
168     final Set<TextRange> defaultResult = Collections.singleton(file.getTextRange());
169     final VirtualFile virtualFile = file.getVirtualFile();
170     if (virtualFile != null) {
171       final Change change = ChangeListManager.getInstance(file.getProject()).getChange(virtualFile);
172       if (change != null && change.getType() == Change.Type.NEW) {
173         return defaultResult;
174       }
175     }
176
177     final LineStatusTrackerManagerI manager = LineStatusTrackerManager.getInstance(file.getProject());
178     if (manager == null) {
179       return defaultResult;
180     }
181     final Document document = PsiDocumentManager.getInstance(file.getProject()).getDocument(file);
182     if (document == null) {
183       return defaultResult;
184     }
185     final LineStatusTracker lineStatusTracker = manager.getLineStatusTracker(document);
186     if (lineStatusTracker == null) {
187       return defaultResult;
188     }
189     final List<Range> ranges = lineStatusTracker.getRanges();
190     if (ranges == null || ranges.isEmpty()) {
191       return defaultResult;
192     }
193     
194     List<TextRange> result = new ArrayList<TextRange>();
195     for (Range range : ranges) {
196       if (range.getType() != Range.DELETED) {
197         final RangeHighlighter highlighter = range.getHighlighter();
198         if (highlighter != null) {
199           result.add(new TextRange(highlighter.getStartOffset(), highlighter.getEndOffset()));
200         }
201       }
202     }
203     return result;
204   }
205
206   @NotNull
207   public static List<PsiFile> getChangedFilesFromDirs(@NotNull Project project, @NotNull List<PsiDirectory> dirs)  {
208     ChangeListManager changeListManager = ChangeListManager.getInstance(project);
209     Collection<Change> changes = ContainerUtil.newArrayList();
210
211     for (PsiDirectory dir : dirs) {
212       changes.addAll(changeListManager.getChangesIn(dir.getVirtualFile()));
213     }
214
215     return getChangedFiles(project, changes);
216   }
217
218   @NotNull
219   public static List<PsiFile> getChangedFiles(@NotNull final Project project, @NotNull Collection<Change> changes) {
220     Function<Change, PsiFile> changeToPsiFileMapper = new Function<Change, PsiFile>() {
221       private PsiManager myPsiManager = PsiManager.getInstance(project);
222
223       @Override
224       public PsiFile fun(Change change) {
225         VirtualFile vFile = change.getVirtualFile();
226         return vFile != null ? myPsiManager.findFile(vFile) : null;
227       }
228     };
229
230     return ContainerUtil.mapNotNull(changes, changeToPsiFileMapper);
231   }
232
233   @NotNull
234   public static List<TextRange> getChangedTextRanges(@NotNull Project project, @NotNull PsiFile file) throws FilesTooBigForDiffException {
235     if (ApplicationManager.getApplication().isUnitTestMode()) {
236       List<TextRange> testData = file.getUserData(CHANGED_RANGES);
237       if (testData != null) {
238         return testData;
239       }
240     }
241
242     Document document = PsiDocumentManager.getInstance(project).getDocument(file);
243     if (document == null) return ContainerUtil.emptyList();
244
245     List<TextRange> cachedChangedLines = getCachedChangedLines(project, document);
246     if (cachedChangedLines != null) {
247       return cachedChangedLines;
248     }
249
250     Change change = ChangeListManager.getInstance(project).getChange(file.getVirtualFile());
251     if (change == null) {
252       return ContainerUtilRt.emptyList();
253     }
254     if (change.getType() == Change.Type.NEW) {
255       return ContainerUtil.newArrayList(file.getTextRange());
256     }
257
258     String contentFromVcs = getRevisionedContentFrom(change);
259     return contentFromVcs != null ? calculateChangedTextRanges(document, contentFromVcs)
260                                   : ContainerUtil.<TextRange>emptyList();
261   }
262
263   @Nullable
264   private static List<TextRange> getCachedChangedLines(@NotNull Project project, @NotNull Document document) {
265     LineStatusTracker tracker = LineStatusTrackerManager.getInstance(project).getLineStatusTracker(document);
266     if (tracker != null) {
267       List<Range> ranges = tracker.getRanges();
268       return getChangedTextRanges(document, ranges);
269     }
270
271     return null;
272   }
273
274   @Nullable
275   private static String getRevisionedContentFrom(@NotNull Change change) {
276     ContentRevision revision = change.getBeforeRevision();
277     if (revision == null) {
278       return null;
279     }
280
281     try {
282       return revision.getContent();
283     }
284     catch (VcsException e) {
285       LOG.error("Can't get content for: " + change.getVirtualFile(), e);
286       return null;
287     }
288   }
289
290   @NotNull
291   protected static List<TextRange> calculateChangedTextRanges(@NotNull Document document,
292                                                               @NotNull CharSequence contentFromVcs) throws FilesTooBigForDiffException
293   {
294     Document documentFromVcs = ((EditorFactoryImpl)EditorFactory.getInstance()).createDocument(contentFromVcs, true, false);
295     List<Range> changedRanges = new RangesBuilder(document, documentFromVcs).getRanges();
296     return getChangedTextRanges(document, changedRanges);
297   }
298
299   @NotNull
300   private static List<TextRange> getChangedTextRanges(@NotNull Document document, @NotNull List<Range> changedRanges) {
301     List<TextRange> ranges = ContainerUtil.newArrayList();
302     for (Range range : changedRanges) {
303       if (range.getType() != Range.DELETED) {
304         int changeStartLine = range.getLine1();
305         int changeEndLine = range.getLine2();
306
307         int lineStartOffset = document.getLineStartOffset(changeStartLine);
308         int lineEndOffset = document.getLineEndOffset(changeEndLine - 1);
309
310         ranges.add(new TextRange(lineStartOffset, lineEndOffset));
311       }
312     }
313     return ranges;
314   }
315 }