Exemplo n.º 1
0
 public void disableTool(@NotNull PsiElement element) {
   final Project project = element.getProject();
   final DependencyValidationManager validationManager =
       DependencyValidationManager.getInstance(project);
   if (myTools != null) {
     for (ScopeToolState state : myTools) {
       final NamedScope scope = state.getScope(project);
       if (scope != null) {
         final PackageSet packageSet = scope.getValue();
         if (packageSet != null) {
           final PsiFile file = element.getContainingFile();
           if (file != null) {
             if (packageSet.contains(file, validationManager)) {
               state.setEnabled(false);
               return;
             }
           } else {
             if (packageSet instanceof PackageSetBase
                 && ((PackageSetBase) packageSet)
                     .contains(PsiUtilCore.getVirtualFile(element), project, validationManager)) {
               state.setEnabled(false);
               return;
             }
           }
         }
       }
     }
     myDefaultState.setEnabled(false);
   } else {
     myDefaultState.setEnabled(false);
     setEnabled(false);
   }
 }
  public LineMarkerInfo getLineMarkerInfo(@NotNull PsiElement element) {
    if (ApplicationManager.getApplication().isUnitTestMode()) {
      return null;
    }

    if (!(element instanceof PsiMethod) && !(element instanceof PsiClass)) {
      return null;
    }

    if (!PsiUtil.isPluginProject(element.getProject())) {
      return null;
    }

    final VirtualFile file = PsiUtilCore.getVirtualFile(element);
    if (file == null
        || !ProjectFileIndex.SERVICE
            .getInstance(element.getProject())
            .isInTestSourceContent(file)) {
      return null;
    }
    if (element instanceof PsiMethod) {
      final PsiMethod method = (PsiMethod) element;
      if (isTestMethod(method)) {
        return new LineMarkerInfo<PsiMethod>(
            method,
            method.getModifierList().getTextRange(),
            PlatformIcons.TEST_SOURCE_FOLDER,
            Pass.UPDATE_ALL,
            null,
            new TestDataNavigationHandler(),
            GutterIconRenderer.Alignment.LEFT);
      }
    } else {
      final PsiClass psiClass = (PsiClass) element;
      final String basePath = getTestDataBasePath(psiClass);
      if (basePath != null) {
        PsiModifierList modifierList = psiClass.getModifierList();
        assert modifierList != null;
        return new LineMarkerInfo<PsiClass>(
            psiClass,
            modifierList.getTextRange(),
            PlatformIcons.TEST_SOURCE_FOLDER,
            Pass.UPDATE_ALL,
            new TooltipProvider(basePath),
            new GutterIconNavigationHandler<PsiClass>() {
              @Override
              public void navigate(MouseEvent e, PsiClass elt) {
                final VirtualFile baseDir = VfsUtil.findFileByIoFile(new File(basePath), true);
                if (baseDir != null) {
                  new OpenFileDescriptor(psiClass.getProject(), baseDir).navigate(true);
                }
              }
            },
            GutterIconRenderer.Alignment.LEFT);
      }
    }
    return null;
  }
 @Override
 public void setHighlightingEnabled(@NotNull PsiFile file, boolean value) {
   VirtualFile virtualFile = PsiUtilCore.getVirtualFile(file);
   if (value) {
     myDisabledHighlightingFiles.remove(virtualFile);
   } else {
     myDisabledHighlightingFiles.add(virtualFile);
   }
 }
  private static boolean notJetAnnotationEntry(final PsiElement found) {
    if (found instanceof JetAnnotationEntry) return false;

    VirtualFile faultyContainer = PsiUtilCore.getVirtualFile(found);
    LOG.error("Non annotation in annotations list: " + faultyContainer + "; element:" + found);
    if (faultyContainer != null && faultyContainer.isValid()) {
      FileBasedIndex.getInstance().requestReindex(faultyContainer);
    }

    return true;
  }
 @Override
 protected boolean isResolved(@NotNull JSReferenceExpression methodExpression) {
   if (JstdResolveUtil.isResolvedToFunction(methodExpression)) {
     return true;
   }
   VirtualFile virtualFile = PsiUtilCore.getVirtualFile(methodExpression);
   if (virtualFile != null) {
     return JstdLibraryUtil.isFileInJstdLibScope(methodExpression.getProject(), virtualFile);
   }
   return true;
 }
 public static boolean shouldEnableDeleteAction(PsiElement[] elements) {
   if (elements == null || elements.length == 0) return false;
   for (PsiElement element : elements) {
     VirtualFile virtualFile = PsiUtilCore.getVirtualFile(element);
     if (virtualFile == null) {
       return false;
     }
     if (!WritingAccessProvider.isPotentiallyWritable(virtualFile, element.getProject())) {
       return false;
     }
   }
   return true;
 }
  @Override
  public boolean isHighlightingAvailable(@Nullable PsiFile file) {
    if (file == null || !file.isPhysical()) return false;
    if (myDisabledHighlightingFiles.contains(PsiUtilCore.getVirtualFile(file))) return false;

    if (file instanceof PsiCompiledElement) return false;
    final FileType fileType = file.getFileType();
    if (fileType == StdFileTypes.GUI_DESIGNER_FORM) {
      return true;
    }
    // To enable T.O.D.O. highlighting
    return !fileType.isBinary();
  }
 private static void collectSourceRoots(
     PsiElement[] psiElements, ProjectFileIndex fileIndex, Set<VirtualFile> initialRoots) {
   for (PsiElement element : psiElements) {
     final VirtualFile file = PsiUtilCore.getVirtualFile(element);
     if (file != null) {
       final VirtualFile sourceRootForFile = fileIndex.getSourceRootForFile(file);
       if (sourceRootForFile != null) {
         initialRoots.add(sourceRootForFile);
       }
     } else if (element instanceof PsiDirectoryContainer) {
       collectSourceRoots(
           ((PsiDirectoryContainer) element).getDirectories(), fileIndex, initialRoots);
     }
   }
 }
  private static void checkAnnotationsJarAttached(@NotNull LocalInspectionToolSession session) {
    PsiFile file = session.getFile();
    final Project project = file.getProject();
    PsiClass event =
        JavaPsiFacade.getInstance(project)
            .findClass("java.awt.event.InputEvent", GlobalSearchScope.allScope(project));
    if (event == null) return; // no jdk to attach
    PsiMethod[] methods = event.findMethodsByName("getModifiers", false);
    if (methods.length != 1) return; // no jdk to attach
    PsiMethod getModifiers = methods[0];
    PsiAnnotation annotation =
        ExternalAnnotationsManager.getInstance(project)
            .findExternalAnnotation(getModifiers, MagicConstant.class.getName());
    if (annotation != null) return;
    final VirtualFile virtualFile = PsiUtilCore.getVirtualFile(getModifiers);
    if (virtualFile == null) return; // no jdk to attach
    final List<OrderEntry> entries =
        ProjectRootManager.getInstance(project).getFileIndex().getOrderEntriesForFile(virtualFile);
    Sdk jdk = null;
    for (OrderEntry orderEntry : entries) {
      if (orderEntry instanceof JdkOrderEntry) {
        jdk = ((JdkOrderEntry) orderEntry).getJdk();
        if (jdk != null) break;
      }
    }
    if (jdk == null) return; // no jdk to attach

    if (!ApplicationManager.getApplication().isUnitTestMode()) {
      final Sdk finalJdk = jdk;
      ApplicationManager.getApplication()
          .invokeLater(
              new Runnable() {
                @Override
                public void run() {
                  ApplicationManager.getApplication()
                      .runWriteAction(
                          new Runnable() {
                            public void run() {
                              attachJdkAnnotations(finalJdk);
                            }
                          });
                }
              },
              ModalityState.NON_MODAL,
              project.getDisposed());
    }
  }
 private static void addIdAndSuperClasses(PsiFile file, @NotNull TIntHashSet forward) {
   if (file instanceof PsiJavaFile
       && file.getName().equals("Object.class")
       && ((PsiJavaFile) file).getPackageName().equals("java.lang")) {
     return;
   }
   VirtualFile virtualFile = PsiUtilCore.getVirtualFile(file);
   if (virtualFile instanceof VirtualFileWithId
       && forward.add(getAbsId(virtualFile))
       && file instanceof PsiClassOwner) {
     for (PsiClass aClass : ((PsiClassOwner) file).getClasses()) {
       for (PsiClass superClass : aClass.getSupers()) {
         addIdAndSuperClasses(superClass.getContainingFile(), forward);
       }
     }
   }
 }
 @Override
 public void invoke(@NotNull final Project project, Editor editor, final PsiFile file)
     throws IncorrectOperationException {
   UIUtil.invokeLaterIfNeeded(
       () -> {
         List<VirtualFile> sources = getLibrarySourceFiles();
         final VirtualFile fileRequestor = PsiUtilCore.getVirtualFile(file);
         DialogWrapper dialog =
             new ChooseScopeAndCreateLibraryDialog(
                 project,
                 JstdLibraryUtil.LIBRARY_NAME,
                 sources,
                 new ScriptingFrameworkDescriptor(JstdLibraryUtil.LIBRARY_NAME, "1.3.5"),
                 fileRequestor,
                 false);
         boolean done = dialog.showAndGet();
         if (done) {
           FileContentUtil.reparseFiles(project, Collections.singletonList(fileRequestor), true);
         }
       });
 }
  public static <Key, Psi extends PsiElement> Collection<Psi> safeGet(
      @NotNull StubIndexKey<Key, Psi> indexKey,
      @NotNull Key key,
      final Project project,
      final GlobalSearchScope scope,
      Class<Psi> requiredClass) {
    Collection<Psi> collection = getInstance().get(indexKey, key, project, scope);
    for (Iterator<Psi> iterator = collection.iterator(); iterator.hasNext(); ) {
      Psi psi = iterator.next();
      if (!requiredClass.isInstance(psi)) {
        iterator.remove();

        VirtualFile faultyContainer = PsiUtilCore.getVirtualFile(psi);
        LOG.error("Invalid stub element type in index: " + faultyContainer + ". found: " + psi);
        if (faultyContainer != null && faultyContainer.isValid()) {
          FileBasedIndex.getInstance().requestReindex(faultyContainer);
        }
      }
    }

    return collection;
  }
 @Override
 public boolean isAvailableOnElement(@NotNull PsiElement element) {
   final VirtualFile virtualFile = PsiUtilCore.getVirtualFile(element);
   if (virtualFile != null
       && ProjectRootManager.getInstance(element.getProject())
           .getFileIndex()
           .isInLibraryClasses(virtualFile)) return false;
   if (element instanceof PyTargetExpression) {
     final PyAssignmentStatement assignmentStatement =
         PsiTreeUtil.getParentOfType(element, PyAssignmentStatement.class);
     if (assignmentStatement != null) {
       final PyExpression assignedValue = assignmentStatement.getAssignedValue();
       if (assignedValue == null) return false;
       final String name = assignedValue.getText();
       return name != null && (PyNames.TRUE.equals(name) || PyNames.FALSE.equals(name));
     }
   }
   if (element instanceof PyNamedParameter) {
     final PyExpression defaultValue = ((PyNamedParameter) element).getDefaultValue();
     if (defaultValue instanceof PyBoolLiteralExpression) return true;
   }
   return element.getParent() instanceof PyBoolLiteralExpression;
 }
Exemplo n.º 14
0
 private void commitToOriginal(final DocumentEvent e) {
   VirtualFile origVirtualFile = PsiUtilCore.getVirtualFile(myNewFile.getContext());
   myCommittingToOriginal = true;
   try {
     if (origVirtualFile == null
         || !ReadonlyStatusHandler.getInstance(myProject)
             .ensureFilesWritable(origVirtualFile)
             .hasReadonlyFiles()) {
       PostprocessReformattingAspect.getInstance(myProject)
           .disablePostprocessFormattingInside(
               () -> {
                 if (myAltFullRange != null) {
                   altCommitToOriginal(e);
                   return;
                 }
                 commitToOriginalInner();
               });
       PsiDocumentManager.getInstance(myProject)
           .doPostponedOperationsAndUnblockDocument(myOrigDocument);
     }
   } finally {
     myCommittingToOriginal = false;
   }
 }
  @Override
  @NotNull
  public List<TextEditorHighlightingPass> instantiatePasses(
      @NotNull final PsiFile psiFile,
      @NotNull final Editor editor,
      @NotNull final int[] passesToIgnore) {
    synchronized (this) {
      if (!checkedForCycles) {
        checkedForCycles = true;
        checkForCycles();
      }
    }
    PsiDocumentManager documentManager = PsiDocumentManager.getInstance(myProject);
    final Document document = editor.getDocument();
    PsiFile fileFromDoc = documentManager.getPsiFile(document);
    if (!(fileFromDoc instanceof PsiCompiledElement)) {
      assert fileFromDoc == psiFile : "Files are different: " + psiFile + ";" + fileFromDoc;
      Document documentFromFile = documentManager.getDocument(psiFile);
      assert documentFromFile == document
          : "Documents are different. Doc: "
              + document
              + "; Doc from file: "
              + documentFromFile
              + "; File: "
              + psiFile
              + "; Virtual file: "
              + PsiUtilCore.getVirtualFile(psiFile);
    }
    final TIntObjectHashMap<TextEditorHighlightingPass> id2Pass =
        new TIntObjectHashMap<TextEditorHighlightingPass>();
    final TIntArrayList passesRefusedToCreate = new TIntArrayList();
    myRegisteredPassFactories.forEachKey(
        new TIntProcedure() {
          @Override
          public boolean execute(int passId) {
            if (ArrayUtil.find(passesToIgnore, passId) != -1) {
              return true;
            }
            PassConfig passConfig = myRegisteredPassFactories.get(passId);
            TextEditorHighlightingPassFactory factory = passConfig.passFactory;
            final TextEditorHighlightingPass pass = factory.createHighlightingPass(psiFile, editor);

            if (pass == null) {
              passesRefusedToCreate.add(passId);
            } else {
              // init with editor's colors scheme
              pass.setColorsScheme(editor.getColorsScheme());

              TIntArrayList ids = new TIntArrayList(passConfig.completionPredecessorIds.length);
              for (int id : passConfig.completionPredecessorIds) {
                if (myRegisteredPassFactories.containsKey(id)) ids.add(id);
              }
              pass.setCompletionPredecessorIds(
                  ids.isEmpty() ? ArrayUtil.EMPTY_INT_ARRAY : ids.toNativeArray());
              ids = new TIntArrayList(passConfig.startingPredecessorIds.length);
              for (int id : passConfig.startingPredecessorIds) {
                if (myRegisteredPassFactories.containsKey(id)) ids.add(id);
              }
              pass.setStartingPredecessorIds(
                  ids.isEmpty() ? ArrayUtil.EMPTY_INT_ARRAY : ids.toNativeArray());
              pass.setId(passId);
              id2Pass.put(passId, pass);
            }
            return true;
          }
        });

    DaemonCodeAnalyzerEx daemonCodeAnalyzer = DaemonCodeAnalyzerEx.getInstanceEx(myProject);
    final FileStatusMap statusMap = daemonCodeAnalyzer.getFileStatusMap();
    passesRefusedToCreate.forEach(
        new TIntProcedure() {
          @Override
          public boolean execute(int passId) {
            statusMap.markFileUpToDate(document, passId);
            return true;
          }
        });

    return (List) Arrays.asList(id2Pass.getValues());
  }