@Nullable private Project findProject(String file) { LocalFileSystem localFileSystem = LocalFileSystem.getInstance(); ProjectLocator projectLocator = ProjectLocator.getInstance(); AtomicReference<Project> ret = new AtomicReference<>(); FileUtil.processFilesRecursively( new File(file), (f) -> { VirtualFile vf = localFileSystem.findFileByIoFile(f); if (vf != null) { ret.set(projectLocator.guessProjectForFile(vf)); return false; } return true; }); return ret.get(); }
@Nullable private static XmlFile getDictionaryFileFromInclude(@NotNull Project project, IncludedXmlTag xmlIncludeTag) { XmlFile xmlFile = null; XmlElement origXmlElement = xmlIncludeTag.getOriginal(); PsiFile origPsiFile = origXmlElement != null ? origXmlElement.getContainingFile() : null; if (origPsiFile instanceof XmlFile) { xmlFile = (XmlFile) origPsiFile; AppleScriptSystemDictionaryRegistryService dictionaryService = ServiceManager.getService(AppleScriptSystemDictionaryRegistryService .class); VirtualFile vFile = origPsiFile.getVirtualFile(); DictionaryInfo dInfo = dictionaryService.getDictionaryInfoByApplicationPath(vFile.getPath()); if (dInfo != null) { File ioFile = dInfo.getDictionaryFile(); if (ioFile.exists()) { vFile = LocalFileSystem.getInstance().findFileByIoFile(ioFile); if (vFile == null || !vFile.isValid()) return null; PsiFile psiFile = PsiManager.getInstance(project).findFile(vFile); xmlFile = (XmlFile) psiFile; } } } return xmlFile; }
@Nullable private ApplicationDictionary createDictionaryFromInfo(final @NotNull DictionaryInfo dInfo) { if (!dInfo.isInitialized()) { //dictionary terms must be ridden from the dictionary file before creating a PSI for it LOG.error("Attempt to create dictionary for not initialized Dictionary Info for application" + dInfo.getApplicationName()); return null; } String applicationName = dInfo.getApplicationName(); VirtualFile vFile = LocalFileSystem.getInstance().findFileByIoFile(dInfo.getDictionaryFile()); if (vFile != null && vFile.isValid()) { PsiFile psiFile = PsiManager.getInstance(project).findFile(vFile); XmlFile xmlFile = (XmlFile) psiFile; if (xmlFile != null) { ApplicationDictionary dictionary = new ApplicationDictionaryImpl(project, xmlFile, applicationName, dInfo.getApplicationFile()); dictionaryMap.put(applicationName, dictionary); return dictionary; } } LOG.warn("Failed to create dictionary from info for application: " + applicationName + ". Reason: file is null"); return null; }
/** * 打开类文件 * * @param filePath * @param project */ public static void openFileInPanel(final String filePath, final Project project) { ApplicationManager.getApplication().invokeLater(new Runnable() { @Override public void run() { VirtualFile file = LocalFileSystem.getInstance().refreshAndFindFileByPath(filePath); if (file != null && file.isValid()) { FileEditorProvider[] providers = FileEditorProviderManager.getInstance() .getProviders(project, file); if (providers.length != 0) { OpenFileDescriptor descriptor = new OpenFileDescriptor(project, file); FileEditorManager.getInstance(project).openTextEditor(descriptor, false); } } } }); }
/** * 调用 Android 文件对比 * @param project * @param f1 * @param f2 */ public static void diff(final Project project, final File f1, final File f2) { ApplicationManager.getApplication().invokeLater(new Runnable() { @Override public void run() { try { VirtualFile v1 = LocalFileSystem.getInstance().refreshAndFindFileByIoFile(f1); Document document1 = FileDocumentManager.getInstance().getDocument(v1); FileDocumentContentImpl fileDocumentContent1 = new FileDocumentContentImpl(project, document1, v1); VirtualFile v2 = LocalFileSystem.getInstance().refreshAndFindFileByIoFile(f2); Document document2 = FileDocumentManager.getInstance().getDocument(v2); FileDocumentContentImpl fileDocumentContent2 = new FileDocumentContentImpl(project, document2, v2); SimpleDiffRequest simpleDiffRequest = new SimpleDiffRequest(Constant.TITLE, fileDocumentContent1, fileDocumentContent2, f1.getName(), f2.getName()); DiffManager.getInstance().showDiff(project, simpleDiffRequest); } catch (Exception e) { NotificationUtils.errorNotification("Diff Source Error:" + e.getMessage()); } } }); }
@Override public void removeAllFiles(@NotNull final Collection<File> files) throws IOException { Validate.notNull(files); if (files.isEmpty()) { return; } final LocalFileSystem localFileSystem = LocalFileSystem.getInstance(); for (File file : files) { final VirtualFile virtualFile = localFileSystem.findFileByIoFile(file); if (null != virtualFile) { ApplicationManager.getApplication().runWriteAction(new RemoveFileComputable(virtualFile)); } else { FileUtil.delete(file); } } }
private static Sdk addDetectedSdk(@NotNull Sdk sdk, @NotNull Project project) { final ProjectSdksModel model = PyConfigurableInterpreterList.getInstance(project).getModel(); final String name = sdk.getName(); VirtualFile sdkHome = WriteAction.compute(() -> LocalFileSystem.getInstance().refreshAndFindFileByPath(name)); sdk = SdkConfigurationUtil.createAndAddSDK(sdkHome.getPath(), PythonSdkType.getInstance()); if (sdk != null) { PythonSdkUpdater.updateOrShowError(sdk, null, project, null); } model.addSdk(sdk); try { model.apply(); } catch (ConfigurationException exception) { LOG.error("Error adding detected python interpreter " + exception.getMessage()); } return sdk; }
@Nullable private String getCurrentTaskFilePath() { String textFile = null; for (Map.Entry<String, TaskFile> entry : myTask.getTaskFiles().entrySet()) { String path = getTaskFilePath(entry.getKey()); if (!entry.getValue().getActivePlaceholders().isEmpty()) { return path; } VirtualFile virtualFile = LocalFileSystem.getInstance().findFileByPath(path); if (virtualFile == null) { continue; } if (TextEditorProvider.isTextFile(virtualFile)) { textFile = path; } } return textFile; }
@Override public void checkConfiguration() throws RuntimeConfigurationException { super.checkConfiguration(); String message = "Select valid path to the file with tests"; VirtualFile testsFile = LocalFileSystem.getInstance().findFileByPath(myPathToTest); if (testsFile == null) { throw new RuntimeConfigurationException(message); } VirtualFile taskDir = StudyUtils.getTaskDir(testsFile); if (taskDir == null) { throw new RuntimeConfigurationException(message); } if (StudyUtils.getTask(myProject, taskDir) == null) { throw new RuntimeConfigurationException(message); } }
private static List<VirtualFile> getAllAnswerTaskFiles(@NotNull Course course, @NotNull Project project) { List<VirtualFile> result = new ArrayList<>(); for (Lesson lesson : course.getLessons()) { for (Task task : lesson.getTaskList()) { for (Map.Entry<String, TaskFile> entry : task.getTaskFiles().entrySet()) { String name = entry.getKey(); String answerName = FileUtil.getNameWithoutExtension(name) + CCUtils.ANSWER_EXTENSION_DOTTED + FileUtilRt.getExtension(name); String taskPath = FileUtil.join(project.getBasePath(), EduNames.LESSON + lesson.getIndex(), EduNames.TASK + task.getIndex()); VirtualFile taskFile = LocalFileSystem.getInstance().findFileByPath(FileUtil.join(taskPath, answerName)); if (taskFile == null) { taskFile = LocalFileSystem.getInstance().findFileByPath(FileUtil.join(taskPath, EduNames.SRC, answerName)); } if (taskFile != null) { result.add(taskFile); } } } } return result; }
@Override public void actionPerformed(AnActionEvent anActionEvent) { Project project = anActionEvent.getProject(); if (project != null) { String currentApkPath = PropertiesManager.getData(project, PropertyKeys.APK_PATH); VirtualFile fileToSelectOnCreate = TextUtils.isEmpty(currentApkPath) ? project.getBaseDir() : LocalFileSystem.getInstance().findFileByPath(currentApkPath); VirtualFile apkFile = new FileChooserDialogManager.Builder(project, fileToSelectOnCreate) .setFileTypes(FileTypes.FILE) .setTitle(Strings.TITLE_ASK_APK_FILE) .setDescription(Strings.MESSAGE_ASK_APK_FILE) .withFileFilter("apk") .create() .getSelectedFile(); if (apkFile != null) { PropertiesManager.putData(project, PropertyKeys.APK_PATH, apkFile.getPath()); } } }
@Override @SuppressWarnings("ConstantConditions") public void onSettingsChange() { prepareTemplateSettings(); for (IdeFrame frame : WindowManager.getInstance().getAllProjectFrames()) { if (frame.getProject() != null) { String projectTitle = getProjectTitle(frame.getProject()); ((IdeFrameImpl)frame).setTitle(projectTitle); try { File currentFile = (File)((IdeFrameImpl) frame).getRootPane().getClientProperty("Window.documentFile"); VirtualFile virtualFile = LocalFileSystem.getInstance().findFileByIoFile(currentFile); IdeFrameImpl.updateTitle((IdeFrameImpl) frame, projectTitle, getFileTitle(frame.getProject(), virtualFile), currentFile); } catch (Exception e) { IdeFrameImpl.updateTitle((IdeFrameImpl) frame, projectTitle, null, null); } } } }
@Override public boolean validate() throws ConfigurationException { if (form.getGravDirectory().isEmpty()) { form.showHint(true); throw new ConfigurationException("Path pointing to Grav installation is empty"); } else { String file = form.getGravDirectory(); VirtualFile vf = LocalFileSystem.getInstance().findFileByIoFile(new File(file)); if (vf == null) { form.showHint(true); throw new ConfigurationException("Path to Grav installation does not exist"); } else { if (!GravSdkType.isValidGravSDK(vf)) { form.showHint(true); throw new ConfigurationException("Grav installation isn't valid"); } } } // if (StringUtil.isEmpty(sdkPanel.getSdkName())) { // throw new ConfigurationException("Specify Grav SDK"); // } form.showHint(false); return super.validate(); }
private int validate0() { if (form.getGravDirectory().isEmpty()) { form.showHint(true); return -1;//new ValidationInfo("Path pointing to Grav installation is empty"); } else { String file = form.getGravDirectory(); VirtualFile vf = LocalFileSystem.getInstance().findFileByIoFile(new File(file)); if (vf == null) { form.showHint(true); return -2; //new ValidationInfo("Path to Grav installation does not exist"); } else { if (!GravSdkType.isValidGravSDK(vf)) { form.showHint(true); return -3; //new ValidationInfo("Grav installation isn't valid"); } } } form.showHint(false); return 0; }
@Override public void generateProject(@NotNull Project project, @NotNull VirtualFile baseDir, @NotNull GravProjectSettings settings, @NotNull Module module) { StatusBar statusBar = WindowManager.getInstance().getStatusBar(project); VirtualFile vf = LocalFileSystem.getInstance().findFileByIoFile(new File(settings.gravInstallationPath)); if (vf == null || !GravSdkType.isValidGravSDK(vf)) { JBPopupFactory.getInstance() .createHtmlTextBalloonBuilder("Project couldn't be created because Grav Installation isn't valid", MessageType.ERROR, null) .setFadeoutTime(3500) .createBalloon() .show(RelativePoint.getSouthEastOf(statusBar.getComponent()), Balloon.Position.above); } else { storage.setDefaultGravDownloadPath(settings.gravInstallationPath); PropertiesComponent.getInstance().setValue(LAST_USED_GRAV_HOME, new File(settings.gravInstallationPath).getAbsolutePath()); GravProjectGeneratorUtil projectGenerator = new GravProjectGeneratorUtil(); projectGenerator.generateProject(project, baseDir, settings, module); try { List<String> includePath = new ArrayList<>(); includePath.add(baseDir.getPath()); PhpIncludePathManager.getInstance(project).setIncludePath(includePath); } catch (Exception e) { e.printStackTrace(); } } }
@Override protected void resetEditorFrom(final @NotNull GoalRunConfiguration s) { this.fileBox.setText("<no file selected>"); if (s.getRunFile() != null) { final VirtualFile file = LocalFileSystem.getInstance().refreshAndFindFileByPath(s.getRunFile()); if (file != null) { final PsiFile selectedFile = PsiManager.getInstance(this.project).findFile(file); if (selectedFile != null) { this.fileChooser.selectFile(selectedFile); this.fileBox.setText(s.getRunFile()); } } } }
public void testNavigationInPlatformXml2() throws Exception { final VirtualFile file = LocalFileSystem.getInstance().findFileByPath( getTestSdkPath() + "/platforms/" + getPlatformDir() + "/data/res/values/resources.xml"); myFixture.configureFromExistingVirtualFile(file); myFixture.getEditor().getCaretModel().moveToLogicalPosition(new LogicalPosition(19, 17)); PsiElement[] targets = GotoDeclarationAction.findAllTargetElements(myFixture.getProject(), myFixture.getEditor(), myFixture.getCaretOffset()); assertNotNull(targets); assertEquals(1, targets.length); final PsiElement targetElement = LazyValueResourceElementWrapper.computeLazyElement(targets[0]); assertInstanceOf(targetElement, XmlAttributeValue.class); final XmlAttributeValue targetAttrValue = (XmlAttributeValue)targetElement; assertEquals("Theme", targetAttrValue.getValue()); assertEquals("name", ((XmlAttribute)targetAttrValue.getParent()).getName()); assertEquals("style", ((XmlTag)targetAttrValue.getParent().getParent()).getName()); assertEquals(file, targetElement.getContainingFile().getVirtualFile()); }
@Nullable private VirtualFile doResolve() { if (myProject == null || myProject.isDisposed()) { return null; } VirtualFile baseDir = myProject.getBaseDir(); String path = FileUtil.toSystemIndependentName(myPath); if (baseDir == null) { return LocalFileSystem.getInstance().findFileByPath(path); } VirtualFile resolvedRelative = baseDir.findFileByRelativePath(path); if (resolvedRelative != null) return resolvedRelative; return LocalFileSystem.getInstance().findFileByPath(path); }
@Override @NotNull public String readFile(@NonNull File file) { final VirtualFile vFile = LocalFileSystem.getInstance().findFileByIoFile(file); if (vFile == null) { LOG.debug("Cannot find file " + file.getPath() + " in the VFS"); return ""; } final String content = getFileContent(vFile); if (content == null) { LOG.info("Cannot find file " + file.getPath() + " in the PSI"); return ""; } return content; }
public void testResolvingSystemScopeDependenciesWithProperties() throws Throwable { String libPath = myIndicesFixture.getRepositoryHelper().getTestDataPath("local1/junit/junit/4.0/junit-4.0.jar"); createProjectPom("<groupId>test</groupId>" + "<artifactId>project</artifactId>" + "<version>1</version>" + "<properties>" + " <depPath>" + libPath + "</depPath>" + "</properties>" + "<dependencies>" + " <dependency>" + " <groupId>xxx</groupId>" + " <artifactId>xxx</artifactId>" + " <version><caret>xxx</version>" + " <scope>system</scope>" + " <systemPath>${depPath}</systemPath>" + " </dependency>" + "</dependencies>"); assertResolved(myProjectPom, findPsiFile(LocalFileSystem.getInstance().refreshAndFindFileByPath(libPath))); checkHighlighting(); }
public void testJarRefreshOnRenameOrMove() throws IOException { File jar = IoTestUtil.createTestJar(); final VirtualFile vFile = LocalFileSystem.getInstance().refreshAndFindFileByIoFile(jar); assertNotNull(vFile); new WriteCommandAction.Simple(myProject) { @Override protected void run() throws Throwable { PsiTestUtil.addContentRoot(myModule, vFile.getParent()); } }.execute(); VirtualFile jarRoot = findByPath(jar.getPath() + JarFileSystem.JAR_SEPARATOR); final PsiFile file = getPsiManager().findFile(vFile); final String newName = vFile.getName() + ".jar"; rename(file, newName); assertFalse(jarRoot.isValid()); checkMove(jar, vFile, file); }
@NotNull @Override protected AnAction createAction(CheckoutProvider provider) { return new CheckoutAction(provider) { @Override protected CheckoutProvider.Listener getListener(Project project) { return new CheckoutProvider.Listener() { @Override public void directoryCheckedOut(File directory, VcsKey vcs) { final VirtualFile dir = LocalFileSystem.getInstance().refreshAndFindFileByIoFile(directory); if (dir != null) { PlatformProjectOpenProcessor.getInstance().doOpenProject(dir, null, false); } } @Override public void checkoutCompleted() { } }; } }; }
static boolean processResources(@NotNull Module module, @NotNull MavenProject mavenProject, ResourceProcessor processor) { for (MavenResource resource : mavenProject.getResources()) { if (resource.isFiltered()) { VirtualFile resDir = LocalFileSystem.getInstance().findFileByPath(resource.getDirectory()); if (resDir == null) continue; List<Pattern> includes = collectPatterns(resource.getIncludes(), "**/*"); List<Pattern> excludes = collectPatterns(resource.getExcludes(), null); final String resourceTargetPath = resource.getTargetPath(); if (resourceTargetPath != null) { String targetPath = FileUtil.toSystemIndependentName(resourceTargetPath); if (processResources(module.getProject(), resDir, resDir, includes, excludes, targetPath, processor)) { return true; } } } } return false; }
@Override public boolean filterElements(@NotNull ChooseByNameBase base, @NotNull String pattern, boolean everywhere, @NotNull ProgressIndicator indicator, @NotNull Processor<Object> consumer) { if (pattern.contains("/") || pattern.contains("\\")) { String path = FileUtil.toSystemIndependentName(ChooseByNamePopup.getTransformedPattern(pattern, myModel)); VirtualFile vFile = LocalFileSystem.getInstance().findFileByPathIfCached(path); if (vFile != null) { ProjectFileIndex index = ProjectFileIndex.SERVICE.getInstance(myProject); if (index.isInContent(vFile) || index.isInLibraryClasses(vFile) || index.isInLibrarySource(vFile)) { PsiFileSystemItem fileOrDir = vFile.isDirectory() ? PsiManager.getInstance(myProject).findDirectory(vFile) : PsiManager.getInstance(myProject).findFile(vFile); if (fileOrDir != null && !consumer.process(fileOrDir)) { return false; } } } } return super.filterElements(base, pattern, everywhere, indicator, consumer); }
public void testNavigationInPlatformXml3() throws Exception { final VirtualFile file = LocalFileSystem.getInstance().findFileByPath( getTestSdkPath() + "/platforms/" + getPlatformDir() + "/data/res/values/resources.xml"); myFixture.configureFromExistingVirtualFile(file); myFixture.getEditor().getCaretModel().moveToLogicalPosition(new LogicalPosition(5, 44)); PsiElement[] targets = GotoDeclarationAction.findAllTargetElements(myFixture.getProject(), myFixture.getEditor(), myFixture.getCaretOffset()); assertNotNull(targets); assertEquals(1, targets.length); final PsiElement targetElement = LazyValueResourceElementWrapper.computeLazyElement(targets[0]); assertInstanceOf(targetElement, XmlAttributeValue.class); final XmlAttributeValue targetAttrValue = (XmlAttributeValue)targetElement; assertEquals("my_white", targetAttrValue.getValue()); assertEquals("name", ((XmlAttribute)targetAttrValue.getParent()).getName()); assertEquals("color", ((XmlTag)targetAttrValue.getParent().getParent()).getName()); assertEquals(file, targetElement.getContainingFile().getVirtualFile()); }
public LookupFile find(@NotNull final String path) { final VirtualFile byUrl = VirtualFileManager.getInstance().findFileByUrl(path); if (byUrl != null) { return new VfsFile(this, byUrl); } String toFind = normalize(path); if (toFind.length() == 0) { File[] roots = File.listRoots(); if (roots.length > 0) { toFind = roots[0].getAbsolutePath(); } } final File file = new File(toFind); // '..' and '.' path components will be eliminated VirtualFile vFile = LocalFileSystem.getInstance().findFileByIoFile(file); if (vFile != null) { return new VfsFile(this, vFile); } else if (file.isAbsolute()) { return new IoFile(new File(path)); } return null; }
@Nullable protected VirtualFile getExternalConfig(@NotNull ExternalConfigPathAware data, ProjectSystemId externalSystemId) { String path = data.getLinkedExternalProjectPath(); LocalFileSystem fileSystem = LocalFileSystem.getInstance(); VirtualFile externalSystemConfigPath = fileSystem.refreshAndFindFileByPath(path); if (externalSystemConfigPath == null) { return null; } VirtualFile toOpen = externalSystemConfigPath; for (ExternalSystemConfigLocator locator : ExternalSystemConfigLocator.EP_NAME.getExtensions()) { if (externalSystemId.equals(locator.getTargetExternalSystemId())) { toOpen = locator.adjust(toOpen); if (toOpen == null) { return null; } break; } } return toOpen.isDirectory() ? null : toOpen; }
@Override @Nullable public ChangesBrowserNode getParentNodeFor(final StaticFilePath node, final ChangesBrowserNode rootNode) { if (myProject.isDefault()) return null; ProjectFileIndex index = ProjectRootManager.getInstance(myProject).getFileIndex(); VirtualFile vFile = node.getVf(); if (vFile == null) { vFile = LocalFileSystem.getInstance().findFileByIoFile(new File(node.getPath())); } boolean hideExcludedFiles = Registry.is("ide.hide.excluded.files"); if (vFile != null && Comparing.equal(vFile, index.getContentRootForFile(vFile, hideExcludedFiles))) { Module module = index.getModuleForFile(vFile, hideExcludedFiles); return getNodeForModule(module, rootNode); } return null; }
public void testPublicVisibility() throws Exception { doTest((rootDir, rootAfter) -> { PsiClass aClass = myJavaFacade.findClass("Test", GlobalSearchScope.projectScope(myProject)); assertNotNull("Class Test not found", aClass); final ArrayList<PsiMethod> methods = new ArrayList<>(); methods.add(aClass.findMethodsByName("foos", false)[0]); final ArrayList<PsiField> fields = new ArrayList<>(); fields.add(aClass.findFieldByName("myT", false)); final ExtractClassProcessor processor = new ExtractClassProcessor(aClass, fields, methods, new ArrayList<>(), "", null, "Extracted", PsiModifier.PUBLIC, false, Collections.<MemberInfo>emptyList()); processor.run(); LocalFileSystem.getInstance().refresh(false); FileDocumentManager.getInstance().saveAllDocuments(); }); }
private Object execIPythonEditor(Vector params) { String path = (String)params.get(0); int line = Integer.parseInt((String)params.get(1)); final VirtualFile file = StringUtil.isEmpty(path) ? null : LocalFileSystem.getInstance().findFileByPath(path); if (file != null) { ApplicationManager.getApplication().invokeLater(new Runnable() { @Override public void run() { AccessToken at = ApplicationManager.getApplication().acquireReadActionLock(); try { FileEditorManager.getInstance(myProject).openFile(file, true); } finally { at.finish(); } } }); return Boolean.TRUE; } return Boolean.FALSE; }
@Override protected void setUp() throws Exception { super.setUp(); final File testRoot = new File(PluginPathManager.getPluginHomePath("eclipse") + "/testData", getRelativeTestPath()); assertTrue(testRoot.getAbsolutePath(), testRoot.isDirectory()); final File currentTestRoot = new File(testRoot, getTestName(true)); assertTrue(currentTestRoot.getAbsolutePath(), currentTestRoot.isDirectory()); final String tempPath = getProject().getBaseDir().getPath(); final File tempDir = new File(tempPath); VirtualFile vTestRoot = LocalFileSystem.getInstance().findFileByIoFile(currentTestRoot); copyDirContentsTo(vTestRoot, getProject().getBaseDir()); final VirtualFile virtualTestDir = LocalFileSystem.getInstance().refreshAndFindFileByIoFile(tempDir); assertNotNull(tempDir.getAbsolutePath(), virtualTestDir); virtualTestDir.refresh(false, true); PathMacros.getInstance().setMacro(VARIABLE, new File(tempPath, VARIABLE + "idea").getPath()); PathMacros.getInstance().setMacro(SRCVARIABLE, new File(tempPath, SRCVARIABLE + "idea").getPath()); }
@Override public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) { final Component rendererComponent = super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus); if (value instanceof String) { final String path = (String)value; final VirtualFile file = LocalFileSystem.getInstance().findFileByPath(path); if (file == null) { setForeground(JBColor.RED); setIcon(null); } else { setForeground(myFilesList.getForeground()); setIcon(file.isDirectory() ? PlatformIcons.FOLDER_ICON : VirtualFilePresentation.getIcon(file)); } setText(path); } return rendererComponent; }
@Nullable protected PsiFileSystemItem[] getPsiFiles(@Nullable List<File> fileList) { if (fileList == null) return null; List<PsiFileSystemItem> sourceFiles = new ArrayList<PsiFileSystemItem>(); for (File file : fileList) { final VirtualFile vFile = LocalFileSystem.getInstance().refreshAndFindFileByIoFile(file); if (vFile != null) { final PsiFileSystemItem psiFile = vFile.isDirectory() ? PsiManager.getInstance(myProject).findDirectory(vFile) : PsiManager.getInstance(myProject).findFile(vFile); if (psiFile != null) { sourceFiles.add(psiFile); } } } return sourceFiles.toArray(new PsiFileSystemItem[sourceFiles.size()]); }
public static VirtualFile createGradleProjectToImport(File dir, String name, String... requiredProjects) throws IOException { File moduleDir = new File(dir, name); if (!moduleDir.mkdirs()) { throw new IllegalStateException("Unable to create module"); } Iterable<String> projectDependencies = Iterables.transform(Arrays.asList(requiredProjects), new Function<String, String>() { @Override public String apply(String input) { return String.format("\tcompile project('%s')", pathToGradleName(input)); } }); String buildGradle = String.format(BUILD_GRADLE_TEMPLATE, Joiner.on("\n").join(projectDependencies)); Files.write(buildGradle, new File(moduleDir, SdkConstants.FN_BUILD_GRADLE), Charset.defaultCharset()); VirtualFile moduleFile = LocalFileSystem.getInstance().refreshAndFindFileByPath(moduleDir.getAbsolutePath()); if (moduleFile == null) { throw new IllegalStateException("Cannot get virtual file for module we just created"); } else { return moduleFile; } }
private static void processIncludes(@NotNull ApplicationDictionary parsedDictionary, @Nullable XmlTag[] includes) { if (includes == null) return; for (XmlTag include : includes) { String hrefIncl = include.getAttributeValue("href"); if (!StringUtil.isEmpty(hrefIncl)) { hrefIncl = hrefIncl.replace("file://localhost", ""); File includedFile = new File(hrefIncl); // ((IncludedXmlTag) suiteTag).getOriginal().getContainingFile(); //as there is assertion error (java.lang.AssertionError: File accessed outside allowed roots), // we are trying to find if the dictionary file for this included dictionary was already generated AppleScriptSystemDictionaryRegistryService dictionarySystemRegistry = ServiceManager .getService(AppleScriptSystemDictionaryRegistryService.class); VirtualFile vFile; File ioFile = null; DictionaryInfo dInfo = dictionarySystemRegistry.getDictionaryInfoByApplicationPath(includedFile.getPath()); if (dInfo != null) { ioFile = dInfo.getDictionaryFile(); } else if (includedFile.isFile()) { String fName = includedFile.getName(); int index = fName.lastIndexOf('.'); fName = index < 0 ? fName : fName.substring(0, index); ioFile = dictionarySystemRegistry.getDictionaryFile(fName); } if (ioFile == null || !ioFile.exists()) ioFile = includedFile; if (ioFile.exists()) { vFile = LocalFileSystem.getInstance().findFileByIoFile(ioFile); if (vFile == null || !vFile.isValid()) continue; PsiFile psiFile = PsiManager.getInstance(parsedDictionary.getProject()).findFile(vFile); XmlFile xmlFile = (XmlFile) psiFile; if (xmlFile != null) { parsedDictionary.processInclude(xmlFile); } } } } }
private void discoverInstalledApplicationNames() { for (String applicationsDirectory : ApplicationDictionary.APP_BUNDLE_DIRECTORIES) { VirtualFile appsDirVFile = LocalFileSystem.getInstance().findFileByPath(applicationsDirectory); if (appsDirVFile != null && appsDirVFile.exists()) { discoverApplicationsInDirectory(appsDirVFile); } } LOG.info("List of installed applications initialized. Count: " + discoveredApplicationNames.size()); }
/** * Template file change listener. */ // TODO remove this code if VirtualFileListener is able to replace this code on all platforms /* private FileDocumentManagerListener templateFileChangeListener = new FileDocumentManagerAdapter() { @Override public void beforeDocumentSaving(@NotNull Document d) { VirtualFile vFile = FileDocumentManager.getInstance().getFile(d); if (vFile != null && vFile.getCanonicalPath().replace('\\', '/').startsWith(CptUtil.getTemplatesPath().getAbsolutePath().replace('\\', '/'))) { reloadTemplates(); } } }; */ protected CustomPostfixTemplateProvider() { // listen to file changes of template files LocalFileSystem.getInstance().addRootToWatch(CptUtil.getTemplatesPath().getAbsolutePath(), true); LocalFileSystem.getInstance().addVirtualFileListener(new VirtualFileContentsChangedAdapter() { @Override protected void onFileChange(@NotNull VirtualFile vFile) { if (CptUtil.isTemplateFile(vFile)) { reloadTemplates(); } } @Override protected void onBeforeFileChange(@NotNull VirtualFile virtualFile) { } }); // listen to settings changes MessageBusConnection messageBus = ApplicationManager.getApplication().getMessageBus().connect(); messageBus.subscribe(CptApplicationSettings.SettingsChangedListener.TOPIC, this); // listen to file changes of template file //messageBus.subscribe(AppTopics.FILE_DOCUMENT_SYNC, templateFileChangeListener); // load templates reload(CptApplicationSettings.getInstance()); }
/** * Loads the postfix templates from the given file and returns them. * * @param file templates file * @return set of postfix templates */ @SuppressWarnings("WeakerAccess") public Set<PostfixTemplate> loadTemplatesFrom(@NotNull File file) { VirtualFile vFile = LocalFileSystem.getInstance().findFileByIoFile(file); if (vFile != null) { return loadTemplatesFrom(vFile); } else { return new OrderedSet<>(); } }
private void showDiff() { Project project = CptUtil.getActiveProject(); CptUtil.getTemplateFile("java").ifPresent(file -> { VirtualFile vFile = LocalFileSystem.getInstance().findFileByIoFile(file); DocumentContent content1 = DiffContentFactory.getInstance().create(templatesText); DocumentContent content2 = DiffContentFactory.getInstance().createDocument(project, vFile); DiffManager.getInstance().showDiff(project, new SimpleDiffRequest("Templates Diff", content1, content2, "Predefined plugin templates", "Your templates")); }); }