Java Code Examples for com.intellij.psi.PsiFile#getVirtualFile()

The following examples show how to use com.intellij.psi.PsiFile#getVirtualFile() . These examples are extracted from open source projects. 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
/**
 * 获取 VirtualFile 的几种方式
 *
 * @param e the e
 */
private void getVirtualFile(AnActionEvent e) {
    // 获取 VirtualFile 方式一:
    VirtualFile virtualFile = e.getData(PlatformDataKeys.VIRTUAL_FILE);
    // 获取多个 VirtualFile
    VirtualFile[] virtualFiles = e.getData(PlatformDataKeys.VIRTUAL_FILE_ARRAY);
    // 方式二: 从本地文件系统路径获取
    VirtualFile virtualFileFromLocalFileSystem = LocalFileSystem.getInstance().findFileByIoFile(new File("path"));
    // 方式三: 从 PSI 文件 (如果 PSI 文件仅存在内存中, 则可能返回 null)
    PsiFile psiFile = e.getData(CommonDataKeys.PSI_FILE);
    if (psiFile != null) {
        psiFile.getVirtualFile();
    }
    // 方式四: 从 document 中
    Document document = Objects.requireNonNull(e.getData(PlatformDataKeys.EDITOR)).getDocument();
    VirtualFile virtualFileFromDocument = FileDocumentManager.getInstance().getFile(document);

    // 获取 document
    getDocument(e);
}
 
Example 2
@Override
protected boolean setupConfigurationFromContext(RunConfiguration configuration, ConfigurationContext context, Ref sourceElement) {
    VirtualFile[] selectedFiles = CommonDataKeys.VIRTUAL_FILE_ARRAY.getData(context.getDataContext());
    if (selectedFiles == null || selectedFiles.length > 1) return false;
    Module module = context.getModule();
    if (context.getPsiLocation() == null || module == null) return false;
    PsiFile file = context.getPsiLocation().getContainingFile();
    if (!isSpecFile(file) || !isInSpecScope(context.getPsiLocation())) return false;
    try {
        VirtualFile virtualFile = file.getVirtualFile();
        if (virtualFile == null) return false;
        String name = virtualFile.getCanonicalPath();
        configuration.setName(file.getName());
        ((GaugeRunConfiguration) configuration).setSpecsToExecute(name);
        ((GaugeRunConfiguration) configuration).setModule(module);
        return true;
    } catch (Exception ex) {
        LOG.debug(ex);
        ex.printStackTrace();
    }
    return true;
}
 
Example 3
@Override
protected DependenciesBuilder createDependenciesBuilder(AnalysisScope scope) {
  return new ForwardDependenciesBuilder(myProject, scope) {
    @Override
    public void analyze() {
      super.analyze();
      final Map<PsiFile,Set<PsiFile>> dependencies = getDependencies();
      for (PsiFile file : dependencies.keySet()) {
        final Set<PsiFile> files = dependencies.get(file);
        final Iterator<PsiFile> iterator = files.iterator();
        while (iterator.hasNext()) {
          PsiFile next = iterator.next();
          final VirtualFile virtualFile = next.getVirtualFile();
          if (virtualFile == null || !myTargetScope.contains(virtualFile)) {
            iterator.remove();
          }
        }
      }
    }
  };
}
 
Example 4
@Override
public void actionPerformed(@NotNull final AnActionEvent event) {
  Project project = event.getProject();
  if (project == null) return;
  Navigatable element = event.getData(CommonDataKeys.NAVIGATABLE);
  if (element instanceof PsiClass) {
    PsiFile file = ((PsiClass) element).getContainingFile();
    if (file == null) return;
    final VirtualFile virtualFile = file.getVirtualFile();
    if (virtualFile == null) return;
    final ProjectFileIndex fileIndex = ProjectRootManager.getInstance(project).getFileIndex();
    final Module module = fileIndex.getModuleForFile(virtualFile);
    if (module == null) return;
    if (!ModuleRootManager.getInstance(module).getFileIndex().isInContent(virtualFile)) {
      ModuleRootModificationUtil.addModuleLibrary(module, virtualFile.getUrl());
    }
  }

}
 
Example 5
private Map<String, String> getSchemasFromSpringSchemas(@NotNull Module module) throws Exception {
    Map<String, String> schemasMap = new HashMap<>();

    PsiFile[] psiFiles = FilenameIndex.getFilesByName(module.getProject(), "spring.schemas", GlobalSearchScope.moduleWithDependenciesAndLibrariesScope(module));

    for (PsiFile nextSpringS : psiFiles) {
        VirtualFile springSchemasFile = nextSpringS.getVirtualFile();
        if (springSchemasFile != null) {
            String springSchemasContent = new String(springSchemasFile.contentsToByteArray());
            schemasMap.putAll(parseSpringSchemas(springSchemasContent));
        }
    }

    //Fix for HTTP module schema vs old HTTP transport schema
    schemasMap.put("http://www.mulesoft.org/schema/mule/http/current/mule-http.xsd", "META-INF/mule-httpn.xsd");

    return schemasMap;
}
 
Example 6
Source Project: consulo   File: LossyEncodingInspection.java    License: Apache License 2.0 6 votes vote down vote up
@Override
@Nullable
public ProblemDescriptor[] checkFile(@Nonnull PsiFile file, @Nonnull InspectionManager manager, boolean isOnTheFly) {
  if (InjectedLanguageManager.getInstance(file.getProject()).isInjectedFragment(file)) return null;
  if (!file.isPhysical()) return null;
  FileViewProvider viewProvider = file.getViewProvider();
  if (viewProvider.getBaseLanguage() != file.getLanguage()) return null;
  VirtualFile virtualFile = file.getVirtualFile();
  if (virtualFile == null) return null;
  if (!virtualFile.isInLocalFileSystem()) return null;
  CharSequence text = viewProvider.getContents();
  Charset charset = LoadTextUtil.extractCharsetFromFileContent(file.getProject(), virtualFile, text);

  // no sense in checking transparently decoded file: all characters there are already safely encoded
  if (charset instanceof Native2AsciiCharset) return null;

  List<ProblemDescriptor> descriptors = new SmartList<ProblemDescriptor>();
  boolean ok = checkFileLoadedInWrongEncoding(file, manager, isOnTheFly, virtualFile, charset, descriptors);
  if (ok) {
    checkIfCharactersWillBeLostAfterSave(file, manager, isOnTheFly, text, charset, descriptors);
  }

  return descriptors.toArray(new ProblemDescriptor[descriptors.size()]);
}
 
Example 7
Source Project: CppTools   File: NavigationCommand.java    License: Apache License 2.0 5 votes vote down vote up
private static String getPath(PsiFile file) {
  VirtualFile virtualFile = file.getVirtualFile();

  if (virtualFile == null && file.getOriginalFile() != null) {
    virtualFile = file.getOriginalFile().getVirtualFile();
  }
  return virtualFile != null ? virtualFile.getPath():"";
}
 
Example 8
Source Project: consulo   File: AnnotationHolderImpl.java    License: Apache License 2.0 5 votes vote down vote up
private void assertMyFile(PsiElement node) {
  if (node == null) return;
  PsiFile myFile = myAnnotationSession.getFile();
  PsiFile containingFile = node.getContainingFile();
  LOG.assertTrue(containingFile != null, node);
  VirtualFile containingVFile = containingFile.getVirtualFile();
  VirtualFile myVFile = myFile.getVirtualFile();
  if (!Comparing.equal(containingVFile, myVFile)) {
    LOG.error(
            "Annotation must be registered for an element inside '" + myFile + "' which is in '" + myVFile + "'.\n" +
            "Element passed: '" + node + "' is inside the '" + containingFile + "' which is in '" + containingVFile + "'");
  }
}
 
Example 9
private static boolean canBeFormatted(PsiFile file) {
  if (!file.isValid()) return false;
  if (LanguageFormatting.INSTANCE.forContext(file) == null) {
    return false;
  }
  VirtualFile virtualFile = file.getVirtualFile();
  if (virtualFile == null) return true;

  if (ProjectCoreUtil.isProjectOrWorkspaceFile(virtualFile)) return false;

  return !GeneratedSourcesFilter.isGenerated(file.getProject(), virtualFile);
}
 
Example 10
Source Project: consulo   File: ProjectRootsUtil.java    License: Apache License 2.0 5 votes vote down vote up
public static boolean isOutsideSourceRoot(@Nullable PsiFile psiFile) {
  if (psiFile == null) return false;
  if (psiFile instanceof PsiCodeFragment) return false;
  final VirtualFile file = psiFile.getVirtualFile();
  if (file == null) return false;
  final ProjectFileIndex projectFileIndex = ProjectRootManager.getInstance(psiFile.getProject()).getFileIndex();
  return !projectFileIndex.isInSource(file) && !projectFileIndex.isInLibraryClasses(file);
}
 
Example 11
@NotNull
@Override
public PsiElementVisitor buildVisitor(
    @NotNull final ProblemsHolder holder,
    final boolean isOnTheFly,
    @NotNull final LocalInspectionToolSession session) {
  final PsiFile file = holder.getFile();
  final VirtualFile virtualFile = file.getVirtualFile();
  final Project project = holder.getProject();

  boolean checkRefs =
      indexFacade.isMainSpecFile(virtualFile, project)
          || indexFacade.isPartialSpecFile(virtualFile, project);

  return new YamlPsiElementVisitor() {
    @Override
    public void visitKeyValue(@NotNull YAMLKeyValue keyValue) {
      if (!checkRefs) {
        return;
      }
      if ("$ref".equals(keyValue.getKeyText())) {
        YAMLValue value = keyValue.getValue();

        if (!(value instanceof YAMLScalar)) {
          return;
        }

        final String unquotedValue = StringUtil.unquoteString(value.getText());

        if (!unquotedValue.startsWith("http")) {
          doCheck(holder, value, new CreateYamlReferenceIntentionAction(unquotedValue));
        }
      }
      super.visitKeyValue(keyValue);
    }
  };
}
 
Example 12
private boolean isEnabled(@Nonnull CodeStyleSettings settings, @Nonnull PsiFile file) {
  if (file instanceof PsiCompiledFile) return false;
  if (ApplicationManager.getApplication().isUnitTestMode()) {
    return myIsEnabledInTest;
  }
  VirtualFile vFile = file.getVirtualFile();
  if (vFile == null || vFile instanceof LightVirtualFile || myDisabledFiles.contains(vFile)) return false;
  return LanguageFormatting.INSTANCE.forContext(file) != null && settings.AUTODETECT_INDENTS;
}
 
Example 13
Source Project: consulo   File: RefElementImpl.java    License: Apache License 2.0 5 votes vote down vote up
@Nullable
public String getURL() {
  final PsiElement element = getPsiElement();
  if (element == null || !element.isPhysical()) return null;
  final PsiFile containingFile = element.getContainingFile();
  if (containingFile == null) return null;
  final VirtualFile virtualFile = containingFile.getVirtualFile();
  if (virtualFile == null) return null;
  return virtualFile.getUrl() + "#" + element.getTextOffset();
}
 
Example 14
Source Project: consulo   File: BaseSandLanguageVersion.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public boolean isMyElement(@Nullable PsiElement element) {
  if (element == null) {
    return false;
  }
  PsiFile containingFile = element.getContainingFile();
  if (containingFile == null) {
    return false;
  }
  VirtualFile virtualFile = containingFile.getVirtualFile();
  if (virtualFile == null) {
    return false;
  }
  return isMyFile(element.getProject(), virtualFile);
}
 
Example 15
private void assertMyFile(PsiElement node) {
  if (node == null) return;
  PsiFile myFile = getCurrentAnnotationSession().getFile();
  PsiFile containingFile = node.getContainingFile();
  LOG.assertTrue(containingFile != null, node);
  VirtualFile containingVFile = containingFile.getVirtualFile();
  VirtualFile myVFile = myFile.getVirtualFile();
  if (!Comparing.equal(containingVFile, myVFile)) {
    LOG.error(
      "Annotation must be registered for an element inside '" + myFile + "' which is in '" + myVFile + "'.\n" +
      "Element passed: '" + node + "' is inside the '" + containingFile + "' which is in '" + containingVFile + "'");
  }
}
 
Example 16
@Nonnull
@Override
public PsiElementVisitor buildVisitor(@Nonnull final ProblemsHolder holder, boolean isOnTheFly) {
  return new PsiElementVisitor() {
    @Override
    public void visitFile(PsiFile file) {
      if (!file.getLanguage().equals(file.getViewProvider().getBaseLanguage())) {
        // There is a possible case that more than a single virtual file/editor contains more than one language (e.g. php and html).
        // We want to process a virtual file once than, hence, ignore all non-base psi files.
        return;
      }

      final Project project = holder.getProject();
      final String projectLineSeparator = CodeStyleFacade.getInstance(project).getLineSeparator();
      if (projectLineSeparator == null) {
        return;
      }

      final VirtualFile virtualFile = file.getVirtualFile();
      if (virtualFile == null || !AbstractConvertLineSeparatorsAction.shouldProcess(virtualFile, project)) {
        return;
      }

      final String curLineSeparator = LoadTextUtil.detectLineSeparator(virtualFile, true);
      if (curLineSeparator != null && !curLineSeparator.equals(projectLineSeparator)) {
        holder.registerProblem(
          file,
          "Line separators in the current file (" + StringUtil.escapeStringCharacters(curLineSeparator) + ") " +
          "differ from the project defaults (" + StringUtil.escapeStringCharacters(projectLineSeparator) + ")",
          SET_PROJECT_LINE_SEPARATORS);
      }
    }
  };
}
 
Example 17
@Nullable
public PubRoot getRoot(@NotNull PsiFile psiFile) {
  final VirtualFile file = psiFile.getVirtualFile();
  if (file == null) {
    return null;
  }

  return getRoot(file);
}
 
Example 18
Source Project: litho   File: ComponentScope.java    License: Apache License 2.0 4 votes vote down vote up
public static VirtualFile getVirtualFile(PsiFile file) {
  final VirtualFile vf = file.getVirtualFile();
  if (vf != null) return vf;

  return file.getViewProvider().getVirtualFile();
}
 
Example 19
@NotNull
public List<HaxeCompilerCompletionItem> getPossibleCompletions(@NotNull PsiFile file,
                                                               @NotNull PsiElement element,
                                                               @NotNull Editor editor) {

    HaxeDebugTimeLog timeLog = HaxeDebugTimeLog.startNew("HaxeCompilerCompletionContributor",
                                                         HaxeDebugTimeLog.Since.StartAndPrevious);
    List<HaxeCompilerCompletionItem> completions = HaxeCompilerCompletionItem.EMPTY_LIST;

    try {
        Project project = file.getProject();
        VirtualFile vfile = file.getVirtualFile();
        VirtualFile compileRoot = HaxeCompilerUtil.findCompileRoot(file);
        if (null == vfile || null == compileRoot) {
            // Can't run a completion on an in-memory file (at least for now).
            // TODO: Allow completion on in-memory files for 3.4 compilers.
            return completions;
        }
        Module moduleForFile = ModuleUtil.findModuleForFile(vfile, project);

        ArrayList<String> commandLineArguments = new ArrayList<String>();

        //Make sure module is Haxe Module
        if (moduleForFile != null
            && ModuleUtil.getModuleType(moduleForFile).equals(HaxeModuleType.getInstance())) {
            //Get module settings
            HaxeModuleSettings moduleSettings = HaxeModuleSettings.getInstance(moduleForFile);
            HaxeConfiguration buildConfig = moduleSettings.getBuildConfiguration();
            VirtualFile projectFile = null;
            switch (buildConfig) {
                case HXML:
                    projectFile = verifyProjectFile(moduleForFile, "HXML", moduleSettings.getHxmlPath(), myErrorNotifier);
                    if (null == projectFile) {
                        break;
                    }

                    commandLineArguments.add(HaxeHelpUtil.getHaxePath(moduleForFile));
                    commandLineArguments.add(projectFile.getPath());

                    completions = collectCompletionsFromCompiler(file, element, editor, commandLineArguments, timeLog);
                    break;
                case NMML:
                    projectFile = verifyProjectFile(moduleForFile, "NMML", moduleSettings.getNmmlPath(), myErrorNotifier);
                    if (null == projectFile) {
                        break;
                    }
                    formatAndAddCompilerArguments(commandLineArguments, moduleSettings.getNmeFlags());
                    completions = collectCompletionsFromNME(file, element, editor, commandLineArguments, timeLog);
                    break;
                case OPENFL:
                    //projectFile = verifyProjectFile(moduleForFile, "OpenFL", moduleSettings.getOpenFLPath(), myErrorNotifier);
                    //if (null == projectFile) {
                    //    break;
                    //}
                    List<String> compilerArgsFromProjectFile = getLimeProjectConfiguration(moduleForFile, timeLog);

                    commandLineArguments.add(HaxeHelpUtil.getHaxePath(moduleForFile));
                    formatAndAddCompilerArguments(commandLineArguments, compilerArgsFromProjectFile);

                    completions = collectCompletionsFromCompiler(file, element, editor, commandLineArguments, timeLog);

                    break;
                case CUSTOM:
                    commandLineArguments.add(HaxeHelpUtil.getHaxePath(moduleForFile));
                    formatAndAddCompilerArguments(commandLineArguments, moduleSettings.getArguments());
                    completions = collectCompletionsFromCompiler(file, element, editor, commandLineArguments, timeLog);
                    break;
            }
        }
    }
    finally {
        timeLog.stamp("Finished");
        timeLog.print();
    }
    return completions;
}
 
Example 20
@Nullable
@Override
public VirtualFile findClassFile(String fqcn) {
  GlobalSearchScope searchScope = module.getModuleRuntimeScope(false);

  PsiClass[] psiClasses =
      ReadAction.compute(
          () ->
              JavaPsiFacade.getInstance(project)
                  .findClasses(getContainingClassName(fqcn), searchScope));
  if (psiClasses.length == 0) {
    return null;
  }

  BlazeProjectData projectData =
      BlazeProjectDataManager.getInstance(project).getBlazeProjectData();
  if (projectData == null) {
    return null;
  }

  // It's possible that there's more than one source file in the project corresponding to
  // the same fully-qualified class name, with Blaze choosing the appropriate source to use
  // according to some configuration flags. Here we check each of them until we find the one
  // that was chosen during Blaze sync.
  for (PsiClass psiClass : psiClasses) {
    PsiFile psiFile = psiClass.getContainingFile();
    if (psiFile == null) {
      continue;
    }

    VirtualFile virtualFile = psiFile.getVirtualFile();
    if (virtualFile == null) {
      continue;
    }

    FileType fileType = psiFile.getFileType();
    VirtualFile classFile = null;

    if (fileType == StdFileTypes.JAVA) {
      classFile =
          findClassFileForSourceAndRegisterResourcePackage(projectData, virtualFile, fqcn);
    } else if (fileType == StdFileTypes.CLASS) {
      classFile = findClassFileForIJarClass(projectData, virtualFile, fqcn);
    }

    if (classFile != null) {
      return classFile;
    }
  }

  return null;
}