@Nullable @Override public String getLocationString() { if (!this.appendBundleLocation) { return this.locationString; } PsiFile psiFile = psiElement.getContainingFile(); if (psiFile == null) { return this.locationString; } String locationPathString = this.locationString; String bundleName = psiFile.getVirtualFile().getPath(); if (bundleName.contains("Bundle")) { bundleName = bundleName.substring(0, bundleName.lastIndexOf("Bundle")); if (bundleName.length() > 1 && bundleName.contains("/")) { return locationPathString + " " + bundleName.substring(bundleName.lastIndexOf("/") + 1, bundleName.length()) + "::" + psiFile.getName(); } } return locationPathString + " " + psiFile.getName(); }
private static void reportInconsistentLength( PsiFile file, CharSequence newFileText, ASTNode node, int start, int end) { String message = "Index out of bounds: type=" + node.getElementType() + "; file=" + file + "; file.class=" + file.getClass() + "; start=" + start + "; end=" + end + "; length=" + node.getTextLength(); String newTextBefore = newFileText.subSequence(0, start).toString(); String oldTextBefore = file.getText().subSequence(0, start).toString(); if (oldTextBefore.equals(newTextBefore)) { message += "; oldTextBefore==newTextBefore"; } LOG.error( message, new Attachment(file.getName() + "_oldNodeText.txt", node.getText()), new Attachment(file.getName() + "_oldFileText.txt", file.getText()), new Attachment(file.getName() + "_newFileText.txt", newFileText.toString())); }
@Override protected boolean isValidForFile( @NotNull Project project, @NotNull Editor editor, @NotNull PsiFile file) { if (file instanceof PsiCompiledElement) return false; if (!GroovyFileType.GROOVY_FILE_TYPE.equals(file.getFileType())) return false; return !GradleConstants.SETTINGS_FILE_NAME.equals(file.getName()) && file.getName().endsWith(GradleConstants.EXTENSION); }
private void findUsagesInEditor( @NotNull UsageInfoToUsageConverter.TargetElementsDescriptor descriptor, @NotNull FindUsagesHandler handler, @NotNull PsiFile scopeFile, @NotNull FileSearchScope direction, @NotNull final FindUsagesOptions findUsagesOptions, @NotNull FileEditor fileEditor) { initLastSearchElement(findUsagesOptions, descriptor); clearStatusBar(); final FileEditorLocation currentLocation = fileEditor.getCurrentLocation(); final UsageSearcher usageSearcher = createUsageSearcher(descriptor, handler, findUsagesOptions, scopeFile); AtomicBoolean usagesWereFound = new AtomicBoolean(); Usage fUsage = findSiblingUsage(usageSearcher, direction, currentLocation, usagesWereFound, fileEditor); if (fUsage != null) { fUsage.navigate(true); fUsage.selectInEditor(); } else if (!usagesWereFound.get()) { String message = getNoUsagesFoundMessage(descriptor.getPrimaryElements()[0]) + " in " + scopeFile.getName(); showHintOrStatusBarMessage(message, fileEditor); } else { fileEditor.putUserData(KEY_START_USAGE_AGAIN, VALUE_START_USAGE_AGAIN); showHintOrStatusBarMessage( getSearchAgainMessage(descriptor.getPrimaryElements()[0], direction), fileEditor); } }
private void chooseDirectoryAndMove(Project project, PsiFile myFile) { try { PsiDirectory directory = MoveClassesOrPackagesUtil.chooseDestinationPackage(project, myTargetPackage, null); if (directory == null) { return; } String error = RefactoringMessageUtil.checkCanCreateFile(directory, myFile.getName()); if (error != null) { Messages.showMessageDialog( project, error, CommonBundle.getErrorTitle(), Messages.getErrorIcon()); return; } new MoveClassesOrPackagesProcessor( project, new PsiElement[] {((PsiJavaFile) myFile).getClasses()[0]}, new SingleSourceRootMoveDestination( PackageWrapper.create(JavaDirectoryService.getInstance().getPackage(directory)), directory), false, false, null) .run(); } catch (IncorrectOperationException e) { LOG.error(e); } }
@Override public PsiElement getTopLevelElement(PsiElement element) { PsiFile file = element.getContainingFile(); if (file == null || !(file instanceof JetFile)) return null; VirtualFile virtualFile = file.getVirtualFile(); if (!fileInRoots(virtualFile)) return file; PsiElement current = element; while (current != null) { if (isSelectable(current)) break; current = current.getParent(); } if (current instanceof JetFile) { List<JetDeclaration> declarations = ((JetFile) current).getDeclarations(); String nameWithoutExtension = virtualFile != null ? virtualFile.getNameWithoutExtension() : file.getName(); if (declarations.size() == 1 && declarations.get(0) instanceof JetClassOrObject && nameWithoutExtension.equals(declarations.get(0).getName())) { current = declarations.get(0); } } return current != null ? current : file; }
@Override public void invoke(@NotNull Project project, Editor editor, PsiFile file) throws IncorrectOperationException { if (!(file instanceof GroovyFile)) return; VirtualFile vfile = file.getVirtualFile(); if (vfile == null) return; final Module module = ModuleUtilCore.findModuleForFile(vfile, project); if (module == null) return; final String packageName = ((GroovyFile) file).getPackageName(); PsiDirectory directory = PackageUtil.findOrCreateDirectoryForPackage(module, packageName, null, true); if (directory == null) return; String error = RefactoringMessageUtil.checkCanCreateFile(directory, file.getName()); if (error != null) { Messages.showMessageDialog( project, error, CommonBundle.getErrorTitle(), Messages.getErrorIcon()); return; } new MoveFilesOrDirectoriesProcessor( project, new PsiElement[] {file}, directory, false, false, false, null, null) .run(); }
@NotNull private static String getFileFqn(final PsiFile file) { final VirtualFile virtualFile = file.getVirtualFile(); if (virtualFile == null) { return file.getName(); } final Project project = file.getProject(); final LogicalRoot logicalRoot = LogicalRootsManager.getLogicalRootsManager(project).findLogicalRoot(virtualFile); if (logicalRoot != null) { String logical = FileUtil.toSystemIndependentName( VfsUtil.virtualToIoFile(logicalRoot.getVirtualFile()).getPath()); String path = FileUtil.toSystemIndependentName(VfsUtil.virtualToIoFile(virtualFile).getPath()); return "/" + FileUtil.getRelativePath(logical, path, '/'); } final VirtualFile contentRoot = ProjectRootManager.getInstance(project).getFileIndex().getContentRootForFile(virtualFile); if (contentRoot != null) { return "/" + FileUtil.getRelativePath( VfsUtil.virtualToIoFile(contentRoot), VfsUtil.virtualToIoFile(virtualFile)); } return virtualFile.getPath(); }
public MavenDomProjectModelFileMemberChooserObjectBase( @NotNull final PsiFile psiFile, @Nullable String projectName) { super( psiFile, StringUtil.isEmptyOrSpaces(projectName) ? psiFile.getName() : projectName, MavenIcons.MavenProject); }
public void checkLineMarkers( @NotNull Collection<LineMarkerInfo> markerInfos, @NotNull String text) { String fileName = myFile == null ? "" : myFile.getName() + ": "; String failMessage = ""; for (LineMarkerInfo info : markerInfos) { if (!containsLineMarker(info, myLineMarkerInfos.values())) { if (!failMessage.isEmpty()) failMessage += '\n'; failMessage += fileName + "Extra line marker highlighted " + rangeString(text, info.startOffset, info.endOffset) + ": '" + info.getLineMarkerTooltip() + "'"; } } for (LineMarkerInfo expectedLineMarker : myLineMarkerInfos.values()) { if (!markerInfos.isEmpty() && !containsLineMarker(expectedLineMarker, markerInfos)) { if (!failMessage.isEmpty()) failMessage += '\n'; failMessage += fileName + "Line marker was not highlighted " + rangeString(text, expectedLineMarker.startOffset, expectedLineMarker.endOffset) + ": '" + expectedLineMarker.getLineMarkerTooltip() + "'"; } } if (!failMessage.isEmpty()) Assert.fail(failMessage); }
private static void checkResult( String[] fileNames, final ArrayList<PsiFile> filesList, int[] starts, final IntArrayList startsList, int[] ends, final IntArrayList endsList) { List<SearchResult> expected = new ArrayList<SearchResult>(); for (int i = 0; i < fileNames.length; i++) { String fileName = fileNames[i]; expected.add( new SearchResult( fileName, i < starts.length ? starts[i] : -1, i < ends.length ? ends[i] : -1)); } List<SearchResult> actual = new ArrayList<SearchResult>(); for (int i = 0; i < filesList.size(); i++) { PsiFile psiFile = filesList.get(i); actual.add( new SearchResult( psiFile.getName(), i < starts.length ? startsList.get(i) : -1, i < ends.length ? endsList.get(i) : -1)); } Collections.sort(expected); Collections.sort(actual); assertEquals("Usages don't match", expected, actual); }
public static boolean isProjectFile(PsiFile file) { if (!(file instanceof XmlFile)) return false; String name = file.getName(); return name.equals(MavenConstants.POM_XML) || name.endsWith(".pom") || name.equals(MavenConstants.SUPER_POM_XML); }
public static void checkFileStructure(PsiFile file) throws IncorrectOperationException { String originalTree = DebugUtil.psiTreeToString(file, false); PsiFile dummyFile = PsiFileFactory.getInstance(file.getProject()) .createFileFromText(file.getName(), file.getFileType(), file.getText()); String reparsedTree = DebugUtil.psiTreeToString(dummyFile, false); Assert.assertEquals(reparsedTree, originalTree); }
public void checkResult(Collection<HighlightInfo> infos, String text, @Nullable String filePath) { if (filePath == null) { VirtualFile virtualFile = myFile == null ? null : myFile.getVirtualFile(); filePath = virtualFile == null ? null : virtualFile.getUserData(VfsTestUtil.TEST_DATA_FILE_PATH); } String fileName = myFile == null ? "" : myFile.getName() + ": "; String failMessage = ""; for (HighlightInfo info : reverseCollection(infos)) { if (!expectedInfosContainsInfo(info) && !myIgnoreExtraHighlighting) { final int startOffset = info.startOffset; final int endOffset = info.endOffset; String s = text.substring(startOffset, endOffset); String desc = info.getDescription(); if (!failMessage.isEmpty()) failMessage += '\n'; failMessage += fileName + "Extra " + rangeString(text, startOffset, endOffset) + " :'" + s + "'" + (desc == null ? "" : " (" + desc + ")") + " [" + info.type + "]"; } } final Collection<ExpectedHighlightingSet> expectedHighlights = myHighlightingTypes.values(); for (ExpectedHighlightingSet highlightingSet : reverseCollection(expectedHighlights)) { final Set<HighlightInfo> expInfos = highlightingSet.infos; for (HighlightInfo expectedInfo : expInfos) { if (!infosContainsExpectedInfo(infos, expectedInfo) && highlightingSet.enabled) { final int startOffset = expectedInfo.startOffset; final int endOffset = expectedInfo.endOffset; String s = text.substring(startOffset, endOffset); String desc = expectedInfo.getDescription(); if (!failMessage.isEmpty()) failMessage += '\n'; failMessage += fileName + "Missing " + rangeString(text, startOffset, endOffset) + " :'" + s + "'" + (desc == null ? "" : " (" + desc + ")"); } } } if (!failMessage.isEmpty()) { compareTexts(infos, text, failMessage + "\n", filePath); } }
private static void createValueResource( @NotNull PsiFile file, @NotNull AndroidFacet facet, @NotNull PsiDirectory dir, @NotNull final String resName, @NotNull final String value, @NotNull final ResourceType type, @NotNull final String oldTagText) { final String filename = file.getName(); final List<String> dirNames = Collections.singletonList(dir.getName()); final Module module = facet.getModule(); final AtomicReference<PsiElement> openAfter = new AtomicReference<PsiElement>(); final WriteCommandAction<Void> action = new WriteCommandAction<Void>( facet.getModule().getProject(), "Override Resource " + resName, file) { @Override protected void run(@NotNull Result<Void> result) { List<ResourceElement> elements = Lists.newArrayListWithExpectedSize(1); // AndroidResourceUtil.createValueResource will create a new resource value in the given // resource // folder (and record the corresponding tags added in the elements list passed into it). // However, it only creates a new element and sets the name attribute on it; it does not // transfer attributes, child content etc. Therefore, we use this utility method first // to // create the corresponding tag, and then *afterwards* we will replace the tag with a // text copy // from the resource tag we are overriding. We do this all under a single write lock // such // that it becomes a single atomic operation. AndroidResourceUtil.createValueResource( module, resName, type, filename, dirNames, value, elements); if (elements.size() == 1) { final XmlTag tag = elements.get(0).getXmlTag(); if (tag != null && tag.isValid()) { try { XmlTag tagFromText = XmlElementFactory.getInstance(tag.getProject()).createTagFromText(oldTagText); PsiElement replaced = tag.replace(tagFromText); openAfter.set(replaced); } catch (IncorrectOperationException e) { // The user tried to override an invalid XML fragment: don't attempt to do a // replacement in that case openAfter.set(tag); } } } } }; action.execute(); PsiElement tag = openAfter.get(); if (tag != null) { NavigationUtil.openFileWithPsiElement(tag, true, true); } }
public static void removeDuplicatingClasses( final Module module, @NotNull final String packageName, @NotNull String className, @Nullable File classFile, String sourceRootPath) { if (sourceRootPath == null) { return; } VirtualFile sourceRoot = LocalFileSystem.getInstance().findFileByPath(sourceRootPath); if (sourceRoot == null) { return; } final Project project = module.getProject(); final JavaPsiFacade facade = JavaPsiFacade.getInstance(project); final String interfaceQualifiedName = packageName + '.' + className; PsiClass[] classes = facade.findClasses(interfaceQualifiedName, GlobalSearchScope.moduleScope(module)); final ProjectFileIndex projectFileIndex = ProjectRootManager.getInstance(project).getFileIndex(); for (PsiClass c : classes) { PsiFile psiFile = c.getContainingFile(); if (className.equals(FileUtil.getNameWithoutExtension(psiFile.getName()))) { VirtualFile virtualFile = psiFile.getVirtualFile(); if (virtualFile != null && projectFileIndex.getSourceRootForFile(virtualFile) == sourceRoot) { final String path = virtualFile.getPath(); File f = new File(path); try { f = f.getCanonicalFile(); classFile = classFile != null ? classFile.getCanonicalFile() : null; if (f != null && !f.equals(classFile) && f.exists()) { if (f.delete()) { virtualFile.refresh(true, false); } else { ApplicationManager.getApplication() .invokeLater( new Runnable() { public void run() { Messages.showErrorDialog( project, "Can't delete file " + path, CommonBundle.getErrorTitle()); } }, project.getDisposed()); } } } catch (IOException e) { LOG.info(e); } } } } }
@Override public Result calculateResult( @NotNull Expression[] expressions, ExpressionContext expressionContext) { PsiFile file = PsiDocumentManager.getInstance(expressionContext.getProject()) .getPsiFile(expressionContext.getEditor().getDocument()); if (file instanceof LuaPsiFile) return new TextResult(file.getName()); return null; }
private static String getNewFileName(PsiFile file, String name) { if (name != null) { if (file instanceof PsiClassOwner) { final PsiClass[] classes = ((PsiClassOwner) file).getClasses(); if (classes.length > 0 && !(classes[0] instanceof SyntheticElement)) { return name + "." + file.getViewProvider().getVirtualFile().getExtension(); } } return name; } return file.getName(); }
private static String getNewFileName(PsiFile file, String name) { if (name != null) { if (file instanceof PsiClassOwner) { for (final PsiClass psiClass : ((PsiClassOwner) file).getClasses()) { if (!isSynthetic(psiClass)) { return name + "." + file.getViewProvider().getVirtualFile().getExtension(); } } } return name; } return file.getName(); }
@NotNull private static PsiFile copyFile( @NotNull PsiFile file, @NotNull StringBuilder fileContentWithoutKey) { final PsiFileFactory psiFileFactory = PsiFileFactory.getInstance(file.getProject()); PsiFile copy = psiFileFactory.createFileFromText( file.getName(), file.getFileType(), fileContentWithoutKey); VirtualFile vFile = copy.getVirtualFile(); if (vFile != null) { vFile.putUserData(UndoConstants.DONT_RECORD_UNDO, Boolean.TRUE); } return copy; }
private static boolean processFile( final PsiFile file, final CssResolveProcessor processor, final ResolveState state) { if (!pushPath(file, state)) { // Already visited, skip return true; } // Process declarations in file if (!PsiTreeUtil.processElements(file, processor)) { return false; } // Process imports in file CssImport cssImport; while ((cssImport = processor.popImport()) != null) { PsiElement resolvedImport = cssImport.resolve(); if (resolvedImport instanceof PsiFile) { if (!processFile((PsiFile) resolvedImport, processor, state)) { return false; } } } // Recurse on files importing this file CssUtils.getPsiSearchHelper(file.getProject()) .processElementsWithWord( new TextOccurenceProcessor() { public boolean execute(PsiElement element, int offsetInElement) { if (element.getParent().getParent() instanceof CssImport) { CssImport cssImport = (CssImport) element.getParent().getParent(); String uri = cssImport.getUriString(); if (uri.endsWith(file.getName())) { PsiElement importedFile = cssImport.resolve(); if (file == importedFile) { if (!processFile(cssImport.getContainingFile(), processor, state)) { return false; } } } } return true; } }, getResolveSearchScope(file), file.getName(), (short) (UsageSearchContext.IN_CODE | UsageSearchContext.IN_STRINGS), true); return true; }
protected void handleFileTooBigException( Logger logger, FilesTooBigForDiffException e, @NotNull PsiFile file) { logger.info("Error while calculating changed ranges for: " + file.getVirtualFile(), e); if (!ApplicationManager.getApplication().isUnitTestMode()) { Notification notification = new Notification( ApplicationBundle.message("reformat.changed.text.file.too.big.notification.groupId"), ApplicationBundle.message("reformat.changed.text.file.too.big.notification.title"), ApplicationBundle.message( "reformat.changed.text.file.too.big.notification.text", file.getName()), NotificationType.INFORMATION); notification.notify(file.getProject()); } }
@Override public void documentChanged(DocumentEvent event) { final Document document = event.getDocument(); final FileViewProvider viewProvider = getCachedViewProvider(document); if (viewProvider == null) return; if (!isRelevant(viewProvider)) return; ApplicationManager.getApplication().assertWriteAccessAllowed(); final List<PsiFile> files = viewProvider.getAllFiles(); boolean commitNecessary = true; for (PsiFile file : files) { mySmartPointerManager.unfastenBelts(file, event.getOffset()); final TextBlock textBlock = TextBlock.get(file); if (textBlock.isLocked()) { commitNecessary = false; continue; } textBlock.documentChanged(event); assert file instanceof PsiFileImpl || "mock.file".equals(file.getName()) && ApplicationManager.getApplication().isUnitTestMode() : event + "; file=" + file + "; allFiles=" + files + "; viewProvider=" + viewProvider; } boolean forceCommit = ApplicationManager.getApplication().hasWriteAction(ExternalChangeAction.class) && (SystemProperties.getBooleanProperty("idea.force.commit.on.external.change", false) || ApplicationManager.getApplication().isHeadlessEnvironment()); // Consider that it's worth to perform complete re-parse instead of merge if the whole document // text is replaced and // current document lines number is roughly above 5000. This makes sense in situations when // external change is performed // for the huge file (that causes the whole document to be reloaded and 'merge' way takes a // while to complete). if (event.isWholeTextReplaced() && document.getTextLength() > 100000) { document.putUserData(BlockSupport.DO_NOT_REPARSE_INCREMENTALLY, Boolean.TRUE); } if (commitNecessary) { myUncommittedDocuments.add(document); if (forceCommit) { commitDocument(document); } else if (!((DocumentEx) document).isInBulkUpdate()) { myDocumentCommitProcessor.commitAsynchronously(myProject, document, event); } } }
@Nullable public static String getSourcePositionClassDisplayName( DebugProcessImpl debugProcess, @Nullable SourcePosition position) { if (position == null) { return null; } final PsiFile positionFile = position.getFile(); if (positionFile instanceof JspFile) { return positionFile.getName(); } final PsiClass psiClass = getClassAt(position); if (psiClass != null) { final String qName = psiClass.getQualifiedName(); if (qName != null) { return qName; } } if (debugProcess != null && debugProcess.isAttached()) { List<ReferenceType> allClasses = debugProcess.getPositionManager().getAllClasses(position); if (!allClasses.isEmpty()) { return allClasses.get(0).name(); } } if (psiClass == null) { if (positionFile instanceof PsiClassOwner) { return positionFile.getName(); } return DebuggerBundle.message( "string.file.line.position", positionFile.getName(), position.getLine()); } return calcClassDisplayName(psiClass); }
@Nullable static HighlightInfo checkFileName(@NotNull PsiJavaModule element, @NotNull PsiFile file) { if (!MODULE_INFO_FILE.equals(file.getName())) { String message = JavaErrorMessages.message("module.file.wrong.name"); HighlightInfo info = HighlightInfo.newHighlightInfo(HighlightInfoType.ERROR) .range(range(element)) .description(message) .create(); QuickFixAction.registerQuickFixAction(info, factory().createRenameFileFix(MODULE_INFO_FILE)); return info; } return null; }
public void markFileScopeDirtyDefensively(@NotNull PsiFile file) { assertAllowModifications(); if (LOG.isDebugEnabled()) { LOG.debug("********************************* Mark dirty file defensively: " + file.getName()); } // mark whole file dirty in case no subsequent PSI events will come, but file requires // rehighlighting nevertheless // e.g. in the case of quick typing/backspacing char synchronized (myDocumentToStatusMap) { Document document = PsiDocumentManager.getInstance(myProject).getCachedDocument(file); if (document == null) return; FileStatus status = myDocumentToStatusMap.get(document); if (status == null) return; // all dirty already status.defensivelyMarked = true; } }
private void checkTodos(@NonNls String[] expectedFiles) { PsiTodoSearchHelper helper = PsiTodoSearchHelper.SERVICE.getInstance(myProject); PsiFile[] files = helper.findFilesWithTodoItems(); assertEquals(expectedFiles.length, files.length); Arrays.sort(files, (file1, file2) -> file1.getName().compareTo(file2.getName())); Arrays.sort(expectedFiles); for (int i = 0; i < expectedFiles.length; i++) { String name = expectedFiles[i]; PsiFile file = files[i]; assertEquals(name, file.getName()); } }
@Nullable public static HighlightInfo checkPackageAnnotationContainingFile( final PsiPackageStatement statement) { if (statement.getAnnotationList() == null) { return null; } PsiFile file = statement.getContainingFile(); if (file != null && !PsiPackage.PACKAGE_INFO_FILE.equals(file.getName())) { String description = JavaErrorMessages.message("invalid.package.annotation.containing.file"); HighlightInfo.Builder builder = HighlightInfo.newHighlightInfo(HighlightInfoType.ERROR); builder.range(statement.getAnnotationList().getTextRange()); builder.descriptionAndTooltip(description); return builder.create(); } return null; }
@Nullable private static String getQuickNavigateInfo(PsiElement element) { final String name = ElementDescriptionUtil.getElementDescription(element, UsageViewShortNameLocation.INSTANCE); if (StringUtil.isEmpty(name)) return null; final String typeName = ElementDescriptionUtil.getElementDescription(element, UsageViewTypeLocation.INSTANCE); final PsiFile file = element.getContainingFile(); final StringBuilder sb = new StringBuilder(); if (StringUtil.isNotEmpty(typeName)) sb.append(typeName).append(" "); sb.append("\"").append(name).append("\""); if (file != null && file.isPhysical()) { sb.append(" [").append(file.getName()).append("]"); } return sb.toString(); }
private static void logIndentOptions( @NotNull PsiFile file, @NotNull FileIndentOptionsProvider provider, @NotNull IndentOptions options) { LOG.debug( "Indent options returned by " + provider.getClass().getName() + " for " + file.getName() + ": indent size=" + options.INDENT_SIZE + ", use tabs=" + options.USE_TAB_CHARACTER + ", tab size=" + options.TAB_SIZE); }