private VirtualFile getVirtualFile(AbstractTreeNode treeNode) {
   if (!(treeNode instanceof MPSPsiModelTreeNode)) {
     return null;
   }
   MPSPsiModelTreeNode modelTreeNode = (MPSPsiModelTreeNode) treeNode;
   VirtualFile modelVFile = modelTreeNode.getVirtualFile();
   if (modelVFile == null
       || (modelVFile.getFileType() != MPSFileTypeFactory.MPS_FILE_TYPE
           && modelVFile.getFileType() != MPSFileTypeFactory.MPS_HEADER_FILE_TYPE)) return null;
   return modelVFile;
 }
  public List<HighlightInfo> runMainPasses(
      @NotNull PsiFile psiFile,
      @NotNull Document document,
      @NotNull final ProgressIndicator progress) {
    final List<HighlightInfo> result = new ArrayList<HighlightInfo>();
    final VirtualFile virtualFile = psiFile.getVirtualFile();
    if (virtualFile != null && !virtualFile.getFileType().isBinary()) {

      final List<TextEditorHighlightingPass> passes =
          TextEditorHighlightingPassRegistrarEx.getInstanceEx(myProject)
              .instantiateMainPasses(psiFile, document);

      Collections.sort(
          passes,
          new Comparator<TextEditorHighlightingPass>() {
            @Override
            public int compare(TextEditorHighlightingPass o1, TextEditorHighlightingPass o2) {
              if (o1 instanceof GeneralHighlightingPass) return -1;
              if (o2 instanceof GeneralHighlightingPass) return 1;
              return 0;
            }
          });

      for (TextEditorHighlightingPass pass : passes) {
        pass.doCollectInformation(progress);
        result.addAll(pass.getInfos());
      }
    }

    return result;
  }
Example #3
0
  public void update(AnActionEvent e) {
    super.update(e);

    final Project project = e.getData(DataKeys.PROJECT);
    final VirtualFile file = e.getData(DataKeys.VIRTUAL_FILE);

    boolean visible =
        project != null
            && file != null
            && !file.isDirectory()
            && file.getFileType() == CppSupportLoader.CPP_FILETYPE
            && !Communicator.isHeaderFile(file);
    boolean enabled = visible;

    if (!visible) {
      visible = ActionPlaces.MAIN_MENU.equals(e.getPlace());
    }

    e.getPresentation().setEnabled(enabled);
    e.getPresentation().setVisible(visible);

    if (visible) {
      final String s =
          "Do c&ompile for " + (file != null ? file.getName() : "selected c/c++ fileToCompile");
      e.getPresentation().setText(s);
      e.getPresentation().setDescription(s);
    }
  }
  private static Language calcBaseLanguage(@NotNull VirtualFile file, @NotNull Project project) {
    if (file instanceof LightVirtualFile) {
      final Language language = ((LightVirtualFile) file).getLanguage();
      if (language != null) {
        return language;
      }
    }

    FileType fileType = file.getFileType();
    // Do not load content
    if (fileType == UnknownFileType.INSTANCE) {
      fileType = FileTypeRegistry.getInstance().detectFileTypeFromContent(file);
    }
    if (fileType.isBinary()) return Language.ANY;
    if (isTooLarge(file)) return PlainTextLanguage.INSTANCE;

    if (fileType instanceof LanguageFileType) {
      return LanguageSubstitutors.INSTANCE.substituteLanguage(
          ((LanguageFileType) fileType).getLanguage(), file, project);
    }

    final ContentBasedFileSubstitutor[] processors =
        Extensions.getExtensions(ContentBasedFileSubstitutor.EP_NAME);
    for (ContentBasedFileSubstitutor processor : processors) {
      Language language = processor.obtainLanguageForFile(file);
      if (language != null) return language;
    }

    return PlainTextLanguage.INSTANCE;
  }
  @Override
  public void beforeDocumentChange(DocumentEvent event) {
    final Document document = event.getDocument();

    final FileViewProvider viewProvider = getCachedViewProvider(document);
    if (viewProvider == null) return;
    if (!isRelevant(viewProvider)) return;

    VirtualFile virtualFile = viewProvider.getVirtualFile();
    if (virtualFile.getFileType().isBinary()) return;

    final List<PsiFile> files = viewProvider.getAllFiles();
    PsiFile psiCause = null;
    for (PsiFile file : files) {
      mySmartPointerManager.fastenBelts(file, event.getOffset(), null);

      if (TextBlock.get(file).isLocked()) {
        psiCause = file;
      }
    }

    if (psiCause == null) {
      beforeDocumentChangeOnUnlockedDocument(viewProvider);
    }

    ((SingleRootFileViewProvider) viewProvider).beforeDocumentChanged(psiCause);
  }
 private void showVFInfo(VirtualFile virtualFile) {
   logger.info("showVFInfo(): XML");
   logger.info("virtualFile: isValid= " + virtualFile.isValid());
   logger.info("virtualFile: isSymLink=" + virtualFile.isSymLink());
   logger.info("virtualFile: url= " + virtualFile.getUrl());
   logger.info("virtualFile: fileType= " + virtualFile.getFileType());
 }
  public static boolean openFileWithPsiElement(
      PsiElement element, boolean searchForOpen, boolean requestFocus) {
    boolean openAsNative = false;
    if (element instanceof PsiFile) {
      VirtualFile virtualFile = ((PsiFile) element).getVirtualFile();
      if (virtualFile != null) {
        openAsNative = ElementBase.isNativeFileType(virtualFile.getFileType());
      }
    }

    if (searchForOpen) {
      element.putUserData(FileEditorManager.USE_CURRENT_WINDOW, null);
    } else {
      element.putUserData(FileEditorManager.USE_CURRENT_WINDOW, true);
    }

    if (openAsNative || !activatePsiElementIfOpen(element, searchForOpen, requestFocus)) {
      final NavigationItem navigationItem = (NavigationItem) element;
      if (!navigationItem.canNavigate()) return false;
      navigationItem.navigate(requestFocus);
      return true;
    }

    element.putUserData(FileEditorManager.USE_CURRENT_WINDOW, null);
    return false;
  }
  @Override
  public boolean canPutAt(
      @NotNull final VirtualFile file, final int line, @NotNull final Project project) {
    final Ref<Boolean> stoppable = Ref.create(false);
    final Document document = FileDocumentManager.getInstance().getDocument(file);
    if (document != null) {
      if (file.getFileType() == PythonFileType.INSTANCE) {
        XDebuggerUtil.getInstance()
            .iterateLine(
                project,
                document,
                line,
                new Processor<PsiElement>() {
                  @Override
                  public boolean process(PsiElement psiElement) {
                    if (psiElement instanceof PsiWhiteSpace || psiElement instanceof PsiComment)
                      return true;
                    if (psiElement.getNode() != null
                        && notStoppableElementType(psiElement.getNode().getElementType()))
                      return true;

                    // Python debugger seems to be able to stop on pretty much everything
                    stoppable.set(true);
                    return false;
                  }
                });

        if (PyDebugSupportUtils.isContinuationLine(document, line - 1)) {
          stoppable.set(false);
        }
      }
    }

    return stoppable.get();
  }
 @Override
 public boolean acceptInput(@NotNull final VirtualFile file) {
   return ourEnabled
       && findDuplicatesProfile(file.getFileType()) != null
       && file.isInLocalFileSystem() // skip library sources
   ;
 }
  @Override
  @Nullable
  public ObjectStubTree readOrBuild(
      Project project, final VirtualFile vFile, @Nullable PsiFile psiFile) {
    final ObjectStubTree fromIndices = readFromVFile(project, vFile);
    if (fromIndices != null) {
      return fromIndices;
    }

    try {
      final FileContent fc = new FileContentImpl(vFile, vFile.contentsToByteArray());
      fc.putUserData(IndexingDataKeys.PROJECT, project);
      if (psiFile != null && !vFile.getFileType().isBinary()) {
        fc.putUserData(
            IndexingDataKeys.FILE_TEXT_CONTENT_KEY, psiFile.getViewProvider().getContents());
        // but don't reuse psiFile itself to avoid loading its contents. If we load AST, the stub
        // will be thrown out anyway.
      }
      Stub element = StubTreeBuilder.buildStubTree(fc);
      if (element instanceof PsiFileStub) {
        StubTree tree = new StubTree((PsiFileStub) element);
        tree.setDebugInfo("created from file content");
        return tree;
      }
    } catch (IOException e) {
      LOG.info(
          e); // content can be not cached yet, and the file can be deleted on disk already, without
              // refresh
    }

    return null;
  }
 @Override
 public StructureViewBuilder getStructureViewBuilder() {
   Document document = myComponent.getEditor().getDocument();
   VirtualFile file = FileDocumentManager.getInstance().getFile(document);
   if (file == null || !file.isValid()) return null;
   return StructureViewBuilder.PROVIDER.getStructureViewBuilder(
       file.getFileType(), file, myProject);
 }
 @Override
 public void editorCreated(@NotNull EditorFactoryEvent event) {
   Document document = event.getEditor().getDocument();
   VirtualFile file = FileDocumentManager.getInstance().getFile(document);
   if (file != null && file.getFileType() instanceof CoqFileType) {
     checkForUpdates();
   }
 }
 public static boolean isSupportedFileType(@NotNull VirtualFile virtualFile) {
   if (virtualFile.isDirectory()) return true;
   if (virtualFile.getFileType() == StdFileTypes.JAVA) return true;
   if (virtualFile.getFileType() == StdFileTypes.XML
       && !ProjectCoreUtil.isProjectOrWorkspaceFile(virtualFile)) return true;
   if ("groovy".equals(virtualFile.getExtension())) return true;
   return false;
 }
Example #14
0
 @Nullable
 private VirtualFile getJarRoot() {
   final VirtualFile file = getVirtualFile();
   if (file == null || !file.isValid() || !(file.getFileType() instanceof ArchiveFileType)) {
     return null;
   }
   return JarFileSystem.getInstance().getJarRootForLocalFile(file);
 }
Example #15
0
  @Override
  public boolean contains(VirtualFile file) {
    if (!super.contains(file)) {
      return false;
    }

    if (includeLibraries && StdFileTypes.CLASS == file.getFileType()) {
      return index.isInLibraryClasses(file);
    }

    if (JetPluginUtil.isKtFileInGradleProjectInWrongFolder(file, getProject())) {
      return false;
    }

    return file.getFileType().equals(JetFileType.INSTANCE)
        && (index.isInSourceContent(file) || includeLibraries && index.isInLibrarySource(file));
  }
 @NotNull
 @Override
 protected TypeScriptGetErrCommand createGetErrCommand(
     @NotNull VirtualFile file, @NotNull String path) {
   if (file.getFileType() == HtmlFileType.INSTANCE) {
     return new Angular2GetHtmlErrorCommand(path);
   }
   return super.createGetErrCommand(file, path);
 }
 @NotNull
 @Override
 protected JSLanguageServiceCommand createProjectCommand(
     @NotNull VirtualFile file, @NotNull String path) {
   FileType type = file.getFileType();
   return type instanceof XmlLikeFileType
       ? new Angular2GetProjectHtmlErrCommand(path)
       : super.createProjectCommand(file, path);
 }
Example #18
0
 @NotNull
 public static CharSequence getTextByBinaryPresentation(
     @NotNull byte[] bytes,
     @NotNull VirtualFile virtualFile,
     boolean saveDetectedSeparators,
     boolean saveBOM) {
   return getTextByBinaryPresentation(
       bytes, virtualFile, saveDetectedSeparators, saveBOM, virtualFile.getFileType());
 }
 @Override
 @NotNull
 protected JSLanguageServiceSimpleCommand createCompletionCommand(
     @NotNull TypeScriptCompletionsRequestArgs args,
     @NotNull VirtualFile virtualFile,
     @NotNull PsiFile file) {
   return file instanceof XmlFile || virtualFile.getFileType() instanceof XmlLikeFileType
       ? new Angular2CompletionsCommand(args)
       : super.createCompletionCommand(args, virtualFile, file);
 }
 @NotNull
 public static String getLocalFileSystemPath(@NotNull VirtualFile file) {
   if (file.getFileType() == FileTypes.ARCHIVE) {
     final VirtualFile jar = JarFileSystem.getInstance().getVirtualFileForJar(file);
     if (jar != null) {
       return jar.getPath();
     }
   }
   return file.getPath();
 }
 private boolean isActionAvailable(AnActionEvent e) {
   final VirtualFile file = getVirtualFiles(e);
   if (getEventProject(e) != null && file != null) {
     final FileType fileType = file.getFileType();
     if (StdFileTypes.JAVA.equals(fileType)) {
       return true;
     }
   }
   return false;
 }
 @Override
 public boolean isCompilableFile(VirtualFile file, CompileContext context) {
   if (!(file.getFileType() instanceof JetFileType)) {
     return false;
   }
   Module module = context.getModuleByFile(file);
   if (module == null) {
     return false;
   }
   return ProjectStructureUtil.isJsKotlinModule(module);
 }
    @Override
    public boolean contains(@NotNull VirtualFile file) {
      if (!super.contains(file)) return false;

      final FileType fileType = file.getFileType();
      for (FileType otherFileType : myFileTypes) {
        if (fileType.equals(otherFileType)) return true;
      }

      return false;
    }
 @Override
 public EditorNotificationPanel createNotificationPanel(
     @NotNull VirtualFile file, @NotNull FileEditor fileEditor) {
   if (file.getFileType() != RESOLVEFileType.INSTANCE) return null;
   Module module = ModuleUtilCore.findModuleForFile(file, project);
   return module == null
           || RESOLVESdkService.getInstance(project).isRESOLVEModule(module)
           || getIgnoredModules(project).contains(module.getName())
       ? null
       : createPanel(project, module);
 }
  @Override
  @Nullable
  public Document getDocument(@NotNull final VirtualFile file) {
    DocumentEx document = (DocumentEx) getCachedDocument(file);
    if (document == null) {
      if (file.isDirectory()
          || isBinaryWithoutDecompiler(file)
          || SingleRootFileViewProvider.isTooLargeForContentLoading(file)) {
        return null;
      }
      final CharSequence text = LoadTextUtil.loadText(file);

      synchronized (lock) {
        document = (DocumentEx) getCachedDocument(file);
        if (document != null) return document; // Double checking

        document = (DocumentEx) createDocument(text);
        document.setModificationStamp(file.getModificationStamp());
        final FileType fileType = file.getFileType();
        document.setReadOnly(!file.isWritable() || fileType.isBinary());
        file.putUserData(DOCUMENT_KEY, new WeakReference<Document>(document));
        document.putUserData(FILE_KEY, file);

        if (!(file instanceof LightVirtualFile
            || file.getFileSystem() instanceof DummyFileSystem)) {
          document.addDocumentListener(
              new DocumentAdapter() {
                @Override
                public void documentChanged(DocumentEvent e) {
                  final Document document = e.getDocument();
                  myUnsavedDocuments.add(document);
                  final Runnable currentCommand =
                      CommandProcessor.getInstance().getCurrentCommand();
                  Project project =
                      currentCommand == null
                          ? null
                          : CommandProcessor.getInstance().getCurrentCommandProject();
                  String lineSeparator = CodeStyleFacade.getInstance(project).getLineSeparator();
                  document.putUserData(LINE_SEPARATOR_KEY, lineSeparator);

                  // avoid documents piling up during batch processing
                  if (areTooManyDocumentsInTheQueue(myUnsavedDocuments)) {
                    saveAllDocumentsLater();
                  }
                }
              });
        }
      }

      myMultiCaster.fileContentLoaded(file, document);
    }

    return document;
  }
 @NotNull
 private static String renderFileReadingErrorMessage(@NotNull VirtualFile file) {
   return "Could not read file: "
       + file.getPath()
       + "; "
       + "size in bytes: "
       + file.getLength()
       + "; "
       + "file type: "
       + file.getFileType().getName();
 }
  @Nullable
  public static ValidationInfo checkIfResourceAlreadyExists(
      @NotNull Module selectedModule,
      @NotNull String resourceName,
      @NotNull ResourceType resourceType,
      @NotNull List<String> dirNames,
      @NotNull String fileName) {
    if (resourceName.length() == 0 || dirNames.size() == 0 || fileName.length() == 0) {
      return null;
    }

    final AndroidFacet facet = AndroidFacet.getInstance(selectedModule);
    final VirtualFile resourceDir = facet != null ? AndroidRootUtil.getResourceDir(facet) : null;
    if (resourceDir == null) {
      return null;
    }

    for (String directoryName : dirNames) {
      final VirtualFile resourceSubdir = resourceDir.findChild(directoryName);
      if (resourceSubdir == null) {
        continue;
      }

      final VirtualFile resFile = resourceSubdir.findChild(fileName);
      if (resFile == null) {
        continue;
      }

      if (resFile.getFileType() != StdFileTypes.XML) {
        return new ValidationInfo(
            "File " + FileUtil.toSystemDependentName(resFile.getPath()) + " is not XML file");
      }

      final Resources resources =
          AndroidUtils.loadDomElement(selectedModule, resFile, Resources.class);
      if (resources == null) {
        return new ValidationInfo(
            AndroidBundle.message(
                "not.resource.file.error", FileUtil.toSystemDependentName(resFile.getPath())));
      }

      for (ResourceElement element :
          AndroidResourceUtil.getValueResourcesFromElement(resourceType.getName(), resources)) {
        if (resourceName.equals(element.getName().getValue())) {
          return new ValidationInfo(
              "resource '"
                  + resourceName
                  + "' already exists in "
                  + FileUtil.toSystemDependentName(resFile.getPath()));
        }
      }
    }
    return null;
  }
Example #28
0
  @Nullable
  public static String extension(@Nullable PsiFile file) {
    if (file != null) {
      VirtualFile vFile = file.getVirtualFile();
      if (vFile != null) {
        return vFile.getFileType().getDefaultExtension();
      }
    }

    return null;
  }
 @Nullable
 public static Icon getIcon(@NotNull ErlangFile file) {
   if (!file.isValid()) return null;
   VirtualFile virtualFile = file.getViewProvider().getVirtualFile();
   FileType fileType = virtualFile.getFileType();
   if (ErlangFileType.MODULE == fileType) {
     ErlangModule module = file.getModule();
     boolean isEunit = module != null && ErlangPsiImplUtil.isEunitTestFile(file);
     return isEunit ? ErlangIcons.EUNIT : getModuleType(file).icon;
   }
   return fileType.getIcon();
 }
  private static boolean isSaveNeeded(@NotNull Document document, @NotNull VirtualFile file)
      throws IOException {
    if (file.getFileType().isBinary()
        || document.getTextLength() > 1000 * 1000) { // don't compare if the file is too big
      return true;
    }

    byte[] bytes = file.contentsToByteArray();
    CharSequence loaded = LoadTextUtil.getTextByBinaryPresentation(bytes, file, false, false);

    return !Comparing.equal(document.getCharsSequence(), loaded);
  }