@Override
    public void selectionChanged(@NotNull FileEditorManagerEvent event) {
      final FileEditor newFileEditor = event.getNewEditor();
      Editor mxmlEditor = null;
      if (newFileEditor instanceof TextEditor) {
        final Editor editor = ((TextEditor) newFileEditor).getEditor();
        if (DesignerApplicationManager.dumbAwareIsApplicable(
            project, PsiDocumentManager.getInstance(project).getPsiFile(editor.getDocument()))) {
          mxmlEditor = editor;
        }
      }

      if (mxmlEditor == null) {
        processFileEditorChange(null);
        return;
      }

      final DumbService dumbService = DumbService.getInstance(project);
      if (dumbService.isDumb()) {
        openWhenSmart(dumbService);
      } else {
        if (!isApplicableEditor(mxmlEditor)) {
          mxmlEditor = null;
        }

        processFileEditorChange(mxmlEditor);
      }
    }
  private Icon getIcon(DaemonCodeAnalyzerStatus status) {
    if (status == null) {
      return NO_ICON;
    }
    if (status.noHighlightingRoots != null
        && status.noHighlightingRoots.length == status.rootsNumber) {
      return NO_ANALYSIS_ICON;
    }

    Icon icon = HighlightDisplayLevel.DO_NOT_SHOW.getIcon();
    for (int i = status.errorCount.length - 1; i >= 0; i--) {
      if (status.errorCount[i] != 0) {
        icon = mySeverityRegistrar.getRendererIconByIndex(i);
        break;
      }
    }

    if (status.errorAnalyzingFinished) {
      if (myProject != null && DumbService.isDumb(myProject)) {
        return new LayeredIcon(NO_ANALYSIS_ICON, icon, STARING_EYE_ICON);
      }

      return icon;
    }
    if (!status.enabled) return NO_ANALYSIS_ICON;

    double progress = getOverallProgress(status);
    TruncatingIcon trunc =
        new TruncatingIcon(icon, icon.getIconWidth(), (int) (icon.getIconHeight() * progress));

    return new LayeredIcon(NO_ANALYSIS_ICON, trunc, STARING_EYE_ICON);
  }
 @Nullable
 protected PsiType inferType(PsiTypeElement typeElement) {
   if (null == typeElement || DumbService.isDumb(typeElement.getProject())) {
     return null;
   }
   return valProcessor.inferType(typeElement);
 }
  void updateFileName(@Nullable final VirtualFile updatedFile) {
    final EditorWindow[] windows = getWindows();
    for (int i = 0; i != windows.length; ++i) {
      for (VirtualFile file : windows[i].getFiles()) {
        if (updatedFile == null || file.getName().equals(updatedFile.getName())) {
          windows[i].updateFileName(file);
        }
      }
    }

    Project project = myManager.getProject();

    final IdeFrame frame = getFrame(project);
    if (frame != null) {
      VirtualFile file = getCurrentFile();

      File ioFile = file == null ? null : new File(file.getPresentableUrl());
      String fileTitle = null;
      if (file != null) {
        fileTitle =
            DumbService.isDumb(project)
                ? file.getName()
                : FrameTitleBuilder.getInstance().getFileTitle(project, file);
      }

      frame.setFileTitle(fileTitle, ioFile);
    }
  }
  @Override
  public void runCheckinHandlers(@NotNull final Runnable finishAction) {
    final VcsConfiguration configuration = VcsConfiguration.getInstance(myProject);
    final Collection<VirtualFile> files = myPanel.getVirtualFiles();

    final Runnable performCheckoutAction =
        new Runnable() {
          @Override
          public void run() {
            FileDocumentManager.getInstance().saveAllDocuments();
            finishAction.run();
          }
        };

    if (reformat(configuration, true) && !DumbService.isDumb(myProject)) {
      new ReformatCodeProcessor(
              myProject,
              CheckinHandlerUtil.getPsiFiles(myProject, files),
              FormatterUtil.REFORMAT_BEFORE_COMMIT_COMMAND_NAME,
              performCheckoutAction,
              true)
          .run();
    } else {
      performCheckoutAction.run();
    }
  }
 private static void doPersistProjectUsages(@NotNull Project project) {
   if (DumbService.isDumb(project)) return;
   for (UsagesCollector usagesCollector : Extensions.getExtensions(UsagesCollector.EP_NAME)) {
     if (usagesCollector instanceof AbstractApplicationUsagesCollector) {
       ((AbstractApplicationUsagesCollector) usagesCollector).persistProjectUsages(project);
     }
   }
 }
  private static void showParameterHint(
      final PsiElement element,
      final Editor editor,
      final Object[] descriptors,
      final Project project,
      @Nullable PsiElement highlighted,
      final int elementStart,
      final ParameterInfoHandler handler,
      final boolean requestFocus) {
    if (ParameterInfoController.isAlreadyShown(editor, elementStart)) return;

    if (editor.isDisposed() || !editor.getComponent().isVisible()) return;
    final ParameterInfoComponent component =
        new ParameterInfoComponent(descriptors, editor, handler, requestFocus);
    component.setParameterOwner(element);
    component.setRequestFocus(requestFocus);
    if (highlighted != null) {
      component.setHighlightedParameter(highlighted);
    }

    component.update(); // to have correct preferred size

    final LightweightHint hint = new LightweightHint(component);
    hint.setSelectingHint(true);
    final HintManagerImpl hintManager = HintManagerImpl.getInstanceImpl();
    final ShowParameterInfoHandler.BestLocationPointProvider provider =
        new MyBestLocationPointProvider(editor);
    final Pair<Point, Short> pos =
        provider.getBestPointPosition(hint, element, elementStart, true, HintManager.UNDER);

    PsiDocumentManager.getInstance(project)
        .performLaterWhenAllCommitted(
            () -> {
              if (editor.isDisposed() || DumbService.isDumb(project)) return;

              final Document document = editor.getDocument();
              if (document.getTextLength() < elementStart) return;

              HintHint hintHint =
                  HintManagerImpl.createHintHint(editor, pos.getFirst(), hint, pos.getSecond());
              hintHint.setExplicitClose(true);
              hintHint.setRequestFocus(requestFocus);

              Editor editorToShow =
                  editor instanceof EditorWindow ? ((EditorWindow) editor).getDelegate() : editor;
              // is case of injection we need to calculate position for EditorWindow
              // also we need to show the hint in the main editor because of intention bulb
              hintManager.showEditorHint(
                  hint,
                  editorToShow,
                  pos.getFirst(),
                  HintManager.HIDE_BY_ESCAPE | HintManager.UPDATE_BY_SCROLLING,
                  0,
                  false,
                  hintHint);
              new ParameterInfoController(project, editor, elementStart, hint, handler, provider);
            });
  }
 private void createConfiguration() {
   LOG.assertTrue(myConfiguration == null);
   final Location location = getLocation();
   myConfiguration =
       location != null && !DumbService.isDumb(location.getProject())
           ? PreferredProducerFind.createConfiguration(location, this)
           : null;
   myInitialized = true;
 }
  @Nullable
  public static TextCompletionProvider getProvider(@NotNull PsiFile file) {
    TextCompletionProvider provider = file.getUserData(COMPLETING_TEXT_FIELD_KEY);

    if (provider == null
        || (DumbService.isDumb(file.getProject()) && !DumbService.isDumbAware(provider))) {
      return null;
    }
    return provider;
  }
Ejemplo n.º 10
0
 @NotNull
 private KotlinPsiElementFinderWrapper[] filteredFinders() {
   DumbService dumbService = DumbService.getInstance(getProject());
   KotlinPsiElementFinderWrapper[] finders = finders();
   if (dumbService.isDumb()) {
     List<KotlinPsiElementFinderWrapper> list =
         dumbService.filterByDumbAwareness(Arrays.asList(finders));
     finders = list.toArray(new KotlinPsiElementFinderWrapper[list.size()]);
   }
   return finders;
 }
Ejemplo n.º 11
0
  /**
   * Makes index snapshot hashsets
   *
   * @return result
   */
  public synchronized boolean makeIndexSnapshot() {
    if (!indexSnapshotDone && !DumbService.isDumb(myProject)) {
      KNOWN_SUBS.addAll(PerlSubUtil.getDeclaredSubsNames(myProject));
      KNOWN_SUBS.addAll(PerlSubUtil.getDefinedSubsNames(myProject));
      KNOWN_SUBS.addAll(PerlGlobUtil.getDefinedGlobsNames(myProject));

      KNOWN_PACKAGES.addAll(PerlPackageUtil.getDefinedPackageNames(myProject));
      indexSnapshotDone = true;
    }
    return indexSnapshotDone;
  }
  void processInPlaceInjectorsFor(@NotNull PsiElement element, @NotNull InjProcessor processor) {
    MultiHostInjector[] infos = getInjectorMap().get(element.getClass());
    if (infos != null) {
      final boolean dumb = myDumbService.isDumb();
      for (MultiHostInjector injector : infos) {
        if (dumb && !DumbService.isDumbAware(injector)) {
          continue;
        }

        if (!processor.process(element, injector)) return;
      }
    }
  }
  @NotNull
  @Override
  public <Psi extends PsiElement> List<Psi> getAugments(
      @NotNull PsiElement element, @NotNull Class<Psi> type) {
    final List<Psi> emptyResult = Collections.emptyList();
    // skip processing during index rebuild
    final Project project = element.getProject();
    if (DumbService.isDumb(project)) {
      return emptyResult;
    }
    // Expecting that we are only augmenting an PsiClass
    // Don't filter !isPhysical elements or code auto completion will not work
    if (!(element instanceof PsiExtensibleClass) || !element.isValid()) {
      return emptyResult;
    }
    // skip processing for other as supported types
    if (type != PsiMethod.class && type != PsiField.class && type != PsiClass.class) {
      return emptyResult;
    }
    // skip processing if plugin is disabled
    if (!ProjectSettings.loadAndGetEnabledInProject(project)) {
      return emptyResult;
    }

    final PsiFile containingFile = element.getContainingFile();
    if (containingFile == null) {
      return emptyResult;
    }

    initRegisteredAnnotations();

    final PsiClass psiClass = (PsiClass) element;

    boolean fileOpenInEditor = true;

    final VirtualFile virtualFile = containingFile.getVirtualFile();
    if (null != virtualFile) {
      fileOpenInEditor = FileEditorManager.getInstance(project).isFileOpen(virtualFile);
    }

    if (fileOpenInEditor || checkLombokPresent(psiClass)) {
      return process(type, project, psiClass);
    }

    return emptyResult;
  }
  public boolean processPropertiesFiles(
      @NotNull final GlobalSearchScope searchScope,
      @NotNull final PropertiesFileProcessor processor,
      @NotNull final BundleNameEvaluator evaluator) {
    for (VirtualFile file : FileTypeIndex.getFiles(PropertiesFileType.INSTANCE, searchScope)) {
      if (!processFile(file, evaluator, processor)) return false;
    }
    if (!myDumbService.isDumb()) {
      for (VirtualFile file :
          FileBasedIndex.getInstance()
              .getContainingFiles(
                  XmlPropertiesIndex.NAME, XmlPropertiesIndex.MARKER_KEY, searchScope)) {
        if (!processFile(file, evaluator, processor)) return false;
      }
    }

    return true;
  }
  @NotNull
  protected Collection<HighlightInfo> checkHighlighting(
      @NotNull final ExpectedHighlightingData data) {
    data.init();
    PsiDocumentManager.getInstance(myProject).commitAllDocuments();

    // to load text
    ApplicationManager.getApplication()
        .runWriteAction(
            new Runnable() {
              @Override
              public void run() {
                TreeUtil.clearCaches((TreeElement) myFile.getNode());
              }
            });

    // to initialize caches
    if (!DumbService.isDumb(getProject())) {
      CacheManager.SERVICE
          .getInstance(myProject)
          .getFilesWithWord(
              "XXX", UsageSearchContext.IN_COMMENTS, GlobalSearchScope.allScope(myProject), true);
    }
    final JavaPsiFacadeEx facade = getJavaFacade();
    if (facade != null) {
      facade.setAssertOnFileLoadingFilter(
          myFileTreeAccessFilter, myTestRootDisposable); // check repository work
    }

    try {
      Collection<HighlightInfo> infos = doHighlighting();

      String text = myEditor.getDocument().getText();
      data.checkLineMarkers(
          DaemonCodeAnalyzerImpl.getLineMarkers(getDocument(getFile()), getProject()), text);
      data.checkResult(infos, text);
      return infos;
    } finally {
      if (facade != null) {
        facade.setAssertOnFileLoadingFilter(VirtualFileFilter.NONE, myTestRootDisposable);
      }
    }
  }
Ejemplo n.º 16
0
  private boolean canRelyOnIndices() {
    if (DumbService.isDumb(myProject)) return false;

    if (myFindModel.isRegularExpressions()) return false;

    // a local scope may be over a non-indexed file
    if (myFindModel.getCustomScope() instanceof LocalSearchScope) return false;

    String text = myFindModel.getStringToFind();
    if (StringUtil.isEmptyOrSpaces(text)) return false;

    if (hasTrigrams(text)) return true;

    // $ is used to separate words when indexing plain-text files but not when indexing
    // Java identifiers, so we can't consistently break a string containing $ characters into words

    return myFindModel.isWholeWordsOnly()
        && text.indexOf('$') < 0
        && !StringUtil.getWordsInStringLongestFirst(text).isEmpty();
  }
 @Nullable
 @Override
 public String getErrorMessage(@NotNull Project project, @NotNull VirtualFile file) {
   final String javaErrorMessage =
       JavaProjectSdkSetupValidator.INSTANCE.getErrorMessage(project, file);
   if (javaErrorMessage != null) {
     return javaErrorMessage;
   }
   if (DumbService.isDumb(project)) {
     return null;
   }
   final PsiClass nodeClass =
       JavaPsiFacade.getInstance(project)
           .findClass(JavaFxCommonNames.JAVAFX_SCENE_NODE, GlobalSearchScope.allScope(project));
   if (nodeClass == null) {
     return "The JavaFX runtime is not configured. "
         + "Either use a JDK that has the JavaFX built in, or add a JavaFX library to the classpath";
   }
   return null;
 }
  protected void doRun() {
    PsiDocumentManager.getInstance(myProject).commitAllDocuments();
    final Ref<UsageInfo[]> refUsages = new Ref<>();
    final Ref<Language> refErrorLanguage = new Ref<>();
    final Ref<Boolean> refProcessCanceled = new Ref<>();
    final Ref<Boolean> anyException = new Ref<>();

    final Runnable findUsagesRunnable =
        new Runnable() {
          @Override
          public void run() {
            try {
              refUsages.set(
                  DumbService.getInstance(myProject)
                      .runReadActionInSmartMode(
                          new Computable<UsageInfo[]>() {
                            @Override
                            public UsageInfo[] compute() {
                              return findUsages();
                            }
                          }));
            } catch (UnknownReferenceTypeException e) {
              refErrorLanguage.set(e.getElementLanguage());
            } catch (ProcessCanceledException e) {
              refProcessCanceled.set(Boolean.TRUE);
            } catch (Throwable e) {
              anyException.set(Boolean.TRUE);
              LOG.error(e);
            }
          }
        };

    if (!ProgressManager.getInstance()
        .runProcessWithProgressSynchronously(
            findUsagesRunnable, RefactoringBundle.message("progress.text"), true, myProject)) {
      return;
    }

    if (!refErrorLanguage.isNull()) {
      Messages.showErrorDialog(
          myProject,
          RefactoringBundle.message(
              "unsupported.refs.found", refErrorLanguage.get().getDisplayName()),
          RefactoringBundle.message("error.title"));
      return;
    }
    if (DumbService.isDumb(myProject)) {
      DumbService.getInstance(myProject)
          .showDumbModeNotification("Refactoring is not available until indices are ready");
      return;
    }
    if (!refProcessCanceled.isNull()) {
      Messages.showErrorDialog(
          myProject,
          "Index corruption detected. Please retry the refactoring - indexes will be rebuilt automatically",
          RefactoringBundle.message("error.title"));
      return;
    }

    if (!anyException.isNull()) {
      // do not proceed if find usages fails
      return;
    }
    assert !refUsages.isNull() : "Null usages from processor " + this;
    if (!preprocessUsages(refUsages)) return;
    final UsageInfo[] usages = refUsages.get();
    assert usages != null;
    UsageViewDescriptor descriptor = createUsageViewDescriptor(usages);

    boolean isPreview = isPreviewUsages(usages);
    if (!isPreview) {
      isPreview =
          !ensureElementsWritable(usages, descriptor) || UsageViewUtil.hasReadOnlyUsages(usages);
      if (isPreview) {
        StatusBarUtil.setStatusBarInfo(
            myProject, RefactoringBundle.message("readonly.occurences.found"));
      }
    }
    if (isPreview) {
      for (UsageInfo usage : usages) {
        LOG.assertTrue(usage != null, getClass());
      }
      previewRefactoring(usages);
    } else {
      execute(usages);
    }
  }
  // return true if panel needs to be rebuilt
  boolean updatePanel(@NotNull DaemonCodeAnalyzerStatus status, Project project) {
    progressBarsEnabled = false;
    progressBarsCompleted = null;
    statistics = "";
    passStatusesVisible = false;
    statusLabel = null;
    statusExtraLine = null;

    boolean result = false;
    if (!status.passStati.equals(new ArrayList<>(passes.keySet()))) {
      // passes set has changed
      rebuildPassesMap(status);
      result = true;
    }

    if (PowerSaveMode.isEnabled()) {
      statusLabel = "Code analysis is disabled in power save mode";
      status.errorAnalyzingFinished = true;
      icon = AllIcons.General.SafeMode;
      return result;
    }
    if (status.reasonWhyDisabled != null) {
      statusLabel = "No analysis has been performed";
      statusExtraLine = "(" + status.reasonWhyDisabled + ")";
      passStatusesVisible = true;
      progressBarsCompleted = Boolean.FALSE;
      icon = AllIcons.General.InspectionsTrafficOff;
      return result;
    }
    if (status.reasonWhySuspended != null) {
      statusLabel = "Code analysis has been suspended";
      statusExtraLine = "(" + status.reasonWhySuspended + ")";
      passStatusesVisible = true;
      progressBarsCompleted = Boolean.FALSE;
      icon = AllIcons.General.InspectionsPause;
      return result;
    }

    Icon icon = AllIcons.General.InspectionsOK;
    for (int i = status.errorCount.length - 1; i >= 0; i--) {
      if (status.errorCount[i] != 0) {
        icon = SeverityRegistrar.getSeverityRegistrar(project).getRendererIconByIndex(i);
        break;
      }
    }

    if (status.errorAnalyzingFinished) {
      boolean isDumb = project != null && DumbService.isDumb(project);
      if (isDumb) {
        statusLabel = "Shallow analysis completed";
        statusExtraLine = "Complete results will be available after indexing";
      } else {
        statusLabel = DaemonBundle.message("analysis.completed");
      }
      progressBarsCompleted = Boolean.TRUE;
    } else {
      statusLabel = DaemonBundle.message("performing.code.analysis");
      passStatusesVisible = true;
      progressBarsEnabled = true;
      progressBarsCompleted = null;
    }

    int currentSeverityErrors = 0;
    @org.intellij.lang.annotations.Language("HTML")
    String text = "";
    for (int i = status.errorCount.length - 1; i >= 0; i--) {
      if (status.errorCount[i] > 0) {
        final HighlightSeverity severity =
            SeverityRegistrar.getSeverityRegistrar(project).getSeverityByIndex(i);
        String name =
            status.errorCount[i] > 1
                ? StringUtil.pluralize(severity.getName().toLowerCase())
                : severity.getName().toLowerCase();
        text +=
            status.errorAnalyzingFinished
                ? DaemonBundle.message("errors.found", status.errorCount[i], name)
                : DaemonBundle.message("errors.found.so.far", status.errorCount[i], name);
        text += "<br>";
        currentSeverityErrors += status.errorCount[i];
      }
    }
    if (currentSeverityErrors == 0) {
      text +=
          status.errorAnalyzingFinished
              ? DaemonBundle.message("no.errors.or.warnings.found")
              : DaemonBundle.message("no.errors.or.warnings.found.so.far") + "<br>";
    }
    statistics = XmlStringUtil.wrapInHtml(text);

    this.icon = icon;
    return result;
  }
Ejemplo n.º 20
0
 private boolean shouldUseSlowResolve() {
   DumbService dumbService = DumbService.getInstance(getProject());
   return dumbService.isDumb() && dumbService.isAlternativeResolveEnabled();
 }