com.intellij.openapi.project.DumbService Java Examples

The following examples show how to use com.intellij.openapi.project.DumbService. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: HaxeComponentFileNameIndex.java    From intellij-haxe with Apache License 2.0 6 votes vote down vote up
@NotNull
public static List<VirtualFile> getFilesNameByQName(@NotNull String qName, @NotNull final GlobalSearchScope filter) {

  Project project = filter.getProject();
  if (project != null) {
    if (DumbService.isDumb(project)) {
      return DUMB_MODE_LIST;
    }
  }

  final List<VirtualFile> result = new ArrayList<VirtualFile>();
  getFileNames(qName, new Processor<VirtualFile>() {
    @Override
    public boolean process(VirtualFile file) {
      result.add(file);
      return true;
    }
  }, filter);
  return result;
}
 
Example #2
Source File: ContextTypeProvider.java    From idea-php-typo3-plugin with MIT License 6 votes vote down vote up
@Nullable
@Override
public PhpType getType(PsiElement psiElement) {
    if (DumbService.getInstance(psiElement.getProject()).isDumb() || !TYPO3CMSProjectSettings.isEnabled(psiElement)) {
        return null;
    }

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

    MethodReference methodReference = (MethodReference) psiElement;
    if (methodReference.getParameters().length == 0) {
        return null;
    }

    PsiElement firstParam = methodReference.getParameters()[0];
    if (firstParam instanceof StringLiteralExpression) {
        StringLiteralExpression contextAlias = (StringLiteralExpression) firstParam;
        if (!contextAlias.getContents().isEmpty()) {
            return new PhpType().add("#" + this.getKey() + contextAlias.getContents());
        }
    }

    return null;
}
 
Example #3
Source File: ParameterInfoController.java    From consulo with Apache License 2.0 6 votes vote down vote up
private void executeUpdateParameterInfo(PsiElement elementForUpdating, MyUpdateParameterInfoContext context, Runnable continuation) {
  PsiElement parameterOwner = context.getParameterOwner();
  if (parameterOwner != null && !parameterOwner.equals(elementForUpdating)) {
    context.removeHint();
    return;
  }

  runTask(myProject, ReadAction.nonBlocking(() -> {
    try {
      myHandler.updateParameterInfo(elementForUpdating, context);
      return elementForUpdating;
    }
    catch (IndexNotReadyException e) {
      DumbService.getInstance(myProject).showDumbModeNotification(CodeInsightBundle.message("parameter.info.indexing.mode.not.supported"));
    }
    return null;
  }).withDocumentsCommitted(myProject).expireWhen(() -> !myKeepOnHintHidden && !myHint.isVisible() && !ApplicationManager.getApplication().isHeadlessEnvironment() ||
                                                        getCurrentOffset() != context.getOffset() ||
                                                        !elementForUpdating.isValid()).expireWith(this), element -> {
    if (element != null && continuation != null) {
      context.applyUIChanges();
      continuation.run();
    }
  }, null, myEditor);
}
 
Example #4
Source File: GeneralHighlightingPass.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Nonnull
private HighlightVisitor[] filterVisitors(@Nonnull HighlightVisitor[] highlightVisitors, @Nonnull PsiFile psiFile) {
  final List<HighlightVisitor> visitors = new ArrayList<>(highlightVisitors.length);
  List<HighlightVisitor> list = Arrays.asList(highlightVisitors);
  for (HighlightVisitor visitor : DumbService.getInstance(myProject).filterByDumbAwareness(list)) {
    if (visitor instanceof RainbowVisitor && !RainbowHighlighter.isRainbowEnabledWithInheritance(getColorsScheme(), psiFile.getLanguage())) {
      continue;
    }
    if (visitor.suitableForFile(psiFile)) {
      visitors.add(visitor);
    }
  }
  if (visitors.isEmpty()) {
    LOG.error("No visitors registered. list=" + list + "; all visitors are:" + Arrays.asList(HighlightVisitor.EP_HIGHLIGHT_VISITOR.getExtensions(myProject)));
  }

  return visitors.toArray(new HighlightVisitor[0]);
}
 
Example #5
Source File: TextEditorHighlightingPass.java    From consulo with Apache License 2.0 6 votes vote down vote up
protected boolean isValid() {
  if (isDumbMode() && !DumbService.isDumbAware(this)) {
    return false;
  }

  if (PsiModificationTracker.SERVICE.getInstance(myProject).getModificationCount() != myInitialPsiStamp) {
    return false;
  }

  if (myDocument != null) {
    if (myDocument.getModificationStamp() != myInitialDocStamp) return false;
    PsiFile file = PsiDocumentManager.getInstance(myProject).getPsiFile(myDocument);
    return file != null && file.isValid();
  }

  return true;
}
 
Example #6
Source File: CSharpTypeRefByQName.java    From consulo-csharp with Apache License 2.0 6 votes vote down vote up
@RequiredReadAction
@Nonnull
@Override
protected DotNetTypeResolveResult resolveResult()
{
	if(DumbService.isDumb(getProject()))
	{
		return DotNetTypeResolveResult.EMPTY;
	}

	DotNetTypeDeclaration type = DotNetPsiSearcher.getInstance(getProject()).findType(myQualifiedName, mySearchScope, CSharpTransform.INSTANCE);

	if(type == null)
	{
		return DotNetTypeResolveResult.EMPTY;
	}

	return new CSharpUserTypeRef.Result<>(type, DotNetGenericExtractor.EMPTY);
}
 
Example #7
Source File: GenerateAction.java    From consulo with Apache License 2.0 6 votes vote down vote up
private static DefaultActionGroup wrapGroup(DefaultActionGroup actionGroup, DataContext dataContext, @Nonnull Project project) {
  final DefaultActionGroup copy = new DefaultActionGroup();
  for (final AnAction action : actionGroup.getChildren(null)) {
    if (DumbService.isDumb(project) && !action.isDumbAware()) {
      continue;
    }

    if (action instanceof GenerateActionPopupTemplateInjector) {
      final AnAction editTemplateAction = ((GenerateActionPopupTemplateInjector)action).createEditTemplateAction(dataContext);
      if (editTemplateAction != null) {
        copy.add(new GenerateWrappingGroup(action, editTemplateAction));
        continue;
      }
    }
    if (action instanceof DefaultActionGroup) {
      copy.add(wrapGroup((DefaultActionGroup)action, dataContext, project));
    }
    else {
      copy.add(action);
    }
  }
  return copy;
}
 
Example #8
Source File: ORProjectRootListener.java    From reasonml-idea-plugin with MIT License 6 votes vote down vote up
private ORProjectRootListener(@NotNull Project project) {
    project.getMessageBus().
            connect(project).
            subscribe(PROJECT_ROOTS, new ModuleRootListener() {
                @Override
                public void rootsChanged(@NotNull ModuleRootEvent event) {
                    DumbService.getInstance(project).queueTask(new DumbModeTask() {
                        @Override
                        public void performInDumbMode(@NotNull ProgressIndicator indicator) {
                            if (!project.isDisposed()) {
                                indicator.setText("Updating resource repository roots");
                                // should be done per module
                                //ModuleManager moduleManager = ModuleManager.getInstance(project);
                                //for (Module module : moduleManager.getModules()) {
                                //    moduleRootsOrDependenciesChanged(module);
                                //}
                                Sdk projectSdk = ProjectRootManager.getInstance(project).getProjectSdk();
                                if (projectSdk != null && projectSdk.getSdkType() instanceof OCamlSdkType) {
                                    OCamlSdkType.reindexSourceRoots(projectSdk);
                                }
                            }
                        }
                    });
                }
            });
}
 
Example #9
Source File: AnalysisScope.java    From consulo with Apache License 2.0 6 votes vote down vote up
private static void commitAndRunInSmartMode(final Runnable runnable, final Project project) {
  while (true) {
    final DumbService dumbService = DumbService.getInstance(project);
    dumbService.waitForSmartMode();
    boolean passed = PsiDocumentManager.getInstance(project).commitAndRunReadAction(new Computable<Boolean>() {
      @Override
      public Boolean compute() {
        if (dumbService.isDumb()) return false;
        runnable.run();
        return true;
      }
    });
    if (passed) {
      break;
    }
  }
}
 
Example #10
Source File: DefaultHighlightVisitor.java    From consulo with Apache License 2.0 6 votes vote down vote up
private void runAnnotators(PsiElement element) {
  List<Annotator> annotators = myCachedAnnotators.get(element.getLanguage().getID());
  if (annotators.isEmpty()) return;
  final boolean dumb = myDumbService.isDumb();

  //noinspection ForLoopReplaceableByForEach
  for (int i = 0; i < annotators.size(); i++) {
    Annotator annotator = annotators.get(i);
    if (dumb && !DumbService.isDumbAware(annotator)) {
      continue;
    }

    ProgressManager.checkCanceled();

    annotator.annotate(element, myAnnotationHolder);
  }
}
 
Example #11
Source File: GraphQLSchemasRootNode.java    From js-graphql-intellij-plugin with MIT License 6 votes vote down vote up
@NotNull
@Override
public SimpleNode[] getChildren() {
    try {
        if (DumbService.getInstance(myProject).isDumb() || !configManager.isInitialized()) {
            // empty the tree view during indexing and until the config has been initialized
            return SimpleNode.NO_CHILDREN;
        }
        final List<SimpleNode> children = Lists.newArrayList();
        for (Map.Entry<VirtualFile, GraphQLConfigData> entry : configManager.getConfigurationsByPath().entrySet()) {
            children.add(new GraphQLConfigSchemaNode(myProject, this, configManager, entry.getValue(), entry.getKey()));
        }
        if (children.isEmpty()) {
            children.add(new GraphQLDefaultSchemaNode(myProject, this));
        }
        children.sort(Comparator.comparing(PresentableNodeDescriptor::getName));
        return children.toArray(SimpleNode.NO_CHILDREN);
    } catch (IndexNotReadyException e) {
        return SimpleNode.NO_CHILDREN;
    }
}
 
Example #12
Source File: GeneratedFilesListener.java    From litho with Apache License 2.0 6 votes vote down vote up
@Override
public void after(List<? extends VFileEvent> events) {
  IntervalLogger logger = new IntervalLogger(LOG);

  final boolean found =
      events.stream()
          .filter(VFileCreateEvent.class::isInstance)
          .map(VFileEvent::getFile)
          .filter(file -> file != null && file.isValid())
          .map(file -> FileUtil.toSystemIndependentName(file.getPath()))
          .anyMatch(GeneratedFilesListener::isOutput);
  logger.logStep("finding created paths: " + found);
  if (!found) return;

  // Wait for indexing
  final Runnable job =
      () -> {
        logger.logStep("start of removing files");
        ComponentsCacheService.getInstance(project).invalidate();
      };
  if (ApplicationManager.getApplication().isUnitTestMode()) {
    job.run();
  } else {
    DumbService.getInstance(project).smartInvokeLater(job);
  }
}
 
Example #13
Source File: GotoClassAction.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Override
public void actionPerformed(@Nonnull AnActionEvent e) {
  Project project = e.getProject();
  if (project == null) return;

  boolean dumb = DumbService.isDumb(project);
  if (Registry.is("new.search.everywhere")) {
    if (!dumb || new ClassSearchEverywhereContributor(project, null).isDumbAware()) {
      showInSearchEverywherePopup(ClassSearchEverywhereContributor.class.getSimpleName(), e, true, true);
    }
    else {
      invokeGoToFile(project, e);
    }
  }
  else {
    if (!dumb) {
      super.actionPerformed(e);
    }
    else {
      invokeGoToFile(project, e);
    }
  }
}
 
Example #14
Source File: IntelliJIDEA.java    From intellijcoder with MIT License 6 votes vote down vote up
public void createModule(final String moduleName, final String className, final String classSource, final String testSource, final String htmlSource, final int memLimit) {
    //We run it in the event thread, so the DataContext would have current Project data;
    DumbService.getInstance(project).smartInvokeLater(new Runnable() {
        public void run() {
            ApplicationManager.getApplication().runWriteAction(new Runnable() {
                public void run() {
                    try {
                        IntelliJIDEA.this.createModule(getCurrentProject(), moduleName, className, classSource, testSource, htmlSource, memLimit);
                    } catch (IntelliJCoderException e) {
                        showErrorMessage("Failed to create problem workspace. " + e.getMessage());
                    }
                }
            });
        }
    });
}
 
Example #15
Source File: CopyPasteDelegator.java    From consulo with Apache License 2.0 6 votes vote down vote up
private boolean performDefaultPaste(final DataContext dataContext) {
  final boolean[] isCopied = new boolean[1];
  final PsiElement[] elements = PsiCopyPasteManager.getInstance().getElements(isCopied);
  if (elements == null) return false;

  DumbService.getInstance(myProject).setAlternativeResolveEnabled(true);
  try {
    final Module module = dataContext.getData(LangDataKeys.MODULE);
    PsiElement target = getPasteTarget(dataContext, module);
    if (isCopied[0]) {
      TransactionGuard.getInstance().submitTransactionAndWait(() -> pasteAfterCopy(elements, module, target, true));
    }
    else if (MoveHandler.canMove(elements, target)) {
      TransactionGuard.getInstance().submitTransactionAndWait(() -> pasteAfterCut(dataContext, elements, target));
    }
    else {
      return false;
    }
  }
  finally {
    DumbService.getInstance(myProject).setAlternativeResolveEnabled(false);
    updateView();
  }
  return true;
}
 
Example #16
Source File: GotoSymbolAction.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Override
public void actionPerformed(@Nonnull AnActionEvent e) {
  Project project = e.getProject();
  if (project == null) return;

  boolean dumb = DumbService.isDumb(project);
  if (Registry.is("new.search.everywhere")) {
    if (!dumb || new SymbolSearchEverywhereContributor(project, null).isDumbAware()) {
      showInSearchEverywherePopup(SymbolSearchEverywhereContributor.class.getSimpleName(), e, true, true);
    }
    else {
      GotoClassAction.invokeGoToFile(project, e);
    }
  }
  else {
    if (!dumb) {
      super.actionPerformed(e);
    }
    else {
      GotoClassAction.invokeGoToFile(project, e);
    }
  }
}
 
Example #17
Source File: ActionUtil.java    From consulo with Apache License 2.0 6 votes vote down vote up
public static void showDumbModeWarning(@Nonnull AnActionEvent... events) {
  Project project = null;
  List<String> actionNames = new ArrayList<>();
  for (final AnActionEvent event : events) {
    final String s = event.getPresentation().getText();
    if (StringUtil.isNotEmpty(s)) {
      actionNames.add(s);
    }

    final Project _project = event.getProject();
    if (_project != null && project == null) {
      project = _project;
    }
  }

  if (project == null) {
    return;
  }

  DumbService.getInstance(project).showDumbModeNotification(getActionUnavailableMessage(actionNames));
}
 
Example #18
Source File: ShowAutoImportPass.java    From consulo with Apache License 2.0 6 votes vote down vote up
private void showImports() {
  Application application = ApplicationManager.getApplication();
  application.assertIsDispatchThread();
  if (!application.isHeadlessEnvironment() && !myEditor.getContentComponent().hasFocus()) return;
  if (DumbService.isDumb(myProject) || !myFile.isValid()) return;
  if (myEditor.isDisposed() || myEditor instanceof EditorWindow && !((EditorWindow)myEditor).isValid()) return;

  int caretOffset = myEditor.getCaretModel().getOffset();
  importUnambiguousImports(caretOffset);
  List<HighlightInfo> visibleHighlights = getVisibleHighlights(myStartOffset, myEndOffset, myProject, myEditor, hasDirtyTextRange);

  for (int i = visibleHighlights.size() - 1; i >= 0; i--) {
    HighlightInfo info = visibleHighlights.get(i);
    if (info.startOffset <= caretOffset && showAddImportHint(info)) return;
  }

  for (HighlightInfo visibleHighlight : visibleHighlights) {
    if (visibleHighlight.startOffset > caretOffset && showAddImportHint(visibleHighlight)) return;
  }
}
 
Example #19
Source File: MuleSdk.java    From mule-intellij-plugins with Apache License 2.0 6 votes vote down vote up
@Nullable
private static String getMuleHome(@NotNull Module module) {
    if (!DumbService.isDumb(module.getProject())) {
        final OrderEnumerator enumerator = ModuleRootManager.getInstance(module)
                .orderEntries().recursively().librariesOnly().exportedOnly();
        final String[] home = new String[1];
        enumerator.forEachLibrary(library -> {
            if (MuleLibraryKind.MULE_LIBRARY_KIND.equals(((LibraryEx) library).getKind()) &&
                    library.getFiles(OrderRootType.CLASSES) != null &&
                    library.getFiles(OrderRootType.CLASSES).length > 0) {
                home[0] = getMuleHome(library.getFiles(OrderRootType.CLASSES)[0]);
                return false;
            } else {
                return true;
            }
        });

        return home[0];
    }
    return null;
}
 
Example #20
Source File: AndroidModuleLibraryManager.java    From flutter-intellij with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
private void scheduleUpdate() {
  if (isUpdating.get()) {
    return;
  }

  final Runnable runnable = this::updateAndroidLibraries;
  DumbService.getInstance(getProject()).smartInvokeLater(runnable, ModalityState.NON_MODAL);
}
 
Example #21
Source File: RailwaysUtils.java    From railways with MIT License 5 votes vote down vote up
public static void updateActionsStatus(Module module, RouteList routeList) {
    RailsApp app = RailsApp.fromModule(module);
    if ((app == null) || (DumbService.isDumb(module.getProject())))
        return;

    // TODO: investigate multiple calls of this method when switching focus from code to tool window without any changes.

    for (Route route: routeList)
        route.updateActionStatus(app);
}
 
Example #22
Source File: IgnoreManager.java    From idea-gitignore with MIT License 5 votes vote down vote up
/** Enable manager. */
private void enable() {
    if (working) {
        return;
    }

    refreshTrackedIgnoredFeature.run();
    virtualFileManager.addVirtualFileListener(virtualFileListener);
    settings.addListener(settingsListener);

    messageBus = project.getMessageBus().connect();

    messageBus.subscribe(TRACKED_IGNORED_REFRESH, () -> debouncedRefreshTrackedIgnores.run(true));

    messageBus.subscribe(ProjectLevelVcsManager.VCS_CONFIGURATION_CHANGED, () -> {
        ExternalIndexableSetContributor.invalidateCache(project);
        vcsRoots.clear();
        vcsRoots.addAll(ContainerUtil.newArrayList(projectLevelVcsManager.getAllVcsRoots()));
    });

    messageBus.subscribe(DumbService.DUMB_MODE, new DumbService.DumbModeListener() {
        @Override
        public void enteredDumbMode() {
        }

        @Override
        public void exitDumbMode() {
            debouncedExitDumbMode.run();
        }
    });

    messageBus.subscribe(ProjectTopics.PROJECT_ROOTS, commonRunnableListeners);
    messageBus.subscribe(RefreshStatusesListener.REFRESH_STATUSES, commonRunnableListeners);
    messageBus.subscribe(ProjectTopics.MODULES, commonRunnableListeners);

    working = true;
}
 
Example #23
Source File: ExtensionProviderUtil.java    From idea-php-toolbox with MIT License 5 votes vote down vote up
synchronized public static Collection<JsonConfigFile> getJsonConfigs(final @NotNull Project project, final @NotNull PhpToolboxApplicationService phpToolboxApplicationService) {
    CachedValue<Collection<JsonConfigFile>> cache = project.getUserData(CONFIGS_CACHE);

    if(cache == null) {
        cache = CachedValuesManager.getManager(project).createCachedValue(() -> CachedValueProvider.Result.create(getJsonConfigsInner(project, phpToolboxApplicationService), PsiModificationTracker.MODIFICATION_COUNT), false);
        project.putUserData(CONFIGS_CACHE, cache);
    }

    Collection<JsonConfigFile> jsonConfigFiles = new ArrayList<>(cache.getValue());

    // prevent reindex issues
    if (!DumbService.getInstance(project).isDumb()) {
        CachedValue<Collection<JsonConfigFile>> indexCache = project.getUserData(CONFIGS_CACHE_INDEX);

        if (indexCache == null) {
            indexCache = CachedValuesManager.getManager(project).createCachedValue(() -> {
                Collection<JsonConfigFile> jsonConfigFiles1 = new ArrayList<>();

                for (final PsiFile psiFile : FilenameIndex.getFilesByName(project, ".ide-toolbox.metadata.json", GlobalSearchScope.allScope(project))) {
                    JsonConfigFile cachedValue = CachedValuesManager.getCachedValue(psiFile, () -> new CachedValueProvider.Result<>(
                        JsonParseUtil.getDeserializeConfig(psiFile.getText()),
                        psiFile,
                        psiFile.getVirtualFile()
                    ));

                    if(cachedValue != null) {
                        jsonConfigFiles1.add(cachedValue);
                    }
                }

                return CachedValueProvider.Result.create(jsonConfigFiles1, PsiModificationTracker.MODIFICATION_COUNT);
            }, false);
        }

        project.putUserData(CONFIGS_CACHE_INDEX, indexCache);
        jsonConfigFiles.addAll(indexCache.getValue());
    }

    return jsonConfigFiles;
}
 
Example #24
Source File: FlutterPerformanceViewFactory.java    From flutter-intellij with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override
public void createToolWindowContent(@NotNull Project project, @NotNull ToolWindow toolWindow) {
  //noinspection CodeBlock2Expr
  DumbService.getInstance(project).runWhenSmart(() -> {
    (ServiceManager.getService(project, FlutterPerformanceView.class)).initToolWindow(toolWindow);
  });
}
 
Example #25
Source File: FlutterViewFactory.java    From flutter-intellij with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override
public void createToolWindowContent(@NotNull Project project, @NotNull ToolWindow toolWindow) {
  //noinspection CodeBlock2Expr
  DumbService.getInstance(project).runWhenSmart(() -> {
    (ServiceManager.getService(project, FlutterView.class)).initToolWindow(toolWindow);
  });
}
 
Example #26
Source File: OttoProjectHandler.java    From otto-intellij-plugin with Apache License 2.0 5 votes vote down vote up
@Override public void projectOpened() {
  DumbService.getInstance(myProject).smartInvokeLater(
      new Runnable() {
        @Override public void run() {
          if (myProject.isInitialized()) {
            findEventsViaMethodsAnnotatedSubscribe();

            psiManager.addPsiTreeChangeListener(listener = new MyPsiTreeChangeAdapter());
          }
        }
      }
  );
}
 
Example #27
Source File: MoveFilesOrDirectoriesUtil.java    From consulo with Apache License 2.0 5 votes vote down vote up
/**
 * Moves the specified directory to the specified parent directory. Does not process non-code usages!
 *
 * @param aDirectory          the directory to move.
 * @param destDirectory the directory to move {@code dir} into.
 * @throws IncorrectOperationException if the modification is not supported or not possible for some reason.
 */
public static void doMoveDirectory(final PsiDirectory aDirectory, final PsiDirectory destDirectory) throws IncorrectOperationException {
  PsiManager manager = aDirectory.getManager();
  // do actual move
  checkMove(aDirectory, destDirectory);

  try {
    aDirectory.getVirtualFile().move(manager, destDirectory.getVirtualFile());
  }
  catch (IOException e) {
    throw new IncorrectOperationException(e);
  }
  DumbService.getInstance(manager.getProject()).completeJustSubmittedTasks();
}
 
Example #28
Source File: AndroidModuleLibraryManager.java    From flutter-intellij with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
private void scheduleUpdate() {
  if (isUpdating.get()) {
    return;
  }

  final Runnable runnable = this::updateAndroidLibraries;
  DumbService.getInstance(getProject()).smartInvokeLater(runnable, ModalityState.NON_MODAL);
}
 
Example #29
Source File: CoreProjectEnvironment.java    From consulo with Apache License 2.0 5 votes vote down vote up
public CoreProjectEnvironment(Disposable parentDisposable, CoreApplicationEnvironment applicationEnvironment) {
  myParentDisposable = parentDisposable;
  myEnvironment = applicationEnvironment;
  myProject = new MockProject(myEnvironment.getApplication(), myParentDisposable);

  preregisterServices();

  myFileIndexFacade = createFileIndexFacade();
  myMessageBus = (MessageBusImpl)myProject.getMessageBus();

  PsiModificationTrackerImpl modificationTracker = new PsiModificationTrackerImpl(applicationEnvironment.getApplication(), myProject);
  myProject.registerService(PsiModificationTracker.class, modificationTracker);
  myProject.registerService(FileIndexFacade.class, myFileIndexFacade);
  myProject.registerService(ResolveCache.class, new ResolveCache(myProject));

  registerProjectExtensionPoint(PsiTreeChangePreprocessor.EP_NAME, PsiTreeChangePreprocessor.class);
  myPsiManager = new PsiManagerImpl(myProject, () -> myFileIndexFacade, modificationTracker);
  ((FileManagerImpl)myPsiManager.getFileManager()).markInitialized();
  registerProjectComponent(PsiManager.class, myPsiManager);

  registerProjectComponent(PsiDocumentManager.class, new CorePsiDocumentManager(myProject, new MockDocumentCommitProcessor()));

  myProject.registerService(ResolveScopeManager.class, createResolveScopeManager(myPsiManager));

  myProject.registerService(PsiFileFactory.class, new PsiFileFactoryImpl(myPsiManager));
  myProject.registerService(CachedValuesManager.class, new CachedValuesManagerImpl(myProject, new PsiCachedValuesFactory(myPsiManager)));
  myProject.registerService(ProjectScopeBuilder.class, createProjectScopeBuilder());
  myProject.registerService(DumbService.class, new MockDumbService(myProject));
}
 
Example #30
Source File: CodeFoldingManagerImpl.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Nullable
@Override
public CodeFoldingState buildInitialFoldings(@Nonnull final Document document) {
  if (myProject.isDisposed()) {
    return null;
  }
  ApplicationManager.getApplication().assertReadAccessAllowed();
  PsiDocumentManager psiDocumentManager = PsiDocumentManager.getInstance(myProject);
  if (psiDocumentManager.isUncommited(document)) {
    // skip building foldings for uncommitted document, CodeFoldingPass invoked by daemon will do it later
    return null;
  }
  //Do not save/restore folding for code fragments
  final PsiFile file = psiDocumentManager.getPsiFile(document);
  if (file == null || !file.isValid() || !file.getViewProvider().isPhysical() && !ApplicationManager.getApplication().isUnitTestMode()) {
    return null;
  }


  final List<FoldingUpdate.RegionInfo> regionInfos = FoldingUpdate.getFoldingsFor(file, document, true);

  return editor -> {
    ApplicationManager.getApplication().assertIsDispatchThread();
    if (myProject.isDisposed() || editor.isDisposed()) return;
    final FoldingModelEx foldingModel = (FoldingModelEx)editor.getFoldingModel();
    if (!foldingModel.isFoldingEnabled()) return;
    if (isFoldingsInitializedInEditor(editor)) return;
    if (DumbService.isDumb(myProject) && !FoldingUpdate.supportsDumbModeFolding(editor)) return;

    foldingModel.runBatchFoldingOperationDoNotCollapseCaret(new UpdateFoldRegionsOperation(myProject, editor, file, regionInfos, UpdateFoldRegionsOperation.ApplyDefaultStateMode.YES, false, false));
    initFolding(editor);
  };
}