private void doSaveDocument(@NotNull final Document document) throws IOException, SaveVetoException { VirtualFile file = getFile(document); if (file == null || file instanceof LightVirtualFile || file.isValid() && !isFileModified(file)) { removeFromUnsaved(document); return; } if (file.isValid() && needsRefresh(file)) { file.refresh(false, false); if (!myUnsavedDocuments.contains(document)) return; } for (FileDocumentSynchronizationVetoer vetoer : Extensions.getExtensions(FileDocumentSynchronizationVetoer.EP_NAME)) { if (!vetoer.maySaveDocument(document)) { throw new SaveVetoException(); } } final AccessToken token = ApplicationManager.getApplication().acquireWriteActionLock(getClass()); try { doSaveDocumentInWriteAction(document, file); } finally { token.finish(); } }
@Nullable private XmlFile createAnnotationsXml( @NotNull VirtualFile root, @NonNls @NotNull String packageName) { final String[] dirs = packageName.split("[\\.]"); for (String dir : dirs) { if (dir.isEmpty()) break; VirtualFile subdir = root.findChild(dir); if (subdir == null) { try { subdir = root.createChildDirectory(null, dir); } catch (IOException e) { LOG.error(e); } } root = subdir; } final PsiDirectory directory = myPsiManager.findDirectory(root); if (directory == null) return null; final PsiFile psiFile = directory.findFile(ANNOTATIONS_XML); if (psiFile instanceof XmlFile) { return (XmlFile) psiFile; } try { final PsiFileFactory factory = PsiFileFactory.getInstance(myPsiManager.getProject()); return (XmlFile) directory.add( factory.createFileFromText(ANNOTATIONS_XML, XmlFileType.INSTANCE, "<root></root>")); } catch (IncorrectOperationException e) { LOG.error(e); } return null; }
private static void retainOnlyJarsAndDirectories(List<VirtualFile> woSdk) { for (Iterator<VirtualFile> iterator = woSdk.iterator(); iterator.hasNext(); ) { VirtualFile file = iterator.next(); final VirtualFile local = ArchiveVfsUtil.getVirtualFileForJar(file); final boolean dir = file.isDirectory(); final String name = file.getName(); if (LOG.isDebugEnabled()) { LOG.debug( "Considering: " + file.getPath() + "; local=" + local + "; dir=" + dir + "; name=" + name); } if (dir || local != null) { continue; } if (name.endsWith(".jar")) { continue; } LOG.debug("Removing"); iterator.remove(); } }
@NotNull public GeneralCommandLine createCommand( @NotNull Module module, @Nullable String jvmParams, boolean forCreation, @NotNull MvcCommand command) throws ExecutionException { final JavaParameters params = createJavaParameters(module, forCreation, false, true, jvmParams, command); addJavaHome(params, module); final GeneralCommandLine commandLine = createCommandLine(params); final VirtualFile griffonHome = getSdkRoot(module); if (griffonHome != null) { commandLine .getEnvironment() .put(getSdkHomePropertyName(), FileUtil.toSystemDependentName(griffonHome.getPath())); } final VirtualFile root = findAppRoot(module); final File ioRoot = root != null ? VfsUtilCore.virtualToIoFile(root) : new File(module.getModuleDirPath()); commandLine.setWorkDirectory(forCreation ? ioRoot.getParentFile() : ioRoot); return commandLine; }
@Nullable private MPSTreeNode getNode(MPSTreeNode rootTreeNode, VirtualFile file) { if (rootTreeNode instanceof AbstractFileTreeNode) { VirtualFile nodeFile = ((AbstractFileTreeNode) rootTreeNode).getFile(); if (nodeFile != null) { if (nodeFile.getUrl().equals(file.getUrl())) { return rootTreeNode; } if (!VfsUtil.isAncestor(nodeFile, file, false)) { return null; } } else { return null; } } for (MPSTreeNode node : rootTreeNode) { node.init(); MPSTreeNode result = getNode(node, file); if (result != null) { return result; } } return null; }
@Override public void contentsChanged(VirtualFileEvent event) { if (event.isFromSave()) return; final VirtualFile file = event.getFile(); final Document document = getCachedDocument(file); if (document == null) { myMultiCaster.fileWithNoDocumentChanged(file); return; } if (isBinaryWithDecompiler(file)) { myMultiCaster.fileWithNoDocumentChanged( file); // This will generate PSI event at FileManagerImpl } long documentStamp = document.getModificationStamp(); long oldFileStamp = event.getOldModificationStamp(); if (documentStamp != oldFileStamp) { LOG.info("reload from disk?"); LOG.info(" documentStamp:" + documentStamp); LOG.info(" oldFileStamp:" + oldFileStamp); if (file.isValid() && askReloadFromDisk(file, document)) { reloadFromDisk(document); } } else { reloadFromDisk(document); } }
@Nullable public static VirtualFile getDirectory(@NotNull final FindModel findModel) { String directoryName = findModel.getDirectoryName(); if (findModel.isProjectScope() || StringUtil.isEmpty(directoryName)) { return null; } String path = directoryName.replace(File.separatorChar, '/'); VirtualFile virtualFile = LocalFileSystem.getInstance().findFileByPath(path); if (virtualFile == null || !virtualFile.isDirectory()) { virtualFile = null; for (LocalFileProvider provider : ((VirtualFileManagerEx) VirtualFileManager.getInstance()).getLocalFileProviders()) { VirtualFile file = provider.findLocalVirtualFileByPath(path); if (file != null && file.isDirectory()) { if (file.getChildren().length > 0) { virtualFile = file; break; } if (virtualFile == null) { virtualFile = file; } } } } return virtualFile; }
public void collectCommonPluginRoots( Map<String, VirtualFile> result, @NotNull Module module, boolean refresh) { if (isCommonPluginsModule(module)) { for (VirtualFile root : ModuleRootManager.getInstance(module).getContentRoots()) { String pluginName = getInstalledPluginNameByPath(module.getProject(), root); if (pluginName != null) { result.put(pluginName, root); } } } else { VirtualFile root = findAppRoot(module); if (root == null) return; extractPlugins( module.getProject(), root.findChild(MvcModuleStructureUtil.PLUGINS_DIRECTORY), result); extractPlugins( module.getProject(), MvcModuleStructureUtil.findFile(getCommonPluginsDir(module), refresh), result); extractPlugins( module.getProject(), MvcModuleStructureUtil.findFile(getGlobalPluginsDir(module), refresh), result); } }
/** * Collects all files which are located in the passed directory. * * @throws IllegalArgumentException if <code>dir</code> isn't a directory. */ public static void collectFiles( final VirtualFile dir, final List<VirtualFile> files, final boolean recursive, final boolean addDirectories) { if (!dir.isDirectory()) { throw new IllegalArgumentException( VcsBundle.message("exception.text.file.should.be.directory", dir.getPresentableUrl())); } final FileTypeManager fileTypeManager = FileTypeManager.getInstance(); VfsUtilCore.visitChildrenRecursively( dir, new VirtualFileVisitor() { @Override public boolean visitFile(@NotNull VirtualFile file) { if (file.isDirectory()) { if (addDirectories) { files.add(file); } if (!recursive && !Comparing.equal(file, dir)) { return false; } } else if (fileTypeManager == null || file.getFileType() != FileTypes.UNKNOWN) { files.add(file); } return true; } }); }
@NotNull private static VirtualFile[] filterByReadOnliness(@NotNull VirtualFile[] files) { List<VirtualFile> result = new ArrayList<VirtualFile>(); for (VirtualFile file : files) { if (file.isInLocalFileSystem()) { result.add(file); } } return VfsUtilCore.toVirtualFileArray(result); }
@Override public void reloadFiles(final VirtualFile... files) { for (VirtualFile file : files) { if (file.exists()) { final Document doc = getCachedDocument(file); if (doc != null) { reloadFromDisk(doc); } } } }
@Nullable public VirtualFile findAppRoot(@Nullable Module module) { if (module == null) return null; String appDirName = getApplicationDirectoryName(); for (VirtualFile root : ModuleRootManager.getInstance(module).getContentRoots()) { if (root.findChild(appDirName) != null) return root; } return null; }
public static void refreshFiles(Project project, HashSet<FilePath> paths) { for (FilePath path : paths) { VirtualFile vFile = path.getVirtualFile(); if (vFile != null) { if (vFile.isDirectory()) { markFileAsDirty(project, vFile); } else { vFile.refresh(true, vFile.isDirectory()); } } } }
private static boolean isSaveNeeded(@NotNull Document document, @NotNull VirtualFile file) throws IOException { if (file.getFileType().isBinary() || document.getTextLength() > 1000 * 1000) { // don't compare if the file is too big return true; } byte[] bytes = file.contentsToByteArray(); CharSequence loaded = LoadTextUtil.getTextByBinaryPresentation(bytes, file, false, false); return !Comparing.equal(document.getCharsSequence(), loaded); }
@Override public boolean requestWriting(@NotNull Document document, Project project) { final VirtualFile file = getInstance().getFile(document); if (project != null && file != null && file.isValid()) { return !file.getFileType().isBinary() && ReadonlyStatusHandler.ensureFilesWritable(project, file); } if (document.isWritable()) { return true; } document.fireReadOnlyModificationAttempt(); return false; }
@Override @Nullable public Document getCachedDocument(@NotNull VirtualFile file) { Reference<Document> reference = file.getUserData(DOCUMENT_KEY); Document document = reference == null ? null : reference.get(); if (document != null && isBinaryWithoutDecompiler(file)) { file.putUserData(DOCUMENT_KEY, null); document.putUserData(FILE_KEY, null); return null; } return document; }
public Object getData(String dataId) { if (PlatformDataKeys.VIRTUAL_FILE_ARRAY.getName().equals(dataId)) { List<VirtualFile> files = new LinkedList<VirtualFile>(); TreePath[] treePaths = getSelectionPaths(); if (treePaths != null) { for (TreePath tp : treePaths) { Object lastPathComponent = tp.getLastPathComponent(); if (lastPathComponent instanceof AbstractFileTreeNode) { AbstractFileTreeNode node = (AbstractFileTreeNode) lastPathComponent; VirtualFile file = node.getFile(); if (file.isValid()) { files.add(file); } } } } return files.toArray(new VirtualFile[files.size()]); } else if (PlatformDataKeys.VIRTUAL_FILE.getName().equals(dataId)) { TreePath tp = getSelectedPath(); if (tp == null) { return super.getData(dataId); } Object lastPathComponent = tp.getLastPathComponent(); if (lastPathComponent instanceof AbstractFileTreeNode) { AbstractFileTreeNode node = (AbstractFileTreeNode) lastPathComponent; VirtualFile file = node.getFile(); if (file.isValid()) { return file; } } } else if (PlatformDataKeys.COPY_PROVIDER.getName().equals(dataId)) { return new FilePaneCopyProvider(); } else if (PlatformDataKeys.PASTE_PROVIDER.getName().equals(dataId)) { return new FilePanePasteProvider(); } else if (PlatformDataKeys.CUT_PROVIDER.getName().equals(dataId)) { return new FilePaneCopyProvider(); } else if (dataId.equals(MPSDataKeys.PLACE.getName())) { TreeNode treeNode = getSelectedTreeNode(TreeNode.class); if (treeNode instanceof ModuleTreeNode) { return ActionPlace.PROJECT_PANE_MODULE; } else if (treeNode instanceof FileTreeNode) { return ActionPlace.PROJECT_PANE_FILE; } else if (treeNode instanceof FolderTreeNode) { return ActionPlace.PROJECT_PANE_FOLDER; } } return super.getData(dataId); }
@Override protected boolean isAlwaysShowPlus(NodeDescriptor nodeDescriptor) { Object element = nodeDescriptor.getElement(); if (element != null) { FileElement descriptor = (FileElement) element; VirtualFile file = descriptor.getFile(); if (file != null) { if (myChooserDescriptor.isChooseJarContents() && FileElement.isArchive(file)) { return true; } return file.isDirectory(); } } return true; }
@Nullable public VirtualFile findAppDirectory(@Nullable PsiElement element) { if (element == null) return null; PsiFile containingFile = element.getContainingFile().getOriginalFile(); VirtualFile file = containingFile.getVirtualFile(); if (file == null) return null; ProjectFileIndex index = ProjectRootManager.getInstance(containingFile.getProject()).getFileIndex(); VirtualFile root = index.getContentRootForFile(file); if (root == null) return null; return root.findChild(getApplicationDirectoryName()); }
private void appendChosenAnnotationsRoot( @NotNull final OrderEntry entry, @NotNull final VirtualFile vFile) { if (entry instanceof LibraryOrderEntry) { Library library = ((LibraryOrderEntry) entry).getLibrary(); LOG.assertTrue(library != null); final ModifiableRootModel rootModel = ModuleRootManager.getInstance(entry.getOwnerModule()).getModifiableModel(); final Library.ModifiableModel model = library.getModifiableModel(); model.addRoot(vFile, AnnotationOrderRootType.getInstance()); model.commit(); rootModel.commit(); } else if (entry instanceof ModuleSourceOrderEntry) { final ModifiableRootModel model = ModuleRootManager.getInstance(entry.getOwnerModule()).getModifiableModel(); final JavaModuleExternalPaths extension = model.getModuleExtension(JavaModuleExternalPaths.class); extension.setExternalAnnotationUrls( ArrayUtil.mergeArrays(extension.getExternalAnnotationsUrls(), vFile.getUrl())); model.commit(); } else if (entry instanceof JdkOrderEntry) { final SdkModificator sdkModificator = ((JdkOrderEntry) entry).getJdk().getSdkModificator(); sdkModificator.addRoot(vFile, AnnotationOrderRootType.getInstance()); sdkModificator.commitChanges(); } myExternalAnnotations.clear(); }
@Override public boolean isFileModified(@NotNull VirtualFile file) { final Document doc = getCachedDocument(file); return doc != null && isDocumentUnsaved(doc) && doc.getModificationStamp() != file.getModificationStamp(); }
public static void setDirectoryName(@NotNull FindModel model, @NotNull DataContext dataContext) { PsiElement psiElement = null; Project project = CommonDataKeys.PROJECT.getData(dataContext); if (project != null && !DumbServiceImpl.getInstance(project).isDumb()) { try { psiElement = CommonDataKeys.PSI_ELEMENT.getData(dataContext); } catch (IndexNotReadyException ignore) { } } String directoryName = null; if (psiElement instanceof PsiDirectory) { directoryName = ((PsiDirectory) psiElement).getVirtualFile().getPresentableUrl(); } if (directoryName == null && psiElement instanceof PsiDirectoryContainer) { final PsiDirectory[] directories = ((PsiDirectoryContainer) psiElement).getDirectories(); directoryName = directories.length == 1 ? directories[0].getVirtualFile().getPresentableUrl() : null; } Module module = LangDataKeys.MODULE_CONTEXT.getData(dataContext); if (module != null) { model.setModuleName(module.getName()); } Editor editor = CommonDataKeys.EDITOR.getData(dataContext); if (model.getModuleName() == null || editor == null) { model.setDirectoryName(directoryName); model.setProjectScope( directoryName == null && module == null && !model.isCustomScope() || editor != null); if (directoryName != null) { model.setCustomScope(false); // to select "Directory: " radio button } // for convenience set directory name to directory of current file, note that we doesn't // change default projectScope if (directoryName == null) { VirtualFile virtualFile = CommonDataKeys.VIRTUAL_FILE.getData(dataContext); if (virtualFile != null && !virtualFile.isDirectory()) virtualFile = virtualFile.getParent(); if (virtualFile != null) model.setDirectoryName(virtualFile.getPresentableUrl()); } } }
private static void addSourceDirectoriesFromLibraries( @NotNull Project project, @NotNull VirtualFile directory, @NotNull Collection<VirtualFile> outSourceRoots) { ProjectFileIndex index = ProjectFileIndex.SERVICE.getInstance(project); VirtualFile classRoot = index.getClassRootForFile(directory); if (classRoot == null) return; String relativePath = VfsUtilCore.getRelativePath(directory, classRoot); if (relativePath == null) return; for (OrderEntry orderEntry : index.getOrderEntriesForFile(directory)) { for (VirtualFile sourceRoot : orderEntry.getFiles(OrderRootType.SOURCES)) { VirtualFile sourceFile = sourceRoot.findFileByRelativePath(relativePath); if (sourceFile != null) { outSourceRoots.add(sourceFile); } } } }
// returns number of hits static int processUsagesInFile( @NotNull final PsiFile psiFile, @NotNull final FindModel findModel, @NotNull final Processor<UsageInfo> consumer) { if (findModel.getStringToFind().isEmpty()) { if (!ApplicationManager.getApplication() .runReadAction((Computable<Boolean>) () -> consumer.process(new UsageInfo(psiFile)))) { throw new ProcessCanceledException(); } return 1; } final VirtualFile virtualFile = psiFile.getVirtualFile(); if (virtualFile == null) return 0; if (virtualFile.getFileType().isBinary()) return 0; // do not decompile .class files final Document document = ApplicationManager.getApplication() .runReadAction( (Computable<Document>) () -> virtualFile.isValid() ? FileDocumentManager.getInstance().getDocument(virtualFile) : null); if (document == null) return 0; final int[] offset = {0}; int count = 0; int found; ProgressIndicator indicator = ProgressWrapper.unwrap(ProgressManager.getInstance().getProgressIndicator()); TooManyUsagesStatus tooManyUsagesStatus = TooManyUsagesStatus.getFrom(indicator); do { tooManyUsagesStatus.pauseProcessingIfTooManyUsages(); // wait for user out of read action found = ApplicationManager.getApplication() .runReadAction( (Computable<Integer>) () -> { if (!psiFile.isValid()) return 0; return addToUsages( document, consumer, findModel, psiFile, offset, USAGES_PER_READ_ACTION); }); count += found; } while (found != 0); return count; }
protected boolean askReloadFromDisk(final VirtualFile file, final Document document) { ApplicationManager.getApplication().assertIsDispatchThread(); if (!isDocumentUnsaved(document)) return true; String message = UIBundle.message("file.cache.conflict.message.text", file.getPresentableUrl()); if (ApplicationManager.getApplication().isUnitTestMode()) throw new RuntimeException(message); final DialogBuilder builder = new DialogBuilder((Project) null); builder.setCenterPanel(new JLabel(message, Messages.getQuestionIcon(), SwingConstants.CENTER)); builder.addOkAction().setText(UIBundle.message("file.cache.conflict.load.fs.changes.button")); builder .addCancelAction() .setText(UIBundle.message("file.cache.conflict.keep.memory.changes.button")); builder.addAction( new AbstractAction(UIBundle.message("file.cache.conflict.show.difference.button")) { @Override public void actionPerformed(ActionEvent e) { String title = UIBundle.message( "file.cache.conflict.for.file.dialog.title", file.getPresentableUrl()); final ProjectEx project = (ProjectEx) ProjectLocator.getInstance().guessProjectForFile(file); SimpleDiffRequest request = new SimpleDiffRequest(project, title); FileType fileType = file.getFileType(); String fsContent = LoadTextUtil.loadText(file).toString(); request.setContents( new SimpleContent(fsContent, fileType), new DocumentContent(project, document, fileType)); request.setContentTitles( UIBundle.message("file.cache.conflict.diff.content.file.system.content"), UIBundle.message("file.cache.conflict.diff.content.memory.content")); DialogBuilder diffBuilder = new DialogBuilder(project); DiffPanelImpl diffPanel = (DiffPanelImpl) DiffManager.getInstance() .createDiffPanel(diffBuilder.getWindow(), project, diffBuilder, null); diffPanel.getOptions().setShowSourcePolicy(DiffPanelOptions.ShowSourcePolicy.DONT_SHOW); diffBuilder.setCenterPanel(diffPanel.getComponent()); diffBuilder.setDimensionServiceKey("FileDocumentManager.FileCacheConflict"); diffPanel.setDiffRequest(request); diffBuilder .addOkAction() .setText(UIBundle.message("file.cache.conflict.save.changes.button")); diffBuilder.addCancelAction(); diffBuilder.setTitle(title); if (diffBuilder.show() == DialogWrapper.OK_EXIT_CODE) { builder.getDialogWrapper().close(DialogWrapper.CANCEL_EXIT_CODE); } } }); builder.setTitle(UIBundle.message("file.cache.conflict.dialog.title")); builder.setButtonsAlignment(SwingConstants.CENTER); builder.setHelpId("reference.dialogs.fileCacheConflict"); return builder.show() == 0; }
@NotNull public static Collection<VcsDirectoryMapping> findRoots( @NotNull VirtualFile rootDir, @NotNull Project project) throws IllegalArgumentException { if (!rootDir.isDirectory()) { throw new IllegalArgumentException( "Can't find VCS at the target file system path. Reason: expected to find a directory there but it's not. The path: " + rootDir.getParent()); } Collection<VcsRoot> roots = ServiceManager.getService(project, VcsRootDetector.class).detect(rootDir); Collection<VcsDirectoryMapping> result = ContainerUtilRt.newArrayList(); for (VcsRoot vcsRoot : roots) { VirtualFile vFile = vcsRoot.getPath(); AbstractVcs rootVcs = vcsRoot.getVcs(); if (rootVcs != null && vFile != null) { result.add(new VcsDirectoryMapping(vFile.getPath(), rootVcs.getName())); } } return result; }
public void actionPerformed(AnActionEvent event) { Project project = event.getData(PlatformDataKeys.PROJECT); Icon i = getQuestionIcon(); //Prompt the user for their choice of dimension filters (only one-at-a-time atm) String dimension = showInputDialog(project, "What dimesion would you like to filter by?", "Dimension name",i); String value = showInputDialog(project, "What choice would you like to make in dimension " + dimension + "?", "Chocie", i); //Grab the file and store it's current state before making any modifications //TODO: this will have to account for if a partial selection has already been made on the file VirtualFile f = event.getData(DataKeys.VIRTUAL_FILE); String name = f.getName(); //Perform the modification to the file, store it's new state, and display to the user Choice c = new Choice(dimension, value); //TODO: rather than passing in names, pass in some representation of the original file and the modified file FileVariation fv = new FileVariation(name, name, c); variedFiles.add(fv); }
public static void registerDocument( @NotNull final Document document, @NotNull VirtualFile virtualFile) { synchronized (lock) { virtualFile.putUserData( DOCUMENT_KEY, new SoftReference<Document>(document) { @Override public Document get() { return document; } }); document.putUserData(FILE_KEY, virtualFile); } }
private void extractPlugins( Project project, @Nullable VirtualFile pluginRoot, Map<String, VirtualFile> res) { if (pluginRoot != null) { VirtualFile[] children = pluginRoot.getChildren(); if (children != null) { for (VirtualFile child : children) { String pluginName = getInstalledPluginNameByPath(project, child); if (pluginName != null) { res.put(pluginName, child); } } } } }
private void doSaveDocumentInWriteAction(@NotNull Document document, @NotNull VirtualFile file) throws IOException { if (!file.isValid()) { removeFromUnsaved(document); return; } if (!file.equals(getFile(document))) { registerDocument(document, file); } if (!isSaveNeeded(document, file)) { if (document instanceof DocumentEx) { ((DocumentEx) document).setModificationStamp(file.getModificationStamp()); } removeFromUnsaved(document); updateModifiedProperty(file); return; } myMultiCaster.beforeDocumentSaving(document); LOG.assertTrue(file.isValid()); String text = document.getText(); String lineSeparator = getLineSeparator(document, file); if (!lineSeparator.equals("\n")) { text = StringUtil.convertLineSeparators(text, lineSeparator); } Project project = ProjectLocator.getInstance().guessProjectForFile(file); LoadTextUtil.write(project, file, this, text, document.getModificationStamp()); myUnsavedDocuments.remove(document); LOG.assertTrue(!myUnsavedDocuments.contains(document)); myTrailingSpacesStripper.clearLineModificationFlags(document); }