protected void doRun(
     @NotNull final ExecutionEnvironment environment, @NotNull final Runnable startRunnable) {
   Boolean allowSkipRun = environment.getUserData(EXECUTION_SKIP_RUN);
   if (allowSkipRun != null && allowSkipRun) {
     environment
         .getProject()
         .getMessageBus()
         .syncPublisher(EXECUTION_TOPIC)
         .processNotStarted(environment.getExecutor().getId(), environment);
   } else {
     // important! Do not use DumbService.smartInvokeLater here because it depends on modality
     // state
     // and execution of startRunnable could be skipped if modality state check fails
     //noinspection SSBasedInspection
     SwingUtilities.invokeLater(
         () -> {
           if (!myProject.isDisposed()) {
             if (!Registry.is("dumb.aware.run.configurations")) {
               DumbService.getInstance(myProject).runWhenSmart(startRunnable);
             } else {
               try {
                 DumbService.getInstance(myProject).setAlternativeResolveEnabled(true);
                 startRunnable.run();
               } catch (IndexNotReadyException ignored) {
                 ExecutionUtil.handleExecutionError(
                     environment,
                     new ExecutionException("cannot start while indexing is in progress."));
               } finally {
                 DumbService.getInstance(myProject).setAlternativeResolveEnabled(false);
               }
             }
           }
         });
   }
 }
  @Override
  public void invoke(
      @NotNull final Project project, @NotNull Editor editor, @NotNull PsiFile file) {
    PsiDocumentManager.getInstance(project).commitAllDocuments();

    DumbService.getInstance(project).setAlternativeResolveEnabled(true);
    try {
      int offset = editor.getCaretModel().getOffset();
      PsiElement[] elements =
          underModalProgress(
              project,
              "Resolving Reference...",
              () -> findAllTargetElements(project, editor, offset));
      FeatureUsageTracker.getInstance().triggerFeatureUsed("navigation.goto.declaration");

      if (elements.length != 1) {
        if (elements.length == 0
            && suggestCandidates(TargetElementUtil.findReference(editor, offset)).isEmpty()) {
          PsiElement element =
              findElementToShowUsagesOf(editor, editor.getCaretModel().getOffset());
          if (startFindUsages(editor, element)) {
            return;
          }

          // disable 'no declaration found' notification for keywords
          final PsiElement elementAtCaret = file.findElementAt(offset);
          if (elementAtCaret != null) {
            final NamesValidator namesValidator =
                LanguageNamesValidation.INSTANCE.forLanguage(elementAtCaret.getLanguage());
            if (namesValidator != null
                && namesValidator.isKeyword(elementAtCaret.getText(), project)) {
              return;
            }
          }
        }
        chooseAmbiguousTarget(editor, offset, elements, file);
        return;
      }

      PsiElement element = elements[0];
      if (element == findElementToShowUsagesOf(editor, editor.getCaretModel().getOffset())
          && startFindUsages(editor, element)) {
        return;
      }

      PsiElement navElement = element.getNavigationElement();
      navElement = TargetElementUtil.getInstance().getGotoDeclarationTarget(element, navElement);
      if (navElement != null) {
        gotoTargetElement(navElement, editor, file);
      }
    } catch (IndexNotReadyException e) {
      DumbService.getInstance(project)
          .showDumbModeNotification("Navigation is not available here during index update");
    } finally {
      DumbService.getInstance(project).setAlternativeResolveEnabled(false);
    }
  }
  @Nullable
  @Override
  public PhpType getType(PsiElement e) {
    if (DumbService.getInstance(e.getProject()).isDumb()) {
      return null;
    }

    if (!ContainerGetHelper.isContainerGetCall(e)) {
      return null;
    }

    String serviceId = ContainerGetHelper.getServiceId((MethodReference) e);
    if (null == serviceId) {
      return null;
    }

    Symfony2ProjectComponent symfony2ProjectComponent =
        e.getProject().getComponent(Symfony2ProjectComponent.class);
    ServiceMap serviceMap = symfony2ProjectComponent.getServicesMap();
    if (null == serviceMap) {
      return null;
    }
    String serviceClass = serviceMap.getMap().get(serviceId);

    if (null == serviceClass) {
      return null;
    }

    return new PhpType().add(serviceClass);
  }
  public static void addJarsToRootsAndImportClass(
      @NotNull List<String> jarPaths,
      final String libraryName,
      @NotNull final Module currentModule,
      @Nullable final Editor editor,
      @Nullable final PsiReference reference,
      @Nullable @NonNls final String className) {
    addJarsToRoots(
        jarPaths, libraryName, currentModule, reference != null ? reference.getElement() : null);

    final Project project = currentModule.getProject();
    if (editor != null && reference != null && className != null) {
      DumbService.getInstance(project)
          .withAlternativeResolveEnabled(
              new Runnable() {
                @Override
                public void run() {
                  GlobalSearchScope scope =
                      GlobalSearchScope.moduleWithLibrariesScope(currentModule);
                  PsiClass aClass = JavaPsiFacade.getInstance(project).findClass(className, scope);
                  if (aClass != null) {
                    new AddImportAction(project, reference, editor, aClass).execute();
                  }
                }
              });
    }
  }
  @Nullable
  @Override
  public String getType(PsiElement e) {
    if (DumbService.getInstance(e.getProject()).isDumb()
        || !Settings.getInstance(e.getProject()).pluginEnabled
        || !Settings.getInstance(e.getProject()).objectManagerFindTypeProvider) {
      return null;
    }

    if (!(e instanceof MethodReference)
        || !PhpElementsUtil.isMethodWithFirstStringOrFieldReference(e, "find")) {
      return null;
    }

    String refSignature = ((MethodReference) e).getSignature();
    if (StringUtil.isEmpty(refSignature)) {
      return null;
    }

    // we need the param key on getBySignature(), since we are already in the resolved method there
    // attach it to signature
    // param can have dotted values split with \
    PsiElement[] parameters = ((MethodReference) e).getParameters();
    if (parameters.length == 2) {
      return PhpTypeProviderUtil.getReferenceSignature((MethodReference) e, TRIM_KEY, 2);
    }

    return null;
  }
  public synchronized void runPostStartupActivities() {
    final Application app = ApplicationManager.getApplication();
    app.assertIsDispatchThread();

    if (myPostStartupActivitiesPassed) return;

    runActivities(myDumbAwarePostStartupActivities);
    DumbService.getInstance(myProject)
        .runWhenSmart(
            new Runnable() {
              public void run() {
                synchronized (StartupManagerImpl.this) {
                  app.assertIsDispatchThread();
                  if (myProject.isDisposed()) return;
                  runActivities(
                      myDumbAwarePostStartupActivities); // they can register activities while in
                                                         // the dumb mode
                  runActivities(myNotDumbAwarePostStartupActivities);

                  myPostStartupActivitiesPassed = true;
                }
              }
            });

    if (!app.isUnitTestMode()) {
      VirtualFileManager.getInstance().refresh(!app.isHeadlessEnvironment());
    }
  }
 @Override
 public void run(@NotNull ProgressIndicator indicator) {
   try {
     mySocket = myServerSocket.accept();
     final ExecutionException[] ex = new ExecutionException[1];
     DumbService.getInstance(getProject())
         .repeatUntilPassesInSmartMode(
             new Runnable() {
               @Override
               public void run() {
                 try {
                   search();
                 } catch (ExecutionException e) {
                   ex[0] = e;
                 }
               }
             });
     if (ex[0] != null) {
       logCantRunException(ex[0]);
     }
   } catch (ProcessCanceledException e) {
     throw e;
   } catch (IOException e) {
     LOG.info(e);
   } catch (Throwable e) {
     LOG.error(e);
   }
 }
  private boolean checkUnderReadAction(
      final MyValidatorProcessingItem item,
      final CompileContext context,
      final Computable<Map<ProblemDescriptor, HighlightDisplayLevel>> runnable) {
    return DumbService.getInstance(context.getProject())
        .runReadActionInSmartMode(
            new Computable<Boolean>() {
              @Override
              public Boolean compute() {
                final PsiFile file = item.getPsiFile();
                if (file == null) return false;

                final Document document = myPsiDocumentManager.getCachedDocument(file);
                if (document != null && myPsiDocumentManager.isUncommited(document)) {
                  final String url = file.getViewProvider().getVirtualFile().getUrl();
                  context.addMessage(
                      CompilerMessageCategory.WARNING,
                      CompilerBundle.message("warning.text.file.has.been.changed"),
                      url,
                      -1,
                      -1);
                  return false;
                }

                if (reportProblems(context, runnable.compute())) return false;
                return true;
              }
            });
  }
  private CompletionInitializationContext runContributorsBeforeCompletion(
      Editor editor, PsiFile psiFile, int invocationCount, Caret caret) {
    final Ref<CompletionContributor> current = Ref.create(null);
    CompletionInitializationContext context =
        new CompletionInitializationContext(
            editor, caret, psiFile, myCompletionType, invocationCount) {
          CompletionContributor dummyIdentifierChanger;

          @Override
          public void setDummyIdentifier(@NotNull String dummyIdentifier) {
            super.setDummyIdentifier(dummyIdentifier);

            if (dummyIdentifierChanger != null) {
              LOG.error(
                  "Changing the dummy identifier twice, already changed by "
                      + dummyIdentifierChanger);
            }
            dummyIdentifierChanger = current.get();
          }
        };
    List<CompletionContributor> contributors =
        CompletionContributor.forLanguage(context.getPositionLanguage());
    Project project = psiFile.getProject();
    List<CompletionContributor> filteredContributors =
        DumbService.getInstance(project).filterByDumbAwareness(contributors);
    for (final CompletionContributor contributor : filteredContributors) {
      current.set(contributor);
      contributor.beforeCompletion(context);
      CompletionAssertions.checkEditorValid(editor);
      assert !PsiDocumentManager.getInstance(project).isUncommited(editor.getDocument())
          : "Contributor " + contributor + " left the document uncommitted";
    }
    return context;
  }
Example #10
0
 private void updateWarnings(@NotNull final MPSFileNodeEditor editor) {
   DumbService.getInstance(myProject)
       .smartInvokeLater(
           new Runnable() {
             @Override
             public void run() {
               final Runnable task =
                   new Runnable() {
                     @Override
                     public void run() {
                       doUpdateWarnings(editor);
                     }
                   };
               Boolean aBoolean =
                   ModelAccess.instance()
                       .tryRead(
                           new Computable<Boolean>() {
                             @Override
                             public Boolean compute() {
                               task.run();
                               return Boolean.TRUE;
                             }
                           });
               if (aBoolean == null) {
                 ModelAccess.instance().runReadInEDT(task);
               }
             }
           });
 }
  public Pair<RenderResources, RenderResources> createResourceResolver(
      final AndroidFacet facet,
      FolderConfiguration config,
      ProjectResources projectResources,
      String themeName,
      boolean isProjectTheme) {
    final Map<ResourceType, Map<String, ResourceValue>> configedProjectRes =
        projectResources.getConfiguredResources(config);

    DumbService.getInstance(facet.getModule().getProject()).waitForSmartMode();

    final Collection<String> ids =
        ApplicationManager.getApplication()
            .runReadAction(
                new Computable<Collection<String>>() {
                  @Override
                  public Collection<String> compute() {
                    return facet.getLocalResourceManager().getIds();
                  }
                });
    final Map<String, ResourceValue> map = configedProjectRes.get(ResourceType.ID);
    for (String id : ids) {
      if (!map.containsKey(id)) {
        map.put(id, new ResourceValue(ResourceType.ID, id, false));
      }
    }

    final Map<ResourceType, Map<String, ResourceValue>> configedFrameworkRes =
        myResources.getConfiguredResources(config);
    final ResourceResolver resolver =
        ResourceResolver.create(
            configedProjectRes, configedFrameworkRes, themeName, isProjectTheme);
    return new Pair<RenderResources, RenderResources>(
        new ResourceResolverDecorator(resolver), resolver);
  }
    @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);
      }
    }
 public final void invokeCompletion(final Project project, final Editor editor) {
   try {
     invokeCompletion(project, editor, 1);
   } catch (IndexNotReadyException e) {
     DumbService.getInstance(project)
         .showDumbModeNotification(
             "Code completion is not available here while indices are being built");
   }
 }
  public boolean processAction(final InputEvent e, ActionProcessor processor) {
    ActionManagerEx actionManager = ActionManagerEx.getInstanceEx();
    final Project project = PlatformDataKeys.PROJECT.getData(myContext.getDataContext());
    final boolean dumb = project != null && DumbService.getInstance(project).isDumb();
    List<AnActionEvent> nonDumbAwareAction = new ArrayList<AnActionEvent>();
    for (final AnAction action : myContext.getActions()) {
      final Presentation presentation = myPresentationFactory.getPresentation(action);

      // Mouse modifiers are 0 because they have no any sense when action is invoked via keyboard
      final AnActionEvent actionEvent =
          processor.createEvent(
              e,
              myContext.getDataContext(),
              ActionPlaces.MAIN_MENU,
              presentation,
              ActionManager.getInstance());

      ActionUtil.performDumbAwareUpdate(action, actionEvent, true);

      if (dumb && !action.isDumbAware()) {
        if (Boolean.FALSE.equals(
            presentation.getClientProperty(ActionUtil.WOULD_BE_ENABLED_IF_NOT_DUMB_MODE))) {
          continue;
        }

        nonDumbAwareAction.add(actionEvent);
        continue;
      }

      if (!presentation.isEnabled()) {
        continue;
      }

      processor.onUpdatePassed(e, action, actionEvent);

      ((DataManagerImpl.MyDataContext) myContext.getDataContext())
          .setEventCount(IdeEventQueue.getInstance().getEventCount(), this);
      actionManager.fireBeforeActionPerformed(action, actionEvent.getDataContext(), actionEvent);
      Component component =
          PlatformDataKeys.CONTEXT_COMPONENT.getData(actionEvent.getDataContext());
      if (component != null && !component.isShowing()) {
        return true;
      }

      processor.performAction(e, action, actionEvent);
      actionManager.fireAfterActionPerformed(action, actionEvent.getDataContext(), actionEvent);
      return true;
    }

    if (!nonDumbAwareAction.isEmpty()) {
      showDumbModeWarningLaterIfNobodyConsumesEvent(
          e, nonDumbAwareAction.toArray(new AnActionEvent[nonDumbAwareAction.size()]));
    }

    return false;
  }
 // queue each activity in smart mode separately so that if one of them starts dumb mode, the next
 // ones just wait for it to finish
 private void queueSmartModeActivity(final Runnable activity) {
   DumbService.getInstance(myProject)
       .runWhenSmart(
           new Runnable() {
             @Override
             public void run() {
               runActivity(activity);
             }
           });
 }
 public static <T> T underModalProgress(
     @NotNull Project project,
     @NotNull @Nls(capitalization = Nls.Capitalization.Title) String progressTitle,
     @NotNull Computable<T> computable)
     throws ProcessCanceledException {
   return ProgressManager.getInstance()
       .runProcessWithProgressSynchronously(
           () -> {
             DumbService.getInstance(project).setAlternativeResolveEnabled(true);
             try {
               return ApplicationManager.getApplication().runReadAction(computable);
             } finally {
               DumbService.getInstance(project).setAlternativeResolveEnabled(false);
             }
           },
           progressTitle,
           true,
           project);
 }
 @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;
 }
  @Override
  @NotNull
  public ProcessingItem[] getProcessingItems(final CompileContext context) {
    final Project project = context.getProject();
    if (project.isDefault() || !ValidationConfiguration.shouldValidate(this, context)) {
      return ProcessingItem.EMPTY_ARRAY;
    }
    final ExcludesConfiguration excludesConfiguration =
        ValidationConfiguration.getExcludedEntriesConfiguration(project);
    final List<ProcessingItem> items =
        DumbService.getInstance(project)
            .runReadActionInSmartMode(
                new Computable<List<ProcessingItem>>() {
                  @Override
                  public List<ProcessingItem> compute() {
                    final CompileScope compileScope = context.getCompileScope();
                    if (!myValidator.isAvailableOnScope(compileScope)) return null;

                    final ArrayList<ProcessingItem> items = new ArrayList<ProcessingItem>();

                    final Processor<VirtualFile> processor =
                        new Processor<VirtualFile>() {
                          @Override
                          public boolean process(VirtualFile file) {
                            if (!file.isValid()) {
                              return true;
                            }

                            if (myCompilerManager.isExcludedFromCompilation(file)
                                || excludesConfiguration.isExcluded(file)) {
                              return true;
                            }

                            final Module module = context.getModuleByFile(file);
                            if (module != null) {
                              final PsiFile psiFile = myPsiManager.findFile(file);
                              if (psiFile != null) {
                                items.add(new MyValidatorProcessingItem(psiFile));
                              }
                            }
                            return true;
                          }
                        };
                    ContainerUtil.process(
                        myValidator.getFilesToProcess(myPsiManager.getProject(), context),
                        processor);
                    return items;
                  }
                });
    if (items == null) return ProcessingItem.EMPTY_ARRAY;

    return items.toArray(new ProcessingItem[items.size()]);
  }
  @Override
  @Nullable
  public ObjectStubTree readFromVFile(Project project, final VirtualFile vFile) {
    if (DumbService.getInstance(project).isDumb()) {
      return null;
    }

    final int id = Math.abs(FileBasedIndex.getFileId(vFile));
    if (id <= 0) {
      return null;
    }

    boolean wasIndexedAlready = FileBasedIndexImpl.isFileIndexed(vFile, StubUpdatingIndex.INDEX_ID);

    final List<SerializedStubTree> datas =
        FileBasedIndex.getInstance()
            .getValues(StubUpdatingIndex.INDEX_ID, id, GlobalSearchScope.fileScope(project, vFile));
    final int size = datas.size();

    if (size == 1) {
      Stub stub;
      try {
        stub = datas.get(0).getStub(false);
      } catch (SerializerNotFoundException e) {
        return processError(
            vFile, "No stub serializer: " + vFile.getPresentableUrl() + ": " + e.getMessage(), e);
      }
      ObjectStubTree tree =
          stub instanceof PsiFileStub
              ? new StubTree((PsiFileStub) stub)
              : new ObjectStubTree((ObjectStubBase) stub, true);
      tree.setDebugInfo(
          "created from index: "
              + StubUpdatingIndex.getIndexingStampInfo(vFile)
              + ", wasIndexedAlready="
              + wasIndexedAlready
              + ", queried at "
              + vFile.getTimeStamp());
      return tree;
    } else if (size != 0) {
      return processError(
          vFile,
          "Twin stubs: "
              + vFile.getPresentableUrl()
              + " has "
              + size
              + " stub versions. Should only have one. id="
              + id,
          null);
    }

    return null;
  }
 @Override
 public void onSuccess() {
   DumbService.getInstance(getProject())
       .runWhenSmart(
           new Runnable() {
             @Override
             public void run() {
               onFound();
               finish();
               startListening();
             }
           });
 }
 private void addAlarmRequest() {
   Runnable request =
       () -> {
         if (!myDisposed && !myProject.isDisposed()) {
           PsiDocumentManager.getInstance(myProject)
               .performLaterWhenAllCommitted(
                   () ->
                       DumbService.getInstance(myProject)
                           .withAlternativeResolveEnabled(this::updateComponent));
         }
       };
   myAlarm.addRequest(request, DELAY, ModalityState.stateForComponent(myEditor.getComponent()));
 }
  void duringCompletion(CompletionInitializationContext initContext) {
    if (isAutopopupCompletion()) {
      if (shouldFocusLookup(myParameters)) {
        myLookup.setFocused(true);
      } else if (FeatureUsageTracker.getInstance()
          .isToBeAdvertisedInLookup(
              CodeCompletionFeatures.EDITING_COMPLETION_CONTROL_ENTER, getProject())) {
        myLookup.addAdvertisement(
            "Press "
                + CompletionContributor.getActionShortcut(
                    IdeActions.ACTION_CHOOSE_LOOKUP_ITEM_ALWAYS)
                + " to choose the first suggestion");
      }
      if (!myEditor.isOneLineMode()
          && FeatureUsageTracker.getInstance()
              .isToBeAdvertisedInLookup(
                  CodeCompletionFeatures.EDITING_COMPLETION_CONTROL_ARROWS, getProject())) {
        myLookup.addAdvertisement(
            CompletionContributor.getActionShortcut(IdeActions.ACTION_LOOKUP_DOWN)
                + " and "
                + CompletionContributor.getActionShortcut(IdeActions.ACTION_LOOKUP_UP)
                + " will move caret down and up in the editor");
      }
    }

    ProgressManager.checkCanceled();

    if (!initContext
        .getOffsetMap()
        .wasModified(CompletionInitializationContext.IDENTIFIER_END_OFFSET)) {
      try {
        final int selectionEndOffset = initContext.getSelectionEndOffset();
        final PsiReference reference = initContext.getFile().findReferenceAt(selectionEndOffset);
        if (reference != null) {
          initContext.setReplacementOffset(findReplacementOffset(selectionEndOffset, reference));
        }
      } catch (IndexNotReadyException ignored) {
      }
    }

    for (CompletionContributor contributor :
        CompletionContributor.forLanguage(initContext.getPositionLanguage())) {
      ProgressManager.checkCanceled();
      if (DumbService.getInstance(initContext.getProject()).isDumb()
          && !DumbService.isDumbAware(contributor)) {
        continue;
      }

      contributor.duringCompletion(initContext);
    }
  }
  @Override
  public void invoke(@NotNull Project project, @NotNull Editor editor, @NotNull PsiFile file) {
    FeatureUsageTracker.getInstance().triggerFeatureUsed(getFeatureUsedKey());

    try {
      GotoData gotoData = getSourceAndTargetElements(editor, file);
      if (gotoData != null) {
        show(project, editor, file, gotoData);
      }
    } catch (IndexNotReadyException e) {
      DumbService.getInstance(project)
          .showDumbModeNotification("Navigation is not available here during index update");
    }
  }
Example #24
0
 private void _updateFilters() {
   try {
     updateFilters();
   } catch (ProcessCanceledException e) {
     DumbService.getInstance(myProject)
         .smartInvokeLater(
             new Runnable() {
               public void run() {
                 _updateFilters();
               }
             },
             ModalityState.NON_MODAL);
   }
 }
Example #25
0
 public static void runDumbAware(final Project project, final Runnable r) {
   if (DumbService.isDumbAware(r)) {
     r.run();
   } else {
     DumbService.getInstance(project)
         .runWhenSmart(
             new Runnable() {
               public void run() {
                 if (project.isDisposed()) return;
                 r.run();
               }
             });
   }
 }
 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 static HighlightVisitor[] filterVisitors(
      HighlightVisitor[] highlightVisitors, final PsiFile file) {
    final List<HighlightVisitor> visitors =
        new ArrayList<HighlightVisitor>(highlightVisitors.length);
    List<HighlightVisitor> list = Arrays.asList(highlightVisitors);
    for (HighlightVisitor visitor :
        DumbService.getInstance(file.getProject()).filterByDumbAwareness(list)) {
      if (visitor.suitableForFile(file)) visitors.add(visitor);
    }
    LOG.assertTrue(!visitors.isEmpty(), list);

    HighlightVisitor[] visitorArray = visitors.toArray(new HighlightVisitor[visitors.size()]);
    Arrays.sort(visitorArray, VISITOR_ORDER_COMPARATOR);
    return visitorArray;
  }
Example #28
0
  public static FoldingDescriptor[] buildFoldingDescriptors(
      FoldingBuilder builder, PsiElement root, Document document, boolean quick) {
    if (!(builder instanceof DumbAware) && DumbService.getInstance(root.getProject()).isDumb()) {
      return FoldingDescriptor.EMPTY;
    }

    if (builder instanceof FoldingBuilderEx) {
      return ((FoldingBuilderEx) builder).buildFoldRegions(root, document, quick);
    }
    final ASTNode astNode = root.getNode();
    if (astNode == null) {
      return FoldingDescriptor.EMPTY;
    }

    return builder.buildFoldRegions(astNode, document);
  }
  protected boolean isAvailable(final DataContext dataContext) {
    final Project project = CommonDataKeys.PROJECT.getData(dataContext);
    if (project == null) {
      return false;
    }

    if (DumbService.getInstance(project).isDumb() && !isDumbAware()) {
      return false;
    }

    final IdeView view = LangDataKeys.IDE_VIEW.getData(dataContext);
    if (view == null || view.getDirectories().length == 0) {
      return false;
    }

    return true;
  }
 private void perform(List<DependenciesBuilder> builders) {
   try {
     PerformanceWatcher.Snapshot snapshot = PerformanceWatcher.takeSnapshot();
     for (AnalysisScope scope : myScopes) {
       builders.add(createDependenciesBuilder(scope));
     }
     for (DependenciesBuilder builder : builders) {
       builder.analyze();
     }
     snapshot.logResponsivenessSinceCreation("Dependency analysis");
   } catch (IndexNotReadyException e) {
     DumbService.getInstance(myProject)
         .showDumbModeNotification(
             "Analyze dependencies is not available until indices are ready");
     throw new ProcessCanceledException();
   }
 }