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

The following examples show how to use com.intellij.psi.PsiFile#isValid() . 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: DesktopPsiAwareTextEditorImpl.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Nonnull
@Override
protected Runnable loadEditorInBackground() {
  Runnable baseAction = super.loadEditorInBackground();
  PsiFile psiFile = PsiManager.getInstance(myProject).findFile(myFile);
  Document document = FileDocumentManager.getInstance().getDocument(myFile);
  CodeFoldingState foldingState = document != null && !myProject.isDefault()
                                  ? CodeFoldingManager.getInstance(myProject).buildInitialFoldings(document)
                                  : null;
  return () -> {
    baseAction.run();
    if (foldingState != null) {
      foldingState.setToEditor(getEditor());
    }
    if (psiFile != null && psiFile.isValid()) {
      DaemonCodeAnalyzer.getInstance(myProject).restart(psiFile);
    }
    EditorNotifications.getInstance(myProject).updateNotifications(myFile);
  };
}
 
Example 2
Source File: ShowUsagesTableCellRenderer.java    From consulo with Apache License 2.0 6 votes vote down vote up
private Color getBackgroundColor(boolean isSelected, Usage usage) {
  Color fileBgColor = null;
  if (isSelected) {
    fileBgColor = UIUtil.getListSelectionBackground();
  }
  else {
    VirtualFile virtualFile = usage instanceof UsageInFile ? ((UsageInFile)usage).getFile() : null;
    if (virtualFile != null) {
      Project project = myUsageView.getProject();
      PsiFile psiFile = PsiManager.getInstance(project).findFile(virtualFile);
      if (psiFile != null && psiFile.isValid()) {
        final Color color = FileColorManager.getInstance(project).getRendererBackground(psiFile);
        if (color != null) fileBgColor = color;
      }
    }
  }
  return fileBgColor;
}
 
Example 3
Source File: DependenciesPanel.java    From consulo with Apache License 2.0 6 votes vote down vote up
private void updateRightTreeModel() {
  Set<PsiFile> deps = new HashSet<PsiFile>();
  Set<PsiFile> scope = getSelectedScope(myLeftTree);
  myIllegalsInRightTree = new HashSet<PsiFile>();
  for (PsiFile psiFile : scope) {
    Map<DependencyRule, Set<PsiFile>> illegalDeps = myIllegalDependencies.get(psiFile);
    if (illegalDeps != null) {
      for (final DependencyRule rule : illegalDeps.keySet()) {
        myIllegalsInRightTree.addAll(illegalDeps.get(rule));
      }
    }
    final Set<PsiFile> psiFiles = myDependencies.get(psiFile);
    if (psiFiles != null) {
      for (PsiFile file : psiFiles) {
        if (file != null && file.isValid()) {
          deps.add(file);
        }
      }
    }
  }
  deps.removeAll(scope);
  myRightTreeExpansionMonitor.freeze();
  myRightTree.setModel(buildTreeModel(deps, myRightTreeMarker));
  myRightTreeExpansionMonitor.restore();
  expandFirstLevel(myRightTree);
}
 
Example 4
Source File: ShowUsagesTableCellRenderer.java    From dagger-intellij-plugin with Apache License 2.0 6 votes vote down vote up
private Color getBackgroundColor(boolean isSelected, Usage usage) {
  Color fileBgColor = null;
  if (isSelected) {
    fileBgColor = UIUtil.getListSelectionBackground();
  } else {
    VirtualFile virtualFile =
        usage instanceof UsageInFile ? ((UsageInFile) usage).getFile() : null;
    if (virtualFile != null) {
      Project project = myUsageView.getProject();
      PsiFile psiFile = PsiManager.getInstance(project).findFile(virtualFile);
      if (psiFile != null && psiFile.isValid()) {
        final Color color = FileColorManager.getInstance(project).getRendererBackground(psiFile);
        if (color != null) fileBgColor = color;
      }
    }
  }
  return fileBgColor;
}
 
Example 5
Source File: FlutterSampleNotificationProvider.java    From flutter-intellij with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Nullable
@Override
public EditorNotificationPanel createNotificationPanel(
  @NotNull VirtualFile file, @NotNull FileEditor fileEditor, @NotNull Project project) {
  if (!(fileEditor instanceof TextEditor)) {
    return null;
  }

  final FlutterSdk sdk = FlutterSdk.getFlutterSdk(project);
  if (sdk == null) {
    return null;
  }

  final String flutterPackagePath = sdk.getHomePath() + "/packages/flutter/lib/src/";
  final String filePath = file.getPath();

  // Only show for files in the flutter sdk.
  if (!filePath.startsWith(flutterPackagePath)) {
    return null;
  }

  final TextEditor textEditor = (TextEditor)fileEditor;
  final Editor editor = textEditor.getEditor();
  final Document document = editor.getDocument();

  final PsiFile psiFile = PsiDocumentManager.getInstance(project).getPsiFile(document);
  if (psiFile == null || !psiFile.isValid()) {
    return null;
  }

  // Run the code to query the document in a read action.
  final List<FlutterSample> samples = ApplicationManager.getApplication().
    runReadAction((Computable<List<FlutterSample>>)() -> {
      //noinspection CodeBlock2Expr
      return getSamplesFromDoc(flutterPackagePath, document, filePath);
    });

  return samples.isEmpty() ? null : new FlutterSampleActionsPanel(samples);
}
 
Example 6
Source File: AbstractLayoutCodeProcessor.java    From consulo with Apache License 2.0 5 votes vote down vote up
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 7
Source File: ScopeBasedTodosTreeStructure.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Override
public boolean accept(final PsiFile psiFile) {
  if (!psiFile.isValid()) return false;

  SearchScope scope = myScopes.getSelectedScope();
  VirtualFile file = psiFile.getVirtualFile();
  boolean isAffected = scope != null && file != null && scope.contains(file);
  return isAffected && (myTodoFilter != null && myTodoFilter.accept(mySearchHelper, psiFile) ||
                        (myTodoFilter == null && mySearchHelper.getTodoItemsCount(psiFile) > 0));
}
 
Example 8
Source File: NavigationUtil.java    From consulo with Apache License 2.0 5 votes vote down vote up
private static boolean activatePsiElementIfOpen(@Nonnull PsiElement elt, boolean searchForOpen, boolean requestFocus) {
  if (!elt.isValid()) return false;
  elt = elt.getNavigationElement();
  final PsiFile file = elt.getContainingFile();
  if (file == null || !file.isValid()) return false;

  VirtualFile vFile = file.getVirtualFile();
  if (vFile == null) return false;

  if (!EditorHistoryManager.getInstance(elt.getProject()).hasBeenOpen(vFile)) return false;

  final FileEditorManager fem = FileEditorManager.getInstance(elt.getProject());
  if (!fem.isFileOpen(vFile)) {
    fem.openFile(vFile, requestFocus, searchForOpen);
  }

  final TextRange range = elt.getTextRange();
  if (range == null) return false;

  final FileEditor[] editors = fem.getEditors(vFile);
  for (FileEditor editor : editors) {
    if (editor instanceof TextEditor) {
      final Editor text = ((TextEditor)editor).getEditor();
      final int offset = text.getCaretModel().getOffset();

      if (range.containsOffset(offset)) {
        // select the file
        fem.openFile(vFile, requestFocus, searchForOpen);
        return true;
      }
    }
  }

  return false;
}
 
Example 9
Source File: FileColorsModel.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Nullable
public String getColor(@Nonnull PsiFile psiFile) {
  if (!psiFile.isValid()) {
    return null;
  }
  VirtualFile virtualFile = psiFile.getVirtualFile();
  return virtualFile == null ? null : getColor(virtualFile, psiFile.getProject());
}
 
Example 10
Source File: PatternDescriptor.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Override
public boolean matches(@Nonnull PsiFile psiFile) {
  if (psiFile.isValid()) {
    VirtualFile virtualFile = psiFile.getVirtualFile();
    if (virtualFile != null) {
      return matches(psiFile.getProject(), virtualFile);
    }
  }
  return false;
}
 
Example 11
Source File: PsiDocumentManagerImpl.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Nonnull
@Override
List<BooleanRunnable> reparseChangedInjectedFragments(@Nonnull Document hostDocument,
                                                      @Nonnull PsiFile hostPsiFile,
                                                      @Nonnull TextRange hostChangedRange,
                                                      @Nonnull ProgressIndicator indicator,
                                                      @Nonnull ASTNode oldRoot,
                                                      @Nonnull ASTNode newRoot) {
  List<DocumentWindow> changedInjected = InjectedLanguageManager.getInstance(myProject).getCachedInjectedDocumentsInRange(hostPsiFile, hostChangedRange);
  if (changedInjected.isEmpty()) return Collections.emptyList();
  FileViewProvider hostViewProvider = hostPsiFile.getViewProvider();
  List<DocumentWindow> fromLast = new ArrayList<>(changedInjected);
  // make sure modifications do not ruin all document offsets after
  fromLast.sort(Collections.reverseOrder(Comparator.comparingInt(doc -> ArrayUtil.getLastElement(doc.getHostRanges()).getEndOffset())));
  List<BooleanRunnable> result = new ArrayList<>(changedInjected.size());
  for (DocumentWindow document : fromLast) {
    Segment[] ranges = document.getHostRanges();
    if (ranges.length != 0) {
      // host document change has left something valid in this document window place. Try to reparse.
      PsiFile injectedPsiFile = getCachedPsiFile(document);
      if (injectedPsiFile == null || !injectedPsiFile.isValid()) continue;

      BooleanRunnable runnable = InjectedLanguageUtil.reparse(injectedPsiFile, document, hostPsiFile, hostDocument, hostViewProvider, indicator, oldRoot, newRoot, this);
      ContainerUtil.addIfNotNull(result, runnable);
    }
  }

  return result;
}
 
Example 12
Source File: FileNode.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Override
public void fillFiles(Set<PsiFile> set, boolean recursively) {
  super.fillFiles(set, recursively);
  final PsiFile file = getFile();
  if (file != null && file.isValid()) {
    set.add(file);
  }
}
 
Example 13
Source File: ShowIntentionActionsHandler.java    From consulo with Apache License 2.0 5 votes vote down vote up
public static boolean availableFor(@Nonnull PsiFile psiFile, @Nonnull Editor editor, @Nonnull IntentionAction action) {
  if (!psiFile.isValid()) return false;

  try {
    Project project = psiFile.getProject();
    action = IntentionActionDelegate.unwrap(action);
    if (action instanceof SuppressIntentionActionFromFix) {
      final ThreeState shouldBeAppliedToInjectionHost = ((SuppressIntentionActionFromFix)action).isShouldBeAppliedToInjectionHost();
      if (editor instanceof EditorWindow && shouldBeAppliedToInjectionHost == ThreeState.YES) {
        return false;
      }
      if (!(editor instanceof EditorWindow) && shouldBeAppliedToInjectionHost == ThreeState.NO) {
        return false;
      }
    }

    if (action instanceof PsiElementBaseIntentionAction) {
      PsiElementBaseIntentionAction psiAction = (PsiElementBaseIntentionAction)action;
      if (!psiAction.checkFile(psiFile)) {
        return false;
      }
      PsiElement leaf = psiFile.findElementAt(editor.getCaretModel().getOffset());
      if (leaf == null || !psiAction.isAvailable(project, editor, leaf)) {
        return false;
      }
    }
    else if (!action.isAvailable(project, editor, psiFile)) {
      return false;
    }
  }
  catch (IndexNotReadyException e) {
    return false;
  }
  return true;
}
 
Example 14
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);
  };
}
 
Example 15
Source File: BaseCompleteMacro.java    From consulo with Apache License 2.0 5 votes vote down vote up
private void invokeCompletion(final ExpressionContext context) {
  final Project project = context.getProject();
  final Editor editor = context.getEditor();

  final PsiFile psiFile = PsiUtilBase.getPsiFileInEditor(editor, project);
  Runnable runnable = new Runnable() {
    @Override
    public void run() {
      if (project.isDisposed() || editor.isDisposed() || psiFile == null || !psiFile.isValid()) return;

      CommandProcessor.getInstance().executeCommand(project, new Runnable() {
        @Override
        public void run() {
          invokeCompletionHandler(project, editor);
          Lookup lookup = LookupManager.getInstance(project).getActiveLookup();

          if (lookup != null) {
            lookup.addLookupListener(new MyLookupListener(context));
          }
          else {
            considerNextTab(editor);
          }
        }
      }, "", null);
    }
  };
  if (ApplicationManager.getApplication().isUnitTestMode()) {
    runnable.run();
  } else {
    ApplicationManager.getApplication().invokeLater(runnable);
  }
}
 
Example 16
Source File: FlutterSampleNotificationProvider.java    From flutter-intellij with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Nullable
@Override
public EditorNotificationPanel createNotificationPanel(
  @NotNull VirtualFile file, @NotNull FileEditor fileEditor, @NotNull Project project) {
  if (!(fileEditor instanceof TextEditor)) {
    return null;
  }

  final FlutterSdk sdk = FlutterSdk.getFlutterSdk(project);
  if (sdk == null) {
    return null;
  }

  final String flutterPackagePath = sdk.getHomePath() + "/packages/flutter/lib/src/";
  final String filePath = file.getPath();

  // Only show for files in the flutter sdk.
  if (!filePath.startsWith(flutterPackagePath)) {
    return null;
  }

  final TextEditor textEditor = (TextEditor)fileEditor;
  final Editor editor = textEditor.getEditor();
  final Document document = editor.getDocument();

  final PsiFile psiFile = PsiDocumentManager.getInstance(project).getPsiFile(document);
  if (psiFile == null || !psiFile.isValid()) {
    return null;
  }

  // Run the code to query the document in a read action.
  final List<FlutterSample> samples = ApplicationManager.getApplication().
    runReadAction((Computable<List<FlutterSample>>)() -> {
      //noinspection CodeBlock2Expr
      return getSamplesFromDoc(flutterPackagePath, document, filePath);
    });

  return samples.isEmpty() ? null : new FlutterSampleActionsPanel(samples);
}
 
Example 17
Source File: DocGenerateAction.java    From CodeMaker with Apache License 2.0 5 votes vote down vote up
/**
 * Check files access.
 *
 * @param beforeElement the before element
 */
private void checkFilesAccess(@NotNull PsiElement beforeElement) {
    PsiFile containingFile = beforeElement.getContainingFile();
    if (containingFile == null || !containingFile.isValid()) {
        throw new IllegalStateException("File cannot be used to generate javadocs");
    }
    OperationStatus status = ReadonlyStatusHandler.getInstance(beforeElement.getProject()).
            ensureFilesWritable(Collections.singletonList(containingFile.getVirtualFile()));
    if (status.hasReadonlyFiles()) {
        throw new IllegalStateException(status.getReadonlyFilesMessage());
    }
}
 
Example 18
Source File: FindDependencyUtil.java    From consulo with Apache License 2.0 4 votes vote down vote up
public static UsageInfo[] findDependencies(@Nullable final List<DependenciesBuilder> builders, Set<PsiFile> searchIn, Set<PsiFile> searchFor) {
  final List<UsageInfo> usages = new ArrayList<UsageInfo>();
  ProgressIndicator indicator = ProgressManager.getInstance().getProgressIndicator();
  int totalCount = searchIn.size();
  int count = 0;

  nextFile: for (final PsiFile psiFile : searchIn) {
    count = updateIndicator(indicator, totalCount, count, psiFile);

    if (!psiFile.isValid()) continue;

    final Set<PsiFile> precomputedDeps;
    if (builders != null) {
      final Set<PsiFile> depsByFile = new HashSet<PsiFile>();
      for (DependenciesBuilder builder : builders) {
        final Set<PsiFile> deps = builder.getDependencies().get(psiFile);
        if (deps != null) {
          depsByFile.addAll(deps);
        }
      }
      precomputedDeps = new HashSet<PsiFile>(depsByFile);
      precomputedDeps.retainAll(searchFor);
      if (precomputedDeps.isEmpty()) continue nextFile;
    }
    else {
      precomputedDeps = Collections.unmodifiableSet(searchFor);
    }

    DependenciesBuilder.analyzeFileDependencies(psiFile, new DependenciesBuilder.DependencyProcessor() {
      @Override
      public void process(PsiElement place, PsiElement dependency) {
        PsiFile dependencyFile = dependency.getContainingFile();
        if (precomputedDeps.contains(dependencyFile)) {
          usages.add(new UsageInfo(place));
        }
      }
    });
  }

  return usages.toArray(new UsageInfo[usages.size()]);
}
 
Example 19
Source File: CompletionAssertions.java    From consulo with Apache License 2.0 4 votes vote down vote up
static void assertCommitSuccessful(Editor editor, PsiFile psiFile) {
  Document document = editor.getDocument();
  int docLength = document.getTextLength();
  int psiLength = psiFile.getTextLength();
  PsiDocumentManager manager = PsiDocumentManager.getInstance(psiFile.getProject());
  boolean committed = !manager.isUncommited(document);
  if (docLength == psiLength && committed) {
    return;
  }

  FileViewProvider viewProvider = psiFile.getViewProvider();

  String message = "unsuccessful commit:";
  message += "\nmatching=" + (psiFile == manager.getPsiFile(document));
  message += "\ninjectedEditor=" + (editor instanceof EditorWindow);
  message += "\ninjectedFile=" + InjectedLanguageManager.getInstance(psiFile.getProject()).isInjectedFragment(psiFile);
  message += "\ncommitted=" + committed;
  message += "\nfile=" + psiFile.getName();
  message += "\nfile class=" + psiFile.getClass();
  message += "\nfile.valid=" + psiFile.isValid();
  message += "\nfile.physical=" + psiFile.isPhysical();
  message += "\nfile.eventSystemEnabled=" + viewProvider.isEventSystemEnabled();
  message += "\nlanguage=" + psiFile.getLanguage();
  message += "\ndoc.length=" + docLength;
  message += "\npsiFile.length=" + psiLength;
  String fileText = psiFile.getText();
  if (fileText != null) {
    message += "\npsiFile.text.length=" + fileText.length();
  }
  FileASTNode node = psiFile.getNode();
  if (node != null) {
    message += "\nnode.length=" + node.getTextLength();
    String nodeText = node.getText();
    message += "\nnode.text.length=" + nodeText.length();
  }
  VirtualFile virtualFile = viewProvider.getVirtualFile();
  message += "\nvirtualFile=" + virtualFile;
  message += "\nvirtualFile.class=" + virtualFile.getClass();
  message += "\n" + DebugUtil.currentStackTrace();

  throw new RuntimeExceptionWithAttachments("Commit unsuccessful", message, new Attachment(virtualFile.getPath() + "_file.txt", StringUtil.notNullize(fileText)), createAstAttachment(psiFile, psiFile),
                                            new Attachment("docText.txt", document.getText()));
}
 
Example 20
Source File: FlutterSaveActionsManager.java    From flutter-intellij with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
private void handleBeforeDocumentSaving(@NotNull Document document) {
  final FlutterSettings settings = FlutterSettings.getInstance();
  if (!settings.isFormatCodeOnSave()) {
    return;
  }

  if (!myProject.isInitialized() || myProject.isDisposed()) {
    return;
  }

  final VirtualFile file = FileDocumentManager.getInstance().getFile(document);
  if (file == null) {
    return;
  }

  if (!FlutterUtils.isDartFile(file)) {
    return;
  }

  final PsiFile psiFile = PsiDocumentManager.getInstance(myProject).getPsiFile(document);
  if (psiFile == null || !psiFile.isValid()) {
    return;
  }

  final Module module = ModuleUtil.findModuleForFile(file, myProject);
  if (module == null) {
    return;
  }

  if (!DartPlugin.isDartSdkEnabled(module)) {
    return;
  }

  // check for errors
  if (PsiErrorElementUtil.hasErrors(myProject, psiFile.getVirtualFile())) {
    return;
  }

  if (DartAnalysisServerService.getInstance(myProject).serverReadyForRequest()) {
    if (settings.isOrganizeImportsOnSave()) {
      performOrganizeThenFormat(document, file);
    }
    else {
      performFormat(document, file, false);
    }
  }
}