Java Code Examples for consulo.application.AccessRule#read()

The following examples show how to use consulo.application.AccessRule#read() . 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: ArtifactCompilerUtil.java    From consulo with Apache License 2.0 8 votes vote down vote up
public static MultiMap<String, Artifact> createOutputToArtifactMap(final Project project) {
  final MultiMap<String, Artifact> result = new MultiMap<String, Artifact>() {
    @Nonnull
    @Override
    protected Map<String, Collection<Artifact>> createMap() {
      return new THashMap<String, Collection<Artifact>>(FileUtil.PATH_HASHING_STRATEGY);
    }
  };
  AccessRule.read(() -> {
    for (Artifact artifact : ArtifactManager.getInstance(project).getArtifacts()) {
      String outputPath = artifact.getOutputFilePath();
      if (!StringUtil.isEmpty(outputPath)) {
        result.putValue(outputPath, artifact);
      }
    }
  });
  return result;
}
 
Example 2
Source File: ChangesUtil.java    From consulo with Apache License 2.0 6 votes vote down vote up
public static FilePath getLocalPath(@Nonnull Project project, FilePath filePath) {
  // check if the file has just been renamed (IDEADEV-15494)
  ThrowableComputable<Change, RuntimeException> action = () -> {
    if (project.isDisposed()) throw new ProcessCanceledException();
    return ChangeListManager.getInstance(project).getChange(filePath);
  };
  Change change = AccessRule.read(action);
  if (change != null) {
    ContentRevision beforeRevision = change.getBeforeRevision();
    ContentRevision afterRevision = change.getAfterRevision();
    if (beforeRevision != null && afterRevision != null && !beforeRevision.getFile().equals(afterRevision.getFile()) &&
        beforeRevision.getFile().equals(filePath)) {
      return afterRevision.getFile();
    }
  }
  return filePath;
}
 
Example 3
Source File: XDebugSessionImpl.java    From consulo with Apache License 2.0 6 votes vote down vote up
private <B extends XBreakpoint<?>> void handleBreakpoint(final XBreakpointHandler<B> handler, final B b, final boolean register,
                                                         final boolean temporary) {
  if (register) {
    ThrowableComputable<Boolean,RuntimeException> action = () -> isBreakpointActive(b);
    boolean active = AccessRule.read(action);
    if (active) {
      synchronized (myRegisteredBreakpoints) {
        myRegisteredBreakpoints.put(b, new CustomizedBreakpointPresentation());
      }
      handler.registerBreakpoint(b);
    }
  }
  else {
    boolean removed;
    synchronized (myRegisteredBreakpoints) {
      removed = myRegisteredBreakpoints.remove(b) != null;
    }
    if (removed) {
      handler.unregisterBreakpoint(b, temporary);
    }
  }
}
 
Example 4
Source File: ShowImplementationsAction.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Nonnull
static PsiElement[] getSelfAndImplementations(Editor editor, @Nonnull PsiElement element, @Nonnull ImplementationSearcher handler, final boolean includeSelfAlways) {
  final PsiElement[] handlerImplementations = handler.searchImplementations(element, editor, includeSelfAlways, true);
  if (handlerImplementations.length > 0) return handlerImplementations;

  ThrowableComputable<PsiElement[], RuntimeException> action = () -> {
    PsiElement psiElement = element;
    PsiFile psiFile = psiElement.getContainingFile();
    if (psiFile == null) {
      // Magically, it's null for ant property declarations.
      psiElement = psiElement.getNavigationElement();
      psiFile = psiElement.getContainingFile();
      if (psiFile == null) {
        return PsiElement.EMPTY_ARRAY;
      }
    }
    if (psiFile.getVirtualFile() != null && (psiElement.getTextRange() != null || psiElement instanceof PsiFile)) {
      return new PsiElement[]{psiElement};
    }
    return PsiElement.EMPTY_ARRAY;
  };
  return AccessRule.read(action);
}
 
Example 5
Source File: ProjectStructureDaemonAnalyzer.java    From consulo with Apache License 2.0 6 votes vote down vote up
private void doCheck(final ProjectStructureElement element) {
  final ProjectStructureProblemsHolderImpl problemsHolder = new ProjectStructureProblemsHolderImpl();
  AccessRule.read(() -> {
    if (myStopped.get()) return;

    if (LOG.isDebugEnabled()) {
      LOG.debug("checking " + element);
    }
    ProjectStructureValidator.check(element, problemsHolder);
  });

  invokeLater(new Runnable() {
    @Override
    public void run() {
      if (myStopped.get()) return;

      if (LOG.isDebugEnabled()) {
        LOG.debug("updating problems for " + element);
      }
      final ProjectStructureProblemDescription warning = myWarningsAboutUnused.get(element);
      if (warning != null) problemsHolder.registerProblem(warning);
      myProblemHolders.put(element, problemsHolder);
      myDispatcher.getMulticaster().problemsChanged(element);
    }
  });
}
 
Example 6
Source File: LazyPatchContentRevision.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Override
public String getContent() {
  if (myContent == null) {
    String localContext = AccessRule.read(() -> {
      final Document doc = FileDocumentManager.getInstance().getDocument(myVf);
      if(doc == null) {
        return null;
      }

      return doc.getText();
    });

    if (localContext == null) {
      myPatchApplyFailed = true;
      return null;
    }

    final GenericPatchApplier applier = new GenericPatchApplier(localContext, myPatch.getHunks());
    if (applier.execute()) {
      myContent = applier.getAfter();
    } else {
      myPatchApplyFailed = true;
    }
  }
  return myContent;
}
 
Example 7
Source File: TreeStructureWrappenModel.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Override
public void fetchChildren(@Nonnull Function<T, TreeNode<T>> nodeFactory, @Nullable T parentValue) {
  ThrowableComputable<Object[],RuntimeException> action = () -> myStructure.getChildElements(parentValue);
  for (Object o : AccessRule.read(action)) {
    T element = (T)o;
    TreeNode<T> apply = nodeFactory.apply(element);

    apply.setLeaf(o instanceof AbstractTreeNode && !((AbstractTreeNode)o).isAlwaysShowPlus());


    apply.setRender((fileElement, itemPresentation) -> {
      NodeDescriptor descriptor = myStructure.createDescriptor(element, null);

      descriptor.update();

      itemPresentation.append(descriptor.toString());
      try {
        AccessRule.read(() -> itemPresentation.setIcon(descriptor.getIcon()));
      }
      catch (Exception e) {
        e.printStackTrace();
      }
    });
  }
}
 
Example 8
Source File: ProjectFileIndexImpl.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Override
public boolean iterateContent(@Nonnull ContentIterator processor, @Nullable VirtualFileFilter filter) {
  Module[] modules = AccessRule.read(() -> ModuleManager.getInstance(myProject).getModules());
  for (final Module module : modules) {
    for (VirtualFile contentRoot : getRootsToIterate(module)) {
      if (!iterateContentUnderDirectory(contentRoot, processor, filter)) {
        return false;
      }
    }
  }
  return true;
}
 
Example 9
Source File: ProjectLevelVcsManagerImpl.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Override
@Nullable
public AbstractVcs getVcsFor(final FilePath file) {
  final VirtualFile vFile = ChangesUtil.findValidParentAccurately(file);
  ThrowableComputable<AbstractVcs, RuntimeException> action = () -> {
    if (!ApplicationManager.getApplication().isUnitTestMode() && !myProject.isInitialized()) return null;
    if (myProject.isDisposed()) throw new ProcessCanceledException();
    if (vFile != null) {
      return getVcsFor(vFile);
    }
    return null;
  };
  return AccessRule.read(action);
}
 
Example 10
Source File: ProjectLevelVcsManagerImpl.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Override
public boolean isFileInContent(@Nullable final VirtualFile vf) {
  ThrowableComputable<Boolean,RuntimeException> action = () ->
                                    vf != null && (myExcludedIndex.isInContent(vf) || isFileInBaseDir(vf) || vf.equals(myProject.getBaseDir()) ||
                                                   hasExplicitMapping(vf) || isInDirectoryBasedRoot(vf)
                                                   || !Registry.is("ide.hide.excluded.files") && myExcludedIndex.isExcludedFile(vf))
                                    && !isIgnored(vf);
  return AccessRule.read(action);
}
 
Example 11
Source File: BackgroundTaskUtil.java    From consulo with Apache License 2.0 5 votes vote down vote up
/**
 * Wraps {@link MessageBus#syncPublisher(Topic)} in a dispose check,
 * and throws a {@link ProcessCanceledException} if the project is disposed,
 * instead of throwing an assertion which would happen otherwise.
 *
 * @see #syncPublisher(Topic)
 */
@Nonnull
public static <L> L syncPublisher(@Nonnull Project project, @Nonnull Topic<L> topic) throws ProcessCanceledException {
  ThrowableComputable<L, RuntimeException> action = () -> {
    if (project.isDisposed()) throw new ProcessCanceledException();
    return project.getMessageBus().syncPublisher(topic);
  };
  return AccessRule.read(action);
}
 
Example 12
Source File: RunConfigurationModule.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Override
public void readExternal(@Nonnull Element element) {
  List<Element> modules = element.getChildren(ELEMENT);
  if (!modules.isEmpty()) {
    if (modules.size() > 1) {
      LOG.warn("Module serialized more than one time");
    }
    // we are unable to set 'null' module from 'not null' one
    String moduleName = modules.get(0).getAttributeValue(ATTRIBUTE);
    if (!StringUtil.isEmpty(moduleName)) {
      myModulePointer = AccessRule.read(() -> ModulePointerManager.getInstance(myProject).create(moduleName));
    }
  }
}
 
Example 13
Source File: LocalHistoryImpl.java    From consulo with Apache License 2.0 5 votes vote down vote up
private Label label(final LabelImpl impl) {
  return new Label() {
    @Override
    public void revert(@Nonnull Project project, @Nonnull VirtualFile file) throws LocalHistoryException {
      revertToLabel(project, file, impl);
    }

    @Override
    public ByteContent getByteContent(final String path) {
      ThrowableComputable<ByteContent, RuntimeException> action = () -> impl.getByteContent(myGateway.createTransientRootEntryForPathOnly(path), path);
      return AccessRule.read(action);
    }
  };
}
 
Example 14
Source File: LocalHistoryImpl.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Nullable
@Override
public byte[] getByteContent(final VirtualFile f, final FileRevisionTimestampComparator c) {
  if (!isInitialized()) return null;
  if (!myGateway.areContentChangesVersioned(f)) return null;
  ThrowableComputable<byte[], RuntimeException> action = () -> new ByteContentRetriever(myGateway, myVcs, f, c).getResult();
  return AccessRule.read(action);
}
 
Example 15
Source File: FileEditorProviderManagerImpl.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Override
@Nonnull
public FileEditorProvider[] getProviders(@Nonnull final Project project, @Nonnull final VirtualFile file) {
  // Collect all possible editors
  List<FileEditorProvider> sharedProviders = new ArrayList<>();
  boolean doNotShowTextEditor = false;
  for (final FileEditorProvider provider : myProviders) {
    ThrowableComputable<Boolean, RuntimeException> action = () -> {
      if (DumbService.isDumb(project) && !DumbService.isDumbAware(provider)) {
        return false;
      }
      return provider.accept(project, file);
    };
    if (AccessRule.read(action)) {
      sharedProviders.add(provider);
      doNotShowTextEditor |= provider.getPolicy() == FileEditorPolicy.HIDE_DEFAULT_EDITOR;
    }
  }

  // Throw out default editors provider if necessary
  if (doNotShowTextEditor) {
    ContainerUtil.retainAll(sharedProviders, provider -> !(provider instanceof TextEditorProvider));
  }

  // Sort editors according policies
  Collections.sort(sharedProviders, MyComparator.ourInstance);

  return sharedProviders.toArray(new FileEditorProvider[sharedProviders.size()]);
}
 
Example 16
Source File: ArtifactsCompilerInstance.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Nonnull
@Override
public List<ArtifactCompilerCompileItem> getItems(@Nonnull ArtifactBuildTarget target) {
  myBuilderContext = new ArtifactsProcessingItemsBuilderContext(myContext);
  final Artifact artifact = target.getArtifact();

  ThrowableComputable<Map<String,String>,RuntimeException> action = () -> ArtifactSortingUtil.getInstance(getProject()).getArtifactToSelfIncludingNameMap();
  final Map<String, String> selfIncludingArtifacts = AccessRule.read(action);
  final String selfIncludingName = selfIncludingArtifacts.get(artifact.getName());
  if (selfIncludingName != null) {
    String name = selfIncludingName.equals(artifact.getName()) ? "it" : "'" + selfIncludingName + "' artifact";
    myContext.addMessage(CompilerMessageCategory.ERROR, "Cannot build '" + artifact.getName() + "' artifact: " + name + " includes itself in the output layout", null, -1, -1);
    return Collections.emptyList();
  }

  final String outputPath = artifact.getOutputPath();
  if (outputPath == null || outputPath.length() == 0) {
    myContext.addMessage(CompilerMessageCategory.ERROR, "Cannot build '" + artifact.getName() + "' artifact: output path is not specified", null, -1, -1);
    return Collections.emptyList();
  }

  DumbService.getInstance(getProject()).waitForSmartMode();
  AccessRule.read(() -> {
    collectItems(artifact, outputPath);
  });
  return new ArrayList<ArtifactCompilerCompileItem>(myBuilderContext.getProcessingItems());
}
 
Example 17
Source File: CompileDriver.java    From consulo with Apache License 2.0 5 votes vote down vote up
private void clearAffectedOutputPathsIfPossible(final CompileContextEx context) {
  ThrowableComputable<List<File>, RuntimeException> action = () -> {
    final MultiMap<File, Module> outputToModulesMap = new MultiMap<>();
    for (Module module : ModuleManager.getInstance(myProject).getModules()) {
      ModuleCompilerPathsManager moduleCompilerPathsManager = ModuleCompilerPathsManager.getInstance(module);
      for (ContentFolderTypeProvider contentFolderTypeProvider : ContentFolderTypeProvider.filter(ContentFolderScopes.productionAndTest())) {
        final String outputPathUrl = moduleCompilerPathsManager.getCompilerOutputUrl(contentFolderTypeProvider);
        if (outputPathUrl != null) {
          final String path = VirtualFileManager.extractPath(outputPathUrl);
          outputToModulesMap.putValue(new File(path), module);
        }
      }
    }
    final Set<Module> affectedModules = new HashSet<>(Arrays.asList(context.getCompileScope().getAffectedModules()));
    List<File> result = new ArrayList<>(affectedModules.size() * 2);
    for (File output : outputToModulesMap.keySet()) {
      if (affectedModules.containsAll(outputToModulesMap.get(output))) {
        result.add(output);
      }
    }

    final Set<Artifact> artifactsToBuild = ArtifactCompileScope.getArtifactsToBuild(myProject, context.getCompileScope(), true);
    for (Artifact artifact : artifactsToBuild) {
      final String outputFilePath = ((ArtifactImpl)artifact).getOutputDirectoryPathToCleanOnRebuild();
      if (outputFilePath != null) {
        result.add(new File(FileUtil.toSystemDependentName(outputFilePath)));
      }
    }
    return result;
  };
  final List<File> scopeOutputs = AccessRule.read(action);
  if (scopeOutputs.size() > 0) {
    CompilerUtil.runInContext(context, CompilerBundle.message("progress.clearing.output"), () -> CompilerUtil.clearOutputDirectories(scopeOutputs));
  }
}
 
Example 18
Source File: ModuleBasedConfiguration.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Override
@Nonnull
public Module[] getModules() {
  ThrowableComputable<Module[],RuntimeException> action = () -> {
    final Module module = getConfigurationModule().getModule();
    return module == null ? Module.EMPTY_ARRAY : new Module[]{module};
  };
  return AccessRule.read(action);
}
 
Example 19
Source File: ModuleDefaultVcsRootPolicy.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Nonnull
private Collection<VirtualFile> getContentRoots() {
  Module[] modules = AccessRule.read(myModuleManager::getModules);
  return Arrays.stream(modules)
          .map(module -> ModuleRootManager.getInstance(module).getContentRoots())
          .flatMap(Arrays::stream)
          .collect(Collectors.toSet());
}
 
Example 20
Source File: ModuleOutputPackagingElementImpl.java    From consulo with Apache License 2.0 4 votes vote down vote up
@Override
public void loadState(ArtifactManager artifactManager, ModuleOutputPackagingElementState state) {
  final String moduleName = state.getModuleName();
  myModulePointer = moduleName != null ? AccessRule.read(() -> ModuleUtilCore.createPointer(myProject, moduleName)) : null;
}