summaryrefslogtreecommitdiff
path: root/platform/lang-impl/src/com/intellij/codeInsight/documentation/DocumentationManager.java
blob: 05a1e01c6aa158e7c67069f8b00ee988b2cab8e5 (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
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
/*
 * 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.codeInsight.documentation;

import com.intellij.codeInsight.CodeInsightBundle;
import com.intellij.codeInsight.TargetElementUtilBase;
import com.intellij.codeInsight.hint.HintManagerImpl;
import com.intellij.codeInsight.hint.ParameterInfoController;
import com.intellij.codeInsight.lookup.Lookup;
import com.intellij.codeInsight.lookup.LookupElement;
import com.intellij.codeInsight.lookup.LookupEx;
import com.intellij.codeInsight.lookup.LookupManager;
import com.intellij.ide.BrowserUtil;
import com.intellij.ide.DataManager;
import com.intellij.ide.actions.BaseNavigateToSourceAction;
import com.intellij.ide.util.PropertiesComponent;
import com.intellij.ide.util.gotoByName.ChooseByNameBase;
import com.intellij.lang.Language;
import com.intellij.lang.LanguageDocumentation;
import com.intellij.lang.documentation.*;
import com.intellij.openapi.actionSystem.*;
import com.intellij.openapi.actionSystem.ex.ActionManagerEx;
import com.intellij.openapi.actionSystem.ex.AnActionListener;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.components.ServiceManager;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.project.IndexNotReadyException;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.roots.OrderEntry;
import com.intellij.openapi.roots.libraries.LibraryUtil;
import com.intellij.openapi.roots.ui.configuration.ProjectSettingsService;
import com.intellij.openapi.ui.popup.JBPopup;
import com.intellij.openapi.ui.popup.JBPopupFactory;
import com.intellij.openapi.util.*;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.openapi.wm.IdeFocusManager;
import com.intellij.openapi.wm.ToolWindowId;
import com.intellij.openapi.wm.ex.WindowManagerEx;
import com.intellij.psi.*;
import com.intellij.psi.presentation.java.SymbolPresentationUtil;
import com.intellij.psi.util.PsiTreeUtil;
import com.intellij.psi.util.PsiUtilCore;
import com.intellij.ui.ListScrollingUtil;
import com.intellij.ui.content.Content;
import com.intellij.ui.popup.AbstractPopup;
import com.intellij.ui.popup.NotLookupOrSearchCondition;
import com.intellij.ui.popup.PopupPositionManager;
import com.intellij.ui.popup.PopupUpdateProcessor;
import com.intellij.util.Alarm;
import com.intellij.util.BooleanFunction;
import com.intellij.util.Consumer;
import com.intellij.util.Processor;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.lang.ref.WeakReference;
import java.util.*;
import java.util.List;

public class DocumentationManager extends DockablePopupManager<DocumentationComponent> implements DocumentationManagerProtocol {

  @NonNls public static final String JAVADOC_LOCATION_AND_SIZE = "javadoc.popup";
  public static final DataKey<String> SELECTED_QUICK_DOC_TEXT = DataKey.create("QUICK_DOC.SELECTED_TEXT");

  private static final Logger LOG = Logger.getInstance("#" + DocumentationManager.class.getName());
  private static final String SHOW_DOCUMENTATION_IN_TOOL_WINDOW = "ShowDocumentationInToolWindow";
  private static final String DOCUMENTATION_AUTO_UPDATE_ENABLED = "DocumentationAutoUpdateEnabled";

  private Editor myEditor = null;
  private ParameterInfoController myParameterInfoController;
  private final Alarm myUpdateDocAlarm;
  private WeakReference<JBPopup> myDocInfoHintRef;
  private Component myPreviouslyFocused = null;
  public static final Key<SmartPsiElementPointer> ORIGINAL_ELEMENT_KEY = Key.create("Original element");

  private final ActionManagerEx myActionManagerEx;

  private static final int ourFlagsForTargetElements = TargetElementUtilBase.getInstance().getAllAccepted();

  private boolean myCloseOnSneeze;

  @Override
  protected String getToolwindowId() {
    return ToolWindowId.DOCUMENTATION;
  }

  @Override
  protected DocumentationComponent createComponent() {
    return new DocumentationComponent(this, createActions());
  }

  @Override
  protected String getRestorePopupDescription() {
    return "Restore documentation popup behavior";
  }

  @Override
  protected String getAutoUpdateDescription() {
    return "Show documentation for current element automatically";
  }

  @Override
  protected String getAutoUpdateTitle() {
    return "Auto Show Documentation for Selected Element";
  }

  /**
   * @return    <code>true</code> if quick doc control is configured to not prevent user-IDE interaction (e.g. should be closed if
   *            the user presses a key);
   *            <code>false</code> otherwise
   */
  public boolean isCloseOnSneeze() {
    return myCloseOnSneeze;
  }
  
  public static DocumentationManager getInstance(Project project) {
    return ServiceManager.getService(project, DocumentationManager.class);
  }

  public DocumentationManager(final Project project, ActionManagerEx managerEx) {
    super(project);
    myActionManagerEx = managerEx;
    final AnActionListener actionListener = new AnActionListener() {
      @Override
      public void beforeActionPerformed(AnAction action, DataContext dataContext, AnActionEvent event) {
        final JBPopup hint = getDocInfoHint();
        if (hint != null) {
          if (action instanceof HintManagerImpl.ActionToIgnore) {
            ((AbstractPopup)hint).focusPreferredComponent();
            return;
          }
          if (action instanceof ListScrollingUtil.ListScrollAction) return;
          if (action == myActionManagerEx.getAction(IdeActions.ACTION_EDITOR_MOVE_CARET_DOWN)) return;
          if (action == myActionManagerEx.getAction(IdeActions.ACTION_EDITOR_MOVE_CARET_UP)) return;
          if (action == myActionManagerEx.getAction(IdeActions.ACTION_EDITOR_MOVE_CARET_PAGE_DOWN)) return;
          if (action == myActionManagerEx.getAction(IdeActions.ACTION_EDITOR_MOVE_CARET_PAGE_UP)) return;
          if (action == ActionManagerEx.getInstanceEx().getAction(IdeActions.ACTION_EDITOR_ESCAPE)) return;
          if (ActionPlaces.JAVADOC_INPLACE_SETTINGS.equals(event.getPlace())) return;
          if (action instanceof BaseNavigateToSourceAction) return;
          closeDocHint();
        }
      }

      @Override
      public void beforeEditorTyping(char c, DataContext dataContext) {
        final JBPopup hint = getDocInfoHint();
        if (hint != null) {
          hint.cancel();
        }
      }


      @Override
      public void afterActionPerformed(final AnAction action, final DataContext dataContext, AnActionEvent event) {
      }
    };
    myActionManagerEx.addAnActionListener(actionListener, project);
    myUpdateDocAlarm = new Alarm(Alarm.ThreadToUse.POOLED_THREAD,myProject);
  }

  private void closeDocHint() {
    JBPopup hint = getDocInfoHint();
    if (hint == null) {
      return;
    }
    myCloseOnSneeze = false;
    hint.cancel();
    Component toFocus = myPreviouslyFocused;
    hint.cancel();
    if (toFocus != null) {
      IdeFocusManager.getInstance(myProject).requestFocus(toFocus, true);
    }
  }

  public void setAllowContentUpdateFromContext(boolean allow) {
    if (hasActiveDockedDocWindow()) {
      restartAutoUpdate(allow);
    }
  }

  public void updateToolwindowContext() {
    if (hasActiveDockedDocWindow()) {
      updateComponent();
    }
  }

  public void showJavaDocInfoAtToolWindow(@NotNull PsiElement element, @NotNull PsiElement original) {
    final Content content = recreateToolWindow(element, original);
    if (content == null) return;

    fetchDocInfo(getDefaultCollector(element, original), (DocumentationComponent)content.getComponent(), true);
  }

  public void showJavaDocInfo(@NotNull final PsiElement element, final PsiElement original) {
    showJavaDocInfo(element, original, false, null);
  }

  /**
   * Asks to show quick doc for the target element.
   *
   * @param editor         editor with an element for which quick do should be shown
   * @param element        target element which documentation should be shown
   * @param original       element that was used as a quick doc anchor. Example: consider a code like {@code Runnable task;}.
   *                       A user wants to see javadoc for the {@code Runnable}, so, original element is a class name from the variable
   *                       declaration but <code>'element'</code> argument is a {@code Runnable} descriptor
   * @param closeCallback  callback to be notified on target hint close (if any)
   * @param closeOnSneeze  flag that defines whether quick doc control should be as non-obtrusive as possible. E.g. there are at least
   *                       two possible situations - the quick doc is shown automatically on mouse over element; the quick doc is shown
   *                       on explicit action call (Ctrl+Q). We want to close the doc on, say, editor viewport position change
   *                       at the first situation but don't want to do that at the second
   * @param allowReuse     defines whether currently requested documentation should reuse existing doc control (if any)
   */
  public void showJavaDocInfo(@NotNull Editor editor,
                              @NotNull final PsiElement element,
                              @NotNull final PsiElement original,
                              @Nullable Runnable closeCallback,
                              boolean closeOnSneeze,
                              boolean allowReuse)
  {
    myEditor = editor;
    myCloseOnSneeze = closeOnSneeze;
    showJavaDocInfo(element, original, allowReuse, closeCallback);
  }
  
  public void showJavaDocInfo(@NotNull final PsiElement element,
                              final PsiElement original,
                              boolean allowReuse,
                              @Nullable Runnable closeCallback)
  {
    PopupUpdateProcessor updateProcessor = new PopupUpdateProcessor(element.getProject()) {
      @Override
      public void updatePopup(Object lookupItemObject) {
        if (lookupItemObject instanceof PsiElement) {
          doShowJavaDocInfo((PsiElement)lookupItemObject, false, this, original, false);
        }
      }
    };

    doShowJavaDocInfo(element, false, updateProcessor, original, allowReuse, closeCallback);
  }

  public void showJavaDocInfo(final Editor editor, @Nullable final PsiFile file, boolean requestFocus) {
    showJavaDocInfo(editor, file, requestFocus, null);
  }

  public void showJavaDocInfo(final Editor editor,
                              @Nullable final PsiFile file,
                              boolean requestFocus,
                              final Runnable closeCallback) {
    showJavaDocInfo(editor, file, requestFocus, true, closeCallback);
  }

  private void showJavaDocInfo(final Editor editor,
                               @Nullable final PsiFile file,
                               boolean requestFocus,
                               final boolean autoupdate, @Nullable final Runnable closeCallback) {
    myEditor = editor;
    final Project project = getProject(file);
    PsiDocumentManager.getInstance(project).commitAllDocuments();

    final PsiElement list =
      ParameterInfoController.findArgumentList(file, editor.getCaretModel().getOffset(), -1);
    if (list != null) {
      LookupEx lookup = LookupManager.getInstance(myProject).getActiveLookup();
      if (lookup != null) {
        myParameterInfoController = null; // take completion variants for documentation then
      } else {
        myParameterInfoController = ParameterInfoController.findControllerAtOffset(editor, list.getTextRange().getStartOffset());
      }
    }

    final PsiElement originalElement = getContextElement(editor, file);
    PsiElement element = assertSameProject(findTargetElement(editor, file));

    if (element == null && myParameterInfoController != null) {
      final Object[] objects = myParameterInfoController.getSelectedElements();

      if (objects != null && objects.length > 0) {
        if (objects[0] instanceof PsiElement) {
          element = assertSameProject((PsiElement)objects[0]);
        }
      }
    }

    if (element == null && file == null) return; //file == null for text field editor

    if (element == null) { // look if we are within a javadoc comment
      element = assertSameProject(originalElement);
      if (element == null) return;

      PsiComment comment = PsiTreeUtil.getParentOfType(element, PsiComment.class);
      if (comment == null) return;

      element = comment instanceof PsiDocCommentBase ? ((PsiDocCommentBase)comment).getOwner() : comment.getParent();
      if (element == null) return;
      //if (!(element instanceof PsiDocCommentOwner)) return null;
    }

    final PopupUpdateProcessor updateProcessor = new PopupUpdateProcessor(project) {
      @Override
      public void updatePopup(Object lookupIteObject) {
        if (lookupIteObject == null) {
          return;
        }
        if (lookupIteObject instanceof PsiElement) {
          doShowJavaDocInfo((PsiElement)lookupIteObject, false, this, originalElement, autoupdate, closeCallback);
          return;
        }

        DocumentationProvider documentationProvider = getProviderFromElement(file);

        PsiElement element = documentationProvider.getDocumentationElementForLookupItem(
          PsiManager.getInstance(myProject),
          lookupIteObject,
          originalElement
        );

        if (element == null) return;

        if (myEditor != null) {
          final PsiFile file = element.getContainingFile();
          if (file != null) {
            Editor editor = myEditor;
            showJavaDocInfo(myEditor, file, false);
            myEditor = editor;
          }
        }
        else {
          doShowJavaDocInfo(element, false, this, originalElement, autoupdate, closeCallback);
        }
      }
    };

    doShowJavaDocInfo(element, requestFocus, updateProcessor, originalElement, autoupdate, closeCallback);
  }

  public PsiElement findTargetElement(Editor editor, PsiFile file) {
    return findTargetElement(editor, file, getContextElement(editor, file));
  }

  private static PsiElement getContextElement(Editor editor, PsiFile file) {
    return file != null ? file.findElementAt(editor.getCaretModel().getOffset()) : null;
  }

  private void doShowJavaDocInfo(final PsiElement element, boolean requestFocus, PopupUpdateProcessor updateProcessor,
                                 final PsiElement originalElement, final boolean autoupdate)
  {
    doShowJavaDocInfo(element, requestFocus, updateProcessor, originalElement, autoupdate, null);
  }

  private void doShowJavaDocInfo(@NotNull final PsiElement element,
                                 boolean requestFocus,
                                 PopupUpdateProcessor updateProcessor,
                                 final PsiElement originalElement,
                                 final boolean allowReuse,
                                 @Nullable final Runnable closeCallback)
  {
    Project project = getProject(element);
    storeOriginalElement(project, originalElement, element);

    if (myToolWindow == null && PropertiesComponent.getInstance().isTrueValue(SHOW_DOCUMENTATION_IN_TOOL_WINDOW)) {
      createToolWindow(element, originalElement);
      return;
    }
    else if (myToolWindow != null) {
      if (allowReuse && !myToolWindow.isAutoHide()) {
        final Content content = myToolWindow.getContentManager().getSelectedContent();
        if (content != null) {
          final DocumentationComponent component = (DocumentationComponent)content.getComponent();
          if (component.getElement() != element) {
            content.setDisplayName(getTitle(element, true));
            fetchDocInfo(getDefaultCollector(element, originalElement), component, true);
          }
        }

        if (!myToolWindow.isVisible()) {
          myToolWindow.show(null);
        }
        return;
      }
      else {
        restorePopupBehavior();
      }
    }

    final JBPopup _oldHint = getDocInfoHint();
    if (_oldHint != null && _oldHint.isVisible() && _oldHint instanceof AbstractPopup) {
      final DocumentationComponent oldComponent = (DocumentationComponent)((AbstractPopup)_oldHint).getComponent();
      fetchDocInfo(getDefaultCollector(element, originalElement), oldComponent);
      return;
    }

    final DocumentationComponent component = new DocumentationComponent(this);
    component.setNavigateCallback(new Consumer<PsiElement>() {
      @Override
      public void consume(PsiElement psiElement) {
        final AbstractPopup jbPopup = (AbstractPopup)getDocInfoHint();
        if (jbPopup != null) {
          final String title = getTitle(psiElement, false);
          jbPopup.setCaption(title);
        }
      }
    });
    Processor<JBPopup> pinCallback = new Processor<JBPopup>() {
      @Override
      public boolean process(JBPopup popup) {
        createToolWindow(element, originalElement);
        popup.cancel();
        return false;
      }
    };

    final KeyboardShortcut keyboardShortcut = ActionManagerEx.getInstanceEx().getKeyboardShortcut("QuickJavaDoc");
    final List<Pair<ActionListener, KeyStroke>> actions =
      Collections.singletonList(Pair.<ActionListener, KeyStroke>create(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
          createToolWindow(element, originalElement);
          final JBPopup hint = getDocInfoHint();
          if (hint != null && hint.isVisible()) hint.cancel();
        }
      }, keyboardShortcut != null ? keyboardShortcut.getFirstKeyStroke() : null)); // Null keyStroke is ok here

    boolean hasLookup = LookupManager.getActiveLookup(myEditor) != null;
    final JBPopup hint = JBPopupFactory.getInstance().createComponentPopupBuilder(component, component)
      .setRequestFocusCondition(project, NotLookupOrSearchCondition.INSTANCE)
      .setProject(project)
      .addListener(updateProcessor)
      .addUserData(updateProcessor)
      .setKeyboardActions(actions)
      .setDimensionServiceKey(myProject, JAVADOC_LOCATION_AND_SIZE, false)
      .setResizable(true)
      .setMovable(true)
      .setRequestFocus(requestFocus)
      .setCancelOnClickOutside(!hasLookup) // otherwise selecting lookup items by mouse would close the doc
      .setTitle(getTitle(element, false))
      .setCouldPin(pinCallback)
      .setModalContext(false)
      .setCancelCallback(new Computable<Boolean>() {
        @Override
        public Boolean compute() {
          myCloseOnSneeze = false;
          if (closeCallback != null) {
            closeCallback.run();
          }
          if (fromQuickSearch()) {
            ((ChooseByNameBase.JPanelProvider)myPreviouslyFocused.getParent()).unregisterHint();
          }

          Disposer.dispose(component);
          myEditor = null;
          myPreviouslyFocused = null;
          myParameterInfoController = null;
          return Boolean.TRUE;
        }
      })
      .setKeyEventHandler(new BooleanFunction<KeyEvent>() {
        @Override
        public boolean fun(KeyEvent e) {
          if (myCloseOnSneeze) {
            closeDocHint();
          }
          if ((AbstractPopup.isCloseRequest(e) && getDocInfoHint() != null)) {
            closeDocHint();
            return true;
          }
          return false;
        }
      })
      .createPopup();


    AbstractPopup oldHint = (AbstractPopup)getDocInfoHint();
    if (oldHint != null) {
      DocumentationComponent oldComponent = (DocumentationComponent)oldHint.getComponent();
      PsiElement element1 = oldComponent.getElement();
      if (Comparing.equal(element, element1)) {
        if (requestFocus) {
          component.getComponent().requestFocus();
        }
        return;
      }
      oldHint.cancel();
    }

    component.setHint(hint);

    if (myEditor == null) {
      // subsequent invocation of javadoc popup from completion will have myEditor == null because of cancel invoked, 
      // so reevaluate the editor for proper popup placement
      Lookup lookup = LookupManager.getInstance(myProject).getActiveLookup();
      myEditor = lookup != null ? lookup.getEditor() : null;
    }
    fetchDocInfo(getDefaultCollector(element, originalElement), component);

    myDocInfoHintRef = new WeakReference<JBPopup>(hint);
    myPreviouslyFocused = WindowManagerEx.getInstanceEx().getFocusedComponent(project);

    if (fromQuickSearch() && myPreviouslyFocused != null) {
      ((ChooseByNameBase.JPanelProvider)myPreviouslyFocused.getParent()).registerHint(hint);
    }
  }

  private static String getTitle(@NotNull final PsiElement element, final boolean _short) {
    final String title = SymbolPresentationUtil.getSymbolPresentableText(element);
    return _short ? title != null ? title : element.getText() : CodeInsightBundle.message("javadoc.info.title", title != null ? title : element.getText());
  }

  public static void storeOriginalElement(final Project project, final PsiElement originalElement, final PsiElement element) {
    if (element == null) return;
    try {
      element.putUserData(
        ORIGINAL_ELEMENT_KEY,
        SmartPointerManager.getInstance(project).createSmartPsiElementPointer(originalElement)
      );
    } catch (RuntimeException ex) {
      // PsiPackage does not allow putUserData
    }
  }

  @Nullable
  public PsiElement findTargetElement(@NotNull final Editor editor, @Nullable final PsiFile file, PsiElement contextElement) {
    return findTargetElement(editor, editor.getCaretModel().getOffset(), file, contextElement);
  }
  
  @Nullable
  public PsiElement findTargetElement(final Editor editor, int offset, @Nullable final PsiFile file, PsiElement contextElement) {
    try {
      return findTargetElementUnsafe(editor, offset, file, contextElement);
    }
    catch (IndexNotReadyException inre) {
      LOG.warn("Index not ready");
      LOG.debug(inre);
      return null;
    }
  }

  /**
   * in case index is not ready will throw IndexNotReadyException
   */
  @Nullable
  private PsiElement findTargetElementUnsafe(final Editor editor, int offset, @Nullable final PsiFile file, PsiElement contextElement) {
    TargetElementUtilBase util = TargetElementUtilBase.getInstance();
    PsiElement element = assertSameProject(getElementFromLookup(editor, file));
    if (element == null && file != null) {
      final DocumentationProvider documentationProvider = getProviderFromElement(file);
      if (documentationProvider instanceof DocumentationProviderEx) {
        element = assertSameProject(((DocumentationProviderEx)documentationProvider).getCustomDocumentationElement(editor, file, contextElement));
      }
    }

    if (element == null) {
      element = assertSameProject(util.findTargetElement(editor, ourFlagsForTargetElements, offset));

      // Allow context doc over xml tag content
      if (element != null || contextElement != null) {
        final PsiElement adjusted = assertSameProject(util.adjustElement(editor, ourFlagsForTargetElements, element, contextElement));
        if (adjusted != null) {
          element = adjusted;
        }
      }
    }

    if (element == null) {
      final PsiReference ref = TargetElementUtilBase.findReference(editor, offset);
      if (ref != null) {
        element = assertSameProject(util.adjustReference(ref));
        if (ref instanceof PsiPolyVariantReference) {
          element = assertSameProject(ref.getElement());
        }
      }
    }

    storeOriginalElement(myProject, contextElement, element);

    return element;
  }

  @Nullable
  public PsiElement getElementFromLookup(final Editor editor, @Nullable final PsiFile file) {

    final Lookup activeLookup = LookupManager.getInstance(myProject).getActiveLookup();

    if (activeLookup != null) {
      LookupElement item = activeLookup.getCurrentItem();
      if (item != null) {


        int offset = editor.getCaretModel().getOffset();
        if (offset > 0 && offset == editor.getDocument().getTextLength()) offset--;
        PsiReference ref = TargetElementUtilBase.findReference(editor, offset);
        PsiElement contextElement = file == null? null : file.findElementAt(offset);
        PsiElement targetElement = ref != null ? ref.getElement() : contextElement;
        if (targetElement != null) {
          PsiUtilCore.ensureValid(targetElement);
        }

        DocumentationProvider documentationProvider = getProviderFromElement(file);

        PsiManager psiManager = PsiManager.getInstance(myProject);
        return documentationProvider.getDocumentationElementForLookupItem(psiManager, item.getObject(), targetElement);
      }
    }
    return null;
  }

  private boolean fromQuickSearch() {
    return myPreviouslyFocused != null && myPreviouslyFocused.getParent() instanceof ChooseByNameBase.JPanelProvider;
  }

  private DocumentationCollector getDefaultCollector(@NotNull final PsiElement element, @Nullable final PsiElement originalElement) {
    return new DefaultDocumentationCollector(element, originalElement);
  }

  @Nullable
  public JBPopup getDocInfoHint() {
    if (myDocInfoHintRef == null) return null;
    JBPopup hint = myDocInfoHintRef.get();
    if (hint == null || !hint.isVisible()) {
      myDocInfoHintRef = null;
      return null;
    }
    return hint;
  }

  public void fetchDocInfo(final DocumentationCollector provider, final DocumentationComponent component) {
    doFetchDocInfo(component, provider, true, false);
  }

  public void fetchDocInfo(final DocumentationCollector provider, final DocumentationComponent component, final boolean clearHistory) {
    doFetchDocInfo(component, provider, true, clearHistory);
  }

  public void fetchDocInfo(final PsiElement element, final DocumentationComponent component) {
    doFetchDocInfo(component, getDefaultCollector(element, null), true, false);
  }

  public ActionCallback queueFetchDocInfo(final DocumentationCollector provider, final DocumentationComponent component, final boolean clearHistory) {
    return doFetchDocInfo(component, provider, false, clearHistory);
  }

  public ActionCallback queueFetchDocInfo(final PsiElement element, final DocumentationComponent component) {
    return queueFetchDocInfo(getDefaultCollector(element, null), component, false);
  }

  private ActionCallback doFetchDocInfo(final DocumentationComponent component, final DocumentationCollector provider, final boolean cancelRequests, final boolean clearHistory) {
    final ActionCallback callback = new ActionCallback();
    component.startWait();
    if (cancelRequests) {
      myUpdateDocAlarm.cancelAllRequests();
    }
    if (component.isEmpty()) {
      component.setText(CodeInsightBundle.message("javadoc.fetching.progress"), null, clearHistory);
      final AbstractPopup jbPopup = (AbstractPopup)getDocInfoHint();
      if (jbPopup != null) {
        jbPopup.setDimensionServiceKey(null);
      }
    }

    myUpdateDocAlarm.addRequest(new Runnable() {
      @Override
      public void run() {
        if (myProject.isDisposed()) return;
        final Throwable[] ex = new Throwable[1];
        String text = null;
        try {
          text = provider.getDocumentation();
        }
        catch (Throwable e) {
          LOG.info(e);
          ex[0] = e;
        }

        if (ex[0] != null) {
          //noinspection SSBasedInspection
          SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
              String message = ex[0] instanceof IndexNotReadyException
                             ? "Documentation is not available until indices are built."
                             : CodeInsightBundle.message("javadoc.external.fetch.error.message", ex[0].getLocalizedMessage());
              component.setText(message, null, true);
              callback.setDone();
            }
          });
          return;
        }

        final PsiElement element = ApplicationManager.getApplication().runReadAction(new Computable<PsiElement>() {
          @Override
          @Nullable
          public PsiElement compute() {
            return provider.getElement();
          }
        });
        if (element == null) {
          return;
        }
        final String documentationText = text;
        //noinspection SSBasedInspection
        SwingUtilities.invokeLater(new Runnable() {
          @Override
          public void run() {
            PsiDocumentManager.getInstance(myProject).commitAllDocuments();

            if (!element.isValid()) {
              callback.setDone();
              return;
            }

            if (documentationText == null) {
              component.setText(CodeInsightBundle.message("no.documentation.found"), element, true);
            }
            else if (documentationText.length() == 0) {
              component.setText(component.getText(), element, true, clearHistory);
            }
            else {
              component.setData(element, documentationText, clearHistory, provider.getEffectiveExternalUrl());
            }

            final AbstractPopup jbPopup = (AbstractPopup)getDocInfoHint();
            if(jbPopup==null){
              callback.setDone();
              return;
            }
            else {
              jbPopup.setDimensionServiceKey(JAVADOC_LOCATION_AND_SIZE);
            }
            jbPopup.setCaption(getTitle(element, false));
            callback.setDone();
          }
        });
      }
    }, 10);
    return callback;
  }

  @NotNull 
  public static DocumentationProvider getProviderFromElement(final PsiElement element) {
    return getProviderFromElement(element, null);
  }

  @NotNull
  public static DocumentationProvider getProviderFromElement(@Nullable PsiElement element, @Nullable PsiElement originalElement) {
    if (element != null && !element.isValid()) {
      element = null;
    }
    if (originalElement != null && !originalElement.isValid()) {
      originalElement = null;
    }

    if (originalElement == null) {
      originalElement = getOriginalElement(element);
    }

    PsiFile containingFile =
      originalElement != null ? originalElement.getContainingFile() : element != null ? element.getContainingFile() : null;
    Set<DocumentationProvider> result = new LinkedHashSet<DocumentationProvider>();

    final Language containingFileLanguage = containingFile != null ? containingFile.getLanguage() : null;
    DocumentationProvider originalProvider =
      containingFile != null ? LanguageDocumentation.INSTANCE.forLanguage(containingFileLanguage) : null;

    final Language elementLanguage = element != null ? element.getLanguage() : null;
    DocumentationProvider elementProvider =
      element == null || elementLanguage.is(containingFileLanguage) ? null : LanguageDocumentation.INSTANCE.forLanguage(elementLanguage);

    result.add(elementProvider);
    result.add(originalProvider);

    if (containingFile != null) {
      final Language baseLanguage = containingFile.getViewProvider().getBaseLanguage();
      if (!baseLanguage.is(containingFileLanguage)) {
        result.add(LanguageDocumentation.INSTANCE.forLanguage(baseLanguage));
      }
    }
    else if (element instanceof PsiDirectory) {
      final Set<Language> langs = new HashSet<Language>();

      for (PsiFile file : ((PsiDirectory)element).getFiles()) {
        final Language baseLanguage = file.getViewProvider().getBaseLanguage();
        if (!langs.contains(baseLanguage)) {
          langs.add(baseLanguage);
          result.add(LanguageDocumentation.INSTANCE.forLanguage(baseLanguage));
        }
      }
    }
    return CompositeDocumentationProvider.wrapProviders(result);
  }

  @Nullable
  public static PsiElement getOriginalElement(final PsiElement element) {
    SmartPsiElementPointer originalElementPointer = element!=null ? element.getUserData(ORIGINAL_ELEMENT_KEY):null;
    return originalElementPointer != null ? originalElementPointer.getElement() : null;
  }

  void navigateByLink(final DocumentationComponent component, final String url) {
    component.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
    final PsiElement psiElement = component.getElement();
    if (psiElement == null) {
      return;
    }
    final PsiManager manager = PsiManager.getInstance(getProject(psiElement));
    if (url.startsWith("open")) {
      final PsiFile containingFile = psiElement.getContainingFile();
      OrderEntry libraryEntry = null;
      if (containingFile != null) {
        final VirtualFile virtualFile = containingFile.getVirtualFile();
        libraryEntry = LibraryUtil.findLibraryEntry(virtualFile, myProject);
      }
      else if (psiElement instanceof PsiDirectoryContainer) {
        PsiDirectory[] directories = ((PsiDirectoryContainer)psiElement).getDirectories();
        for (PsiDirectory directory : directories) {
          final VirtualFile virtualFile = directory.getVirtualFile();
          libraryEntry = LibraryUtil.findLibraryEntry(virtualFile, myProject);
          if (libraryEntry != null) {
            break;
          }
        }
      }
      if (libraryEntry != null) {
        ProjectSettingsService.getInstance(myProject).openLibraryOrSdkSettings(libraryEntry);
      }
    } else if (url.startsWith(PSI_ELEMENT_PROTOCOL)) {
      final String refText = url.substring(PSI_ELEMENT_PROTOCOL.length());
      DocumentationProvider provider = getProviderFromElement(psiElement);
      final PsiElement targetElement = provider.getDocumentationElementForLink(manager, refText, psiElement);
      if (targetElement != null) {
        fetchDocInfo(getDefaultCollector(targetElement, null), component);
      }
    }
    else {
      final DocumentationProvider provider = getProviderFromElement(psiElement);
      boolean processed = false;
      if (provider instanceof CompositeDocumentationProvider) {
        for (DocumentationProvider documentationProvider : ((CompositeDocumentationProvider)provider).getProviders()) {
          if (documentationProvider instanceof ExternalDocumentationHandler) {
            final ExternalDocumentationHandler externalDocumentationHandler = (ExternalDocumentationHandler)documentationProvider;
            if (externalDocumentationHandler.canFetchDocumentationLink(url)) {
              fetchDocInfo(new DocumentationCollector() {
                @Override
                public String getDocumentation() throws Exception {
                  return externalDocumentationHandler.fetchExternalDocumentation(url, psiElement);
                }

                @Override
                public PsiElement getElement() {
                  return psiElement;
                }

                @Nullable
                @Override
                public String getEffectiveExternalUrl() {
                  return url;
                }
              }, component);
              processed = true;
            }
            else if (externalDocumentationHandler.handleExternalLink(manager, url, psiElement)) {
              processed = true;
              break;
            }
          }
        }
      }

      if (!processed) {

        fetchDocInfo
          (new DocumentationCollector() {
            @Override
            public String getDocumentation() throws Exception {
              if (url.startsWith(DOC_ELEMENT_PROTOCOL)) {
                final List<String> urls = ApplicationManager.getApplication().runReadAction(
                  new NullableComputable<List<String>>() {
                    @Override
                    public List<String> compute() {
                      final DocumentationProvider provider = getProviderFromElement(psiElement);
                      return provider.getUrlFor(psiElement, getOriginalElement(psiElement));
                    }
                  }
                );
                String url1 = urls != null && !urls.isEmpty() ? urls.get(0) : url;
                BrowserUtil.browse(url1);
              }
              else {
                BrowserUtil.browse(url);
              }
              return "";
            }

            @Override
            public PsiElement getElement() {
              //String loc = getElementLocator(docUrl);
              //
              //if (loc != null) {
              //  PsiElement context = component.getElement();
              //  return JavaDocUtil.findReferenceTarget(context.getManager(), loc, context);
              //}

              return psiElement;
            }

            @Nullable
            @Override
            public String getEffectiveExternalUrl() {
              return url;
            }
          }, component);
      }
    }

    component.setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
  }

  void showHint(final JBPopup hint) {
    final Component focusOwner = IdeFocusManager.getInstance(myProject).getFocusOwner();
    DataContext dataContext = DataManager.getInstance().getDataContext(focusOwner);
    PopupPositionManager.positionPopupInBestPosition(hint, myEditor, dataContext);
  }

  public void requestFocus() {
    if (fromQuickSearch()) {
      myPreviouslyFocused.getParent().requestFocus();
    }
  }

  public Project getProject(@Nullable final PsiElement element) {
    assertSameProject(element);
    return myProject;
  }

  private PsiElement assertSameProject(@Nullable PsiElement element) {
    if (element != null && element.isValid() && myProject != element.getProject()) {
      throw new AssertionError(myProject + "!=" + element.getProject() + "; element=" + element);
    }
    return element;
  }

  public static void createHyperlink(StringBuilder buffer, String refText,String label,boolean plainLink) {
    DocumentationManagerUtil.createHyperlink(buffer, refText, label, plainLink);
  }

  @Override
  public String getShowInToolWindowProperty() {
    return SHOW_DOCUMENTATION_IN_TOOL_WINDOW;
  }

  @Override
  public String getAutoUpdateEnabledProperty() {
    return DOCUMENTATION_AUTO_UPDATE_ENABLED;
  }

  @Override
  protected void doUpdateComponent(PsiElement element, PsiElement originalElement, DocumentationComponent component) {
    fetchDocInfo(getDefaultCollector(element, originalElement), component);
  }
  
  @Override
  protected void doUpdateComponent(Editor editor, PsiFile psiFile) {
    showJavaDocInfo(editor, psiFile, false, true, null);
  }

  @Override
  protected void doUpdateComponent(@NotNull PsiElement element) {
    showJavaDocInfo(element, element, true, null);
  }

  @Override
  protected String getTitle(PsiElement element) {
    return getTitle(element, true);
  }

  private interface DocumentationCollector {
    @Nullable
    String getDocumentation() throws Exception;
    @Nullable
    PsiElement getElement();
    @Nullable
    String getEffectiveExternalUrl();
  }

  private class DefaultDocumentationCollector implements DocumentationCollector {

    private final PsiElement myElement;
    private final PsiElement myOriginalElement;

    private String myEffectiveUrl;

    public DefaultDocumentationCollector(PsiElement element, PsiElement originalElement) {
      myElement = element;
      myOriginalElement = originalElement;
    }

    @Override
    @Nullable
    public String getDocumentation() throws Exception {
      final DocumentationProvider provider = ApplicationManager.getApplication().runReadAction(
          new Computable<DocumentationProvider>() {
            @Override
            public DocumentationProvider compute() {
              return getProviderFromElement(myElement, myOriginalElement);
            }
          }
      );
      if (myParameterInfoController != null) {
        final String doc = ApplicationManager.getApplication().runReadAction(
            new NullableComputable<String>() {
              @Override
              public String compute() {
                return generateParameterInfoDocumentation(provider);
              }
            }
        );
        if (doc != null) return doc;
      }
      if (provider instanceof ExternalDocumentationProvider) {
        final List<String> urls = ApplicationManager.getApplication().runReadAction(
            new NullableComputable<List<String>>() {
              @Override
              public List<String> compute() {
                final SmartPsiElementPointer originalElementPtr = myElement.getUserData(ORIGINAL_ELEMENT_KEY);
                final PsiElement originalElement = originalElementPtr != null ? originalElementPtr.getElement() : null;
                if (((ExternalDocumentationProvider)provider).hasDocumentationFor(myElement, originalElement)) {
                  return provider.getUrlFor(myElement, originalElement);
                }
                return null;
              }
            }
        );
        if (urls != null) {
          for (String url : urls) {
            final String doc = ((ExternalDocumentationProvider)provider).fetchExternalDocumentation(myProject, myElement, Collections.singletonList(url));
            if (doc != null) {
              myEffectiveUrl = url;
              return doc;
            }
          }
        }
      }
      return ApplicationManager.getApplication().runReadAction(
          new Computable<String>() {
            @Override
            @Nullable
            public String compute() {
              final SmartPsiElementPointer originalElement = myElement.getUserData(ORIGINAL_ELEMENT_KEY);
              return provider.generateDoc(myElement, originalElement != null ? originalElement.getElement() : null);
            }
          }
      );
    }

    @Nullable
    private String generateParameterInfoDocumentation(DocumentationProvider provider) {
      final Object[] objects = myParameterInfoController.getSelectedElements();

      if (objects.length > 0) {
        @NonNls StringBuffer sb = null;

        for (Object o : objects) {
          PsiElement parameter = null;
          if (o instanceof PsiElement) {
            parameter = (PsiElement)o;
          }

          if (parameter != null) {
            final SmartPsiElementPointer originalElement = parameter.getUserData(ORIGINAL_ELEMENT_KEY);
            final String str2 = provider.generateDoc(parameter, originalElement != null ? originalElement.getElement() : null);
            if (str2 == null) continue;
            if (sb == null) sb = new StringBuffer();
            sb.append(str2);
            sb.append("<br>");
          }
          else {
            sb = null;
            break;
          }
        }

        if (sb != null) return sb.toString();
      }
      return null;
    }

    @Override
    @Nullable
    public PsiElement getElement() {
      return myElement.isValid() ? myElement : null;
    }

    @Nullable
    @Override
    public String getEffectiveExternalUrl() {
      return myEffectiveUrl;
    }
  }
}