summaryrefslogtreecommitdiff
path: root/platform/lang-impl/src/com/intellij/ide/util/scopeChooser/ScopeChooserCombo.java
blob: 1e36c2e5c0b86b69fa18b6d4efeb416fb3f0a638 (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
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
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.ide.util.scopeChooser;

import com.intellij.ide.DataManager;
import com.intellij.ide.util.treeView.WeighedItem;
import com.intellij.openapi.Disposable;
import com.intellij.openapi.actionSystem.DataContext;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.ComboBox;
import com.intellij.openapi.util.Condition;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.packageDependencies.DependencyValidationManager;
import com.intellij.psi.search.PredefinedSearchScopeProvider;
import com.intellij.psi.search.SearchScope;
import com.intellij.psi.search.SearchScopeProvider;
import com.intellij.psi.search.scope.packageSet.NamedScope;
import com.intellij.psi.search.scope.packageSet.NamedScopeManager;
import com.intellij.psi.search.scope.packageSet.NamedScopesHolder;
import com.intellij.ui.ComboboxWithBrowseButton;
import com.intellij.ui.SimpleListCellRenderer;
import com.intellij.ui.TitledSeparator;
import com.intellij.ui.scale.JBUIScale;
import com.intellij.util.BitUtil;
import com.intellij.util.Processor;
import com.intellij.util.SlowOperations;
import com.intellij.util.containers.ContainerUtil;
import com.intellij.util.ui.JBEmptyBorder;
import com.intellij.util.ui.UIUtil;
import org.intellij.lang.annotations.MagicConstant;
import org.jetbrains.annotations.Nls;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.concurrency.Promise;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;

/**
 * Instances of {@code ScopeChooserCombo} <b>must be disposed</b> when the corresponding dialog or settings page is closed. Otherwise
 * listeners registered in {@code init()} cause memory leak.<br/><br/>
 * Example: if {@code ScopeChooserCombo} is used in a
 * {@code DialogWrapper} subclass, call {@code Disposer.register(getDisposable(), myScopeChooserCombo)}, where
 * {@code getDisposable()} is {@code DialogWrapper}'s method.
 */
public class ScopeChooserCombo extends ComboboxWithBrowseButton implements Disposable {
  public static final int OPT_LIBRARIES = 0x1;
  public static final int OPT_SEARCH_RESULTS = 0x2;
  public static final int OPT_FROM_SELECTION = 0x4;
  public static final int OPT_USAGE_VIEW = 0x8;
  public static final int OPT_EMPTY_SCOPES = 0x10;

  private Project myProject;
  private int myOptions = OPT_FROM_SELECTION | OPT_USAGE_VIEW;
  private Condition<? super ScopeDescriptor> myScopeFilter;
  private BrowseListener myBrowseListener;

  private SearchScope preselectedScope;

  public ScopeChooserCombo() {
    super(new MyComboBox());
  }

  public ScopeChooserCombo(final Project project, boolean suggestSearchInLibs, boolean prevSearchWholeFiles, String preselect) {
    this();
    init(project, suggestSearchInLibs, prevSearchWholeFiles, preselect, null);
  }

  public void init(final Project project, final String preselect){
    init(project, false, true, preselect, null);
  }

  public void init(final Project project,
                   final boolean suggestSearchInLibs,
                   final boolean prevSearchWholeFiles,
                   final Object selection,
                   @Nullable Condition<? super ScopeDescriptor> scopeFilter) {
    initialize(project, suggestSearchInLibs, prevSearchWholeFiles, selection, scopeFilter);
  }

  public Promise<?> initialize(final Project project,
                               final boolean suggestSearchInLibs,
                               final boolean prevSearchWholeFiles,
                               final Object selection,
                               @Nullable Condition<? super ScopeDescriptor> scopeFilter) {
    if (myProject != null) {
      throw new IllegalStateException("scope chooser combo already initialized");
    }
    myOptions = BitUtil.set(myOptions, OPT_LIBRARIES, suggestSearchInLibs);
    myOptions = BitUtil.set(myOptions, OPT_SEARCH_RESULTS, prevSearchWholeFiles);
    myProject = project;

    NamedScopesHolder.ScopeListener scopeListener = () -> {
      SearchScope selectedScope = getSelectedScope();
      rebuildModelAndSelectScopeOnSuccess(selectedScope);
    };
    myScopeFilter = scopeFilter;
    NamedScopeManager.getInstance(project).addScopeListener(scopeListener, this);
    DependencyValidationManager.getInstance(project).addScopeListener(scopeListener, this);
    addActionListener(this::handleScopeChooserAction);

    ComboBox<ScopeDescriptor> combo = getComboBox();
    combo.setMinimumAndPreferredWidth(JBUIScale.scale(300));
    combo.setRenderer(createDefaultRenderer());
    combo.setSwingPopup(false);

    if (selection != null) {
      var provider = PredefinedSearchScopeProvider.getInstance();
      var scopes = provider.getPredefinedScopes(project,
                                                null,
                                                suggestSearchInLibs,
                                                prevSearchWholeFiles,
                                                false,
                                                false,
                                                false);
      for (SearchScope s : scopes) {
        if (selection.equals(s.getDisplayName())) {
          preselectedScope = s;
          break;
        }
      }
    }

    return rebuildModelAndSelectScopeOnSuccess(selection);
  }

  @NotNull
  public static ListCellRenderer<ScopeDescriptor> createDefaultRenderer() {
    return new MyRenderer();
  }

  @Override
  public ComboBox<ScopeDescriptor> getComboBox() {
    //noinspection unchecked
    return (ComboBox<ScopeDescriptor>)super.getComboBox();
  }

  public void setBrowseListener(BrowseListener browseListener) {
    myBrowseListener = browseListener;
  }

  public void setCurrentSelection(boolean currentSelection) {
    myOptions = BitUtil.set(myOptions, OPT_FROM_SELECTION, currentSelection);
  }

  public void setUsageView(boolean usageView) {
    myOptions = BitUtil.set(myOptions, OPT_USAGE_VIEW, usageView);
  }

  public void selectItem(@Nullable Object selection) {
    if (selection == null) return;
    JComboBox<ScopeDescriptor> combo = getComboBox();
    DefaultComboBoxModel<ScopeDescriptor> model = (DefaultComboBoxModel<ScopeDescriptor>)combo.getModel();
    for (int i = 0; i < model.getSize(); i++) {
      ScopeDescriptor descriptor = model.getElementAt(i);
      if (selection instanceof String && selection.equals(descriptor.getDisplayName()) ||
          selection instanceof SearchScope && descriptor.scopeEquals((SearchScope)selection)) {
        combo.setSelectedIndex(i);
        break;
      }
    }
  }

  private void handleScopeChooserAction(ActionEvent ignore) {
    String selection = getSelectedScopeName();
    if (myBrowseListener != null) myBrowseListener.onBeforeBrowseStarted();
    EditScopesDialog dlg = EditScopesDialog.showDialog(myProject, selection);
    if (dlg.isOK()){
      NamedScope namedScope = dlg.getSelectedScope();
      rebuildModelAndSelectScopeOnSuccess(namedScope == null ? null : namedScope.getScopeId());
    }
    if (myBrowseListener != null) myBrowseListener.onAfterBrowseFinished();
  }

  /**
   * @deprecated use {@link #processScopesAsync(Project, DataContext, int, Processor)} instead, this method may block UI
   */
  @Deprecated
  public static boolean processScopes(@NotNull Project project,
                                      @NotNull DataContext dataContext,
                                      @MagicConstant(flagsFromClass = ScopeChooserCombo.class) int options,
                                      @NotNull Processor<? super ScopeDescriptor> processor) {
    List<SearchScope> scopes = PredefinedSearchScopeProvider.getInstance().getPredefinedScopes(
      project, dataContext,
      BitUtil.isSet(options, OPT_LIBRARIES),
      BitUtil.isSet(options, OPT_SEARCH_RESULTS),
      BitUtil.isSet(options, OPT_FROM_SELECTION),
      BitUtil.isSet(options, OPT_USAGE_VIEW),
      BitUtil.isSet(options, OPT_EMPTY_SCOPES)
    );
    return doProcessScopes(project, dataContext, scopes, processor);
  }

  public static Promise<Boolean> processScopesAsync(@NotNull Project project,
                                                    @NotNull DataContext dataContext,
                                                    @MagicConstant(flagsFromClass = ScopeChooserCombo.class) int options,
                                                    @NotNull Processor<? super ScopeDescriptor> processor) {
    return PredefinedSearchScopeProvider.getInstance().getPredefinedScopesAsync(
      project, dataContext,
      BitUtil.isSet(options, OPT_LIBRARIES),
      BitUtil.isSet(options, OPT_SEARCH_RESULTS),
      BitUtil.isSet(options, OPT_FROM_SELECTION),
      BitUtil.isSet(options, OPT_USAGE_VIEW),
      BitUtil.isSet(options, OPT_EMPTY_SCOPES)
    ).then(predefinedScopes -> doProcessScopes(project, dataContext, predefinedScopes, processor));
  }

  // called in EDT
  @NotNull
  private static Boolean doProcessScopes(@NotNull Project project,
                                         @NotNull DataContext dataContext,
                                         List<? extends SearchScope> predefinedScopes,
                                         @NotNull Processor<? super ScopeDescriptor> processor) {
    for (SearchScope searchScope : predefinedScopes) {
      if (!processor.process(new ScopeDescriptor(searchScope))) return false;
    }
    for (ScopeDescriptorProvider provider : ScopeDescriptorProvider.EP_NAME.getExtensionList()) {
      for (ScopeDescriptor descriptor : provider.getScopeDescriptors(project)) {
        if (!processor.process(descriptor)) return false;
      }
    }
    Comparator<SearchScope> comparator = (o1, o2) -> {
      int w1 = o1 instanceof WeighedItem ? ((WeighedItem)o1).getWeight() : Integer.MAX_VALUE;
      int w2 = o2 instanceof WeighedItem ? ((WeighedItem)o2).getWeight() : Integer.MAX_VALUE;
      if (w1 == w2) return StringUtil.naturalCompare(o1.getDisplayName(), o2.getDisplayName());
      return w1 - w2;
    };
    for (SearchScopeProvider each : SearchScopeProvider.EP_NAME.getExtensions()) {
      if (StringUtil.isEmpty(each.getDisplayName())) continue;
      List<SearchScope> scopes = SlowOperations.allowSlowOperations(() -> each.getSearchScopes(project, dataContext));
      if (scopes.isEmpty()) continue;
      if (!processor.process(new ScopeSeparator(each.getDisplayName()))) return false;
      for (SearchScope scope : ContainerUtil.sorted(scopes, comparator)) {
        if (!processor.process(new ScopeDescriptor(scope))) return false;
      }
    }
    return true;
  }

  private @NotNull Promise<?> rebuildModelAndSelectScopeOnSuccess(@Nullable Object selection) {
    DefaultComboBoxModel<ScopeDescriptor> model = new DefaultComboBoxModel<>();
    return DataManager.getInstance()
      .getDataContextFromFocusAsync()
      .thenAsync(c -> processScopes(model, c)
      .onSuccess(__ -> {
        getComboBox().setModel(model);
        selectItem(selection);
        preselectedScope = null;
      })
    );
  }

  private @NotNull Promise<?> processScopes(DefaultComboBoxModel<ScopeDescriptor> model, DataContext c) {
    List<ScopeDescriptor> descriptors = new ArrayList<>();
    return processScopesAsync(myProject, c, myOptions, descriptor -> {
      if (myScopeFilter == null || myScopeFilter.value(descriptor)) {
        descriptors.add(descriptor);
      }
      return true;
    }).onSuccess(__ -> updateModel(model, descriptors));
  }

  // called in EDT
  protected void updateModel(DefaultComboBoxModel<ScopeDescriptor> model, List<? extends ScopeDescriptor> descriptors) {
    for (ScopeDescriptor descriptor : descriptors) {
      model.addElement(descriptor);
    }
  }

  @Override
  public Dimension getPreferredSize() {
    if (isPreferredSizeSet()) {
      return super.getPreferredSize();
    }
    Dimension preferredSize = super.getPreferredSize();
    return new Dimension(Math.min(400, preferredSize.width), preferredSize.height);
  }

  @Override
  public Dimension getMinimumSize() {
    if (isMinimumSizeSet()) {
      return super.getMinimumSize();
    }
    Dimension minimumSize = super.getMinimumSize();
    return new Dimension(Math.min(200, minimumSize.width), minimumSize.height);
  }

  public void setShowEmptyScopes(boolean showEmptyScopes) {
    myOptions = BitUtil.set(myOptions, OPT_EMPTY_SCOPES, showEmptyScopes);
  }

  @Nullable
  public SearchScope getSelectedScope() {
    ScopeDescriptor item = (ScopeDescriptor)getComboBox().getSelectedItem();
    return item == null ? preselectedScope : item.getScope();
  }

  public @Nullable @Nls String getSelectedScopeName() {
    ScopeDescriptor item = (ScopeDescriptor)getComboBox().getSelectedItem();
    if (item == null) {
      return preselectedScope == null ? null : preselectedScope.getDisplayName();
    }
    return item.getDisplayName();
  }

  public @Nullable @NonNls String getSelectedScopeId() {
    ScopeDescriptor item = (ScopeDescriptor)getComboBox().getSelectedItem();
    String scopeName;
    if (item != null) {
      scopeName = item.getDisplayName();
    }
    else {
      if (preselectedScope != null) {
        scopeName = preselectedScope.getDisplayName();
      } else {
        scopeName = null;
      }
    }
    return scopeName != null ? ScopeIdMapper.getInstance().getScopeSerializationId(scopeName) : null;
  }

  private static class ScopeSeparator extends ScopeDescriptor {
    final @Nls String text;

    ScopeSeparator(@NotNull @Nls String text) {
      super(null);
      this.text = text;
    }

    @Override
    public String getDisplayName() {
      return text;
    }
  }

  private static class MyRenderer extends SimpleListCellRenderer<ScopeDescriptor> {
    final TitledSeparator separator = new TitledSeparator();

    @Override
    public void customize(@NotNull JList<? extends ScopeDescriptor> list, ScopeDescriptor value, int index, boolean selected, boolean hasFocus) {
      if (value == null) return;
      setIcon(value.getIcon());
      setText(value.getDisplayName());
    }

    @Override
    public Component getListCellRendererComponent(JList<? extends ScopeDescriptor> list,
                                                  ScopeDescriptor value,
                                                  int index,
                                                  boolean selected,
                                                  boolean hasFocus) {
      if (value instanceof ScopeSeparator) {
        separator.setText(value.getDisplayName());
        separator.setBorder(index == -1 ? null : new JBEmptyBorder(UIUtil.DEFAULT_VGAP, 2, UIUtil.DEFAULT_VGAP, 0));
        return separator;
      }
      return super.getListCellRendererComponent(list, value, index, selected, hasFocus);
    }
  }

  public interface BrowseListener {
    void onBeforeBrowseStarted();

    void onAfterBrowseFinished();
  }

  private static class MyComboBox extends ComboBox {

    @Override
    public void setSelectedItem(Object item) {
      if (!(item instanceof ScopeSeparator)) {
        super.setSelectedItem(item);
      }
    }

    @Override
    public void setSelectedIndex(final int anIndex) {
      Object item = getItemAt(anIndex);
      if (!(item instanceof ScopeSeparator)) {
        super.setSelectedIndex(anIndex);
      }
    }
  }
}