summaryrefslogtreecommitdiff
path: root/platform/diff-impl/src/com/intellij/diff/tools/external/ExternalDiffTool.java
blob: e5f9eb381a85aa9ffa39f2edd30db6c28d49ed4e (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
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
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.diff.tools.external;

import com.intellij.diff.DiffDialogHints;
import com.intellij.diff.DiffManagerEx;
import com.intellij.diff.chains.*;
import com.intellij.diff.contents.DiffContent;
import com.intellij.diff.requests.ContentDiffRequest;
import com.intellij.diff.requests.DiffRequest;
import com.intellij.execution.ExecutionException;
import com.intellij.notification.Notification;
import com.intellij.notification.NotificationType;
import com.intellij.openapi.ListSelection;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.diff.DiffBundle;
import com.intellij.openapi.fileTypes.FileTypeManager;
import com.intellij.openapi.fileTypes.UnknownFileType;
import com.intellij.openapi.progress.ProcessCanceledException;
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.ui.Messages;
import com.intellij.openapi.util.Conditions;
import com.intellij.openapi.util.NlsContexts;
import com.intellij.openapi.util.UserDataHolderBase;
import com.intellij.openapi.util.io.FileUtilRt;
import com.intellij.openapi.util.text.HtmlBuilder;
import com.intellij.openapi.util.text.HtmlChunk;
import com.intellij.util.ThrowableConvertor;
import com.intellij.util.concurrency.annotations.RequiresBackgroundThread;
import com.intellij.util.concurrency.annotations.RequiresEdt;
import com.intellij.util.containers.ContainerUtil;
import com.intellij.util.containers.JBIterable;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;

public final class ExternalDiffTool {
  private static final Logger LOG = Logger.getInstance(ExternalDiffTool.class);

  public static boolean isEnabled() {
    return ExternalDiffSettings.getInstance().isExternalToolsEnabled();
  }

  public static boolean isDefault() {
    return isEnabled() && ExternalDiffSettings.isNotBuiltinDiffTool();
  }

  public static boolean wantShowExternalToolFor(@NotNull List<? extends DiffRequestProducer> diffProducers) {
    if (isDefault()) return true;

    FileTypeManager fileTypeManager = FileTypeManager.getInstance();
    return JBIterable.from(diffProducers)
             .map(DiffRequestProducer::getName)
             .filter(filePath -> !FileUtilRt.getExtension(filePath).equals("tmp"))
             .map(filePath -> fileTypeManager.getFileTypeByFileName(filePath))
             .unique()
             .map(fileType -> ExternalDiffSettings.findDiffTool(fileType))
             .filter(Conditions.notNull())
             .first() != null;
  }

  @Nullable
  private static ExternalDiffSettings.ExternalTool getExternalToolFor(@NotNull ContentDiffRequest request) {
    ExternalDiffSettings.ExternalTool diffTool = JBIterable.from(request.getContents())
      .map(content -> content.getContentType())
      .filter(Conditions.notNull())
      .unique()
      .sort(Comparator.comparing(fileType -> fileType != UnknownFileType.INSTANCE ? -1 : 1))
      .map(fileType -> ExternalDiffSettings.findDiffTool(fileType))
      .filter(Conditions.notNull())
      .first();
    if (diffTool != null) return diffTool;

    if (isDefault()) {
      return ExternalDiffSettings.findDefaultDiffTool();
    }
    return null;
  }

  public static boolean showIfNeeded(@Nullable Project project,
                                     @NotNull DiffRequestChain chain,
                                     @NotNull DiffDialogHints hints) {
    return show(project, hints, indicator -> {
      List<? extends DiffRequestProducer> producers = loadProducersFromChain(chain);
      if (!wantShowExternalToolFor(producers)) return null;
      return collectRequests(project, producers, indicator);
    });
  }

  public static void show(@Nullable Project project,
                          @NotNull List<? extends DiffRequestProducer> requestProducers,
                          @NotNull DiffDialogHints hints) {
    show(project, hints, indicator -> {
      return collectRequests(project, requestProducers, indicator);
    });
  }

  private static boolean show(@Nullable Project project,
                              @NotNull DiffDialogHints hints,
                              @NotNull ThrowableConvertor<? super ProgressIndicator, List<DiffRequest>, ? extends Exception> requestsProducer) {
    try {
      List<DiffRequest> requests = computeWithModalProgress(project,
                                                            DiffBundle.message("progress.title.loading.requests"),
                                                            requestsProducer);
      if (requests == null) return false;

      showRequests(project, requests, hints);
      return true;
    }
    catch (ProcessCanceledException ignore) {
    }
    catch (Throwable e) {
      LOG.warn(e);
      Messages.showErrorDialog(project, e.getMessage(), DiffBundle.message("can.t.show.diff.in.external.tool"));
    }
    return false;
  }

  @RequiresEdt
  private static void showRequests(@Nullable Project project,
                                   @NotNull List<DiffRequest> requests,
                                   @NotNull DiffDialogHints hints) throws IOException, ExecutionException {
    List<DiffRequest> showInBuiltin = new ArrayList<>();
    for (DiffRequest request : requests) {
      boolean success = tryShowRequestInExternal(project, request);
      if (!success) {
        showInBuiltin.add(request);
      }
    }

    if (!showInBuiltin.isEmpty()) {
      DiffManagerEx.getInstance().showDiffBuiltin(project, new SimpleDiffRequestChain(showInBuiltin), hints);
    }
  }

  private static boolean tryShowRequestInExternal(@Nullable Project project, @NotNull DiffRequest request)
    throws IOException, ExecutionException {
    if (!canShow(request)) return false;

    ExternalDiffSettings.ExternalTool externalTool = getExternalToolFor(((ContentDiffRequest)request));
    if (externalTool == null) return false;

    showRequest(project, request, externalTool);
    return true;
  }

  @NotNull
  @RequiresBackgroundThread
  private static List<? extends DiffRequestProducer> loadProducersFromChain(@NotNull DiffRequestChain chain) {
    ListSelection<? extends DiffRequestProducer> listSelection;
    if (chain instanceof AsyncDiffRequestChain) {
      listSelection = ((AsyncDiffRequestChain)chain).loadRequestsInBackground();
    }
    else if (chain instanceof DiffRequestSelectionChain) {
      listSelection = ((DiffRequestSelectionChain)chain).getListSelection();
    }
    else {
      listSelection = ListSelection.createAt(chain.getRequests(), chain.getIndex());
    }
    return listSelection.getExplicitSelection();
  }

  @NotNull
  private static List<DiffRequest> collectRequests(@Nullable Project project,
                                                   @NotNull List<? extends DiffRequestProducer> producers,
                                                   @NotNull ProgressIndicator indicator) {
    List<DiffRequest> requests = new ArrayList<>();

    UserDataHolderBase context = new UserDataHolderBase();
    List<DiffRequestProducer> errorRequests = new ArrayList<>();

    for (DiffRequestProducer producer : producers) {
      try {
        requests.add(producer.process(context, indicator));
      }
      catch (DiffRequestProducerException e) {
        LOG.warn(e);
        errorRequests.add(producer);
      }
    }

    if (!errorRequests.isEmpty()) {
      HtmlBuilder message = new HtmlBuilder()
        .appendWithSeparators(HtmlChunk.br(), ContainerUtil.map(errorRequests, producer -> HtmlChunk.text(producer.getName())));
      new Notification("Diff Changes Loading Error", DiffBundle.message("can.t.load.some.changes"), message.toString(),
                       NotificationType.ERROR).notify(project);
    }

    return requests;
  }

  private static <T> T computeWithModalProgress(@Nullable Project project,
                                                @NotNull @NlsContexts.DialogTitle String title,
                                                @NotNull ThrowableConvertor<? super ProgressIndicator, T, ? extends Exception> computable)
    throws Exception {
    return ProgressManager.getInstance().run(new Task.WithResult<T, Exception>(project, title, true) {
      @Override
      protected T compute(@NotNull ProgressIndicator indicator) throws Exception {
        return computable.convert(indicator);
      }
    });
  }

  public static void showRequest(@Nullable Project project,
                                 @NotNull DiffRequest request,
                                 @NotNull ExternalDiffSettings.ExternalTool externalDiffTool) throws ExecutionException, IOException {
    request.onAssigned(true);
    try {
      List<DiffContent> contents = ((ContentDiffRequest)request).getContents();
      List<String> titles = ((ContentDiffRequest)request).getContentTitles();
      ExternalDiffToolUtil.execute(project, externalDiffTool, contents, titles, request.getTitle());
    }
    finally {
      request.onAssigned(false);
    }
  }

  public static boolean canShow(@NotNull DiffRequest request) {
    if (!(request instanceof ContentDiffRequest)) return false;
    List<DiffContent> contents = ((ContentDiffRequest)request).getContents();
    if (contents.size() != 2 && contents.size() != 3) return false;
    for (DiffContent content : contents) {
      if (!ExternalDiffToolUtil.canCreateFile(content)) return false;
    }
    return true;
  }
}