summaryrefslogtreecommitdiff
path: root/platform/platform-impl/src/com/intellij/ui/popup/PopupFactoryImpl.java
blob: 2d7a8e3fb2765c18aa3a547feac7a9073ffbb97a (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
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
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
/*
 * Copyright 2000-2012 JetBrains s.r.o.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.intellij.ui.popup;

import com.intellij.CommonBundle;
import com.intellij.icons.AllIcons;
import com.intellij.ide.DataManager;
import com.intellij.ide.IdeEventQueue;
import com.intellij.ide.IdeTooltipManager;
import com.intellij.openapi.Disposable;
import com.intellij.openapi.actionSystem.*;
import com.intellij.openapi.actionSystem.ex.ActionUtil;
import com.intellij.openapi.actionSystem.impl.ActionMenu;
import com.intellij.openapi.actionSystem.impl.Utils;
import com.intellij.openapi.application.ex.ApplicationEx;
import com.intellij.openapi.application.ex.ApplicationManagerEx;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.editor.CaretModel;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.editor.VisualPosition;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.MessageType;
import com.intellij.openapi.ui.popup.*;
import com.intellij.openapi.ui.popup.util.BaseListPopupStep;
import com.intellij.openapi.util.Condition;
import com.intellij.openapi.util.EmptyRunnable;
import com.intellij.openapi.util.Key;
import com.intellij.openapi.wm.WindowManager;
import com.intellij.openapi.wm.ex.WindowManagerEx;
import com.intellij.openapi.wm.impl.IdeFrameImpl;
import com.intellij.ui.ColorUtil;
import com.intellij.ui.FocusTrackback;
import com.intellij.ui.HintHint;
import com.intellij.ui.awt.RelativePoint;
import com.intellij.ui.components.panels.NonOpaquePanel;
import com.intellij.ui.popup.list.ListPopupImpl;
import com.intellij.ui.popup.mock.MockConfirmation;
import com.intellij.ui.popup.tree.TreePopupImpl;
import com.intellij.util.PlatformIcons;
import com.intellij.util.containers.HashMap;
import com.intellij.util.containers.WeakHashMap;
import com.intellij.util.ui.EmptyIcon;
import com.intellij.util.ui.UIUtil;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import javax.swing.*;
import javax.swing.border.EmptyBorder;
import javax.swing.event.HyperlinkListener;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import java.awt.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

public class PopupFactoryImpl extends JBPopupFactory {

  /**
   * Allows to get an editor position for which a popup with auxiliary information might be shown.
   * <p/>
   * Primary intention for this key is to hint popup position for the non-caret location.
   */
  public static final Key<VisualPosition> ANCHOR_POPUP_POSITION = Key.create("popup.anchor.position");

  private static final Logger LOG = Logger.getInstance("#com.intellij.ui.popup.PopupFactoryImpl");

  private final Map<Disposable, List<Balloon>> myStorage = new WeakHashMap<Disposable, List<Balloon>>();

  @NotNull
  @Override
  public ListPopup createConfirmation(String title, final Runnable onYes, int defaultOptionIndex) {
    return createConfirmation(title, CommonBundle.getYesButtonText(), CommonBundle.getNoButtonText(), onYes, defaultOptionIndex);
  }

  @NotNull
  @Override
  public ListPopup createConfirmation(String title, final String yesText, String noText, final Runnable onYes, int defaultOptionIndex) {
    return createConfirmation(title, yesText, noText, onYes, EmptyRunnable.getInstance(), defaultOptionIndex);
  }

  @NotNull
  @Override
  public JBPopup createMessage(String text) {
    return createListPopup(new BaseListPopupStep<String>(null, new String[]{text}));
  }

  @Override
  public Balloon getParentBalloonFor(@Nullable Component c) {
    if (c == null) return null;
    Component eachParent = c;
    while (eachParent != null) {
      if (eachParent instanceof JComponent) {
        Object balloon = ((JComponent)eachParent).getClientProperty(Balloon.KEY);
        if (balloon instanceof Balloon) {
          return (Balloon)balloon;
        }
      }
      eachParent = eachParent.getParent();
    }

    return null;
  }

  @NotNull
  @Override
  public ListPopup createConfirmation(String title,
                                      final String yesText,
                                      String noText,
                                      final Runnable onYes,
                                      final Runnable onNo,
                                      int defaultOptionIndex)
  {

    final BaseListPopupStep<String> step = new BaseListPopupStep<String>(title, new String[]{yesText, noText}) {
      @Override
      public PopupStep onChosen(String selectedValue, final boolean finalChoice) {
        if (selectedValue.equals(yesText)) {
          onYes.run();
        }
        else {
          onNo.run();
        }
        return FINAL_CHOICE;
      }

      @Override
      public void canceled() {
        onNo.run();
      }

      @Override
      public boolean isMnemonicsNavigationEnabled() {
        return true;
      }
    };
    step.setDefaultOptionIndex(defaultOptionIndex);

    final ApplicationEx app = ApplicationManagerEx.getApplicationEx();
    return app == null || !app.isUnitTestMode() ? new ListPopupImpl(step) : new MockConfirmation(step, yesText);
  }


  private static ListPopup createActionGroupPopup(final String title,
                                                  @NotNull ActionGroup actionGroup,
                                                  @NotNull DataContext dataContext,
                                                  boolean showNumbers,
                                                  boolean useAlphaAsNumbers,
                                                  boolean showDisabledActions,
                                                  boolean honorActionMnemonics,
                                                  final Runnable disposeCallback,
                                          final int maxRowCount) {
    return createActionGroupPopup(title, actionGroup, dataContext, showNumbers, useAlphaAsNumbers, showDisabledActions, honorActionMnemonics, disposeCallback,
                                  maxRowCount, null, null);
  }

  public ListPopup createActionGroupPopup(final String title,
                                          final ActionGroup actionGroup,
                                          @NotNull DataContext dataContext,
                                          boolean showNumbers,
                                          boolean showDisabledActions,
                                          boolean honorActionMnemonics,
                                          final Runnable disposeCallback,
                                          final int maxRowCount) {
    return createActionGroupPopup(title, actionGroup, dataContext, showNumbers, showDisabledActions, honorActionMnemonics, disposeCallback,
                                  maxRowCount, null);
  }

  private static ListPopup createActionGroupPopup(final String title,
                                                  @NotNull ActionGroup actionGroup,
                                                  @NotNull DataContext dataContext,
                                                  boolean showNumbers,
                                                  boolean useAlphaAsNumbers,
                                                  boolean showDisabledActions,
                                                  boolean honorActionMnemonics,
                                                  final Runnable disposeCallback,
                                                  final int maxRowCount,
                                                  final Condition<AnAction> preselectActionCondition, @Nullable final String actionPlace) {
    return new ActionGroupPopup(title, actionGroup, dataContext, showNumbers, useAlphaAsNumbers, showDisabledActions, honorActionMnemonics,
                                disposeCallback, maxRowCount, preselectActionCondition, actionPlace);
  }

  public static class ActionGroupPopup extends ListPopupImpl {

    private final Runnable myDisposeCallback;
    private final Component myComponent;

    public ActionGroupPopup(final String title,
                            @NotNull ActionGroup actionGroup,
                            @NotNull DataContext dataContext,
                            boolean showNumbers,
                            boolean useAlphaAsNumbers,
                            boolean showDisabledActions,
                            boolean honorActionMnemonics,
                            final Runnable disposeCallback,
                            final int maxRowCount,
                            final Condition<AnAction> preselectActionCondition,
                            @Nullable final String actionPlace) {
      super(createStep(title, actionGroup, dataContext, showNumbers, useAlphaAsNumbers, showDisabledActions, honorActionMnemonics,
                       preselectActionCondition, actionPlace),
            maxRowCount);
      myDisposeCallback = disposeCallback;
      myComponent = PlatformDataKeys.CONTEXT_COMPONENT.getData(dataContext);

      addListSelectionListener(new ListSelectionListener() {
        @Override
        public void valueChanged(ListSelectionEvent e) {
          final JList list = (JList)e.getSource();
          final ActionItem actionItem = (ActionItem)list.getSelectedValue();
          if (actionItem == null) return;
          AnAction action = actionItem.getAction();
          Presentation presentation = new Presentation();
          presentation.setDescription(action.getTemplatePresentation().getDescription());
          final String actualActionPlace = actionPlace == null ? ActionPlaces.UNKNOWN : actionPlace;
          final AnActionEvent actionEvent =
            new AnActionEvent(null, DataManager.getInstance().getDataContext(myComponent), actualActionPlace, presentation,
                              ActionManager.getInstance(), 0);
          actionEvent.setInjectedContext(action.isInInjectedContext());
          action.update(actionEvent);
          ActionMenu.showDescriptionInStatusBar(true, myComponent, presentation.getDescription());
        }
      });
    }

    private static ListPopupStep createStep(String title,
                                            @NotNull ActionGroup actionGroup,
                                            @NotNull DataContext dataContext,
                                            boolean showNumbers,
                                            boolean useAlphaAsNumbers,
                                            boolean showDisabledActions,
                                            boolean honorActionMnemonics,
                                            Condition<AnAction> preselectActionCondition,
                                            @Nullable String actionPlace) {
      final Component component = PlatformDataKeys.CONTEXT_COMPONENT.getData(dataContext);
      LOG.assertTrue(component != null, "dataContext has no component for new ListPopupStep");

      final ActionStepBuilder builder =
        new ActionStepBuilder(dataContext, showNumbers, useAlphaAsNumbers, showDisabledActions, honorActionMnemonics);
      if (actionPlace != null) {
        builder.setActionPlace(actionPlace);
      }
      builder.buildGroup(actionGroup);
      final List<ActionItem> items = builder.getItems();

      return new ActionPopupStep(items, title, component, showNumbers || honorActionMnemonics && itemsHaveMnemonics(items),
                                 preselectActionCondition, false, showDisabledActions);
    }

    @Override
    public void dispose() {
      if (myDisposeCallback != null) {
        myDisposeCallback.run();
      }
      ActionMenu.showDescriptionInStatusBar(true, myComponent, null);
      super.dispose();
    }
  }

  @NotNull
  @Override
  public ListPopup createActionGroupPopup(final String title,
                                          @NotNull final ActionGroup actionGroup,
                                          @NotNull DataContext dataContext,
                                          boolean showNumbers,
                                          boolean showDisabledActions,
                                          boolean honorActionMnemonics,
                                          final Runnable disposeCallback,
                                          final int maxRowCount,
                                          final Condition<AnAction> preselectActionCondition) {
    return createActionGroupPopup(title, actionGroup, dataContext, showNumbers, true, showDisabledActions, honorActionMnemonics,
                                  disposeCallback, maxRowCount, preselectActionCondition, null);
  }

  @NotNull
  @Override
  public ListPopup createActionGroupPopup(String title,
                                          @NotNull ActionGroup actionGroup,
                                          @NotNull DataContext dataContext,
                                          ActionSelectionAid selectionAidMethod,
                                          boolean showDisabledActions) {
    return createActionGroupPopup(title, actionGroup, dataContext,
                                  selectionAidMethod == ActionSelectionAid.NUMBERING || selectionAidMethod == ActionSelectionAid.ALPHA_NUMBERING,
                                  selectionAidMethod == ActionSelectionAid.ALPHA_NUMBERING,
                                  showDisabledActions,
                                  selectionAidMethod == ActionSelectionAid.MNEMONICS,
                                  null, -1);
  }

  @NotNull
  @Override
  public ListPopup createActionGroupPopup(String title,
                                          @NotNull ActionGroup actionGroup,
                                          @NotNull DataContext dataContext,
                                          ActionSelectionAid selectionAidMethod,
                                          boolean showDisabledActions,
                                          @Nullable String actionPlace) {
    return createActionGroupPopup(title, actionGroup, dataContext,
                                  selectionAidMethod == ActionSelectionAid.NUMBERING || selectionAidMethod == ActionSelectionAid.ALPHA_NUMBERING,
                                  selectionAidMethod == ActionSelectionAid.ALPHA_NUMBERING,
                                  showDisabledActions,
                                  selectionAidMethod == ActionSelectionAid.MNEMONICS,
                                  null, -1, null, actionPlace);
  }

  @NotNull
  @Override
  public ListPopup createActionGroupPopup(String title,
                                          @NotNull ActionGroup actionGroup,
                                          @NotNull DataContext dataContext,
                                          ActionSelectionAid selectionAidMethod,
                                          boolean showDisabledActions,
                                          Runnable disposeCallback,
                                          int maxRowCount) {
    return createActionGroupPopup(title, actionGroup, dataContext,
                                  selectionAidMethod == ActionSelectionAid.NUMBERING || selectionAidMethod == ActionSelectionAid.ALPHA_NUMBERING,
                                  selectionAidMethod == ActionSelectionAid.ALPHA_NUMBERING,
                                  showDisabledActions,
                                  selectionAidMethod == ActionSelectionAid.MNEMONICS,
                                  disposeCallback,
                                  maxRowCount);
  }

  @NotNull
  @Override
  public ListPopupStep createActionsStep(@NotNull final ActionGroup actionGroup,
                                         @NotNull DataContext dataContext,
                                         final boolean showNumbers,
                                         final boolean showDisabledActions,
                                         final String title,
                                         final Component component,
                                         final boolean honorActionMnemonics) {
    return createActionsStep(actionGroup, dataContext, showNumbers, showDisabledActions, title, component, honorActionMnemonics, 0, false);
  }

  private static ListPopupStep createActionsStep(@NotNull ActionGroup actionGroup, @NotNull DataContext dataContext,
                                                 boolean showNumbers, boolean useAlphaAsNumbers, boolean showDisabledActions,
                                                 String title, Component component, boolean honorActionMnemonics,
                                                 final int defaultOptionIndex, final boolean autoSelectionEnabled) {
    final List<ActionItem> items = makeActionItemsFromActionGroup(actionGroup, dataContext, showNumbers, useAlphaAsNumbers,
                                                                  showDisabledActions, honorActionMnemonics);
    return new ActionPopupStep(items, title, component, showNumbers || honorActionMnemonics && itemsHaveMnemonics(items),
                               new Condition<AnAction>() {
                                 @Override
                                 public boolean value(AnAction action) {
                                   return defaultOptionIndex >= 0 &&
                                          defaultOptionIndex < items.size() &&
                                          items.get(defaultOptionIndex).getAction().equals(action);
                                 }
                               }, autoSelectionEnabled, showDisabledActions);
  }

  @NotNull
  private static List<ActionItem> makeActionItemsFromActionGroup(@NotNull ActionGroup actionGroup,
                                                                 @NotNull DataContext dataContext,
                                                                 boolean showNumbers,
                                                                 boolean useAlphaAsNumbers,
                                                                 boolean showDisabledActions,
                                                                 boolean honorActionMnemonics) {
    final ActionStepBuilder builder = new ActionStepBuilder(dataContext, showNumbers, useAlphaAsNumbers, showDisabledActions,
                                                            honorActionMnemonics);
    builder.buildGroup(actionGroup);
    return builder.getItems();
  }

  @NotNull
  private static ListPopupStep createActionsStep(@NotNull ActionGroup actionGroup, @NotNull DataContext dataContext,
                                                 boolean showNumbers, boolean useAlphaAsNumbers, boolean showDisabledActions,
                                                 String title, Component component, boolean honorActionMnemonics,
                                                 Condition<AnAction> preselectActionCondition, boolean autoSelectionEnabled) {
    final List<ActionItem> items = makeActionItemsFromActionGroup(actionGroup, dataContext, showNumbers, useAlphaAsNumbers,
                                                                  showDisabledActions, honorActionMnemonics);
    return new ActionPopupStep(items, title, component, showNumbers || honorActionMnemonics && itemsHaveMnemonics(items), preselectActionCondition,
                               autoSelectionEnabled, showDisabledActions);
  }

  @NotNull
  @Override
  public ListPopupStep createActionsStep(@NotNull ActionGroup actionGroup, @NotNull DataContext dataContext, boolean showNumbers, boolean showDisabledActions,
                                         String title, Component component, boolean honorActionMnemonics, int defaultOptionIndex,
                                         final boolean autoSelectionEnabled) {
    return createActionsStep(actionGroup, dataContext, showNumbers, true, showDisabledActions, title, component, honorActionMnemonics,
                             defaultOptionIndex, autoSelectionEnabled);
  }

  private static boolean itemsHaveMnemonics(final List<ActionItem> items) {
    for (ActionItem item : items) {
      if (item.getAction().getTemplatePresentation().getMnemonic() != 0) return true;
    }

    return false;
  }

  @NotNull
  @Override
  public ListPopup createWizardStep(@NotNull PopupStep step) {
    return new ListPopupImpl((ListPopupStep) step);
  }

  @NotNull
  @Override
  public ListPopup createListPopup(@NotNull ListPopupStep step) {
    return new ListPopupImpl(step);
  }

  @NotNull
  @Override
  public TreePopup createTree(JBPopup parent, @NotNull TreePopupStep aStep, Object parentValue) {
    return new TreePopupImpl(parent, aStep, parentValue);
  }

  @NotNull
  @Override
  public TreePopup createTree(@NotNull TreePopupStep aStep) {
    return new TreePopupImpl(aStep);
  }

  @NotNull
  @Override
  public ComponentPopupBuilder createComponentPopupBuilder(@NotNull JComponent content, JComponent prefferableFocusComponent) {
    return new ComponentPopupBuilderImpl(content, prefferableFocusComponent);
  }

 
  @NotNull
  @Override
  public RelativePoint guessBestPopupLocation(@NotNull DataContext dataContext) {
    Component component = PlatformDataKeys.CONTEXT_COMPONENT.getData(dataContext);
    JComponent focusOwner = component instanceof JComponent ? (JComponent)component : null;

    if (focusOwner == null) {
      Project project = CommonDataKeys.PROJECT.getData(dataContext);
      IdeFrameImpl frame = project == null ? null : ((WindowManagerEx)WindowManager.getInstance()).getFrame(project);
      focusOwner = frame == null ? null : frame.getRootPane();
      if (focusOwner == null) {
        throw new IllegalArgumentException("focusOwner cannot be null");
      }
    }

    final Point point = PlatformDataKeys.CONTEXT_MENU_POINT.getData(dataContext);
    if (point != null) {
      return new RelativePoint(focusOwner, point);
    }

    Editor editor = CommonDataKeys.EDITOR.getData(dataContext);
    if (editor != null && focusOwner == editor.getContentComponent()) {
      return guessBestPopupLocation(editor);
    }
    else {
      return guessBestPopupLocation(focusOwner);
    }
  }

  @NotNull
  @Override
  public RelativePoint guessBestPopupLocation(@NotNull final JComponent component) {
    Point popupMenuPoint = null;
    final Rectangle visibleRect = component.getVisibleRect();
    if (component instanceof JList) { // JList
      JList list = (JList)component;
      int firstVisibleIndex = list.getFirstVisibleIndex();
      int lastVisibleIndex = list.getLastVisibleIndex();
      int[] selectedIndices = list.getSelectedIndices();
      for (int index : selectedIndices) {
        if (firstVisibleIndex <= index && index <= lastVisibleIndex) {
          Rectangle cellBounds = list.getCellBounds(index, index);
          popupMenuPoint = new Point(visibleRect.x + visibleRect.width / 4, cellBounds.y + cellBounds.height);
          break;
        }
      }
    }
    else if (component instanceof JTree) { // JTree
      JTree tree = (JTree)component;
      int[] selectionRows = tree.getSelectionRows();
      if (selectionRows != null) {
        Arrays.sort(selectionRows);
        for (int i = 0; i < selectionRows.length; i++) {
          int row = selectionRows[i];
          Rectangle rowBounds = tree.getRowBounds(row);
          if (visibleRect.contains(rowBounds)) {
            popupMenuPoint = new Point(rowBounds.x + 2, rowBounds.y + rowBounds.height - 1);
            break;
          }
        }
        if (popupMenuPoint == null) {//All selected rows are out of visible rect
          Point visibleCenter = new Point(visibleRect.x + visibleRect.width / 2, visibleRect.y + visibleRect.height / 2);
          double minDistance = Double.POSITIVE_INFINITY;
          int bestRow = -1;
          Point rowCenter;
          double distance;
          for (int i = 0; i < selectionRows.length; i++) {
            int row = selectionRows[i];
            Rectangle rowBounds = tree.getRowBounds(row);
            rowCenter = new Point(rowBounds.x + rowBounds.width / 2, rowBounds.y + rowBounds.height / 2);
            distance = visibleCenter.distance(rowCenter);
            if (minDistance > distance) {
              minDistance = distance;
              bestRow = row;
            }
          }

          if (bestRow != -1) {
            Rectangle rowBounds = tree.getRowBounds(bestRow);
            tree.scrollRectToVisible(new Rectangle(rowBounds.x, rowBounds.y, Math.min(visibleRect.width, rowBounds.width), rowBounds.height));
            popupMenuPoint = new Point(rowBounds.x + 2, rowBounds.y + rowBounds.height - 1);
          }
        }
      }
    }
    else if (component instanceof JTable) {
      JTable table = (JTable)component;
      int column = table.getColumnModel().getSelectionModel().getLeadSelectionIndex();
      int row = Math.max(table.getSelectionModel().getLeadSelectionIndex(), table.getSelectionModel().getAnchorSelectionIndex());
      Rectangle rect = table.getCellRect(row, column, false);
      if (!visibleRect.intersects(rect)) {
        table.scrollRectToVisible(rect);
      }
      popupMenuPoint = new Point(rect.x, rect.y + rect.height);
    }
    else if (component instanceof PopupOwner) {
      popupMenuPoint = ((PopupOwner)component).getBestPopupPosition();
    }
    if (popupMenuPoint == null) {
      popupMenuPoint = new Point(visibleRect.x + visibleRect.width / 2, visibleRect.y + visibleRect.height / 2);
    }

    return new RelativePoint(component, popupMenuPoint);
  }

  @Override
  public boolean isBestPopupLocationVisible(@NotNull Editor editor) {
    return getVisibleBestPopupLocation(editor) != null;
  }

  @NotNull
  @Override
  public RelativePoint guessBestPopupLocation(@NotNull Editor editor) {
    Point p = getVisibleBestPopupLocation(editor);
    if (p == null) {
      final Rectangle visibleArea = editor.getScrollingModel().getVisibleArea();
      p = new Point((visibleArea.x + visibleArea.width) / 2, (visibleArea.y + visibleArea.height) / 2);
    }
    return new RelativePoint(editor.getContentComponent(), p);
  }

  @Nullable
  private static Point getVisibleBestPopupLocation(@NotNull Editor editor) {
    VisualPosition visualPosition = editor.getUserData(ANCHOR_POPUP_POSITION);

    if (visualPosition == null) {
      CaretModel caretModel = editor.getCaretModel();
      if (caretModel.isUpToDate()) {
        visualPosition = caretModel.getVisualPosition();
      }
      else {
        visualPosition = editor.offsetToVisualPosition(caretModel.getOffset());
      }
    }

    Point p = editor.visualPositionToXY(new VisualPosition(visualPosition.line + 1, visualPosition.column));

    final Rectangle visibleArea = editor.getScrollingModel().getVisibleArea();
    return visibleArea.contains(p) ? p : null;
  }

  @Override
  public Point getCenterOf(JComponent container, JComponent content) {
    return AbstractPopup.getCenterOf(container, content);
  }

  public static class ActionItem {
    private final AnAction myAction;
    private final String myText;
    private final boolean myIsEnabled;
    private final Icon myIcon;
    private final boolean myPrependWithSeparator;
    private final String mySeparatorText;

    private ActionItem(@NotNull AnAction action, @NotNull String text, boolean enabled, Icon icon, final boolean prependWithSeparator, String separatorText) {
      myAction = action;
      myText = text;
      myIsEnabled = enabled;
      myIcon = icon;
      myPrependWithSeparator = prependWithSeparator;
      mySeparatorText = separatorText;
    }

    @NotNull
    public AnAction getAction() {
      return myAction;
    }

    @NotNull
    public String getText() {
      return myText;
    }

    public Icon getIcon() {
      return myIcon;
    }                                                                                                                           

    public boolean isPrependWithSeparator() {
      return myPrependWithSeparator;
    }

    public String getSeparatorText() {
      return mySeparatorText;
    }

    public boolean isEnabled() { return myIsEnabled; }
  }

  private static class ActionPopupStep implements ListPopupStepEx<ActionItem>, MnemonicNavigationFilter<ActionItem>, SpeedSearchFilter<ActionItem> {
    private final List<ActionItem> myItems;
    private final String myTitle;
    private final Component myContext;
    private final boolean myEnableMnemonics;
    private final int myDefaultOptionIndex;
    private final boolean myAutoSelectionEnabled;
    private final boolean myShowDisabledActions;
    private Runnable myFinalRunnable;
    @Nullable private final Condition<AnAction> myPreselectActionCondition;

    private ActionPopupStep(@NotNull final List<ActionItem> items, final String title, Component context, boolean enableMnemonics,
                            @Nullable Condition<AnAction> preselectActionCondition, final boolean autoSelection, boolean showDisabledActions) {
      myItems = items;
      myTitle = title;
      myContext = context;
      myEnableMnemonics = enableMnemonics;
      myDefaultOptionIndex = getDefaultOptionIndexFromSelectCondition(preselectActionCondition, items);
      myPreselectActionCondition = preselectActionCondition;
      myAutoSelectionEnabled = autoSelection;
      myShowDisabledActions = showDisabledActions;
    }

    private static int getDefaultOptionIndexFromSelectCondition(@Nullable Condition<AnAction> preselectActionCondition,
                                                                @NotNull List<ActionItem> items) {
      int defaultOptionIndex = 0;
      if (preselectActionCondition != null) {
        for (int i = 0; i < items.size(); i++) {
          final AnAction action = items.get(i).getAction();
          if (preselectActionCondition.value(action)) {
            defaultOptionIndex = i;
            break;
          }
        }
      }
      return defaultOptionIndex;
    }

    @Override
    @NotNull
    public List<ActionItem> getValues() {
      return myItems;
    }

    @Override
    public boolean isSelectable(final ActionItem value) {
      return value.isEnabled();
    }

    @Override
    public int getMnemonicPos(final ActionItem value) {
      final String text = getTextFor(value);
      int i = text.indexOf(UIUtil.MNEMONIC);
      if (i < 0) {
        i = text.indexOf('&');
      }
      if (i < 0) {
        i = text.indexOf('_');
      }
      return i;
    }

    @Override
    public Icon getIconFor(final ActionItem aValue) {
      return aValue.getIcon();
    }

    @Override
    @NotNull
    public String getTextFor(final ActionItem value) {
      return value.getText();
    }

    @Override
    public ListSeparator getSeparatorAbove(final ActionItem value) {
      return value.isPrependWithSeparator() ? new ListSeparator(value.getSeparatorText()) : null;
    }

    @Override
    public int getDefaultOptionIndex() {
      return myDefaultOptionIndex;
    }

    @Override
    public String getTitle() {
      return myTitle;
    }

    @Override
    public PopupStep onChosen(final ActionItem actionChoice, final boolean finalChoice) {
      return onChosen(actionChoice, finalChoice, 0);
    }

    @Override
    public PopupStep onChosen(ActionItem actionChoice, boolean finalChoice, final int eventModifiers) {
      if (!actionChoice.isEnabled()) return FINAL_CHOICE;
      final AnAction action = actionChoice.getAction();
      DataManager mgr = DataManager.getInstance();

      final DataContext dataContext = myContext != null ? mgr.getDataContext(myContext) : mgr.getDataContext();

      if (action instanceof ActionGroup && (!finalChoice || !((ActionGroup)action).canBePerformed(dataContext))) {
          return createActionsStep((ActionGroup)action, dataContext, myEnableMnemonics, true, myShowDisabledActions, null, myContext, false,
                                   myPreselectActionCondition, false);
      }
      else {
        myFinalRunnable = new Runnable() {
          @Override
          public void run() {
            final AnActionEvent event = new AnActionEvent(null, dataContext, ActionPlaces.UNKNOWN, action.getTemplatePresentation().clone(),
                                                          ActionManager.getInstance(), eventModifiers);
            event.setInjectedContext(action.isInInjectedContext());
            action.actionPerformed(event);
          }
        };
        return FINAL_CHOICE;
      }
    }

    @Override
    public Runnable getFinalRunnable() {
      return myFinalRunnable;
    }

    @Override
    public boolean hasSubstep(final ActionItem selectedValue) {
      return selectedValue != null && selectedValue.isEnabled() && selectedValue.getAction() instanceof ActionGroup;
    }

    @Override
    public void canceled() {
    }

    @Override
    public boolean isMnemonicsNavigationEnabled() {
      return myEnableMnemonics;
    }

    @Override
    public MnemonicNavigationFilter<ActionItem> getMnemonicNavigationFilter() {
      return this;
    }

    @Override
    public boolean canBeHidden(final ActionItem value) {
      return true;
    }

    @Override
    public String getIndexedString(final ActionItem value) {
      return getTextFor(value);
    }

    @Override
    public boolean isSpeedSearchEnabled() {
      return true;
    }

    @Override
    public boolean isAutoSelectionEnabled() {
      return myAutoSelectionEnabled;
    }

    @Override
    public SpeedSearchFilter<ActionItem> getSpeedSearchFilter() {
      return this;
    }
  }

  @Override
  @NotNull
  public List<JBPopup> getChildPopups(@NotNull final Component component) {
    return FocusTrackback.getChildPopups(component);
  }

  @Override
  public boolean isPopupActive() {
  return IdeEventQueue.getInstance().isPopupActive();
  }

  private static class ActionStepBuilder {
    private final List<ActionItem>                myListModel;
    private final DataContext                     myDataContext;
    private final boolean                         myShowNumbers;
    private final boolean                         myUseAlphaAsNumbers;
    private final boolean                         myShowDisabled;
    private final HashMap<AnAction, Presentation> myAction2presentation;
    private       int                             myCurrentNumber;
    private       boolean                         myPrependWithSeparator;
    private       String                          mySeparatorText;
    private final boolean                         myHonorActionMnemonics;
    private       Icon                            myEmptyIcon;
    private int myMaxIconWidth  = -1;
    private int myMaxIconHeight = -1;
    @NotNull private String myActionPlace;

    private ActionStepBuilder(@NotNull DataContext dataContext, final boolean showNumbers, final boolean useAlphaAsNumbers,
                              final boolean showDisabled, final boolean honorActionMnemonics)
    {
      myUseAlphaAsNumbers = useAlphaAsNumbers;
      myListModel = new ArrayList<ActionItem>();
      myDataContext = dataContext;
      myShowNumbers = showNumbers;
      myShowDisabled = showDisabled;
      myAction2presentation = new HashMap<AnAction, Presentation>();
      myCurrentNumber = 0;
      myPrependWithSeparator = false;
      mySeparatorText = null;
      myHonorActionMnemonics = honorActionMnemonics;
      myActionPlace = ActionPlaces.UNKNOWN;
    }

    public void setActionPlace(@NotNull String actionPlace) {
      myActionPlace = actionPlace;
    }

    @NotNull
    public List<ActionItem> getItems() {
      return myListModel;
    }

    public void buildGroup(@NotNull ActionGroup actionGroup) {
      calcMaxIconSize(actionGroup);
      myEmptyIcon = myMaxIconHeight != -1 && myMaxIconWidth != -1 ? new EmptyIcon(myMaxIconWidth, myMaxIconHeight) : null;

      appendActionsFromGroup(actionGroup);

      if (myListModel.isEmpty()) {
        myListModel.add(new ActionItem(Utils.EMPTY_MENU_FILLER, Utils.NOTHING_HERE, false, null, false, null));
      }
    }

    private void calcMaxIconSize(final ActionGroup actionGroup) {
      AnAction[] actions = actionGroup.getChildren(createActionEvent(actionGroup));
      for (AnAction action : actions) {
        if (action == null) continue;
        if (action instanceof ActionGroup) {
          final ActionGroup group = (ActionGroup)action;
          if (!group.isPopup()) {
            calcMaxIconSize(group);
            continue;
          }
        }

        Icon icon = action.getTemplatePresentation().getIcon();
        if (icon == null && action instanceof Toggleable) icon = PlatformIcons.CHECK_ICON;
        if (icon != null) {
          final int width = icon.getIconWidth();
          final int height = icon.getIconHeight();
          if (myMaxIconWidth < width) {
            myMaxIconWidth = width;
          }
          if (myMaxIconHeight < height) {
            myMaxIconHeight = height;
          }
        }
      }
    }

    @NotNull
    private AnActionEvent createActionEvent(@NotNull AnAction actionGroup) {
      final AnActionEvent actionEvent =
        new AnActionEvent(null, myDataContext, myActionPlace, getPresentation(actionGroup), ActionManager.getInstance(), 0);
      actionEvent.setInjectedContext(actionGroup.isInInjectedContext());
      return actionEvent;
    }

    private void appendActionsFromGroup(@NotNull ActionGroup actionGroup) {
      AnAction[] actions = actionGroup.getChildren(createActionEvent(actionGroup));
      for (AnAction action : actions) {
        if (action == null) {
          LOG.error("null action in group " + actionGroup);
          continue;
        }
        if (action instanceof Separator) {
          myPrependWithSeparator = true;
          mySeparatorText = ((Separator)action).getText();
        }
        else {
          if (action instanceof ActionGroup) {
            ActionGroup group = (ActionGroup)action;
            if (group.isPopup()) {
              appendAction(group);
            }
            else {
              appendActionsFromGroup(group);
            }
          }
          else {
            appendAction(action);
          }
        }
      }
    }

    private void appendAction(@NotNull AnAction action) {
      Presentation presentation = getPresentation(action);
      AnActionEvent event = createActionEvent(action);

      ActionUtil.performDumbAwareUpdate(action, event, true);
      if ((myShowDisabled || presentation.isEnabled()) && presentation.isVisible()) {
        String text = presentation.getText();
        if (myShowNumbers) {
          if (myCurrentNumber < 9) {
            text = "&" + (myCurrentNumber + 1) + ". " + text;
          }
          else if (myCurrentNumber == 9) {
            text = "&" + 0 + ". " + text;
          }
          else if (myUseAlphaAsNumbers) {
            text = "&" + (char)('A' + myCurrentNumber - 10) + ". " + text;
          }
          myCurrentNumber++;
        }
        else if (myHonorActionMnemonics) {
          text = Presentation.restoreTextWithMnemonic(text, action.getTemplatePresentation().getMnemonic());
        }

        Icon icon = presentation.getIcon();
        if (icon == null) {
          @NonNls final String actionId = ActionManager.getInstance().getId(action);
          if (actionId != null && actionId.startsWith("QuickList.")) {
            icon = AllIcons.Actions.QuickList;
          }
          else if (action instanceof Toggleable) {
            boolean toggled = Boolean.TRUE.equals(presentation.getClientProperty(Toggleable.SELECTED_PROPERTY));
            icon = toggled? new IconWrapper(PlatformIcons.CHECK_ICON) : myEmptyIcon;
          }
          else {
            icon = myEmptyIcon;
          }
        }
        else {
          icon = new IconWrapper(icon);
        }
        boolean prependSeparator = (!myListModel.isEmpty() || mySeparatorText != null) && myPrependWithSeparator;
        assert text != null : action + " has no presentation";
        myListModel.add(new ActionItem(action, text, presentation.isEnabled(), icon, prependSeparator, mySeparatorText));
        myPrependWithSeparator = false;
        mySeparatorText = null;
      }
    }

    /**
     * Adjusts icon size to maximum, so that icons with different sizes were aligned correctly.
     */
    private class IconWrapper implements Icon {

      private Icon myIcon;

      IconWrapper(Icon icon) {
        myIcon = icon;
      }

      @Override
      public void paintIcon(Component c, Graphics g, int x, int y) {
        myIcon.paintIcon(c, g, x, y);
      }

      @Override
      public int getIconWidth() {
        return myMaxIconWidth;
      }

      @Override
      public int getIconHeight() {
        return myMaxIconHeight;
      }
    }

    private Presentation getPresentation(@NotNull AnAction action) {
      Presentation presentation = myAction2presentation.get(action);
      if (presentation == null) {
        presentation = action.getTemplatePresentation().clone();
        myAction2presentation.put(action, presentation);
      }
      return presentation;
    }
  }

  @NotNull
  @Override
  public BalloonBuilder createBalloonBuilder(@NotNull final JComponent content) {
    return new BalloonPopupBuilderImpl(myStorage, content);
  }

  @NotNull
  @Override
  public BalloonBuilder createDialogBalloonBuilder(@NotNull JComponent content, String title) {
    final BalloonPopupBuilderImpl builder = new BalloonPopupBuilderImpl(myStorage, content);
    final Color bg = UIManager.getColor("Panel.background");
    final Color borderOriginal = Color.darkGray;
    final Color border = ColorUtil.toAlpha(borderOriginal, 75);
    builder
      .setDialogMode(true)
      .setTitle(title)
      .setAnimationCycle(200)
      .setFillColor(bg)
      .setBorderColor(border)
      .setHideOnClickOutside(false)
      .setHideOnKeyOutside(false)
      .setHideOnAction(false)
      .setCloseButtonEnabled(true)
      .setShadow(true);

    return builder;
  }

  @NotNull
  @Override
  public BalloonBuilder createHtmlTextBalloonBuilder(@NotNull final String htmlContent, @Nullable final Icon icon, final Color fillColor,
                                                     @Nullable final HyperlinkListener listener)
  {


    JEditorPane text = IdeTooltipManager.initPane(htmlContent, new HintHint().setAwtTooltip(true), null);

    if (listener != null) {
      text.addHyperlinkListener(listener);
    }
    text.setEditable(false);
    NonOpaquePanel.setTransparent(text);
    text.setBorder(null);


    JLabel label = new JLabel();
    final JPanel content = new NonOpaquePanel(new BorderLayout((int)(label.getIconTextGap() * 1.5), (int)(label.getIconTextGap() * 1.5)));

    final NonOpaquePanel textWrapper = new NonOpaquePanel(new GridBagLayout());
    JScrollPane scrolledText = new JScrollPane(text);
    scrolledText.setBackground(fillColor);
    scrolledText.getViewport().setBackground(fillColor);
    scrolledText.getViewport().setBorder(null);
    scrolledText.setBorder(null);
    textWrapper.add(scrolledText);
    content.add(textWrapper, BorderLayout.CENTER);

    final NonOpaquePanel north = new NonOpaquePanel(new BorderLayout());
    north.add(new JLabel(icon), BorderLayout.NORTH);
    content.add(north, BorderLayout.WEST);

    content.setBorder(new EmptyBorder(2, 4, 2, 4));

    final BalloonBuilder builder = createBalloonBuilder(content);

    builder.setFillColor(fillColor);

    return builder;
  }

  @NotNull
  @Override
  public BalloonBuilder createHtmlTextBalloonBuilder(@NotNull String htmlContent,
                                                     MessageType messageType,
                                                     @Nullable HyperlinkListener listener)
  {
    return createHtmlTextBalloonBuilder(htmlContent, messageType.getDefaultIcon(), messageType.getPopupBackground(), listener);
  }
}