@NotNull private PsiClass[] getCachedClassesByName(@NotNull String name, GlobalSearchScope scope) { if (DumbService.getInstance(getProject()).isDumb()) { return getCachedClassInDumbMode(name, scope); } Map<String, PsiClass[]> map = SoftReference.dereference(myClassCache); if (map == null) { myClassCache = new SoftReference<Map<String, PsiClass[]>>(map = ContainerUtil.createConcurrentSoftValueMap()); } PsiClass[] classes = map.get(name); if (classes != null) { return classes; } final String qName = getQualifiedName(); final String classQName = !qName.isEmpty() ? qName + "." + name : name; map.put(name, classes = getFacade().findClasses(classQName, new EverythingGlobalScope(getProject()))); return classes; }
private boolean elementHasSourceCode() { PsiFileSystemItem[] items; if (myElement instanceof PsiDirectory) { final PsiPackage aPackage = JavaDirectoryService.getInstance().getPackage((PsiDirectory)myElement); if (aPackage == null) return false; items = aPackage.getDirectories(new EverythingGlobalScope(myProject)); } else if (myElement instanceof PsiPackage) { items = ((PsiPackage)myElement).getDirectories(new EverythingGlobalScope(myProject)); } else { PsiFile containingFile = myElement.getNavigationElement().getContainingFile(); if (containingFile == null) return false; items = new PsiFileSystemItem[] {containingFile}; } ProjectFileIndex projectFileIndex = ProjectFileIndex.SERVICE.getInstance(myProject); for (PsiFileSystemItem item : items) { VirtualFile file = item.getVirtualFile(); if (file != null && projectFileIndex.isInSource(file)) return true; } return false; }
public void setSelectedPatch(Patch selectedPatch) { System.out.println(selectedPatch.asString() + " selected! "); this.selectedPatch = selectedPatch; final SourceLocation location = this.selectedPatch.getSourceLocation(); PsiClass classToBeFix = JavaPsiFacade.getInstance(this.project).findClass(this.selectedPatch.getRootClassName(), new EverythingGlobalScope(this.project)); classToBeFix.accept(new JavaRecursiveElementVisitor() { @Override public void visitStatement(PsiStatement statement) { if (location.getBeginSource() == statement.getTextOffset() && location.getEndSource() == statement.getTextOffset() + statement.getTextLength() - 1) { buggyElement = statement; } super.visitStatement(statement); } }); }
private void addInit(@Nullable String rootViewStr) { PsiClass activityClass = JavaPsiFacade.getInstance(mProject).findClass( "android.app.Activity", new EverythingGlobalScope(mProject)); PsiClass fragmentClass = JavaPsiFacade.getInstance(mProject).findClass( "android.app.Fragment", new EverythingGlobalScope(mProject)); PsiClass supportFragmentClass = JavaPsiFacade.getInstance(mProject).findClass( "android.support.v4.app.Fragment", new EverythingGlobalScope(mProject)); // Check for Activity class if (activityClass != null && mClass.isInheritor(activityClass, true)) { addInitViewAfterOnCreate(rootViewStr); // Check for Fragment class } else if ((fragmentClass != null && mClass.isInheritor(fragmentClass, true)) || (supportFragmentClass != null && mClass.isInheritor(supportFragmentClass, true))) { addInitViewAfterOnCreateView(rootViewStr); } else { Utils.showInfoNotification(mEditor.getProject(), "Add " + getInitViewStatementAsString(rootViewStr) + " where relevant!"); } }
private static PsiFile resolveLayoutResourceFile(PsiElement element, Project project, String name) { // restricting the search to the current module - searching the whole project could return wrong layouts Module module = ModuleUtil.findModuleForPsiElement(element); PsiFile[] files = null; if (module != null) { GlobalSearchScope moduleScope = module.getModuleWithDependenciesAndLibrariesScope(false); files = FilenameIndex.getFilesByName(project, name, moduleScope); } if (files == null || files.length <= 0) { // fallback to search through the whole project // useful when the project is not properly configured - when the resource directory is not configured files = FilenameIndex.getFilesByName(project, name, new EverythingGlobalScope(project)); if (files.length <= 0) { return null; //no matching files } } // TODO - we have a problem here - we still can have multiple layouts (some coming from a dependency) // we need to resolve R class properly and find the proper layout for the R class return files[0]; }
/** * Try to find layout XML file in selected element * * @param element * @return */ public static PsiFile findLayoutResource(PsiElement element) { if (element == null) { return null; // nothing to be used } if (!(element instanceof PsiIdentifier)) { return null; // nothing to be used } PsiElement layout = element.getParent().getFirstChild(); if (layout == null) { return null; // no file to process } if (!"R.layout".equals(layout.getText())) { return null; // not layout file } Project project = element.getProject(); String name = String.format("%s.xml", element.getText()); PsiFile[] files = FilenameIndex.getFilesByName(project, name, new EverythingGlobalScope(project)); if (files.length <= 0) { return null; //no matching files } return files[0]; }
@Override public void run() throws Throwable { PsiClass injectViewClass = JavaPsiFacade.getInstance(mProject).findClass("net.tsz.afinal.annotation.view.ViewInject", new EverythingGlobalScope(mProject)); if (injectViewClass == null) { return; // Butterknife library is not available for project } if (mCreateHolder) { generateAdapter(); } else { generateFields(); } // reformat class JavaCodeStyleManager styleManager = JavaCodeStyleManager.getInstance(mProject); styleManager.optimizeImports(mFile); styleManager.shortenClassReferences(mClass); new ReformatAndOptimizeImportsProcessor(mProject, mClass.getContainingFile(), false).runWithoutProgress(); }
protected void generateInjects(@NotNull IButterKnife butterKnife) { PsiClass activityClass = JavaPsiFacade.getInstance(mProject).findClass( "android.app.Activity", new EverythingGlobalScope(mProject)); PsiClass fragmentClass = JavaPsiFacade.getInstance(mProject).findClass( "android.app.Fragment", new EverythingGlobalScope(mProject)); PsiClass supportFragmentClass = JavaPsiFacade.getInstance(mProject).findClass( "android.support.v4.app.Fragment", new EverythingGlobalScope(mProject)); // Check for Activity class if (activityClass != null && mClass.isInheritor(activityClass, true)) { generateActivityBind(butterKnife); // Check for Fragment class } else if ((fragmentClass != null && mClass.isInheritor(fragmentClass, true)) || (supportFragmentClass != null && mClass.isInheritor(supportFragmentClass, true))) { generateFragmentBindAndUnbind(butterKnife); } }
private void generatePackageJavaDoc(final StringBuilder buffer, final PsiPackage psiPackage, boolean generatePrologueAndEpilogue) { for (PsiDirectory directory : psiPackage.getDirectories(new EverythingGlobalScope(myProject))) { final PsiFile packageInfoFile = directory.findFile(PsiPackage.PACKAGE_INFO_FILE); if (packageInfoFile != null) { final ASTNode node = packageInfoFile.getNode(); if (node != null) { final ASTNode docCommentNode = node.findChildByType(JavaDocElementType.DOC_COMMENT); if (docCommentNode != null) { final PsiDocComment docComment = (PsiDocComment)docCommentNode.getPsi(); if (generatePrologueAndEpilogue) generatePrologue(buffer); generateCommonSection(buffer, docComment); if (generatePrologueAndEpilogue) generateEpilogue(buffer); break; } } } PsiFile packageHtmlFile = directory.findFile("package.html"); if (packageHtmlFile != null) { generatePackageHtmlJavaDoc(buffer, packageHtmlFile, generatePrologueAndEpilogue); break; } } }
@Override public PsiClass findClass(@NotNull String qualifiedName, @NotNull GlobalSearchScope scope) { PsiClass aClass = super.findClass(qualifiedName, scope); if (aClass == null || scope instanceof ExternalModuleBuildGlobalSearchScope || scope instanceof EverythingGlobalScope) { return aClass; } PsiFile containingFile = aClass.getContainingFile(); VirtualFile file = containingFile != null ? containingFile.getVirtualFile() : null; return (file != null && !ProjectFileIndex.SERVICE.getInstance(myProject).isInContent(file)) ? aClass : null; }
@Nullable @Override public GlobalSearchScope getScopeToExclude(PsiElement element) { if (element instanceof PsiFileSystemItem) { return GlobalSearchScope.getScopeRestrictedByFileTypes( new EverythingGlobalScope(), BuildFileType.INSTANCE); } return null; }
private static PsiFile getGradleSettingsFile(Project project) { PsiFile[] files = FilenameIndex.getFilesByName(project, "settings.gradle", new EverythingGlobalScope(project)); if (files.length <= 0) { return null; //no matching files } return files[0];// 根目录下的 }
public AppendHTMLCommandAction(Project project, PsiFile file, List<XmlItem> content, Module module) { super(project, file); this.content = content; this.module = module; String indexPath="index.html"; PsiFile[] files = FilenameIndex.getFilesByName(project,indexPath , new EverythingGlobalScope(project)); if (files != null && files.length > 0) { for (PsiFile psiFile:files){ if (ModuleUtil.findModuleForFile(psiFile.getVirtualFile(), project).getModuleFilePath().equals(module.getModuleFilePath())) { htmlIndexFile =psiFile; } } } }
public void generateMainClass(){ // VirtualFile mainClassFile=project.getProjectFile().findChild(Util.getEnterClassNameByProjectName(project.getName())+".java"); String mainClassName=Util.getEnterClassNameByProjectName(module.getName()); PsiFile[] files= FilenameIndex.getFilesByName(project,mainClassName+".java",new EverythingGlobalScope(project)); if (files.length<=0){ return; } PsiJavaFile mainClassFile=(PsiJavaFile)files[0]; PsiFile[] jsFiles= FilenameIndex.getFilesByName(project,"JsConst.java",new EverythingGlobalScope(project)); if (files.length<=0){ return; } PsiJavaFile jsJavaFile=(PsiJavaFile)jsFiles[0]; PsiClass jsClass=JavaPsiFacade.getInstance(project).findClass(mainClassFile.getPackageName() + "." + "JsConst", GlobalSearchScope.allScope(project)); psiClass= JavaPsiFacade.getInstance(project).findClass(mainClassFile.getPackageName() + "." + mainClassName, GlobalSearchScope.allScope(project)); int index=getIndex(psiClass); for (XmlItem method:content){ if (method.getType()==2||method.getType()==1){ //添加JS 回调 if (!hasJsConst(jsClass,method)){ addJSConst(jsClass,method,module.getName()); } } if (method.getType()==0||method.getType()==1){ //添加方法 if (hasMethod(psiClass, method.getMethodName())){ continue; } addMethodAndFiled(psiClass, method, index); index++; } } }
/** * Try to find layout XML file by name * * @param project * @param fileName * @return */ public static PsiFile findLayoutResource(Project project, String fileName) { String name = String.format("%s.xml", fileName); PsiFile[] files = FilenameIndex.getFilesByName(project, name, new EverythingGlobalScope(project)); if (files.length <= 0) { return null; //no matching files } return files[0]; }
private static PsiFile resolveLayoutResourceFile(PsiElement element, Project project, String name) { // restricting the search to the current module - searching the whole project could return wrong layouts Module module = ModuleUtil.findModuleForPsiElement(element); PsiFile[] files = null; if (module != null) { // first omit libraries, it might cause issues like (#103) GlobalSearchScope moduleScope = module.getModuleWithDependenciesScope(); files = FilenameIndex.getFilesByName(project, name, moduleScope); if (files == null || files.length <= 0) { // now let's do a fallback including the libraries moduleScope = module.getModuleWithDependenciesAndLibrariesScope(false); files = FilenameIndex.getFilesByName(project, name, moduleScope); } } if (files == null || files.length <= 0) { // fallback to search through the whole project // useful when the project is not properly configured - when the resource directory is not configured files = FilenameIndex.getFilesByName(project, name, new EverythingGlobalScope(project)); if (files.length <= 0) { return null; //no matching files } } // TODO - we have a problem here - we still can have multiple layouts (some coming from a dependency) // we need to resolve R class properly and find the proper layout for the R class for (PsiFile file : files) { log.info("Resolved layout resource file for name [" + name + "]: " + file.getVirtualFile()); } return files[0]; }
private boolean elementHasSourceCode() { PsiFileSystemItem[] items; if(myElement instanceof PsiDirectory) { final PsiJavaPackage aPackage = JavaDirectoryService.getInstance().getPackage((PsiDirectory) myElement); if(aPackage == null) { return false; } items = aPackage.getDirectories(new EverythingGlobalScope(myProject)); } else if(myElement instanceof PsiJavaPackage) { items = ((PsiJavaPackage) myElement).getDirectories(new EverythingGlobalScope(myProject)); } else { PsiFile containingFile = myElement.getNavigationElement().getContainingFile(); if(containingFile == null) { return false; } items = new PsiFileSystemItem[]{containingFile}; } ProjectFileIndex projectFileIndex = ProjectFileIndex.SERVICE.getInstance(myProject); for(PsiFileSystemItem item : items) { VirtualFile file = item.getVirtualFile(); if(file != null && projectFileIndex.isInSource(file)) { return true; } } return false; }
private void generatePackageJavaDoc(final StringBuilder buffer, final PsiJavaPackage PsiJavaPackage, boolean generatePrologueAndEpilogue) { for(PsiDirectory directory : PsiJavaPackage.getDirectories(new EverythingGlobalScope(myProject))) { final PsiFile packageInfoFile = directory.findFile(PsiJavaPackage.PACKAGE_INFO_FILE); if(packageInfoFile != null) { final ASTNode node = packageInfoFile.getNode(); if(node != null) { final ASTNode docCommentNode = findRelevantCommentNode(node); if(docCommentNode != null) { if(generatePrologueAndEpilogue) { generatePrologue(buffer); } generateCommonSection(buffer, (PsiDocComment) docCommentNode.getPsi()); if(generatePrologueAndEpilogue) { generateEpilogue(buffer); } break; } } } PsiFile packageHtmlFile = directory.findFile("package.html"); if(packageHtmlFile != null) { generatePackageHtmlJavaDoc(buffer, packageHtmlFile, generatePrologueAndEpilogue); break; } } }
public static boolean isClassAvailableForProject(Project project, String className) { PsiClass classInModule = JavaPsiFacade.getInstance(project).findClass(className, new EverythingGlobalScope(project)); return classInModule != null; }
@Override public boolean containsClassNamed(@NotNull String name) { return getCachedClassesByName(name, new EverythingGlobalScope(getProject())).length > 0; }
public static GlobalSearchScope searchScopeFor(Project project, boolean searchInLibraries) { if (project == null) return new EverythingGlobalScope(); return searchInLibraries? ProjectScope.getAllScope(project) : ProjectScope.getProjectScope(project); }
@NotNull @Override public GlobalSearchScope buildAllScope() { return new EverythingGlobalScope(); }
@Override public <K> boolean processAllKeys(@NotNull final ID<K, ?> indexId, @NotNull Processor<K> processor, @Nullable Project project) { return processAllKeys(indexId, processor, project == null ? new EverythingGlobalScope() : GlobalSearchScope.allScope(project), null); }
@Override public void actionPerformed(ActionEvent e) { final Project project = this.parent.getProject(); PsiElement buggyElement = this.parent.getBuggyElement(); final Patch selectedPatch = this.parent.getSelectedPatch(); PsiClass classToBeFix = JavaPsiFacade.getInstance(project).findClass(selectedPatch.getRootClassName(), new EverythingGlobalScope(project)); OpenFileDescriptor descriptor = new OpenFileDescriptor(project, classToBeFix.getContainingFile().getVirtualFile(), buggyElement.getTextOffset()); Editor editor = FileEditorManager.getInstance(project).openTextEditor(descriptor, true); Document modifiedDocument = editor.getDocument(); final String patch; if (selectedPatch.getType() == StatementType.CONDITIONAL) { buggyElement = ((PsiIfStatement) buggyElement).getCondition(); patch = selectedPatch.asString(); } else { String newline = FileDocumentManager.getInstance().getFile(modifiedDocument).getDetectedLineSeparator(); StringBuilder sb = new StringBuilder(); sb.append("if( "); sb.append(selectedPatch.asString()); sb.append(" ) {" + newline); sb.append(buggyElement.getText() + newline); sb.append("}"); patch = sb.toString(); } final PsiElement finalBuggyElement = buggyElement; CommandProcessor.getInstance().executeCommand(project, () -> WriteCommandAction.runWriteCommandAction(project, () -> { //Apply the patch modifiedDocument.replaceString(finalBuggyElement.getTextOffset(), finalBuggyElement.getTextOffset() + finalBuggyElement.getTextLength(), patch); //Move caret to modification editor.getCaretModel().moveToOffset(finalBuggyElement.getTextOffset()); //Select patch editor.getSelectionModel().setSelection(finalBuggyElement.getTextOffset(), finalBuggyElement.getTextOffset() + (selectedPatch.getType() == StatementType.CONDITIONAL ? finalBuggyElement.getTextLength() : patch.length())); PsiDocumentManager.getInstance(project).commitDocument(modifiedDocument); CodeStyleManager.getInstance(project).reformat(PsiDocumentManager.getInstance(project).getPsiFile(modifiedDocument), false); }), "Apply Patch", DocCommandGroupId.noneGroupId(modifiedDocument)); PsiDocumentManager.getInstance(project).commitDocument(modifiedDocument); parent.close(0); }
@Override protected boolean isValidForClass(final PsiClass targetClass) { PsiClass injectViewClass = JavaPsiFacade.getInstance(targetClass.getProject()).findClass("org.androidannotations.annotations.ViewById", new EverythingGlobalScope(targetClass.getProject())); return (injectViewClass != null && super.isValidForClass(targetClass) && Utils.findAndroidSDK() != null && !(targetClass instanceof PsiAnonymousClass)); }
@Override public boolean isValidForFile(Project project, Editor editor, PsiFile file) { PsiClass injectViewClass = JavaPsiFacade.getInstance(project).findClass("org.androidannotations.annotations.ViewById", new EverythingGlobalScope(project)); return (injectViewClass != null && super.isValidForFile(project, editor, file) && Utils.getLayoutFileFromCaret(editor, file) != null); }
@Override protected boolean isValidForClass(final PsiClass targetClass) { PsiClass injectViewClass = JavaPsiFacade.getInstance(targetClass.getProject()).findClass("net.tsz.afinal.annotation.view.ViewInject", new EverythingGlobalScope(targetClass.getProject())); return (injectViewClass != null && super.isValidForClass(targetClass) && Utils.findAndroidSDK() != null && !(targetClass instanceof PsiAnonymousClass)); }
@Override public boolean isValidForFile(Project project, Editor editor, PsiFile file) { PsiClass injectViewClass = JavaPsiFacade.getInstance(project).findClass("net.tsz.afinal.annotation.view.ViewInject", new EverythingGlobalScope(project)); return (injectViewClass != null && super.isValidForFile(project, editor, file) && Utils.getLayoutFileFromCaret(editor, file) != null); }
@Override public boolean execute(@NotNull final DirectTypeInheritorsSearch.SearchParameters p, @NotNull final Processor<DotNetTypeDeclaration> consumer) { String vmQName = p.getVmQName(); /*if(DotNetTypes.System_Object.equals(qualifiedName)) { final SearchScope scope = useScope; return AllClassesSearch.search(scope, aClass.getProject()).forEach(new Processor<DotNetTypeDeclaration>() { @Override public boolean process(final DotNetTypeDeclaration typeDcl) { if(typeDcl.isInterface()) { return consumer.process(typeDcl); } final DotNetTypeDeclaration superClass = typeDcl.getSuperClass(); if(superClass != null && DotNetTypes.System_Object.equals(ApplicationManager.getApplication().runReadAction( new Computable<String>() { public String compute() { return superClass.getPresentableQName(); } }))) { return consumer.process(typeDcl); } return true; } }); } */ SearchScope useScope = p.getScope(); final GlobalSearchScope scope = useScope instanceof GlobalSearchScope ? (GlobalSearchScope) useScope : new EverythingGlobalScope(p .getProject()); final String searchKey = MsilHelper.cutGenericMarker(StringUtil.getShortName(vmQName)); if(StringUtil.isEmpty(searchKey)) { return true; } Collection<DotNetTypeList> candidates = ApplicationManager.getApplication().runReadAction((Computable<Collection<DotNetTypeList>>) () -> ExtendsListIndex.getInstance().get(searchKey, p.getProject(), scope)); Map<String, List<DotNetTypeDeclaration>> classes = new HashMap<>(); for(DotNetTypeList referenceList : candidates) { ProgressIndicatorProvider.checkCanceled(); final DotNetTypeDeclaration candidate = ReadAction.compute(() -> (DotNetTypeDeclaration) referenceList.getParent()); if(!checkInheritance(p, vmQName, candidate)) { continue; } String fqn = ReadAction.compute(candidate::getPresentableQName); List<DotNetTypeDeclaration> list = classes.get(fqn); if(list == null) { list = new ArrayList<>(); classes.put(fqn, list); } list.add(candidate); } for(List<DotNetTypeDeclaration> sameNamedClasses : classes.values()) { for(DotNetTypeDeclaration sameNamedClass : sameNamedClasses) { if(!consumer.process(sameNamedClass)) { return false; } } } return true; }
@Override public GlobalSearchScope buildAllScope() { return new EverythingGlobalScope(); }
@Override public <K> boolean processAllKeys(@Nonnull final ID<K, ?> indexId, @Nonnull Processor<K> processor, @Nullable Project project) { return processAllKeys(indexId, processor, project == null ? new EverythingGlobalScope() : GlobalSearchScope.allScope(project), null); }
/** * Check whether classpath of a the whole project contains given class. * This is only fallback for wrongly setup projects. * * @param project Project * @param className Class name of the searched class * @return True if the class is present on the classpath * @since 1.3.1 */ public static boolean isClassAvailableForProject(@NotNull Project project, @NotNull String className) { PsiClass classInModule = JavaPsiFacade.getInstance(project).findClass(className, new EverythingGlobalScope(project)); return classInModule != null; }