summaryrefslogtreecommitdiff
path: root/platform/usageView-impl/src/com/intellij/usages/impl/UsageViewManagerImpl.java
blob: 0afac01f2ccebfc5c981748473031a2301c095a8 (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
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
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.usages.impl;

import com.intellij.find.SearchInBackgroundOption;
import com.intellij.ide.impl.DataManagerImpl;
import com.intellij.injected.editor.VirtualFileWindow;
import com.intellij.lang.Language;
import com.intellij.notebook.editor.BackedVirtualFile;
import com.intellij.openapi.actionSystem.DataProvider;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.application.ReadAction;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.progress.ProgressIndicator;
import com.intellij.openapi.progress.ProgressManager;
import com.intellij.openapi.progress.Task;
import com.intellij.openapi.progress.util.TooManyUsagesStatus;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.Factory;
import com.intellij.openapi.util.Key;
import com.intellij.openapi.util.NlsContexts;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.openapi.vfs.newvfs.impl.NullVirtualFile;
import com.intellij.openapi.wm.ToolWindow;
import com.intellij.openapi.wm.ToolWindowId;
import com.intellij.openapi.wm.ToolWindowManager;
import com.intellij.psi.PsiElement;
import com.intellij.psi.search.*;
import com.intellij.psi.util.PsiUtilCore;
import com.intellij.ui.content.Content;
import com.intellij.usageView.UsageViewBundle;
import com.intellij.usageView.UsageViewContentManager;
import com.intellij.usages.*;
import com.intellij.usages.rules.PsiElementUsage;
import com.intellij.usages.rules.UsageInFile;
import com.intellij.util.ui.UIUtil;
import org.jetbrains.annotations.Nls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import java.util.Arrays;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.Consumer;
import java.util.function.Supplier;

import static org.jetbrains.annotations.Nls.Capitalization.Sentence;

public class UsageViewManagerImpl extends UsageViewManager {
  private static final Logger LOG = Logger.getInstance(UsageViewManagerImpl.class);
  private final Project myProject;
  private static final Key<UsageView> USAGE_VIEW_KEY = Key.create("USAGE_VIEW");

  public UsageViewManagerImpl(@NotNull Project project) {
    myProject = project;
  }

  @Override
  @NotNull
  public UsageViewEx createUsageView(UsageTarget @NotNull [] targets,
                                     Usage @NotNull [] usages,
                                     @NotNull UsageViewPresentation presentation,
                                     @Nullable Factory<? extends UsageSearcher> usageSearcherFactory) {
    for (UsageViewFactory factory : UsageViewFactory.EP_NAME.getExtensionList()) {
      UsageViewEx result = factory.createUsageView(targets, usages, presentation, usageSearcherFactory);
      if (result != null) {
        return result;
      }
    }

    UsageViewEx usageView = new UsageViewImpl(myProject, presentation, targets, usageSearcherFactory);
    if (usages.length != 0) {
      usageView.appendUsagesInBulk(Arrays.asList(usages));
      ProgressManager.getInstance().run(new Task.Modal(myProject, UsageViewBundle.message("progress.title.waiting.for.usages"), false) {
        @Override
        public void run(@NotNull ProgressIndicator indicator) {
          usageView.waitForUpdateRequestsCompletion();
        }
      });
    }
    usageView.setSearchInProgress(false);
    return usageView;
  }

  @Override
  public @NotNull UsageView showUsages(UsageTarget @NotNull [] searchedFor,
                                       Usage @NotNull [] foundUsages,
                                       @NotNull UsageViewPresentation presentation,
                                       @Nullable Factory<? extends UsageSearcher> factory) {
    UsageViewEx usageView = createUsageView(searchedFor, foundUsages, presentation, factory);
    showUsageView(usageView, presentation);
    if (usageView instanceof UsageViewImpl) {
      showToolWindow(true);
      UIUtil.invokeLaterIfNeeded(() -> {
        if (!((UsageViewImpl)usageView).isDisposed()) {
          ((UsageViewImpl)usageView).expandRoot();
        }
      });
    }
    return usageView;
  }

  @Override
  public @NotNull UsageView showUsages(UsageTarget @NotNull [] searchedFor,
                                       Usage @NotNull [] foundUsages,
                                       @NotNull UsageViewPresentation presentation) {
    return showUsages(searchedFor, foundUsages, presentation, null);
  }

  void showUsageView(@NotNull UsageViewEx usageView, @NotNull UsageViewPresentation presentation) {
    boolean wasPinned = false;
    Content selectedContent = UsageViewContentManager.getInstance(myProject).getSelectedContent();
    if (selectedContent != null && System.identityHashCode(selectedContent) == presentation.getRerunHash()) {
      wasPinned = selectedContent.isPinned();
      selectedContent.setPinned(false);//Unpin explicitly to make old content removed as we rerun search
    }
    Content content = UsageViewContentManager.getInstance(myProject).addContent(
      presentation.getTabText(),
      presentation.getTabName(),
      presentation.getToolwindowTitle(),
      true,
      usageView.getComponent(),
      presentation.isOpenInNewTab() && presentation.getRerunHash() == 0,
      true
    );
    content.setPinned(wasPinned);
    ((UsageViewImpl)usageView).setContent(content);
    content.putUserData(USAGE_VIEW_KEY, usageView);
  }

  @Override
  public @Nullable UsageView searchAndShowUsages(UsageTarget @NotNull [] searchFor,
                                                 @NotNull Factory<? extends UsageSearcher> searcherFactory,
                                                 boolean showPanelIfOnlyOneUsage,
                                                 boolean showNotFoundMessage,
                                                 @NotNull UsageViewPresentation presentation,
                                                 @Nullable UsageViewStateListener listener) {
    FindUsagesProcessPresentation processPresentation = new FindUsagesProcessPresentation(presentation);
    processPresentation.setShowNotFoundMessage(showNotFoundMessage);
    processPresentation.setShowPanelIfOnlyOneUsage(showPanelIfOnlyOneUsage);

    return doSearchAndShow(searchFor, searcherFactory, presentation, processPresentation, listener);
  }

  private UsageView doSearchAndShow(UsageTarget @NotNull [] searchFor,
                                    @NotNull Factory<? extends UsageSearcher> searcherFactory,
                                    @NotNull UsageViewPresentation presentation,
                                    @NotNull FindUsagesProcessPresentation processPresentation,
                                    @Nullable UsageViewStateListener listener) {
    if (ApplicationManager.getApplication().isWriteAccessAllowed()) {
      throw new IllegalStateException("Can't start find usages from under write action. Please consider Application.invokeLater() it instead.");
    }
    SearchScope searchScopeToWarnOfFallingOutOf = getMaxSearchScopeToWarnOfFallingOutOf(searchFor);
    AtomicReference<UsageViewEx> usageViewRef = new AtomicReference<>();
    long start = System.nanoTime();
    AtomicLong firstItemFoundTS = new AtomicLong();
    AtomicBoolean tooManyUsages = new AtomicBoolean();
    Task.Backgroundable task = new Task.Backgroundable(myProject, getProgressTitle(presentation), true, new SearchInBackgroundOption()) {
      @Override
      public void run(@NotNull ProgressIndicator indicator) {
        new SearchForUsagesRunnable(UsageViewManagerImpl.this, UsageViewManagerImpl.this.myProject, usageViewRef, presentation, searchFor, searcherFactory,
                                    processPresentation, searchScopeToWarnOfFallingOutOf, listener, firstItemFoundTS, tooManyUsages).run();
      }

      @NotNull
      @Override
      public NotificationInfo getNotificationInfo() {
        UsageViewEx usageView = usageViewRef.get();
        int count = usageView == null ? 0 : usageView.getUsagesCount();
        long currentTS = System.nanoTime();
        long durationFirstResults = TimeUnit.NANOSECONDS.toMillis(firstItemFoundTS.get() - start);
        long duration = TimeUnit.NANOSECONDS.toMillis(currentTS - start);

        String notification = StringUtil.capitalizeWords(UsageViewBundle.message("usages.n", count), true);
        LOG.debug(notification + " in " + duration + "ms.");

        reportFUS(count, durationFirstResults, duration, tooManyUsages.get());

        return new NotificationInfo("Find Usages",
                                    UsageViewBundle.message("notification.title.find.usages.finished"), notification);
      }

      private void reportFUS(int count, long durationFirstResults, long duration, boolean tooManyUsages) {
          PsiElement element = SearchForUsagesRunnable.getPsiElement(searchFor);
          if (element != null) {
            Class<? extends PsiElement> targetClass = element.getClass();
            Language language = ReadAction.compute(element::getLanguage);
            SearchScope scope = null;

            if (element instanceof DataProvider) {
              scope = UsageView.USAGE_SCOPE.getData((DataProvider)element);
            }

            UsageViewStatisticsCollector.logSearchFinished(myProject, targetClass, scope, language,
                                                           count, durationFirstResults, duration, tooManyUsages,
                                                           CodeNavigateSource.FindToolWindow);
          }
      }
    };
    ProgressManager.getInstance().run(task);
    return usageViewRef.get();
  }

  @NotNull
  SearchScope getMaxSearchScopeToWarnOfFallingOutOf(UsageTarget @NotNull [] searchFor) {
    UsageTarget target = searchFor.length > 0 ? searchFor[0] : null;
    DataProvider dataProvider = DataManagerImpl.getDataProviderEx(target);
    SearchScope scope = dataProvider != null ? UsageView.USAGE_SCOPE.getData(dataProvider) : null;
    if (scope != null) {
      return scope;
    }
    return GlobalSearchScope.everythingScope(myProject); // by default do not warn of falling out of scope
  }

  @Override
  public void searchAndShowUsages(UsageTarget @NotNull [] searchFor,
                                  @NotNull Factory<? extends UsageSearcher> searcherFactory,
                                  @NotNull FindUsagesProcessPresentation processPresentation,
                                  @NotNull UsageViewPresentation presentation,
                                  @Nullable UsageViewStateListener listener) {
    doSearchAndShow(searchFor, searcherFactory, presentation, processPresentation, listener);
  }

  @Override
  public UsageView getSelectedUsageView() {
    Content content = UsageViewContentManager.getInstance(myProject).getSelectedContent();
    if (content != null) {
      return content.getUserData(USAGE_VIEW_KEY);
    }

    return null;
  }

  @NotNull
  public static @NlsContexts.ProgressTitle String getProgressTitle(@NotNull UsageViewPresentation presentation) {
    return UsageViewBundle.message("search.progress.0.in.1", presentation.getSearchString(), presentation.getScopeText());
  }

  void showToolWindow(boolean activateWindow) {
    ToolWindow toolWindow = ToolWindowManager.getInstance(myProject).getToolWindow(ToolWindowId.FIND);
    toolWindow.show(null);
    if (activateWindow && !toolWindow.isActive()) {
      toolWindow.activate(null);
    }
  }


  public static void showTooManyUsagesWarningLater(@NotNull Project project,
                                                   @NotNull TooManyUsagesStatus tooManyUsagesStatus,
                                                   @NotNull ProgressIndicator indicator,
                                                   @Nullable UsageViewEx usageView,
                                                   @NotNull Supplier<String> messageSupplier,
                                                   @Nullable Consumer<UsageLimitUtil.Result> onUserClicked) {
    UIUtil.invokeLaterIfNeeded(() -> {
      if (usageView != null && usageView.searchHasBeenCancelled() || indicator.isCanceled()) return;
      UsageLimitUtil.Result ret = UsageLimitUtil.showTooManyUsagesWarning(project, messageSupplier.get());
      if (ret == UsageLimitUtil.Result.ABORT) {
        if (usageView != null) {
          usageView.cancelCurrentSearch();
        }
        indicator.cancel();
      }
      tooManyUsagesStatus.userResponded();

      if (onUserClicked != null) {
        onUserClicked.accept(ret);
      }
    });
  }

  public static long getFileLength(@NotNull VirtualFile virtualFile) {
    long[] length = {-1L};
    ApplicationManager.getApplication().runReadAction(() -> {
      if (!virtualFile.isValid()) return;
      length[0] = virtualFile.getLength();
    });
    return length[0];
  }

  @NotNull
  public static String presentableSize(long bytes) {
    long megabytes = bytes / (1024 * 1024);
    return UsageViewBundle.message("find.file.size.megabytes", Long.toString(megabytes));
  }

  public static boolean isInScope(@NotNull Usage usage, @NotNull SearchScope searchScope) {
    VirtualFile file = ReadAction.compute(() -> {
      if (usage instanceof PsiElementUsage) {
        PsiElement element = ((PsiElementUsage)usage).getElement();
        if (element == null) return null;
        if (searchScope instanceof EverythingGlobalScope ||
            searchScope instanceof ProjectScopeImpl ||
            searchScope instanceof ProjectAndLibrariesScope) return NullVirtualFile.INSTANCE;
        return PsiUtilCore.getVirtualFile(element);
      }
      return usage instanceof UsageInFile ? ((UsageInFile)usage).getFile() : null;
    });
    //noinspection UseVirtualFileEquals
    return file == NullVirtualFile.INSTANCE || file != null && isFileInScope(file, searchScope);
  }

  private static boolean isFileInScope(@NotNull VirtualFile file, @NotNull SearchScope searchScope) {
    if (file instanceof VirtualFileWindow) {
      file = ((VirtualFileWindow)file).getDelegate();
    }
    file = BackedVirtualFile.getOriginFileIfBacked(file);
    return searchScope.contains(file);
  }

  public static @Nls(capitalization = Sentence) @NotNull String outOfScopeMessage(int nUsages, @NotNull SearchScope searchScope) {
    return UsageViewBundle.message("0.usages.are.out.of.scope", nUsages, searchScope.getDisplayName());
  }
}