Java Code Examples for com.intellij.openapi.vfs.VirtualFile

The following are top voted examples for showing how to use com.intellij.openapi.vfs.VirtualFile. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: ijaas   File: JavaGetImportCandidatesHandler.java   Source Code and License 6 votes vote down vote up
@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();
}
 
Example 2
Project: ijaas   File: JavaCompleteHandler.java   Source Code and License 6 votes vote down vote up
@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();
}
 
Example 3
Project: educational-plugin   File: TaskDirectoryNode.java   Source Code and License 6 votes vote down vote up
@Nullable
@Override
public AbstractTreeNode modifyChildNode(AbstractTreeNode childNode) {
  Object value = childNode.getValue();
  if (value instanceof PsiDirectory && !((PsiDirectory)value).getName().equals(EduNames.SRC)) {
    return createChildDirectoryNode(null, (PsiDirectory)value);
  }
  if (value instanceof PsiElement) {
    PsiFile psiFile = ((PsiElement) value).getContainingFile();
    if (psiFile == null) return null;
    VirtualFile virtualFile = psiFile.getVirtualFile();
    if (virtualFile == null) {
      return null;
    }
    return StudyUtils.getTaskFile(myProject, virtualFile) != null ? childNode : null;
  }
  return null;
}
 
Example 4
Project: intellij-crystal   File: CrystalUtil.java   Source Code and License 6 votes vote down vote up
public static List<CrystalProperty> findProperties(Project project) {
    List<CrystalProperty> result = new ArrayList<CrystalProperty>();
    Collection<VirtualFile> virtualFiles =
            FileBasedIndex.getInstance().getContainingFiles(FileTypeIndex.NAME, CrystalFileType.INSTANCE,
                    GlobalSearchScope.allScope(project));
    for (VirtualFile virtualFile : virtualFiles) {
        CrystalFile simpleFile = (CrystalFile) PsiManager.getInstance(project).findFile(virtualFile);
        if (simpleFile != null) {
            CrystalProperty[] properties = PsiTreeUtil.getChildrenOfType(simpleFile, CrystalProperty.class);
            if (properties != null) {
                Collections.addAll(result, properties);
            }
        }
    }
    return result;
}
 
Example 5
Project: branch-window-title   File: BranchNameFrameTitleBuilder.java   Source Code and License 6 votes vote down vote up
private String determineBranchName(VirtualFile headFile) {
  if (headFile != null) {
    try {
      String headLinkAsString = new String(headFile.contentsToByteArray());
      Matcher matcher = FIRST_LINE_PATTERN.matcher(headLinkAsString);
      if (matcher.find() && matcher.groupCount() >= 2) {
        String branchName = matcher.group(2).trim();
        branchName = removePrefix("refs/", branchName);
        branchName = removePrefix("heads/", branchName);
        return branchName;
      }
    } catch (Exception e) {
      // ignore
    }
  }

  // could not determine branch name, returning null
  return null;
}
 
Example 6
Project: watchMe   File: ProjectFileIterator.java   Source Code and License 6 votes vote down vote up
@Override
public boolean processFile(final VirtualFile file) {
    final String fileName = file.getName();
    final String filePath = file.getPath();
    boolean isTarget = false;
    if(fileContent.isPython()){
        isTarget = !file.isDirectory() && !fileContent.contains(filePath);
    }else{
        isTarget = !file.isDirectory() && fileContent.contains(filePath);
    }

    if (isTarget && !this.fileContent.hasFile(fileName)) {
        fileContent.get().put(fileName, filePath);
        //System.out.println("include: " + fileName);
    }

    return true;
}
 
Example 7
Project: Specflow.Rider   File: SpecflowGenerateCodeTest.java   Source Code and License 6 votes vote down vote up
@Test
public void actionFileReadFailDoesNotBubbleExcepted() throws IOException {

    AnActionEvent action = mock(AnActionEvent.class);
    ISpecflowAnalyzer lexer = mock(ISpecflowAnalyzer.class);
    FileFactory fileFactory = mock(FileFactory.class);
    DirectoryFactory directoryFactory = mock(DirectoryFactory.class);
    VirtualFile file = mock(VirtualFile.class);

    when(action.getData(PlatformDataKeys.VIRTUAL_FILE)).thenReturn(file);
    when(file.contentsToByteArray()).thenThrow(new IOException());

    SpecflowGenerateCode generator = new SpecflowGenerateCode(lexer, fileFactory, directoryFactory);
    generator.actionPerformed(action);

    verify(lexer, never()).analyze(anyString(), anyString());
}
 
Example 8
Project: magento2-phpstorm-plugin   File: LayoutIndex.java   Source Code and License 6 votes vote down vote up
private static List<XmlTag> getComponentDeclarations(String componentValue, String componentType, ID<String, Void> id, Project project, ComponentMatcher componentMatcher) {
    List<XmlTag> results = new ArrayList<XmlTag>();
    Collection<VirtualFile> containingFiles = FileBasedIndex.getInstance()
        .getContainingFiles(
            id,
            componentValue,
            GlobalSearchScope.allScope(project)
        );
    PsiManager psiManager = PsiManager.getInstance(project);

    for (VirtualFile virtualFile: containingFiles) {
        XmlFile xmlFile = (XmlFile)psiManager.findFile(virtualFile);
        if (xmlFile == null) {
            continue;
        }

        XmlTag rootTag = xmlFile.getRootTag();
        if (rootTag == null) {
            continue;
        }
        collectComponentDeclarations(rootTag, results, componentValue, componentType, componentMatcher);
    }

    return results;
}
 
Example 9
Project: JNomad-Plugin   File: JNomadQueryVisitor.java   Source Code and License 6 votes vote down vote up
private static int getLineNumber(VirtualFile virtualFile, TextRange textRange) {
    try {
        BufferedReader br = new BufferedReader(new InputStreamReader(virtualFile.getInputStream()));
        String line;
        int pos = 0;
        int lineNumber = 0;

        while ((line = br.readLine()) != null) {
            pos += line.length() + 1; //+1 for new line
            lineNumber++;

            if (pos >= textRange.getStartOffset()) {
                return lineNumber;
            }
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
    return -1;
}
 
Example 10
Project: magento2-phpstorm-plugin   File: LayoutIndex.java   Source Code and License 6 votes vote down vote up
public static List<XmlFile> getLayoutFiles(Project project, @Nullable String fileName) {
    List<XmlFile> results = new ArrayList<XmlFile>();
    Collection<VirtualFile> xmlFiles = FilenameIndex.getAllFilesByExt(project, "xml");

    PsiManager psiManager = PsiManager.getInstance(project);
    for (VirtualFile xmlFile: xmlFiles) {
        if (isLayoutFile(xmlFile)) {
            if (fileName != null && !xmlFile.getNameWithoutExtension().equals(fileName)) {
                continue;
            }

            PsiFile file = psiManager.findFile(xmlFile);
            if (file != null) {
                results.add((XmlFile)file);
            }
        }
    }

    return results;
}
 
Example 11
Project: EmojiPrefix   File: EmojiCheckinHandler.java   Source Code and License 6 votes vote down vote up
public EmojiCheckinHandler(CheckinProjectPanel checkinProjectPanel) {
	JPanel emojiPanel = new JPanel();
	emojiPanel.setLayout(new VerticalFlowLayout());
	VirtualFile emojirc = checkinProjectPanel.getProject().getBaseDir().findChild(".emojirc");
	if (emojirc == null) return;
	PsiFile psiFile = PsiManager.getInstance(checkinProjectPanel.getProject()).findFile(emojirc);
	if (psiFile == null) return;
	for (PsiElement psiElement : psiFile.getChildren()) {
		if (!(psiElement instanceof EmojiResourceProperty)) continue;
		emojiPanel.add(createEmojiButton(psiElement.getFirstChild().getText(), psiElement.getLastChild().getText(), false, buttonGroup));
	}
	emojiPanel.add(createEmojiButton(null, NO_EMOJI, true, buttonGroup));
	Splitter splitter = (Splitter) checkinProjectPanel.getComponent();
	CommitMessage commitMessage = (CommitMessage) splitter.getSecondComponent();
	JComponent component = (JComponent) commitMessage.getComponent(1);
	JBScrollPane scrollPane = new JBScrollPane(emojiPanel);
	scrollPane.setBorder(null);
	Splitter commitSplitter = new Splitter();
	commitSplitter.setFirstComponent(scrollPane);
	commitSplitter.setSecondComponent((JComponent) commitMessage.getComponent(0));
	commitMessage.add(commitSplitter, 0);
	for (EmojiPanelFactory factory : factories) {
		factory.createPanel(commitMessage);
	}
	this.checkinProjectPanel = checkinProjectPanel;
}
 
Example 12
Project: educational-plugin   File: PyEduPluginConfigurator.java   Source Code and License 6 votes vote down vote up
@Override
public void createTestsForNewSubtask(@NotNull Project project, @NotNull TaskWithSubtasks task) {
  VirtualFile taskDir = task.getTaskDir(project);
  if (taskDir == null) {
    return;
  }
  int nextSubtaskIndex = task.getLastSubtaskIndex() + 1;
  String nextSubtaskTestsFileName = getSubtaskTestsFileName(nextSubtaskIndex);
  ApplicationManager.getApplication().runWriteAction(() -> {
    try {
      PsiDirectory taskPsiDir = PsiManager.getInstance(project).findDirectory(taskDir);
      FileTemplate testsTemplate = FileTemplateManager.getInstance(project).getInternalTemplate(TESTS_PY);
      if (taskPsiDir == null || testsTemplate == null) {
        return;
      }
      FileTemplateUtil.createFromTemplate(testsTemplate, nextSubtaskTestsFileName, null, taskPsiDir);
    }
    catch (Exception e) {
      LOG.error(e);
    }
  });
}
 
Example 13
Project: educational-plugin   File: CCDirectoryNode.java   Source Code and License 6 votes vote down vote up
@Nullable
@Override
public AbstractTreeNode modifyChildNode(AbstractTreeNode childNode) {
  final AbstractTreeNode node = super.modifyChildNode(childNode);
  if (node != null) return node;
  Object value = childNode.getValue();
  if (value instanceof PsiElement) {
    PsiFile psiFile = ((PsiElement) value).getContainingFile();
    VirtualFile virtualFile = psiFile.getVirtualFile();

    Course course = StudyTaskManager.getInstance(myProject).getCourse();
    if (course == null) {
      return null;
    }
    EduPluginConfigurator configurator = EduPluginConfigurator.INSTANCE.forLanguage(course.getLanguageById());
    if (configurator == null) {
      return new CCStudentInvisibleFileNode(myProject, psiFile, myViewSettings);
    }
    if (!CCUtils.isTestsFile(myProject, virtualFile)) {
      return new CCStudentInvisibleFileNode(myProject, psiFile, myViewSettings);
    }
  }
  return null;
}
 
Example 14
Project: AppleScript-IDEA   File: AppleScriptProjectDictionaryService.java   Source Code and License 6 votes vote down vote up
@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;
}
 
Example 15
Project: educational-plugin   File: CCCreateCourseArchive.java   Source Code and License 6 votes vote down vote up
private static void packCourse(@NotNull final VirtualFile baseDir, String locationDir, String zipName, boolean showMessage) {
  try {
    final File zipFile = new File(locationDir, zipName + ".zip");
    ZipOutputStream zos = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(zipFile)));
    VirtualFile[] courseFiles = baseDir.getChildren();
    for (VirtualFile file : courseFiles) {
      ZipUtil.addFileOrDirRecursively(zos, null, new File(file.getPath()), file.getName(), null, null);
    }
    zos.close();
    if (showMessage) {
      ApplicationManager.getApplication().invokeLater(
        () -> Messages.showInfoMessage("Course archive was saved to " + zipFile.getPath(),
                                       "Course Archive Was Created Successfully"));

    }
  }
  catch (IOException e1) {
    LOG.error(e1);
  }
}
 
Example 16
Project: educational-plugin   File: StudyGenerator.java   Source Code and License 6 votes vote down vote up
public static void createChildFile(@NotNull VirtualFile taskDir, @NotNull String name, @NotNull String text) throws IOException {
  String newDirectories = null;
  String fileName = name;
  VirtualFile dir = taskDir;
  if (name.contains("/")) {
    int pos = name.lastIndexOf("/");
    fileName = name.substring(pos + 1);
    newDirectories = name.substring(0, pos);
  }
  if (newDirectories != null) {
    dir = VfsUtil.createDirectoryIfMissing(taskDir, newDirectories);
  }
  if (dir != null) {
    VirtualFile virtualTaskFile = dir.findChild(fileName);
    if (virtualTaskFile == null) {
      virtualTaskFile = dir.createChildData(taskDir, fileName);
    }
    if (EduUtils.isImage(name)) {
      virtualTaskFile.setBinaryContent(Base64.decodeBase64(text));
    }
    else {
      VfsUtil.saveText(virtualTaskFile, text);
    }
  }
}
 
Example 17
Project: AndroidSourceViewer   File: DiffSourceAction.java   Source Code and License 6 votes vote down vote up
/**
 * 调用 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());
            }
        }
    });
}
 
Example 18
Project: educational-plugin   File: Task.java   Source Code and License 6 votes vote down vote up
@Nullable
public VirtualFile getTaskDir(@NotNull final Project project) {
  String lessonDirName = EduNames.LESSON + String.valueOf(myLesson.getIndex());
  String taskDirName = EduNames.TASK + String.valueOf(myIndex);
  VirtualFile courseDir = project.getBaseDir();
  if (courseDir != null) {
    VirtualFile lessonDir = courseDir.findChild(lessonDirName);
    if (lessonDir != null) {
      VirtualFile taskDir = lessonDir.findChild(taskDirName);
      if (taskDir == null) {
        return null;
      }
      VirtualFile srcDir = taskDir.findChild(EduNames.SRC);
      return srcDir != null ? srcDir : taskDir;
    }
  }
  return null;
}
 
Example 19
Project: GravSupport   File: SystemSettingsToolWindowFactory.java   Source Code and License 6 votes vote down vote up
private SmartPsiElementPointer<YAMLFile> getSystemFile(@NotNull Project project) {
    String prefix = "";
    try {
        prefix = GravProjectSettings.getInstance(project).withSrcDirectory ? "src/" + "" : "";
    } catch (NullPointerException ignored) {
    }

    String path = prefix + SYSTEM_SYSTEM_CONFIG_FILE;
    VirtualFile systemFile = project.getBaseDir().findFileByRelativePath(path);
    if (systemFile != null) {
        PsiFile psiFile = PsiManager.getInstance(project).findFile(systemFile);
        if (psiFile != null && psiFile instanceof YAMLFile) {
            systemYamlFile = SmartPointerManagerImpl.getInstance(project).createSmartPsiElementPointer((YAMLFile) psiFile);
            return systemYamlFile;
        }
    }
    return null;
}
 
Example 20
Project: manifold-ij   File: FileModificationManager.java   Source Code and License 6 votes vote down vote up
private void _before( final List<? extends VFileEvent> events )
{
  if( _project.isDisposed() )
  {
    return;
  }

  for( VFileEvent event : events )
  {
    final VirtualFile file = event.getFile();
    if( file != null )
    {
      if( isMoveOrRename( event ) )
      {
        processRenameBefore( event );
      }
    }
  }
}
 
Example 21
Project: hybris-integration-intellij-idea-plugin   File: DefaultLibRootsConfigurator.java   Source Code and License 6 votes vote down vote up
@Nullable
private VirtualFile getSourceCodeRoot(final @NotNull HybrisModuleDescriptor moduleDescriptor) {
    final VirtualFile sourceCodeRoot;
    final File sourceCodeFile = moduleDescriptor.getRootProjectDescriptor().getSourceCodeFile();

    if (null != sourceCodeFile) {
        final VirtualFile sourceVFile = VfsUtil.findFileByIoFile(sourceCodeFile, true);
        if (null == sourceVFile) {
            sourceCodeRoot = null;
        } else if (sourceVFile.isDirectory()) {
            sourceCodeRoot = sourceVFile;
        } else {
            sourceCodeRoot = JarFileSystem.getInstance().getJarRootForLocalFile(sourceVFile);
        }
    } else {
        sourceCodeRoot = null;
    }

    return sourceCodeRoot;
}
 
Example 22
Project: JNomad-Plugin   File: JNomadInspection.java   Source Code and License 6 votes vote down vote up
@NotNull
@Override
public PsiElementVisitor buildVisitor(@NotNull final ProblemsHolder holder, boolean isOnTheFly) {
    if (JNomadInspection.jnomad == null) {
        setupJNomad();
    }

    List<EnvFileFullReport> fileFullReports;
    VirtualFile virtualFile = holder.getFile().getVirtualFile();
    if (virtualFile.getPath().endsWith("java") && virtualFile instanceof VirtualFileImpl) {
        CharSequence contents = holder.getFile().getViewProvider().getContents();
        fileFullReports = getFileFullReports(contents);
        return new JNomadQueryVisitor(holder, holder.getFile().getVirtualFile(), fileFullReports.toArray(new EnvFileFullReport[0]));
    }
    return new JNomadQueryVisitor(holder, holder.getFile().getVirtualFile(), null);
}
 
Example 23
Project: GravSupport   File: LanguageFileStrategy.java   Source Code and License 6 votes vote down vote up
@Override
public TranslationTableModel createTableModel() {
    detactLanguages();
    Collection<String> availableKeys = new LinkedHashSet<>();//preserve order, no dups
    ConcurrentHashMap<String, Collection<YAMLKeyValue>> dataMap = new ConcurrentHashMap<>();
    VirtualFile virtualFile = fileMap.elements().nextElement();
    YAMLFileImpl yamlFile = (YAMLFileImpl) PsiManager.getInstance(project).findFile(virtualFile);
    if (yamlFile != null) {
        Collection<YAMLKeyValue> topLevelKeys = YAMLUtil.getTopLevelKeys(yamlFile);
        for (String eachLanguage : languages) {
            dataMap.put(eachLanguage, new HashSet<>());
            Collection<YAMLKeyValue> topLevelValuesLang = findChildValues(topLevelKeys, eachLanguage);
            for (YAMLKeyValue keyValue : topLevelValuesLang) {
                if (keyValue.getValue() instanceof YAMLCompoundValue) {
                    List<String> keysBuffer = new ArrayList<>();
                    getCompoundKeys0(keyValue, keyValue.getKeyText(), keysBuffer, dataMap, eachLanguage);
                    availableKeys.addAll(keysBuffer);
                } else {
                    availableKeys.add(keyValue.getKeyText());
                    dataMap.get(eachLanguage).add(keyValue);
                }
            }
        }
    }
    return new TranslationTableModel(availableKeys, dataMap).setPrefixKey(true);
}
 
Example 24
Project: custom-title-plugin   File: CustomFrameTitleBuilder.java   Source Code and License 6 votes vote down vote up
@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);
            }
        }
    }
}
 
Example 25
Project: android-studio-plugin   File: FileChangeListener.java   Source Code and License 6 votes vote down vote up
public void after(List<? extends VFileEvent> events) {
    String sources = Utils.getPropertyValue("sources", true);
    List<String> sourcesList = Utils.getSourcesList(sources);
    for (VFileEvent e : events) {
        VirtualFile virtualFile = e.getFile();
        if (virtualFile != null && sourcesList.contains(virtualFile.getName()) && SOURCE_FOLDER_DEFAULT.equals(virtualFile.getParent().getName())) {
            Project[] projects = ProjectManager.getInstance().getOpenProjects();
            Project project = null;
            if (projects.length == 1) {
                project = projects[0];
            }
            System.out.println("Changed file " + virtualFile.getCanonicalPath());
            Crowdin crowdin = new Crowdin();
            String branch = Utils.getCurrentBranch(project);
            crowdin.uploadFile(virtualFile, branch);
        }
    }
}
 
Example 26
Project: SmartQQ4IntelliJ   File: VFSUtils.java   Source Code and License 6 votes vote down vote up
private static void findInRoots(final Set<VirtualFile> found, VirtualFile[] roots, String relativePath) {
    if (relativePath == null) return;

    for (VirtualFile root : roots) {
        String probeName;
        if (isArchive(root)) {
            probeName = root.getPath() + '!' + relativePath;
        } else {
            probeName = root.getPath() + relativePath;
        }
        VirtualFile virtualFile = root.getFileSystem().findFileByPath(probeName);
        if (virtualFile != null) {
            found.add(virtualFile);
        }
    }
}
 
Example 27
Project: yii2support   File: ViewLookupElement.java   Source Code and License 5 votes vote down vote up
ViewLookupElement(PsiFile psiFile) {
    myFile = psiFile;
    VirtualFile file = psiFile.getVirtualFile();

    if (file.getNameWithoutExtension().contains(".")) {
        myName = file.getName();
        myTail = null;
    } else {
        myName = file.getNameWithoutExtension();
        myTail = "." + file.getExtension();
    }
}
 
Example 28
Project: GravSupport   File: LanguageFolderStrategy.java   Source Code and License 5 votes vote down vote up
@Override
public void initTab(LanguageFileEditorGUI gui) {
    for (VirtualFile file : fileMap.values()) {
        PsiFile psiFile = PsiManager.getInstance(project).findFile(file);
        if (psiFile != null) {
            Document document = PsiDocumentManager.getInstance(project).getDocument(psiFile);
            if (document != null) {
                Editor editorTextField = gui.createEditor(document, project, psiFile.getFileType());
                editorMap.put(psiFile.getVirtualFile().getNameWithoutExtension(), editorTextField);
                gui.addTab(psiFile.getVirtualFile().getNameWithoutExtension(), editorTextField.getComponent());
            }
        }
    }
}
 
Example 29
Project: educational-plugin   File: PyStudyDirectoryProjectGenerator.java   Source Code and License 5 votes vote down vote up
private static void createTestHelper(@NotNull Project project, @NotNull VirtualFile baseDir) {
  final String testHelper = EduNames.TEST_HELPER;
  if (baseDir.findChild(testHelper) != null) return;
  final FileTemplate template = FileTemplateManager.getInstance(project).getInternalTemplate("test_helper");
  final PsiDirectory projectDir = PsiManager.getInstance(project).findDirectory(baseDir);
  if (projectDir == null) return;
  try {
    FileTemplateUtil.createFromTemplate(template, testHelper, null, projectDir);
  }
  catch (Exception exception) {
    LOG.error("Can't copy test_helper.py " + exception.getMessage());
  }
}
 
Example 30
Project: educational-plugin   File: EduIntellijUtils.java   Source Code and License 5 votes vote down vote up
private static void createFromText(@NotNull Project project, @Nullable String taskFileName, @NotNull Task task) {
  TaskFile taskFile = task.getTaskFile(taskFileName);
  VirtualFile taskDir = task.getTaskDir(project);
  if (taskFile != null && taskDir != null) {
    taskFile.text = StringUtil.notNullize(taskFile.text);
    nameTaskFileAfterContainingClass(task, taskFile, project);

    try {
      StudyGenerator.createTaskFile(taskDir, taskFile);
    }
    catch (IOException e) {
      LOG.warn(e.getMessage());
    }
  }
}
 
Example 31
Project: intellij-plugin   File: ConfigurationNode.java   Source Code and License 5 votes vote down vote up
@Override
public MultiMap<PsiFile, ConfigFileNode> computeChildren(PsiFile psiFile) {
    Project project = getProject();
    MultiMap<PsiFile, ConfigFileNode> children = new MultiMap<>();
    if (project != null) {
        PsiManager psiManager = PsiManager.getInstance(project);
        for (VirtualFile virtualFile : CoffigUtil.findCoffigFiles(getProject())) {
            PsiFile file = psiManager.findFile(virtualFile);
            children.putValue(file, new ConfigFileNode(this, psiManager.findFile(virtualFile)));
        }
    }
    return children;
}
 
Example 32
Project: intellij-postfix-templates   File: CustomPostfixTemplateProvider.java   Source Code and License 5 votes vote down vote up
/**
 * Loads the postfix templates from the given virtual file and returns them.
 *
 * @param vFile virtual templates file
 * @return set of postfix templates
 */
@SuppressWarnings("WeakerAccess")
public Set<PostfixTemplate> loadTemplatesFrom(@NotNull VirtualFile vFile) {
	Set<PostfixTemplate> templates = new OrderedSet<>();

	ApplicationManager.getApplication().runReadAction(() -> {
		Project project = ProjectManager.getInstance().getOpenProjects()[0];

		CptFile cptFile = (CptFile) PsiManager.getInstance(project).findFile(vFile);
		if (cptFile != null) {
			CptTemplate[] cptTemplates = PsiTreeUtil.getChildrenOfType(cptFile, CptTemplate.class);
			if (cptTemplates != null) {
				for (CptTemplate cptTemplate : cptTemplates) {
					for (CptMapping mapping : cptTemplate.getMappings().getMappingList()) {
						StringBuilder sb = new StringBuilder();
						for (PsiElement element : mapping.getReplacement().getChildren()) {
							sb.append(element.getText());
						}

						templates.add(createTemplate(mapping.getMatchingClass(), mapping.getConditionClass(), cptTemplate.getTemplateName(), cptTemplate.getTemplateDescription(), sb.toString()));
					}
				}
			}
		}
	});

	return combineTemplatesWithSameName(templates);
}
 
Example 33
Project: Android-ORM-ASPlugin   File: AddAnnotationAction.java   Source Code and License 5 votes vote down vote up
@Override
public void actionPerformed(AnActionEvent e) {
    Project project = e.getData(PlatformDataKeys.PROJECT);
    List<VirtualFile> javaFiles = Utils.getSelectJavaFiles(e, true);

    if (!javaFiles.isEmpty()) {
        AddAnnotationDialog dialog = new AddAnnotationDialog(project, javaFiles);
        dialog.pack();
        dialog.setLocationRelativeTo(null);
        dialog.setVisible(true);
        dialog.dispose();
    }
}
 
Example 34
Project: educational-plugin   File: CCUtils.java   Source Code and License 5 votes vote down vote up
public static VirtualFile getGeneratedFilesFolder(@NotNull Project project, @NotNull Module module) {
  VirtualFile baseDir = project.getBaseDir();
  VirtualFile folder = baseDir.findChild(GENERATED_FILES_FOLDER);
  if (folder != null) {
    return folder;
  }
  final Ref<VirtualFile> generatedRoot = new Ref<>();
  ApplicationManager.getApplication().runWriteAction(new Runnable() {
    @Override
    public void run() {
      try {
        generatedRoot.set(baseDir.createChildDirectory(this, GENERATED_FILES_FOLDER));
        VirtualFile contentRootForFile =
          ProjectRootManager.getInstance(module.getProject()).getFileIndex().getContentRootForFile(generatedRoot.get());
        if (contentRootForFile == null) {
          return;
        }
        ModuleRootModificationUtil.updateExcludedFolders(module, contentRootForFile, Collections.emptyList(),
                                                         Collections.singletonList(generatedRoot.get().getUrl()));
      }
      catch (IOException e) {
        LOG.info("Failed to create folder for generated files", e);
      }
    }
  });
  return generatedRoot.get();
}
 
Example 35
Project: GravSupport   File: LanguageFileViewProvider.java   Source Code and License 5 votes vote down vote up
@NotNull
@Override
public FileViewProvider createFileViewProvider(@NotNull VirtualFile file, Language language, @NotNull PsiManager manager, boolean eventSystemEnabled) {
    return new SingleRootFileViewProvider(manager, file, eventSystemEnabled) {
        @NotNull
        @Override
        public Language getBaseLanguage() {
            return YAMLLanguage.INSTANCE;
        }
    };
}
 
Example 36
Project: AppleScript-IDEA   File: LoadDictionaryAction.java   Source Code and License 5 votes vote down vote up
public void actionPerformed(final AnActionEvent e) {
  DataContext dataContext = e.getDataContext();
  final IdeView view = LangDataKeys.IDE_VIEW.getData(dataContext);
  if (view == null) return;
  final PsiDirectory[] directories = view.getDirectories();

  PsiDirectory currentDirectory = directories.length > 0 ? directories[0] : null;
  final Project project = e.getData(CommonDataKeys.PROJECT);
  if (project == null) return;

  VirtualFile directoryFile = currentDirectory != null ? currentDirectory.getVirtualFile() : project.getBaseDir();
  openLoadDirectoryDialog(project, directoryFile, null);
}
 
Example 37
Project: GravSupport   File: LanguageFileStrategy.java   Source Code and License 5 votes vote down vote up
@Override
public void initTab(LanguageFileEditorGUI gui) {
    VirtualFile file = fileMap.elements().nextElement();
    PsiFile psiFile = PsiManager.getInstance(project).findFile(file);
    if (psiFile != null) {
        Document document = PsiDocumentManager.getInstance(project).getDocument(psiFile);
        if (document != null) {
            for (String eachLang : languages) {
                Editor editorTextField = gui.createEditor(document, project, psiFile.getFileType());
                editorMap.put(eachLang, editorTextField);
                gui.addTab(eachLang, editorTextField.getComponent());
            }
        }
    }
}
 
Example 38
Project: educational-plugin   File: StudyGenerator.java   Source Code and License 5 votes vote down vote up
public static void createLesson(@NotNull final Lesson lesson, @NotNull final VirtualFile courseDir) throws IOException {
  if (EduNames.PYCHARM_ADDITIONAL.equals(lesson.getName())) {
    createAdditionalFiles(lesson, courseDir);
  }
  else {
    String lessonDirName = EduNames.LESSON + Integer.toString(lesson.getIndex());
    VirtualFile lessonDir = VfsUtil.createDirectoryIfMissing(courseDir, lessonDirName);
    final List<Task> taskList = lesson.getTaskList();
    for (int i = 1; i <= taskList.size(); i++) {
      Task task = taskList.get(i - 1);
      task.setIndex(i);
      createTask(task, lessonDir);
    }
  }
}
 
Example 39
Project: intellij-bpmn-editor   File: BPMNFileTypeFactory.java   Source Code and License 5 votes vote down vote up
public static boolean isBPMN(@NotNull VirtualFile virtualFile) {
    if (BPMN_EXTENSION.equals(virtualFile.getExtension())) {
        final FileType fileType = virtualFile.getFileType();
        if (fileType == getFileType() && !fileType.isBinary()) {
            return virtualFile.getName().endsWith(DOT_BPMN_EXTENSION);
        }
    }
    return false;
}
 
Example 40
Project: educational-plugin   File: StudyUtils.java   Source Code and License 5 votes vote down vote up
@Nullable
public static Task getTaskForFile(@NotNull Project project, @NotNull VirtualFile taskFile) {
  VirtualFile taskDir = getTaskDir(taskFile);
  if (taskDir == null) {
    return null;
  }
  return getTask(project, taskDir);
}