-
Notifications
You must be signed in to change notification settings - Fork 11
/
DiffWindow.java
467 lines (416 loc) · 20.8 KB
/
DiffWindow.java
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
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
package org.jetbrains.research.refactorinsight.ui.windows;
import com.intellij.diff.*;
import com.intellij.diff.chains.DiffRequestChain;
import com.intellij.diff.chains.SimpleDiffRequestChain;
import com.intellij.diff.contents.DiffContent;
import com.intellij.diff.contents.DocumentContent;
import com.intellij.diff.requests.DiffRequest;
import com.intellij.diff.tools.simple.*;
import com.intellij.diff.tools.util.base.DiffViewerListener;
import com.intellij.diff.tools.util.base.IgnorePolicy;
import com.intellij.diff.tools.util.side.OnesideTextDiffViewer;
import com.intellij.diff.tools.util.side.TwosideTextDiffViewer;
import com.intellij.diff.util.DiffUserDataKeysEx;
import com.intellij.ide.highlighter.JavaClassFileType;
import com.intellij.ide.highlighter.JavaFileType;
import com.intellij.openapi.Disposable;
import com.intellij.openapi.actionSystem.impl.ActionToolbarImpl;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.editor.EditorFactory;
import com.intellij.openapi.editor.colors.EditorColorsManager;
import com.intellij.openapi.editor.colors.EditorColorsScheme;
import com.intellij.openapi.editor.colors.TextAttributesKey;
import com.intellij.openapi.editor.impl.EditorImpl;
import com.intellij.openapi.editor.markup.HighlighterTargetArea;
import com.intellij.openapi.editor.markup.TextAttributes;
import com.intellij.openapi.externalSystem.util.ExternalSystemApiUtil;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.TitlePanel;
import com.intellij.openapi.ui.WindowWrapper;
import com.intellij.openapi.util.Disposer;
import com.intellij.openapi.util.Pair;
import com.intellij.openapi.vcs.VcsException;
import com.intellij.openapi.vcs.changes.Change;
import com.intellij.openapi.vcs.changes.ContentRevision;
import com.intellij.openapi.vcs.changes.actions.diff.ChangeDiffRequestProducer;
import com.intellij.ui.components.JBList;
import com.intellij.ui.components.JBScrollPane;
import com.intellij.ui.components.panels.Wrapper;
import com.intellij.util.ui.components.BorderLayoutPanel;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.research.refactorinsight.data.RefactoringInfo;
import org.jetbrains.research.refactorinsight.diff.MoreSidedDiffRequestGenerator.MoreSidedRange;
import org.jetbrains.research.refactorinsight.diff.ThreeSidedRange;
import org.jetbrains.research.refactorinsight.folding.ImportFolder;
import org.jetbrains.research.refactorinsight.folding.RefactoringFolder;
import org.jetbrains.research.refactorinsight.processors.RefactoringType;
import org.jetbrains.research.refactorinsight.ui.Keys;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ContainerEvent;
import java.awt.event.ContainerListener;
import java.util.List;
import java.util.*;
import java.util.function.Predicate;
import java.util.stream.Collectors;
import static org.jetbrains.research.refactorinsight.utils.TextUtils.fixPath;
/**
* Deals with refactoring diff requests.
* Generates ui components and disposes them.
* Ui components are generated by fetching the right file revisions and adjusting
* the existing diff viewer components.
*/
public class DiffWindow extends DiffExtension {
/**
* Requests diff window to show specific refactoring with two editors.
*
* @param info RefactoringInfo
* @param project Current project
*/
public static void showDiff(Collection<Change> changes, RefactoringInfo info,
Project project, List<RefactoringInfo> refactoringInfos) {
final Predicate<RefactoringInfo> showable =
i -> !i.isHidden() && i.getLeftPath() != null;
List<DiffRequest> requests = refactoringInfos.stream()
.filter(showable)
.map(i -> i.generate(getDiffContents(changes, i, project)))
.filter(Objects::nonNull)
.collect(Collectors.toList());
final int index = refactoringInfos.stream()
.filter(showable).collect(Collectors.toList()).indexOf(info);
if (index != -1) {
DiffRequestChain chain = new SimpleDiffRequestChain(requests, index);
chain.putUserData(DiffUserDataKeysEx.FORCE_DIFF_TOOL, SimpleDiffTool.INSTANCE);
ExternalSystemApiUtil.executeOnEdt(false, () ->
DiffManager.getInstance().showDiff(project, chain,
new DiffDialogHints(WindowWrapper.Mode.FRAME))
);
}
}
private static DiffContent[] getDiffContents(Collection<Change> changes,
RefactoringInfo info, Project project) {
if (info.getLeftPath() == null || info.getRightPath() == null) {
return null;
}
return info.isMoreSided() ? getMoreSidedDiffContents(changes, info, project) :
getStandardDiffContents(changes, info, project);
}
/**
* This method is for "More Sided" refactoring diff.
*/
private static DiffContent[] getMoreSidedDiffContents(Collection<Change> changes,
RefactoringInfo info, Project project) {
try {
DiffContentFactoryEx myDiffContentFactory = DiffContentFactoryEx.getInstanceEx();
ArrayList<DiffContent> contentList = new ArrayList<>();
for (Change change : changes) {
if (change.getAfterRevision() != null
&& change.getAfterRevision().getFile().getPath().contains(info.getRightPath())) {
contentList.add(myDiffContentFactory
.create(project, change.getAfterRevision().getContent(),
JavaClassFileType.INSTANCE));
break;
}
}
for (Pair<String, Boolean> pathPair : info.getMoreSidedLeftPaths()) {
for (Change change : changes) {
ContentRevision revision = pathPair.second
? change.getAfterRevision() : change.getBeforeRevision();
if (revision != null
&& revision.getFile().getPath().contains(fixPath(pathPair.first))) {
contentList.add(myDiffContentFactory
.create(project, revision.getContent(),
JavaClassFileType.INSTANCE));
break;
}
}
}
return contentList.toArray(new DiffContent[0]);
} catch (VcsException ex) {
ex.printStackTrace();
return null;
}
}
/**
* This is contents getter is for standard two or three sided refactoring diff.
*/
private static DiffContent[] getStandardDiffContents(Collection<Change> changes,
RefactoringInfo info, Project project) {
try {
DiffContentFactoryEx myDiffContentFactory = DiffContentFactoryEx.getInstanceEx();
DiffContent[] contents = {null, null, null};
for (Change change : changes) {
if (change.getBeforeRevision() != null) {
if (change.getBeforeRevision().getFile().getPath().contains(info.getLeftPath())) {
String content = RefactoringType.EXTRACT_AND_MOVE_OPERATION.getName().equals(info.getType()) ?
change.getAfterRevision().getContent() : change.getBeforeRevision().getContent();
contents[0] = myDiffContentFactory.create(project,
content,
JavaClassFileType.INSTANCE);
}
}
if (info.isThreeSided()
&& change.getAfterRevision() != null
&& change.getAfterRevision().getFile().getPath().contains(info.getMidPath())) {
contents[1] = myDiffContentFactory.create(project,
change.getAfterRevision().getContent(),
JavaClassFileType.INSTANCE);
}
if (change.getAfterRevision() != null
&& change.getAfterRevision().getFile().getPath().contains(info.getRightPath())) {
contents[2] = myDiffContentFactory.create(project,
change.getAfterRevision().getContent(),
JavaClassFileType.INSTANCE);
}
}
return contents;
} catch (VcsException ex) {
ex.printStackTrace();
return null;
}
}
/**
* IntelliJ Diff Extension.
* This is needed to obtain the viewer object.
* Sets a listener which is activated once classical diff is calculated and
* code ranges can be replaced with refactoring specific ranges.
*/
@Override
public void onViewerCreated(@NotNull FrameDiffTool.DiffViewer viewer,
@NotNull DiffContext context, @NotNull DiffRequest request) {
putCommitIdData(viewer, request);
//Check diff viewer type for refactoring
Boolean isRefactoring = request.getUserData(Keys.REFACTORING);
ImportFolder.foldImports(viewer);
//Fold Move Method refactorings in the base diff that contains the information about all changes in the file.
if (isRefactoring == null) {
RefactoringFolder.foldRefactorings(viewer, request);
return;
}
//Check if diff viewer is three sided
List<ThreeSidedRange> threeSidedRanges = request.getUserData(Keys.THREESIDED_RANGES);
if (threeSidedRanges != null) {
SimpleThreesideDiffViewer myViewer = (SimpleThreesideDiffViewer) viewer;
myViewer.getTextSettings().setExpandByDefault(false);
myViewer.addListener(new MyThreeSidedDiffViewerListener(myViewer, threeSidedRanges));
return;
}
//Check if diff viewer is more sided
List<MoreSidedRange> moreSidedRanges =
request.getUserData(Keys.MORESIDED_RANGES);
SimpleDiffViewer myViewer = (SimpleDiffViewer) viewer;
//Set diff window settings and hide
try {
myViewer.getTextSettings().setIgnorePolicy(IgnorePolicy.DEFAULT);
} catch (IllegalStateException ignored) {
//
}
myViewer.addListener(new MyTwoSidedDiffViewerListener(myViewer));
if (moreSidedRanges != null) {
myViewer.getTextSettings().setExpandByDefault(true);
//Sort on filename and code ranges.
List<MoreSidedRange> sortedRanges =
new ArrayList<>(moreSidedRanges);
Collections.sort(sortedRanges);
//Highlight right part of diff window
// Get diff colors of current theme.
EditorColorsScheme scheme = EditorColorsManager.getInstance().getGlobalScheme();
TextAttributes lineColors = scheme.getAttributes(TextAttributesKey.find("DIFF_MODIFIED"));
TextAttributes offsetColors = scheme.getAttributes(TextAttributesKey.find("DIFF_INSERTED"));
sortedRanges.forEach(moreSidedRange -> {
// Highlight lines
if (moreSidedRange.startLineRight != -1 && moreSidedRange.endLineRight != -1) {
for (int i = moreSidedRange.startLineRight - 1; i < moreSidedRange.endLineRight; i++) {
myViewer.getEditor2().getMarkupModel().addLineHighlighter(i, 2, lineColors);
}
// Highlight offsets
myViewer.getEditor2().getMarkupModel()
.addRangeHighlighter(moreSidedRange.startOffsetRight, moreSidedRange.endOffsetRight,
3, offsetColors, HighlighterTargetArea.EXACT_RANGE);
}
});
//Generate list for left side of diff window
List<Pair<MoreSidedRange, Project>> pairs = new ArrayList<>();
String current = "";
for (MoreSidedRange moreSidedRange : sortedRanges) {
//If new file add title row first by setting project null (this is tested in renderer)
if (!moreSidedRange.leftPath.equals(current)) {
current = moreSidedRange.leftPath;
pairs.add(new Pair<>(moreSidedRange, null));
}
pairs.add(new Pair<>(moreSidedRange, myViewer.getProject()));
}
//Generate Left Side UI
JBList<Pair<MoreSidedRange, Project>> editorList =
new JBList<>(JBList.createDefaultListModel(pairs));
MoreSidedRenderer renderer = new MoreSidedRenderer(editorList.getItemsCount());
Disposer.register(myViewer, renderer);
editorList.setCellRenderer(renderer);
JPanel leftPanel = (JPanel) myViewer.getEditor1().getComponent();
leftPanel.remove(0);
leftPanel.add(new JBScrollPane(editorList));
return;
}
// Assume diff viewer is two-sided
myViewer.getTextSettings().setExpandByDefault(false);
}
private void putCommitIdData(FrameDiffTool.DiffViewer viewer, @NotNull DiffRequest request) {
if (viewer instanceof TwosideTextDiffViewer twosideTextDiffViewer) {
Change change = request.getUserData(ChangeDiffRequestProducer.CHANGE_KEY);
if (change != null && change.getBeforeRevision() != null && change.getAfterRevision() != null) {
// revision before changes
twosideTextDiffViewer.getEditor1().getVirtualFile()
.putUserData(Keys.COMMIT_ID, change.getBeforeRevision().getRevisionNumber().asString());
// revision after changes
twosideTextDiffViewer.getEditor2().getVirtualFile()
.putUserData(Keys.COMMIT_ID, change.getAfterRevision().getRevisionNumber().asString());
twosideTextDiffViewer.getEditor1().getVirtualFile()
.putUserData(Keys.CHILD_COMMIT_ID, change.getAfterRevision().getRevisionNumber().asString());
}
} else if (viewer instanceof OnesideTextDiffViewer) {
Change change = request.getUserData(ChangeDiffRequestProducer.CHANGE_KEY);
if (change != null && change.getType() == Change.Type.NEW && change.getAfterRevision() != null) {
((OnesideTextDiffViewer) viewer).getEditor().getVirtualFile().putUserData(Keys.COMMIT_ID, change.getAfterRevision().getRevisionNumber().asString());
} else if (change != null && change.getType() == Change.Type.DELETED && change.getBeforeRevision() != null) {
((OnesideTextDiffViewer) viewer).getEditor().getVirtualFile().putUserData(Keys.COMMIT_ID, change.getBeforeRevision().getRevisionNumber().asString());
}
}
}
/**
* Renders the editors and title rows on the left side of diff window.
*/
public static class MoreSidedRenderer implements Disposable,
ListCellRenderer<Pair<MoreSidedRange, Project>> {
TitlePanel[] titles;
Editor[] editors;
public MoreSidedRenderer(int size) {
titles = new TitlePanel[size];
editors = new Editor[size];
}
@Override
public Component getListCellRendererComponent(
JList<? extends Pair<MoreSidedRange, Project>> jlist,
Pair<MoreSidedRange, Project> pair, int i, boolean b,
boolean b1) {
//is title panel
if (pair.second == null) {
if (titles[i] == null) {
titles[i] = new TitlePanel(pair.first.leftPath, null);
}
return titles[i];
} else if (editors[i] == null) {
generateEditor(i, pair);
}
editors[i].getScrollingModel().scrollVertically(
Math.max(pair.first.startLineLeft - 2, 0) * editors[i].getLineHeight());
return editors[i].getComponent();
}
/**
* Generate Editor UI for left side of diffwindow.
*
* @param i Index of row in left side
* @param pair RangeData and Project
*/
public void generateEditor(int i, Pair<MoreSidedRange, Project> pair) {
//Instantiate editor
DocumentContent content = (DocumentContent) pair.first.content;
Editor editor = EditorFactory.getInstance().createEditor(content.getDocument(),
pair.second, JavaFileType.INSTANCE, true);
//Get highlight colors corresponding with theme and revision
EditorColorsScheme scheme = EditorColorsManager.getInstance().getGlobalScheme();
TextAttributes lineColor = scheme.getAttributes(TextAttributesKey.find("DIFF_MODIFIED"));
TextAttributes offsetColor
= pair.first.startLineRight == -1 && pair.first.endLineRight == -1
? scheme.getAttributes(TextAttributesKey.find("DIFF_INSERTED"))
: scheme.getAttributes(TextAttributesKey.find("DIFF_DELETED"));
//Highlighting process
// Hide caret line highlighting
editor.getSettings().setCaretRowShown(false);
// Highlight lines
for (int ind = pair.first.startLineLeft - 1; ind < pair.first.endLineLeft; ind++) {
editor.getMarkupModel().addLineHighlighter(ind, 2, lineColor);
}
// Highlight offsets
editor.getMarkupModel().addRangeHighlighter(pair.first.startOffsetLeft,
pair.first.endOffsetLeft, 10, offsetColor,
HighlighterTargetArea.EXACT_RANGE);
//Set editor size to fit coderange
int editorSize = editor.getLineHeight()
* (pair.first.endLineLeft - Math.max(pair.first.startLineLeft - 1, 1) + 2);
editor.getComponent().setPreferredSize(new Dimension(400, editorSize));
//Hide scrollbar
((EditorImpl) editor).getScrollPane().getVerticalScrollBar()
.setPreferredSize(new Dimension(0, 0));
editors[i] = editor;
}
@Override
public void dispose() {
for (Editor editor : editors) {
if (editor != null) {
EditorFactory.getInstance().releaseEditor(editor);
}
}
}
}
/**
* Hides diff settings which might crash the refactorings diff viewer.
* Should be called onAfterRediff.
*
* @param diffViewerComponent Component from diff viewer
*/
public static void hideToolbarActions(Component diffViewerComponent) {
BorderLayoutPanel panel =
(BorderLayoutPanel) diffViewerComponent.getParent().getParent().getParent().getComponent(0);
Wrapper wrapper = (Wrapper) panel.getComponent(0);
ActionToolbarImpl toolbar = (ActionToolbarImpl) wrapper.getComponent(0);
toolbar.addContainerListener(new ContainerListener() {
@Override
public void componentAdded(ContainerEvent containerEvent) {
if (containerEvent.getChild() instanceof JPanel) {
containerEvent.getChild().setVisible(false);
}
}
@Override
public void componentRemoved(ContainerEvent containerEvent) {
}
});
}
public static class MyTwoSidedDiffViewerListener extends DiffViewerListener {
private final SimpleDiffViewer viewer;
public MyTwoSidedDiffViewerListener(SimpleDiffViewer viewer) {
this.viewer = viewer;
}
@Override
protected void onAfterRediff() {
super.onAfterRediff();
hideToolbarActions(viewer.getComponent());
}
}
public static class MyThreeSidedDiffViewerListener extends DiffViewerListener {
private final SimpleThreesideDiffViewer viewer;
private final List<ThreeSidedRange> ranges;
/**
* EventListener for DiffWindow finishing diff calculation.
*
* @param viewer DiffViewer
* @param ranges List of ThreeSidedRanges
*/
public MyThreeSidedDiffViewerListener(SimpleThreesideDiffViewer viewer,
List<ThreeSidedRange> ranges) {
this.ranges = ranges;
this.viewer = viewer;
}
@Override
protected void onAfterRediff() {
/*TODO: check if it actually works
List<SimpleThreesideDiffChange> oldMarkings = viewer.getChanges();
oldMarkings.forEach(ThreesideDiffChangeBase::destroy);
oldMarkings.clear();
oldMarkings.addAll(ranges.stream()
.map(r -> r.getDiffChange(viewer))
.collect(Collectors.toList())
);*/
hideToolbarActions(viewer.getComponent());
}
}
}