public TrafficLightRenderer(Project project, Document document, PsiFile file) {
    myProject = project;
    myDaemonCodeAnalyzer =
        project == null ? null : (DaemonCodeAnalyzerImpl) DaemonCodeAnalyzer.getInstance(project);
    myDocument = document;
    myFile = file;
    mySeverityRegistrar = SeverityRegistrar.getInstance(myProject);
    refresh();

    if (project != null) {
      MarkupModelEx model =
          (MarkupModelEx) DocumentMarkupModel.forDocument(document, project, true);
      model.addMarkupModelListener(
          this,
          new MarkupModelListener() {
            @Override
            public void afterAdded(@NotNull RangeHighlighterEx highlighter) {
              incErrorCount(highlighter, 1);
            }

            @Override
            public void beforeRemoved(@NotNull RangeHighlighterEx highlighter) {
              incErrorCount(highlighter, -1);
            }

            @Override
            public void attributesChanged(@NotNull RangeHighlighterEx highlighter) {}
          });
      for (RangeHighlighter rangeHighlighter : model.getAllHighlighters()) {
        incErrorCount(rangeHighlighter, 1);
      }
    }
  }
  public void invoke(
      @NotNull final Project project, @NotNull final Editor editor, @NotNull final PsiFile file) {
    PsiDocumentManager.getInstance(project).commitAllDocuments();

    final LookupEx lookup = LookupManagerImpl.getActiveLookup(editor);
    if (lookup != null) {
      lookup.showElementActions();
      return;
    }

    if (HintManagerImpl.getInstanceImpl().performCurrentQuestionAction()) return;

    // intentions check isWritable before modification: if (!file.isWritable()) return;
    if (file instanceof PsiCodeFragment) return;

    TemplateState state = TemplateManagerImpl.getTemplateState(editor);
    if (state != null && !state.isFinished()) {
      return;
    }

    final DaemonCodeAnalyzerImpl codeAnalyzer =
        (DaemonCodeAnalyzerImpl) DaemonCodeAnalyzer.getInstance(project);
    codeAnalyzer.autoImportReferenceAtCursor(editor, file); // let autoimport complete

    ShowIntentionsPass.IntentionsInfo intentions = new ShowIntentionsPass.IntentionsInfo();
    ShowIntentionsPass.getActionsToShow(editor, file, intentions, -1);

    if (!intentions.isEmpty()) {
      IntentionHintComponent.showIntentionHint(project, file, editor, intentions, true);
    }
  }
  static void setOrRefreshErrorStripeRenderer(
      @NotNull EditorMarkupModel editorMarkupModel,
      @NotNull Project project,
      @NotNull Document document,
      PsiFile file) {
    ApplicationManager.getApplication().assertIsDispatchThread();
    if (!editorMarkupModel.isErrorStripeVisible()
        || !DaemonCodeAnalyzer.getInstance(project).isHighlightingAvailable(file)) {
      return;
    }
    ErrorStripeRenderer renderer = editorMarkupModel.getErrorStripeRenderer();
    if (renderer instanceof TrafficLightRenderer) {
      TrafficLightRenderer tlr = (TrafficLightRenderer) renderer;
      tlr.refresh();
      ((EditorMarkupModelImpl) editorMarkupModel).repaintVerticalScrollBar();
      if (tlr.myFile == null || tlr.myFile.isValid()) return;
      Disposer.dispose(tlr);
    }
    EditorImpl editor = (EditorImpl) editorMarkupModel.getEditor();

    if (!editor.isDisposed()) {
      renderer = new TrafficLightRenderer(project, document, file);
      Disposer.register(editor.getDisposable(), (Disposable) renderer);
      editorMarkupModel.setErrorStripeRenderer(renderer);
    }
  }
 private void forceDaemonRestart() {
   final FileViewProvider viewProvider = myFile.getViewProvider();
   for (Language language : mySliders.keySet()) {
     JSlider slider = mySliders.get(language);
     PsiElement root = viewProvider.getPsi(language);
     assert root != null : "No root in " + viewProvider + " for " + language;
     int value = slider.getValue();
     if (value == 1) {
       HighlightLevelUtil.forceRootHighlighting(root, FileHighlightingSetting.SKIP_HIGHLIGHTING);
     } else if (value == 2) {
       HighlightLevelUtil.forceRootHighlighting(root, FileHighlightingSetting.SKIP_INSPECTION);
     } else {
       HighlightLevelUtil.forceRootHighlighting(root, FileHighlightingSetting.FORCE_HIGHLIGHTING);
     }
   }
   final DaemonCodeAnalyzer analyzer = DaemonCodeAnalyzer.getInstance(myFile.getProject());
   analyzer.restart();
 }
  public static void invokeImpl(
      Project project, Editor editor, final PsiFile file, Injectable injectable) {
    final PsiLanguageInjectionHost host = findInjectionHost(editor, file);
    if (host == null) return;
    if (defaultFunctionalityWorked(host, injectable.getId())) return;

    try {
      host.putUserData(FIX_KEY, null);
      Language language = injectable.toLanguage();
      for (LanguageInjectionSupport support : InjectorUtils.getActiveInjectionSupports()) {
        if (support.isApplicableTo(host) && support.addInjectionInPlace(language, host)) {
          return;
        }
      }
      if (TemporaryPlacesRegistry.getInstance(project)
          .getLanguageInjectionSupport()
          .addInjectionInPlace(language, host)) {
        final Processor<PsiLanguageInjectionHost> data = host.getUserData(FIX_KEY);
        String text =
            StringUtil.escapeXml(language.getDisplayName()) + " was temporarily injected.";
        if (data != null) {
          if (!ApplicationManager.getApplication().isUnitTestMode()) {
            final SmartPsiElementPointer<PsiLanguageInjectionHost> pointer =
                SmartPointerManager.getInstance(project).createSmartPsiElementPointer(host);
            final TextRange range = host.getTextRange();
            HintManager.getInstance()
                .showQuestionHint(
                    editor,
                    text
                        + "<br>Do you want to insert annotation? "
                        + KeymapUtil.getFirstKeyboardShortcutText(
                            ActionManager.getInstance()
                                .getAction(IdeActions.ACTION_SHOW_INTENTION_ACTIONS)),
                    range.getStartOffset(),
                    range.getEndOffset(),
                    new QuestionAction() {
                      @Override
                      public boolean execute() {
                        return data.process(pointer.getElement());
                      }
                    });
          }
        } else {
          HintManager.getInstance().showInformationHint(editor, text);
        }
      }
    } finally {
      if (injectable.getLanguage() != null) { // no need for reference injection
        FileContentUtil.reparseFiles(project, Collections.<VirtualFile>emptyList(), true);
      } else {
        ((PsiModificationTrackerImpl) PsiManager.getInstance(project).getModificationTracker())
            .incCounter();
        DaemonCodeAnalyzer.getInstance(project).restart();
      }
    }
  }
  private static void applyChangesToEditors() {
    EditorFactory.getInstance().refreshAllEditors();

    TodoConfiguration.getInstance().colorSettingsChanged();
    Project[] openProjects = ProjectManager.getInstance().getOpenProjects();
    for (Project openProject : openProjects) {
      FileStatusManager.getInstance(openProject).fileStatusesChanged();
      DaemonCodeAnalyzer.getInstance(openProject).restart();
    }
  }
  protected static Editor createEditor(@NotNull VirtualFile file) {
    PsiDocumentManager.getInstance(getProject()).commitAllDocuments();
    Editor editor =
        FileEditorManager.getInstance(getProject())
            .openTextEditor(new OpenFileDescriptor(getProject(), file, 0), false);
    DaemonCodeAnalyzer.getInstance(getProject()).restart();

    ((EditorImpl) editor).setCaretActive();
    return editor;
  }
 @Override
 protected void createSuppression(
     @NotNull Project project, @NotNull PsiElement element, @NotNull PsiElement container)
     throws IncorrectOperationException {
   final GrModifierList modifierList =
       (GrModifierList) ((PsiModifierListOwner) container).getModifierList();
   if (modifierList != null) {
     addSuppressAnnotation(project, modifierList, myID);
   }
   DaemonCodeAnalyzer.getInstance(project).restart();
 }
  @Override
  public void customize(@NotNull EditorEx editor) {
    boolean apply = isEnabled();

    if (!READY) {
      return;
    }

    Project project = editor.getProject();
    if (project == null) {
      return;
    }

    PsiFile file = PsiDocumentManager.getInstance(project).getPsiFile(editor.getDocument());
    if (file == null) {
      return;
    }

    Function<InspectionProfileImpl, InspectionProfileWrapper> strategy =
        file.getUserData(InspectionProfileWrapper.CUSTOMIZATION_KEY);
    if (strategy == null) {
      file.putUserData(
          InspectionProfileWrapper.CUSTOMIZATION_KEY, strategy = new MyInspectionProfileStrategy());
    }

    if (!(strategy instanceof MyInspectionProfileStrategy)) {
      return;
    }

    ((MyInspectionProfileStrategy) strategy).setUseSpellCheck(apply);

    if (apply) {
      editor.putUserData(IntentionManager.SHOW_INTENTION_OPTIONS_KEY, false);
    }

    // Update representation.
    DaemonCodeAnalyzer analyzer = DaemonCodeAnalyzer.getInstance(project);
    if (analyzer != null) {
      analyzer.restart(file);
    }
  }
 public final void applyInformationToEditor() {
   if (!isValid()) return; // Document has changed.
   if (DumbService.getInstance(myProject).isDumb() && !(this instanceof DumbAware)) {
     Document document = getDocument();
     PsiFile file =
         document == null ? null : PsiDocumentManager.getInstance(myProject).getPsiFile(document);
     if (file != null) {
       ((DaemonCodeAnalyzerImpl) DaemonCodeAnalyzer.getInstance(myProject))
           .getFileStatusMap()
           .markFileUpToDate(file.getProject(), getDocument(), getId());
     }
     return;
   }
   doApplyInformationToEditor();
 }
  private boolean showAddImportHint(HighlightInfo info) {
    if (!DaemonCodeAnalyzerSettings.getInstance().isImportHintEnabled()) return false;
    if (!DaemonCodeAnalyzer.getInstance(myProject).isImportHintsEnabled(myFile)) return false;
    PsiElement element = myFile.findElementAt(info.startOffset);
    if (element == null || !element.isValid()) return false;

    final List<Pair<HighlightInfo.IntentionActionDescriptor, TextRange>> list =
        info.quickFixActionRanges;
    for (Pair<HighlightInfo.IntentionActionDescriptor, TextRange> pair : list) {
      final IntentionAction action = pair.getFirst().getAction();
      if (action instanceof HintAction && action.isAvailable(myProject, myEditor, myFile)) {
        return ((HintAction) action).showHint(myEditor);
      }
    }
    return false;
  }
  public GeneralHighlightingPass(
      @NotNull Project project,
      @NotNull PsiFile file,
      @NotNull Document document,
      int startOffset,
      int endOffset,
      boolean updateAll,
      @NotNull ProperTextRange priorityRange,
      @Nullable Editor editor) {
    super(project, document, PRESENTABLE_NAME, file, true);
    myStartOffset = startOffset;
    myEndOffset = endOffset;
    myUpdateAll = updateAll;
    myPriorityRange = priorityRange;
    myEditor = editor;

    LOG.assertTrue(file.isValid());
    setId(Pass.UPDATE_ALL);
    myHasErrorElement =
        !isWholeFileHighlighting() && Boolean.TRUE.equals(myFile.getUserData(HAS_ERROR_ELEMENT));
    FileStatusMap fileStatusMap =
        ((DaemonCodeAnalyzerImpl) DaemonCodeAnalyzer.getInstance(myProject)).getFileStatusMap();
    myErrorFound = !isWholeFileHighlighting() && fileStatusMap.wasErrorFound(myDocument);

    myApplyCommand =
        new Runnable() {
          @Override
          public void run() {
            ProperTextRange range = new ProperTextRange(myStartOffset, myEndOffset);
            MarkupModel model = DocumentMarkupModel.forDocument(myDocument, myProject, true);
            UpdateHighlightersUtil.cleanFileLevelHighlights(myProject, Pass.UPDATE_ALL, myFile);
            final EditorColorsScheme colorsScheme = getColorsScheme();
            UpdateHighlightersUtil.setHighlightersInRange(
                myProject,
                myDocument,
                range,
                colorsScheme,
                myHighlights,
                (MarkupModelEx) model,
                Pass.UPDATE_ALL);
          }
        };

    // initial guess to show correct progress in the traffic light icon
    setProgressLimit(document.getTextLength() / 2); // approx number of PSI elements = file length/2
    myGlobalScheme = EditorColorsManager.getInstance().getGlobalScheme();
  }
 @Override
 public void invoke(
     @NotNull final Project project, final Editor editor, @NotNull final PsiElement element)
     throws IncorrectOperationException {
   PsiDocCommentOwner container = getContainer(element);
   assert container != null;
   if (!CodeInsightUtilBase.preparePsiElementForWrite(container)) return;
   if (use15Suppressions(container)) {
     final PsiModifierList modifierList = container.getModifierList();
     if (modifierList != null) {
       addSuppressAnnotation(project, editor, container, container, getID(container));
     }
   } else {
     PsiDocComment docComment = container.getDocComment();
     PsiManager manager = PsiManager.getInstance(project);
     if (docComment == null) {
       String commentText =
           "/** @" + SuppressionUtil.SUPPRESS_INSPECTIONS_TAG_NAME + " " + getID(container) + "*/";
       docComment =
           JavaPsiFacade.getInstance(manager.getProject())
               .getElementFactory()
               .createDocCommentFromText(commentText);
       PsiElement firstChild = container.getFirstChild();
       container.addBefore(docComment, firstChild);
     } else {
       PsiDocTag noInspectionTag =
           docComment.findTagByName(SuppressionUtil.SUPPRESS_INSPECTIONS_TAG_NAME);
       if (noInspectionTag != null) {
         String tagText = noInspectionTag.getText() + ", " + getID(container);
         noInspectionTag.replace(
             JavaPsiFacade.getInstance(manager.getProject())
                 .getElementFactory()
                 .createDocTagFromText(tagText));
       } else {
         String tagText =
             "@" + SuppressionUtil.SUPPRESS_INSPECTIONS_TAG_NAME + " " + getID(container);
         docComment.add(
             JavaPsiFacade.getInstance(manager.getProject())
                 .getElementFactory()
                 .createDocTagFromText(tagText));
       }
     }
   }
   DaemonCodeAnalyzer.getInstance(project).restart();
 }
示例#14
0
  public boolean showLookup() {
    ApplicationManager.getApplication().assertIsDispatchThread();
    checkValid();
    LOG.assertTrue(!myShown);
    myShown = true;
    myStampShown = System.currentTimeMillis();

    if (ApplicationManager.getApplication().isUnitTestMode()) return true;

    if (!myEditor.getContentComponent().isShowing()) {
      hide();
      return false;
    }

    myAdComponent.showRandomText();

    myUi = new LookupUi(this, myAdComponent, myList, myProject);
    myUi.setCalculating(myCalculating);
    Point p = myUi.calculatePosition().getLocation();
    try {
      HintManagerImpl.getInstanceImpl()
          .showEditorHint(
              this,
              myEditor,
              p,
              HintManager.HIDE_BY_ESCAPE | HintManager.UPDATE_BY_SCROLLING,
              0,
              false,
              HintManagerImpl.createHintHint(myEditor, p, this, HintManager.UNDER)
                  .setAwtTooltip(false));
    } catch (Exception e) {
      LOG.error(e);
    }

    if (!isVisible() || !myList.isShowing()) {
      hide();
      return false;
    }

    DaemonCodeAnalyzer.getInstance(myProject).disableUpdateByTimer(this);

    return true;
  }
  public FileStructurePopup(
      StructureViewModel structureViewModel,
      @Nullable Editor editor,
      Project project,
      @NotNull final Disposable auxDisposable,
      final boolean applySortAndFilter) {
    myProject = project;
    myEditor = editor;

    // Stop code analyzer to speedup EDT
    final DaemonCodeAnalyzer analyzer = DaemonCodeAnalyzer.getInstance(myProject);
    if (analyzer != null) {
      myDaemonUpdateEnabled = ((DaemonCodeAnalyzerImpl) analyzer).isUpdateByTimerEnabled();
      analyzer.setUpdateByTimerEnabled(false);
    } else {
      myDaemonUpdateEnabled = false;
    }

    IdeFocusManager.getInstance(myProject).typeAheadUntil(myTreeHasBuilt);
    myBaseTreeModel = structureViewModel;
    Disposer.register(this, auxDisposable);
    if (applySortAndFilter) {
      myTreeActionsOwner = new TreeStructureActionsOwner(myBaseTreeModel);
      myTreeModel = new TreeModelWrapper(structureViewModel, myTreeActionsOwner);
    } else {
      myTreeActionsOwner = null;
      myTreeModel = structureViewModel;
    }

    myTreeStructure =
        new SmartTreeStructure(project, myTreeModel) {
          public void rebuildTree() {
            if (ApplicationManager.getApplication().isUnitTestMode() || !myPopup.isDisposed()) {
              super.rebuildTree();
            }
          }

          public boolean isToBuildChildrenInBackground(final Object element) {
            return getRootElement() == element;
          }

          protected TreeElementWrapper createTree() {
            return new StructureViewComponent.StructureViewTreeElementWrapper(
                myProject, myModel.getRoot(), myModel);
          }

          @Override
          public String toString() {
            return "structure view tree structure(model=" + myTreeModel + ")";
          }
        };

    myTree =
        new FileStructureTree(
            myTreeStructure.getRootElement(), Registry.is("fast.tree.expand.in.structure.view"));

    myTree.setCellRenderer(
        new NodeRenderer() {
          @Override
          protected void doAppend(
              @NotNull @Nls String fragment,
              @NotNull SimpleTextAttributes attributes,
              boolean isMainText,
              boolean selected) {
            SpeedSearchUtil.appendFragmentsForSpeedSearch(
                myTree, fragment, attributes, selected, this);
          }

          @Override
          public void doAppend(
              @NotNull String fragment,
              @NotNull SimpleTextAttributes attributes,
              boolean selected) {
            SpeedSearchUtil.appendFragmentsForSpeedSearch(
                myTree, fragment, attributes, selected, this);
          }

          @Override
          public void doAppend(String fragment, boolean selected) {
            SpeedSearchUtil.appendFragmentsForSpeedSearch(
                myTree, fragment, SimpleTextAttributes.REGULAR_ATTRIBUTES, selected, this);
          }
        });

    mySpeedSearch = new MyTreeSpeedSearch();
    mySpeedSearch.setComparator(new SpeedSearchComparator(false, true));

    final FileStructurePopupFilter filter = new FileStructurePopupFilter();
    myFilteringStructure =
        new FilteringTreeStructure(
            filter, myTreeStructure, ApplicationManager.getApplication().isUnitTestMode());
    myAbstractTreeBuilder =
        new FilteringTreeBuilder(myTree, filter, myFilteringStructure, null) {
          @Override
          public void initRootNode() {}

          @Override
          protected boolean validateNode(Object child) {
            return StructureViewComponent.isValid(child);
          }

          @Override
          public void revalidateTree() {
            // myTree.revalidate();
            // myTree.repaint();
          }

          @Override
          public boolean isToEnsureSelectionOnFocusGained() {
            return false;
          }
        };

    myTreeExpander = new DefaultTreeExpander(myTree);

    // myAbstractTreeBuilder.getUi().setPassthroughMode(true);
    myAbstractTreeBuilder.getUi().getUpdater().setDelay(1);
    myInitialPsiElement = getCurrentElement(getPsiFile(myProject));
    // myAbstractTreeBuilder.setCanYieldUpdate(true);
    Disposer.register(this, myAbstractTreeBuilder);
  }
  @Override
  protected void collectInformationWithProgress(final ProgressIndicator progress) {
    final Set<HighlightInfo> gotHighlights = new THashSet<HighlightInfo>(100);
    final Set<HighlightInfo> outsideResult = new THashSet<HighlightInfo>(100);

    DaemonCodeAnalyzer daemonCodeAnalyzer = DaemonCodeAnalyzer.getInstance(myProject);
    HighlightVisitor[] highlightVisitors = getHighlightVisitors();
    final HighlightVisitor[] filteredVisitors = filterVisitors(highlightVisitors, myFile);
    final List<PsiElement> inside = new ArrayList<PsiElement>();
    final List<PsiElement> outside = new ArrayList<PsiElement>();
    try {
      Divider.divideInsideAndOutside(
          myFile,
          myStartOffset,
          myEndOffset,
          myPriorityRange,
          inside,
          outside,
          HighlightLevelUtil.AnalysisLevel.HIGHLIGHT,
          false);

      setProgressLimit((long) (inside.size() + outside.size()));

      final boolean forceHighlightParents = forceHighlightParents();

      if (!isDumbMode()) {
        highlightTodos(
            myFile,
            myDocument.getCharsSequence(),
            myStartOffset,
            myEndOffset,
            progress,
            myPriorityRange,
            gotHighlights,
            outsideResult);
      }

      collectHighlights(
          inside,
          new Runnable() {
            @Override
            public void run() {
              // all infos for the "injected fragment for the host which is inside" are indeed
              // inside
              // but some of the infos for the "injected fragment for the host which is outside" can
              // be still inside
              Set<HighlightInfo> injectedResult = new THashSet<HighlightInfo>();
              final Set<PsiFile> injected = new THashSet<PsiFile>();
              getInjectedPsiFiles(inside, outside, progress, injected);
              if (!addInjectedPsiHighlights(
                  injected, progress, Collections.synchronizedSet(injectedResult)))
                throw new ProcessCanceledException();
              final List<HighlightInfo> injectionsOutside =
                  new ArrayList<HighlightInfo>(gotHighlights.size());

              Set<HighlightInfo> result;
              synchronized (injectedResult) {
                // sync here because all writes happened in another thread
                result = injectedResult;
              }
              for (HighlightInfo info : result) {
                if (myPriorityRange.containsRange(info.getStartOffset(), info.getEndOffset())) {
                  gotHighlights.add(info);
                } else {
                  // nonconditionally apply injected results regardless whether they are in
                  // myStartOffset,myEndOffset
                  injectionsOutside.add(info);
                }
              }

              if (outsideResult.isEmpty() && injectionsOutside.isEmpty()) {
                return; // apply only result (by default apply command) and only within inside
              }

              final ProperTextRange priorityIntersection =
                  myPriorityRange.intersection(new TextRange(myStartOffset, myEndOffset));
              if ((!inside.isEmpty() || !gotHighlights.isEmpty())
                  && priorityIntersection
                      != null) { // do not apply when there were no elements to highlight
                // clear infos found in visible area to avoid applying them twice
                final List<HighlightInfo> toApplyInside =
                    new ArrayList<HighlightInfo>(gotHighlights);
                myHighlights.addAll(toApplyInside);
                gotHighlights.clear();
                gotHighlights.addAll(outsideResult);
                final long modificationStamp = myDocument.getModificationStamp();
                UIUtil.invokeLaterIfNeeded(
                    new Runnable() {
                      @Override
                      public void run() {
                        if (myProject.isDisposed()
                            || modificationStamp != myDocument.getModificationStamp()) return;
                        MarkupModel markupModel =
                            DocumentMarkupModel.forDocument(myDocument, myProject, true);

                        UpdateHighlightersUtil.setHighlightersInRange(
                            myProject,
                            myDocument,
                            priorityIntersection,
                            getColorsScheme(),
                            toApplyInside,
                            (MarkupModelEx) markupModel,
                            Pass.UPDATE_ALL);
                        if (myEditor != null) {
                          new ShowAutoImportPass(myProject, myFile, myEditor)
                              .applyInformationToEditor();
                        }
                      }
                    });
              }

              myApplyCommand =
                  new Runnable() {
                    @Override
                    public void run() {
                      ProperTextRange range = new ProperTextRange(myStartOffset, myEndOffset);

                      List<HighlightInfo> toApply = new ArrayList<HighlightInfo>();
                      for (HighlightInfo info : gotHighlights) {
                        if (!range.containsRange(info.getStartOffset(), info.getEndOffset()))
                          continue;
                        if (!myPriorityRange.containsRange(
                            info.getStartOffset(), info.getEndOffset())) {
                          toApply.add(info);
                        }
                      }
                      toApply.addAll(injectionsOutside);

                      UpdateHighlightersUtil.setHighlightersOutsideRange(
                          myProject,
                          myDocument,
                          toApply,
                          getColorsScheme(),
                          myStartOffset,
                          myEndOffset,
                          myPriorityRange,
                          Pass.UPDATE_ALL);
                    }
                  };
            }
          },
          outside,
          progress,
          filteredVisitors,
          gotHighlights,
          forceHighlightParents);

      if (myUpdateAll) {
        ((DaemonCodeAnalyzerImpl) daemonCodeAnalyzer)
            .getFileStatusMap()
            .setErrorFoundFlag(myDocument, myErrorFound);
      }
    } finally {
      incVisitorUsageCount(-1);
    }
    myHighlights.addAll(gotHighlights);
  }
  public void invoke(@NotNull Project project, Editor editor, PsiFile file)
      throws IncorrectOperationException {
    LOG.assertTrue(myOutOfScopeVariable != null);
    PsiManager manager = file.getManager();
    myOutOfScopeVariable.normalizeDeclaration();
    PsiUtil.setModifierProperty(myOutOfScopeVariable, PsiModifier.FINAL, false);
    PsiElement commonParent =
        PsiTreeUtil.findCommonParent(myOutOfScopeVariable, myUnresolvedReference);
    LOG.assertTrue(commonParent != null);
    PsiElement child =
        myOutOfScopeVariable.getTextRange().getStartOffset()
                < myUnresolvedReference.getTextRange().getStartOffset()
            ? myOutOfScopeVariable
            : myUnresolvedReference;

    while (child.getParent() != commonParent) child = child.getParent();
    PsiDeclarationStatement newDeclaration =
        (PsiDeclarationStatement)
            JavaPsiFacade.getInstance(manager.getProject())
                .getElementFactory()
                .createStatementFromText("int i = 0", null);
    PsiVariable variable =
        (PsiVariable) newDeclaration.getDeclaredElements()[0].replace(myOutOfScopeVariable);
    if (variable.getInitializer() != null) {
      variable.getInitializer().delete();
    }

    while (!(child instanceof PsiStatement) || !(child.getParent() instanceof PsiCodeBlock)) {
      child = child.getParent();
      commonParent = commonParent.getParent();
    }
    LOG.assertTrue(commonParent != null);
    PsiDeclarationStatement added =
        (PsiDeclarationStatement) commonParent.addBefore(newDeclaration, child);
    PsiLocalVariable addedVar = (PsiLocalVariable) added.getDeclaredElements()[0];
    manager.getCodeStyleManager().reformat(commonParent);

    // Leave initializer assignment
    PsiExpression initializer = myOutOfScopeVariable.getInitializer();
    if (initializer != null) {
      PsiExpressionStatement assignment =
          (PsiExpressionStatement)
              JavaPsiFacade.getInstance(manager.getProject())
                  .getElementFactory()
                  .createStatementFromText(myOutOfScopeVariable.getName() + "= e;", null);
      ((PsiAssignmentExpression) assignment.getExpression()).getRExpression().replace(initializer);
      assignment = (PsiExpressionStatement) manager.getCodeStyleManager().reformat(assignment);
      PsiDeclarationStatement declStatement =
          PsiTreeUtil.getParentOfType(myOutOfScopeVariable, PsiDeclarationStatement.class);
      LOG.assertTrue(declStatement != null);
      PsiElement parent = declStatement.getParent();
      if (parent instanceof PsiForStatement) {
        declStatement.replace(assignment);
      } else {
        parent.addAfter(assignment, declStatement);
      }
    }

    if (myOutOfScopeVariable.isValid()) {
      myOutOfScopeVariable.delete();
    }

    if (HighlightControlFlowUtil.checkVariableInitializedBeforeUsage(
            myUnresolvedReference,
            addedVar,
            new THashMap<PsiElement, Collection<PsiReferenceExpression>>())
        != null) {
      initialize(addedVar);
    }

    DaemonCodeAnalyzer.getInstance(project).updateVisibleHighlighters(editor);
  }
示例#18
0
 static void refreshMarkers(@NotNull Project project) {
   DaemonCodeAnalyzer.getInstance(project).restart();
 }
 public void dispose() {
   final DaemonCodeAnalyzer analyzer = DaemonCodeAnalyzer.getInstance(myProject);
   if (analyzer != null) {
     analyzer.setUpdateByTimerEnabled(myDaemonUpdateEnabled);
   }
 }
 public static void restartDaemons() {
   Project[] projects = ProjectManager.getInstance().getOpenProjects();
   for (Project project : projects) {
     DaemonCodeAnalyzer.getInstance(project).settingsChanged();
   }
 }
 public void apply() throws ConfigurationException {
   myEditor.apply();
   DaemonCodeAnalyzer.getInstance(myProject).restart();
 }
  /**
   * @param packageNames Packages to be reindexd if version has changed or package has been
   *     installed since last indexing run.If non are provided all packages will be refreshed.
   */
  public boolean refreshIndex(String... packageNames) {
    RHelperUtil.runHelperWithArgs(RHelperUtil.R_HELPER_INSTALL_TIDYVERSE);

    Set<RPackage> installedPackages = LocalRUtil.getInstalledPackages();

    // remove packages from index that are no longer present
    if (packageNames.length == 0) {
      Sets.SetView<RPackage> noLongerInstalled = Sets.difference(allPackages, installedPackages);
      allPackages.removeAll(noLongerInstalled);
    }

    // cut down packges to be refreshed to speed up calculations
    //        if(packageNames.length>0){
    //            installedPackages = installedPackages.stream().
    //                    filter(p -> Arrays.asList(packageNames).contains(p.getName())).
    //                    collect(Collectors.toSet());
    //        }

    ExecutorService executorService = Executors.newFixedThreadPool(8);

    final boolean[] hasChanged = {false};

    for (final RPackage rPackage : installedPackages) {
      final RPackage indexPackage = getByName(rPackage.getName());

      if (indexPackage != null
          && ObjectUtils.equals(indexPackage.getVersion(), rPackage.getVersion())) {
        continue;
      }

      executorService.submit(
          new Runnable() {
            @Override
            public void run() {
              reindexPackage(rPackage, indexPackage);
              hasChanged[0] = true;
            }
          });
    }

    executorService.shutdown();
    try {
      executorService.awaitTermination(1, TimeUnit.DAYS);
    } catch (InterruptedException e) {
      e.printStackTrace();
    }
    //        allPackages.clear();
    //        allPackages.addAll(installedPackages);

    if (hasChanged[0]) {
      if (ApplicationManager.getApplication() != null) {
        Project[] projects = ProjectManager.getInstance().getOpenProjects();
        for (Project project : projects) {
          if (project.isInitialized() && project.isOpen() && !project.isDefault()) {
            SpellCheckerManager spellCheckerManager = SpellCheckerManager.getInstance(project);
            EditableDictionary dictionary = spellCheckerManager.getUserDictionary();

            for (RPackage rPackage : RPackageService.getInstance().allPackages) {
              dictionary.addToDictionary(rPackage.getName());
              dictionary.addToDictionary(rPackage.getFunctionNames());
            }

            DaemonCodeAnalyzer.getInstance(project).restart();
          }
        }
      }
    }

    return hasChanged[0];
  }