private void createTreeModel() {
    final PsiManager psiManager = PsiManager.getInstance(myProject);
    final FileIndex fileIndex =
        myModule != null
            ? ModuleRootManager.getInstance(myModule).getFileIndex()
            : ProjectRootManager.getInstance(myProject).getFileIndex();
    fileIndex.iterateContent(
        new ContentIterator() {
          public boolean processFile(VirtualFile fileOrDir) {
            if (fileOrDir.isDirectory() && fileIndex.isInSourceContent(fileOrDir)) {
              final PsiDirectory psiDirectory = psiManager.findDirectory(fileOrDir);
              LOG.assertTrue(psiDirectory != null);
              PsiPackage aPackage = JavaDirectoryService.getInstance().getPackage(psiDirectory);
              if (aPackage != null) {
                addPackage(aPackage);
              }
            }
            return true;
          }
        });

    TreeUtil.sort(
        myModel,
        new Comparator() {
          public int compare(Object o1, Object o2) {
            DefaultMutableTreeNode n1 = (DefaultMutableTreeNode) o1;
            DefaultMutableTreeNode n2 = (DefaultMutableTreeNode) o2;
            PsiNamedElement element1 = (PsiNamedElement) n1.getUserObject();
            PsiNamedElement element2 = (PsiNamedElement) n2.getUserObject();
            return element1.getName().compareToIgnoreCase(element2.getName());
          }
        });
  }
Exemplo n.º 2
0
    public void merge(final Binding b, final boolean removeObject) {
      for (final PsiTypeVariable var : b.getBoundVariables()) {
        final int index = var.getIndex();

        if (myBindings.get(index) != null) {
          LOG.error("Oops... Binding conflict...");
        } else {
          final PsiType type = b.apply(var);
          final PsiClassType javaLangObject =
              PsiType.getJavaLangObject(
                  PsiManager.getInstance(myProject), GlobalSearchScope.allScope(myProject));

          if (removeObject && javaLangObject.equals(type)) {
            final HashSet<PsiTypeVariable> cluster = myFactory.getClusterOf(var.getIndex());

            if (cluster != null) {
              for (final PsiTypeVariable war : cluster) {
                final PsiType wtype = b.apply(war);

                if (!javaLangObject.equals(wtype)) {
                  myBindings.put(index, type);
                  break;
                }
              }
            }
          } else {
            myBindings.put(index, type);
          }
        }
      }
    }
  @Nullable
  static HighlightInfo checkFileDuplicates(@NotNull PsiJavaModule element, @NotNull PsiFile file) {
    Module module = ModuleUtilCore.findModuleForPsiElement(element);
    if (module != null) {
      Project project = file.getProject();
      Collection<VirtualFile> others =
          FilenameIndex.getVirtualFilesByName(project, MODULE_INFO_FILE, new ModulesScope(module));
      if (others.size() > 1) {
        String message = JavaErrorMessages.message("module.file.duplicate");
        HighlightInfo info =
            HighlightInfo.newHighlightInfo(HighlightInfoType.ERROR)
                .range(range(element))
                .description(message)
                .create();
        others
            .stream()
            .map(f -> PsiManager.getInstance(project).findFile(f))
            .filter(f -> f != file)
            .findFirst()
            .ifPresent(
                duplicate ->
                    QuickFixAction.registerQuickFixAction(
                        info,
                        new GoToSymbolFix(
                            duplicate, JavaErrorMessages.message("module.open.duplicate.text"))));
        return info;
      }
    }

    return null;
  }
  @Nullable
  public static PsiDirectory selectFolderDir(
      final Project project, VirtualFile res, ResourceFolderType folderType) {
    final PsiDirectory directory = PsiManager.getInstance(project).findDirectory(res);
    if (directory == null) {
      return null;
    }
    if (ApplicationManager.getApplication().isUnitTestMode() && ourTargetFolderName != null) {
      PsiDirectory subDirectory = directory.findSubdirectory(ourTargetFolderName);
      if (subDirectory != null) {
        return subDirectory;
      }
      return directory.createSubdirectory(ourTargetFolderName);
    }
    final CreateResourceDirectoryDialog dialog =
        new CreateResourceDirectoryDialog(project, folderType, directory, null) {
          @Override
          protected InputValidator createValidator() {
            return new ResourceDirectorySelector(project, directory);
          }
        };
    dialog.setTitle("Select Resource Directory");
    dialog.show();
    final InputValidator validator = dialog.getValidator();
    if (validator != null) {
      PsiElement[] createdElements = ((ResourceDirectorySelector) validator).getCreatedElements();
      if (createdElements != null && createdElements.length > 0) {
        return (PsiDirectory) createdElements[0];
      }
    }

    return null;
  }
Exemplo n.º 5
0
 @Nullable
 public static PsiDirectory findPossiblePackageDirectoryInModule(
     Module module, String packageName) {
   PsiDirectory psiDirectory = null;
   if (!"".equals(packageName)) {
     PsiPackage rootPackage = findLongestExistingPackage(module.getProject(), packageName);
     if (rootPackage != null) {
       final PsiDirectory[] psiDirectories = getPackageDirectoriesInModule(rootPackage, module);
       if (psiDirectories.length > 0) {
         psiDirectory = psiDirectories[0];
       }
     }
   }
   if (psiDirectory == null) {
     if (checkSourceRootsConfigured(module)) {
       final List<VirtualFile> sourceRoots =
           ModuleRootManager.getInstance(module).getSourceRoots(JavaModuleSourceRootTypes.SOURCES);
       for (VirtualFile sourceRoot : sourceRoots) {
         final PsiDirectory directory =
             PsiManager.getInstance(module.getProject()).findDirectory(sourceRoot);
         if (directory != null) {
           psiDirectory = directory;
           break;
         }
       }
     }
   }
   return psiDirectory;
 }
  @Nullable
  private static PsiElement getElementToCopy(
      @Nullable final Editor editor, final DataContext dataContext) {
    PsiElement element = null;
    if (editor != null) {
      PsiReference reference = TargetElementUtilBase.findReference(editor);
      if (reference != null) {
        element = reference.getElement();
      }
    }

    if (element == null) {
      element = LangDataKeys.PSI_ELEMENT.getData(dataContext);
    }
    if (element == null && editor == null) {
      VirtualFile virtualFile = PlatformDataKeys.VIRTUAL_FILE.getData(dataContext);
      Project project = PlatformDataKeys.PROJECT.getData(dataContext);
      if (virtualFile != null && project != null) {
        element = PsiManager.getInstance(project).findFile(virtualFile);
      }
    }
    if (element instanceof PsiFile && !((PsiFile) element).getViewProvider().isPhysical()) {
      return null;
    }

    for (QualifiedNameProvider provider : Extensions.getExtensions(QualifiedNameProvider.EP_NAME)) {
      PsiElement adjustedElement = provider.adjustElementToCopy(element);
      if (adjustedElement != null) return adjustedElement;
    }
    return element;
  }
 @Nullable
 @Override
 public RefEntity getReference(final String type, final String fqName) {
   for (RefManagerExtension extension : myExtensions.values()) {
     final RefEntity refEntity = extension.getReference(type, fqName);
     if (refEntity != null) return refEntity;
   }
   if (SmartRefElementPointer.FILE.equals(type)) {
     return RefFileImpl.fileFromExternalName(this, fqName);
   }
   if (SmartRefElementPointer.MODULE.equals(type)) {
     return RefModuleImpl.moduleFromName(this, fqName);
   }
   if (SmartRefElementPointer.PROJECT.equals(type)) {
     return getRefProject();
   }
   if (SmartRefElementPointer.DIR.equals(type)) {
     String url =
         VfsUtilCore.pathToUrl(PathMacroManager.getInstance(getProject()).expandPath(fqName));
     VirtualFile vFile = VirtualFileManager.getInstance().findFileByUrl(url);
     if (vFile != null) {
       final PsiDirectory dir = PsiManager.getInstance(getProject()).findDirectory(vFile);
       return getReference(dir);
     }
   }
   return null;
 }
Exemplo n.º 8
0
  @Nullable
  public static PsiClass[] getAllTestClasses(final TestClassFilter filter, boolean sync) {
    final PsiClass[][] holder = new PsiClass[1][];
    final Runnable process =
        () -> {
          final ProgressIndicator indicator = ProgressManager.getInstance().getProgressIndicator();

          final Collection<PsiClass> set = new LinkedHashSet<>();
          final PsiManager manager = PsiManager.getInstance(filter.getProject());
          final GlobalSearchScope projectScope =
              GlobalSearchScope.projectScope(manager.getProject());
          final GlobalSearchScope scope = projectScope.intersectWith(filter.getScope());
          for (final PsiClass psiClass : AllClassesSearch.search(scope, manager.getProject())) {
            if (filter.isAccepted(psiClass)) {
              if (indicator != null) {
                indicator.setText2(
                    "Found test class " + ReadAction.compute(psiClass::getQualifiedName));
              }
              set.add(psiClass);
            }
          }
          holder[0] = set.toArray(new PsiClass[set.size()]);
        };
    if (sync) {
      ProgressManager.getInstance()
          .runProcessWithProgressSynchronously(
              process, "Searching For Tests...", true, filter.getProject());
    } else {
      process.run();
    }
    return holder[0];
  }
Exemplo n.º 9
0
    @Override
    public void hyperlinkUpdate(@NotNull HyperlinkEvent e) {
      if (e.getEventType() != HyperlinkEvent.EventType.ACTIVATED) {
        return;
      }

      String description = e.getDescription();
      if (StringUtil.isEmpty(description)
          || !description.startsWith(DocumentationManager.PSI_ELEMENT_PROTOCOL)) {
        return;
      }

      String elementName =
          e.getDescription().substring(DocumentationManager.PSI_ELEMENT_PROTOCOL.length());

      final PsiElement targetElement =
          myProvider.getDocumentationElementForLink(
              PsiManager.getInstance(myProject), elementName, myContext);
      if (targetElement != null) {
        LightweightHint hint = myHint;
        if (hint != null) {
          hint.hide(true);
        }
        myDocumentationManager.showJavaDocInfo(targetElement, myContext, true, null);
      }
    }
    @Override
    public void navigate(Project project) {
      VirtualFile currentVirtualFile = null;

      AccessToken accessToken = ReadAction.start();

      try {
        if (!myVirtualFile.isValid()) return;

        PsiFile psiFile = PsiManager.getInstance(project).findFile(myVirtualFile);
        if (psiFile != null) {
          PsiElement navigationElement =
              psiFile.getNavigationElement(); // Sources may be downloaded.
          if (navigationElement instanceof PsiFile) {
            currentVirtualFile = ((PsiFile) navigationElement).getVirtualFile();
          }
        }

        if (currentVirtualFile == null) {
          currentVirtualFile = myVirtualFile;
        }
      } finally {
        accessToken.finish();
      }

      new OpenFileHyperlinkInfo(myProject, currentVirtualFile, myLineNumber - 1).navigate(project);
    }
    private PsiElement[] getElementsToDelete() {
      ArrayList<PsiElement> result = new ArrayList<PsiElement>();
      Object[] elements = getSelectedNodeElements();
      for (int idx = 0; elements != null && idx < elements.length; idx++) {
        if (elements[idx] instanceof PsiElement) {
          final PsiElement element = (PsiElement) elements[idx];
          result.add(element);
          if (element instanceof PsiDirectory) {
            final VirtualFile virtualFile = ((PsiDirectory) element).getVirtualFile();
            final String path = virtualFile.getPath();
            if (path.endsWith(JarFileSystem.JAR_SEPARATOR)) { // if is jar-file root
              final VirtualFile vFile =
                  LocalFileSystem.getInstance()
                      .findFileByPath(
                          path.substring(0, path.length() - JarFileSystem.JAR_SEPARATOR.length()));
              if (vFile != null) {
                final PsiFile psiFile = PsiManager.getInstance(myProject).findFile(vFile);
                if (psiFile != null) {
                  elements[idx] = psiFile;
                }
              }
            }
          }
        }
      }

      return result.toArray(new PsiElement[result.size()]);
    }
Exemplo n.º 12
0
    public PsiType apply(final PsiType type) {
      if (type instanceof PsiTypeVariable) {
        final PsiType t = myBindings.get(((PsiTypeVariable) type).getIndex());
        return t == null ? type : t;
      } else if (type instanceof PsiArrayType) {
        return apply(((PsiArrayType) type).getComponentType()).createArrayType();
      } else if (type instanceof PsiClassType) {
        final PsiClassType.ClassResolveResult result = Util.resolveType(type);
        final PsiClass theClass = result.getElement();
        final PsiSubstitutor aSubst = result.getSubstitutor();

        PsiSubstitutor theSubst = PsiSubstitutor.EMPTY;

        if (theClass != null) {
          for (final PsiTypeParameter aParm : aSubst.getSubstitutionMap().keySet()) {
            final PsiType aType = aSubst.substitute(aParm);

            theSubst = theSubst.put(aParm, apply(aType));
          }

          return JavaPsiFacade.getInstance(theClass.getProject())
              .getElementFactory()
              .createType(theClass, theSubst);
        } else {
          return type;
        }
      } else if (type instanceof PsiWildcardType) {
        final PsiWildcardType wcType = (PsiWildcardType) type;
        final PsiType bound = wcType.getBound();

        if (bound != null) {
          final PsiType abound = apply(bound);

          if (abound instanceof PsiWildcardType) {
            return null;
          }

          return wcType.isExtends()
              ? PsiWildcardType.createExtends(PsiManager.getInstance(myProject), abound)
              : PsiWildcardType.createSuper(PsiManager.getInstance(myProject), abound);
        }

        return type;
      } else {
        return type;
      }
    }
Exemplo n.º 13
0
    public KotlinPsiElementFinderImpl(Project project) {
      this.javaFileManager = findJavaFileManager(project);
      this.psiPackageManager = PsiPackageManager.getInstance(project);
      this.isCliFileManager = javaFileManager instanceof KotlinCliJavaFileManager;

      this.packageIndex = DirectoryIndex.getInstance(project);
      this.psiManager = PsiManager.getInstance(project);
    }
Exemplo n.º 14
0
 protected PsiPackage getPackage(JUnitConfiguration.Data data) throws CantRunException {
   final Project project = myConfiguration.getProject();
   final String packageName = data.getPackageName();
   final PsiManager psiManager = PsiManager.getInstance(project);
   final PsiPackage aPackage =
       JavaPsiFacade.getInstance(psiManager.getProject()).findPackage(packageName);
   if (aPackage == null) throw CantRunException.packageNotFound(packageName);
   return aPackage;
 }
 @NotNull
 @Override
 public PsiType getForcedType() {
   final PsiType selectedType = mySettings.getSelectedType();
   if (selectedType != null) return selectedType;
   final PsiManager manager = PsiManager.getInstance(myProject);
   final GlobalSearchScope resolveScope = mySettings.getToReplaceIn().getResolveScope();
   return PsiType.getJavaLangObject(manager, resolveScope);
 }
  public static void invokeImpl(
      Project project, Editor editor, final PsiFile file, Injectable injectable) {
    final PsiLanguageInjectionHost host = findInjectionHost(editor, file);
    if (host == null) return;
    if (defaultFunctionalityWorked(host, injectable.getId())) return;

    try {
      host.putUserData(FIX_KEY, null);
      Language language = injectable.toLanguage();
      for (LanguageInjectionSupport support : InjectorUtils.getActiveInjectionSupports()) {
        if (support.isApplicableTo(host) && support.addInjectionInPlace(language, host)) {
          return;
        }
      }
      if (TemporaryPlacesRegistry.getInstance(project)
          .getLanguageInjectionSupport()
          .addInjectionInPlace(language, host)) {
        final Processor<PsiLanguageInjectionHost> data = host.getUserData(FIX_KEY);
        String text =
            StringUtil.escapeXml(language.getDisplayName()) + " was temporarily injected.";
        if (data != null) {
          if (!ApplicationManager.getApplication().isUnitTestMode()) {
            final SmartPsiElementPointer<PsiLanguageInjectionHost> pointer =
                SmartPointerManager.getInstance(project).createSmartPsiElementPointer(host);
            final TextRange range = host.getTextRange();
            HintManager.getInstance()
                .showQuestionHint(
                    editor,
                    text
                        + "<br>Do you want to insert annotation? "
                        + KeymapUtil.getFirstKeyboardShortcutText(
                            ActionManager.getInstance()
                                .getAction(IdeActions.ACTION_SHOW_INTENTION_ACTIONS)),
                    range.getStartOffset(),
                    range.getEndOffset(),
                    new QuestionAction() {
                      @Override
                      public boolean execute() {
                        return data.process(pointer.getElement());
                      }
                    });
          }
        } else {
          HintManager.getInstance().showInformationHint(editor, text);
        }
      }
    } finally {
      if (injectable.getLanguage() != null) { // no need for reference injection
        FileContentUtil.reparseFiles(project, Collections.<VirtualFile>emptyList(), true);
      } else {
        ((PsiModificationTrackerImpl) PsiManager.getInstance(project).getModificationTracker())
            .incCounter();
        DaemonCodeAnalyzer.getInstance(project).restart();
      }
    }
  }
Exemplo n.º 17
0
  public static void doTearDown() throws Exception {
    UsefulTestCase.doPostponedFormatting(ourProject);

    LookupManager.getInstance(ourProject).hideActiveLookup();

    InspectionProfileManager.getInstance().deleteProfile(PROFILE);
    assertNotNull("Application components damaged", ProjectManager.getInstance());

    ApplicationManager.getApplication()
        .runWriteAction(
            new Runnable() {
              public void run() {
                try {
                  final VirtualFile[] children = ourSourceRoot.getChildren();
                  for (VirtualFile child : children) {
                    child.delete(this);
                  }
                } catch (IOException e) {
                  //noinspection CallToPrintStackTrace
                  e.printStackTrace();
                }
                FileDocumentManager manager = FileDocumentManager.getInstance();
                if (manager instanceof FileDocumentManagerImpl) {
                  ((FileDocumentManagerImpl) manager).dropAllUnsavedDocuments();
                }
              }
            });
    //    final Project[] openProjects = ProjectManagerEx.getInstanceEx().getOpenProjects();
    //    assertTrue(Arrays.asList(openProjects).contains(ourProject));
    assertFalse(PsiManager.getInstance(getProject()).isDisposed());
    if (!ourAssertionsInTestDetected) {
      if (IdeaLogger.ourErrorsOccurred != null) {
        throw IdeaLogger.ourErrorsOccurred;
      }
      // assertTrue("Logger errors occurred. ", IdeaLogger.ourErrorsOccurred == null);
    }
    ((PsiDocumentManagerImpl) PsiDocumentManager.getInstance(getProject()))
        .clearUncommitedDocuments();

    ((UndoManagerImpl) UndoManager.getGlobalInstance()).dropHistoryInTests();

    ProjectManagerEx.getInstanceEx().setCurrentTestProject(null);
    ourApplication.setDataProvider(null);
    ourTestCase = null;
    ((PsiManagerImpl) ourPsiManager).cleanupForNextTest();

    final Editor[] allEditors = EditorFactory.getInstance().getAllEditors();
    if (allEditors.length > 0) {
      for (Editor allEditor : allEditors) {
        EditorFactory.getInstance().releaseEditor(allEditor);
      }
      fail("Unreleased editors: " + allEditors.length);
    }
  }
  public void testExternalFileModificationWhileProjectClosed() throws Exception {
    VirtualFile root = ProjectRootManager.getInstance(myProject).getContentRoots()[0];

    PsiClass objectClass =
        myJavaFacade.findClass(
            CommonClassNames.JAVA_LANG_OBJECT, GlobalSearchScope.allScope(getProject()));
    assertNotNull(objectClass);
    checkUsages(objectClass, new String[] {});
    FileBasedIndex.getInstance()
        .getContainingFiles(
            TodoIndex.NAME,
            new TodoIndexEntry("todo", true),
            GlobalSearchScope.allScope(getProject()));

    final String projectLocation = myProject.getPresentableUrl();
    assert projectLocation != null : myProject;
    PlatformTestUtil.saveProject(myProject);
    final VirtualFile content = ModuleRootManager.getInstance(getModule()).getContentRoots()[0];
    Project project = myProject;
    ProjectUtil.closeAndDispose(project);
    InjectedLanguageManagerImpl.checkInjectorsAreDisposed(project);

    assertTrue("Project was not disposed", myProject.isDisposed());
    myModule = null;

    final File file = new File(root.getPath(), "1.java");
    assertTrue(file.exists());

    FileUtil.writeToFile(file, "class A{ Object o;}".getBytes(CharsetToolkit.UTF8_CHARSET));
    root.refresh(false, true);

    LocalFileSystem.getInstance().refresh(false);

    myProject = ProjectManager.getInstance().loadAndOpenProject(projectLocation);
    InjectedLanguageManagerImpl.pushInjectors(getProject());

    setUpModule();
    setUpJdk();
    ProjectManagerEx.getInstanceEx().openTestProject(myProject);
    UIUtil.dispatchAllInvocationEvents(); // startup activities

    runStartupActivities();
    PsiTestUtil.addSourceContentToRoots(getModule(), content);

    assertNotNull(myProject);
    myPsiManager = (PsiManagerImpl) PsiManager.getInstance(myProject);
    myJavaFacade = JavaPsiFacadeEx.getInstanceEx(myProject);

    objectClass =
        myJavaFacade.findClass(
            CommonClassNames.JAVA_LANG_OBJECT, GlobalSearchScope.allScope(getProject()));
    assertNotNull(objectClass);
    checkUsages(objectClass, new String[] {"1.java"});
  }
Exemplo n.º 19
0
 @Nullable
 private static DeclarationDescriptor findSuperFunction(
     @NotNull Collection<Pair<FunctionDescriptor, PsiMethod>> superFunctionCandidates,
     @NotNull PsiMethod superMethod) {
   PsiManager psiManager = PsiManager.getInstance(superMethod.getProject());
   for (Pair<FunctionDescriptor, PsiMethod> candidate : superFunctionCandidates) {
     if (psiManager.areElementsEquivalent(candidate.second, superMethod)) {
       return candidate.first;
     }
   }
   return null;
 }
  private static void checkMagicParameterArgument(
      @NotNull PsiParameter parameter,
      PsiExpression argument,
      @NotNull AllowedValues allowedValues,
      @NotNull ProblemsHolder holder) {
    final PsiManager manager = PsiManager.getInstance(holder.getProject());

    if (!argument.getTextRange().isEmpty()
        && !isAllowed(parameter.getDeclarationScope(), argument, allowedValues, manager)) {
      registerProblem(argument, allowedValues, holder);
    }
  }
  @Nullable
  private <T> T processSchema(String schema, SchemaProcessor<T> processor) {
    VirtualFile file = MavenSchemaProvider.getSchemaFile(schema);
    PsiFile psiFile = PsiManager.getInstance(myProject).findFile(file);
    if (!(psiFile instanceof XmlFile)) return null;

    XmlFile xmlFile = (XmlFile) psiFile;
    XmlDocument document = xmlFile.getDocument();
    XmlNSDescriptor desc = (XmlNSDescriptor) document.getMetaData();
    XmlElementDescriptor[] descriptors = desc.getRootElementsDescriptors(document);
    return doProcessSchema(descriptors, null, processor, new THashSet<XmlElementDescriptor>());
  }
  public MoveClassesOrPackagesDialog(
      Project project,
      boolean searchTextOccurences,
      PsiElement[] elementsToMove,
      final PsiElement initialTargetElement,
      MoveCallback moveCallback) {
    super(project, true);
    myElementsToMove = elementsToMove;
    myMoveCallback = moveCallback;
    myManager = PsiManager.getInstance(myProject);
    setTitle(MoveHandler.REFACTORING_NAME);
    mySearchTextOccurencesEnabled = searchTextOccurences;

    selectInitialCard();

    init();

    if (initialTargetElement instanceof PsiClass) {
      myMakeInnerClassOfRadioButton.setSelected(true);

      myInnerClassChooser.setText(((PsiClass) initialTargetElement).getQualifiedName());

      ApplicationManager.getApplication()
          .invokeLater(
              () -> myInnerClassChooser.requestFocus(),
              ModalityState.stateForComponent(myMainPanel));
    } else if (initialTargetElement instanceof PsiPackage) {
      myClassPackageChooser.setText(((PsiPackage) initialTargetElement).getQualifiedName());
    }

    updateControlsEnabled();
    myToPackageRadioButton.addActionListener(
        new ActionListener() {
          public void actionPerformed(ActionEvent e) {
            updateControlsEnabled();
            myClassPackageChooser.requestFocus();
          }
        });
    myMakeInnerClassOfRadioButton.addActionListener(
        new ActionListener() {
          public void actionPerformed(ActionEvent e) {
            updateControlsEnabled();
            myInnerClassChooser.requestFocus();
          }
        });

    for (PsiElement element : elementsToMove) {
      if (element.getContainingFile() != null) {
        myOpenInEditorPanel.add(initOpenInEditorCb(), BorderLayout.EAST);
        break;
      }
    }
  }
Exemplo n.º 23
0
    public PsiType substitute(final PsiType t) {
      if (t instanceof PsiWildcardType) {
        final PsiWildcardType wcType = (PsiWildcardType) t;
        final PsiType bound = wcType.getBound();

        if (bound == null) {
          return t;
        }

        final PsiManager manager = PsiManager.getInstance(myProject);
        final PsiType subst = substitute(bound);
        if (subst == null) return null;
        return subst instanceof PsiWildcardType
            ? subst
            : wcType.isExtends()
                ? PsiWildcardType.createExtends(manager, subst)
                : PsiWildcardType.createSuper(manager, subst);
      } else if (t instanceof PsiTypeVariable) {
        final PsiType b = apply(t);

        if (b instanceof Bottom || b instanceof PsiTypeVariable) {
          return null;
        }

        return substitute(b);
      } else if (t instanceof Bottom) {
        return null;
      } else if (t instanceof PsiArrayType) {
        return substitute(((PsiArrayType) t).getComponentType()).createArrayType();
      } else if (t instanceof PsiClassType) {
        final PsiClassType.ClassResolveResult result = ((PsiClassType) t).resolveGenerics();

        final PsiClass aClass = result.getElement();
        final PsiSubstitutor aSubst = result.getSubstitutor();

        if (aClass != null) {
          PsiSubstitutor theSubst = PsiSubstitutor.EMPTY;

          for (final PsiTypeParameter parm : aSubst.getSubstitutionMap().keySet()) {
            final PsiType type = aSubst.substitute(parm);

            theSubst = theSubst.put(parm, substitute(type));
          }

          return JavaPsiFacade.getInstance(aClass.getProject())
              .getElementFactory()
              .createType(aClass, theSubst);
        }
      }
      return t;
    }
Exemplo n.º 24
0
 @Override
 @Nullable
 public PsiFile getFile() {
   if (myProject.isDisposed() || !myVirtualFile.isValid()) {
     return null;
   }
   final PsiFile file = PsiManager.getInstance(myProject).findFile(myVirtualFile);
   if (file == null) {
     return null;
   }
   if (file.getLanguage() == myLanguage) {
     return file;
   }
   return file.getViewProvider().getPsi(myLanguage);
 }
Exemplo n.º 25
0
 private static PsiPackage findLongestExistingPackage(Project project, String packageName) {
   PsiManager manager = PsiManager.getInstance(project);
   String nameToMatch = packageName;
   while (true) {
     PsiPackage aPackage =
         JavaPsiFacade.getInstance(manager.getProject()).findPackage(nameToMatch);
     if (aPackage != null && isWritablePackage(aPackage)) return aPackage;
     int lastDotIndex = nameToMatch.lastIndexOf('.');
     if (lastDotIndex >= 0) {
       nameToMatch = nameToMatch.substring(0, lastDotIndex);
     } else {
       return null;
     }
   }
 }
Exemplo n.º 26
0
 @NotNull
 public static CharSequence decompile(@NotNull VirtualFile file) {
   PsiManager manager =
       PsiManager.getInstance(DefaultProjectFactory.getInstance().getDefaultProject());
   final ClsFileImpl clsFile = new ClsFileImpl(new ClassFileViewProvider(manager, file), true);
   final StringBuilder buffer = new StringBuilder();
   ApplicationManager.getApplication()
       .runReadAction(
           new Runnable() {
             @Override
             public void run() {
               clsFile.appendMirrorText(0, buffer);
             }
           });
   return buffer;
 }
  @SuppressWarnings("ConstantConditions")
  public void testCustomTagCompletion0() throws Throwable {
    final VirtualFile labelViewJava =
        copyFileToProject("LabelView.java", "src/p1/p2/LabelView.java");

    VirtualFile lf1 =
        myFixture.copyFileToProject(testFolder + '/' + "ctn0.xml", "res/layout/layout1.xml");
    myFixture.configureFromExistingVirtualFile(lf1);
    myFixture.complete(CompletionType.BASIC);
    List<String> variants = myFixture.getLookupElementStrings();
    assertTrue(variants.contains("p1.p2.LabelView"));

    final PsiFile psiLabelViewFile = PsiManager.getInstance(getProject()).findFile(labelViewJava);
    assertInstanceOf(psiLabelViewFile, PsiJavaFile.class);
    final PsiClass labelViewClass = ((PsiJavaFile) psiLabelViewFile).getClasses()[0];
    assertNotNull(labelViewClass);
    myFixture.renameElement(labelViewClass, "LabelView1");

    VirtualFile lf2 =
        myFixture.copyFileToProject(testFolder + '/' + "ctn0.xml", "res/layout/layout2.xml");
    myFixture.configureFromExistingVirtualFile(lf2);
    myFixture.complete(CompletionType.BASIC);
    variants = myFixture.getLookupElementStrings();
    assertFalse(variants.contains("p1.p2.LabelView"));
    assertTrue(variants.contains("p1.p2.LabelView1"));

    WriteCommandAction.runWriteCommandAction(
        null,
        new Runnable() {
          @Override
          public void run() {
            try {
              labelViewJava.delete(null);
            } catch (IOException e) {
              throw new RuntimeException(e);
            }
          }
        });

    VirtualFile lf3 =
        myFixture.copyFileToProject(testFolder + '/' + "ctn0.xml", "res/layout/layout3.xml");
    myFixture.configureFromExistingVirtualFile(lf3);
    myFixture.complete(CompletionType.BASIC);
    variants = myFixture.getLookupElementStrings();
    assertFalse(variants.contains("p1.p2.LabelView"));
    assertFalse(variants.contains("p1.p2.LabelView1"));
  }
  public PsiVFSListener(Project project) {
    myProject = project;
    myFileTypeManager = FileTypeManager.getInstance();
    myProjectRootManager = ProjectRootManager.getInstance(project);
    myManager = (PsiManagerImpl) PsiManager.getInstance(project);
    myFileManager = (FileManagerImpl) myManager.getFileManager();

    myConnection = project.getMessageBus().connect(project);

    StartupManager.getInstance(project)
        .registerPreStartupActivity(
            new Runnable() {
              @Override
              public void run() {
                final BulkVirtualFileListenerAdapter adapter =
                    new BulkVirtualFileListenerAdapter(PsiVFSListener.this);
                myConnection.subscribe(
                    VirtualFileManager.VFS_CHANGES,
                    new BulkFileListener() {
                      @Override
                      public void before(@NotNull List<? extends VFileEvent> events) {
                        adapter.before(events);
                      }

                      @Override
                      public void after(@NotNull List<? extends VFileEvent> events) {
                        myReportedUnloadedPsiChange = false;
                        adapter.after(events);
                        myReportedUnloadedPsiChange = false;
                      }
                    });
                myConnection.subscribe(ProjectTopics.PROJECT_ROOTS, new MyModuleRootListener());
                myConnection.subscribe(
                    FileTypeManager.TOPIC,
                    new FileTypeListener.Adapter() {
                      @Override
                      public void fileTypesChanged(@NotNull FileTypeEvent e) {
                        myFileManager.processFileTypesChanged();
                      }
                    });
                myConnection.subscribe(
                    AppTopics.FILE_DOCUMENT_SYNC, new MyFileDocumentManagerAdapter());
                myFileManager.markInitialized();
              }
            });
  }
  @Nullable
  private static PsiDirectory tryNotNullizeDirectory(
      @NotNull Project project, @Nullable PsiDirectory defaultTargetDirectory) {
    if (defaultTargetDirectory == null) {
      VirtualFile root =
          ArrayUtil.getFirstElement(ProjectRootManager.getInstance(project).getContentRoots());
      if (root == null) root = project.getBaseDir();
      if (root == null) root = VfsUtil.getUserHomeDir();
      defaultTargetDirectory =
          root != null ? PsiManager.getInstance(project).findDirectory(root) : null;

      if (defaultTargetDirectory == null) {
        LOG.warn("No directory found for project: " + project.getName() + ", root: " + root);
      }
    }
    return defaultTargetDirectory;
  }
Exemplo n.º 30
0
 @Override
 public void invoke(
     @NotNull final Project project, final Editor editor, @NotNull final PsiElement element)
     throws IncorrectOperationException {
   PsiDocCommentOwner container = getContainer(element);
   assert container != null;
   if (!CodeInsightUtilBase.preparePsiElementForWrite(container)) return;
   if (use15Suppressions(container)) {
     final PsiModifierList modifierList = container.getModifierList();
     if (modifierList != null) {
       addSuppressAnnotation(project, editor, container, container, getID(container));
     }
   } else {
     PsiDocComment docComment = container.getDocComment();
     PsiManager manager = PsiManager.getInstance(project);
     if (docComment == null) {
       String commentText =
           "/** @" + SuppressionUtil.SUPPRESS_INSPECTIONS_TAG_NAME + " " + getID(container) + "*/";
       docComment =
           JavaPsiFacade.getInstance(manager.getProject())
               .getElementFactory()
               .createDocCommentFromText(commentText);
       PsiElement firstChild = container.getFirstChild();
       container.addBefore(docComment, firstChild);
     } else {
       PsiDocTag noInspectionTag =
           docComment.findTagByName(SuppressionUtil.SUPPRESS_INSPECTIONS_TAG_NAME);
       if (noInspectionTag != null) {
         String tagText = noInspectionTag.getText() + ", " + getID(container);
         noInspectionTag.replace(
             JavaPsiFacade.getInstance(manager.getProject())
                 .getElementFactory()
                 .createDocTagFromText(tagText));
       } else {
         String tagText =
             "@" + SuppressionUtil.SUPPRESS_INSPECTIONS_TAG_NAME + " " + getID(container);
         docComment.add(
             JavaPsiFacade.getInstance(manager.getProject())
                 .getElementFactory()
                 .createDocTagFromText(tagText));
       }
     }
   }
   DaemonCodeAnalyzer.getInstance(project).restart();
 }