Java 类com.intellij.psi.impl.file.PsiDirectoryFactory 实例源码

项目:idea-php-typo3-plugin    文件:ExtensionFileGenerationUtil.java   
/**
 * @param templateFile        Name of the generated file
 * @param destinationPath     Relative path to the target file system entry
 * @param extensionDefinition Extension definition containing all relevant metadata
 * @param context             Template Context variables
 * @param project             Project in context
 */
public static PsiElement fromTemplate(@NotNull String templateFile, @NotNull String destinationPath, @NotNull String destinationFileName, @NotNull TYPO3ExtensionDefinition extensionDefinition, @NotNull Map<String, String> context, Project project) {
    String template = readTemplateToString(templateFile, context);

    VirtualFile targetDirectory = getOrCreateDestinationPath(extensionDefinition.getRootDirectory(), destinationPath);

    LanguageFileType fileType = FileTypes.PLAIN_TEXT;
    if (templateFile.endsWith(".php")) {
        fileType = PhpFileType.INSTANCE;
    }

    PsiFile fileFromText = PsiFileFactory.getInstance(project).createFileFromText(destinationFileName, fileType, template);
    CodeStyleManager.getInstance(project).reformat(fileFromText);
    return PsiDirectoryFactory
            .getInstance(project)
            .createDirectory(targetDirectory)
            .add(fileFromText);
}
项目:idea-php-typo3-plugin    文件:ExtensionFileGenerationUtil.java   
/**
 * @param templateFile           Name of the generated file
 * @param destinationPath        Relative path to the target file system entry
 * @param extensionRootDirectory Extension definition containing all relevant metadata
 * @param context                Template Context variables
 * @param project                Project in context
 */
public static PsiElement fromTemplate(@NotNull String templateFile, @NotNull String destinationPath, @NotNull String destinationFileName, @NotNull PsiDirectory extensionRootDirectory, @NotNull Map<String, String> context, Project project) {
    String template = readTemplateToString(templateFile, context);

    VirtualFile targetDirectory = getOrCreateDestinationPath(extensionRootDirectory.getVirtualFile(), destinationPath);

    LanguageFileType fileType = FileTypes.PLAIN_TEXT;
    if (templateFile.endsWith(".php")) {
        fileType = PhpFileType.INSTANCE;
    }

    PsiFile fileFromText = PsiFileFactory.getInstance(project).createFileFromText(destinationFileName, fileType, template);
    CodeStyleManager.getInstance(project).reformat(fileFromText);
    return PsiDirectoryFactory
            .getInstance(project)
            .createDirectory(targetDirectory)
            .add(fileFromText);
}
项目:CodeGen    文件:PsiUtil.java   
public static PsiDirectory createDirectory(Project project, String title, String description) {
    final FileChooserDescriptor descriptor = FileChooserDescriptorFactory.createSingleFolderDescriptor();
    descriptor.setTitle(title);
    descriptor.setShowFileSystemRoots(false);
    descriptor.setDescription(description);
    descriptor.setHideIgnored(true);
    descriptor.setRoots(project.getBaseDir());
    descriptor.setForcedToUseIdeaFileChooser(true);
    VirtualFile file = FileChooser.chooseFile(descriptor, project, project.getBaseDir());
    if(Objects.isNull(file)){
        Messages.showInfoMessage("Cancel " + title, "Error");
        return null;
    }

    PsiDirectory psiDirectory = PsiDirectoryFactory.getInstance(project).createDirectory(file);
    if(PsiDirectoryFactory.getInstance(project).isPackage(psiDirectory)){
        return psiDirectory;
    }else {
        Messages.showInfoMessage("请选择正确的 package 路径。", "Error");
        return createDirectory(project, title, description);
    }
}
项目:intellij-ce-playground    文件:FileManagerImpl.java   
@Nullable
private PsiDirectory findDirectoryImpl(@NotNull VirtualFile vFile) {
  PsiDirectory psiDir = myVFileToPsiDirMap.get(vFile);
  if (psiDir != null) return psiDir;

  if (Registry.is("ide.hide.excluded.files")) {
    if (myFileIndex.isExcludedFile(vFile)) return null;
  }
  else {
    if (myFileIndex.isUnderIgnored(vFile)) return null;
  }

  VirtualFile parent = vFile.getParent();
  if (parent != null) { //?
    findDirectoryImpl(parent);// need to cache parent directory - used for firing events
  }

  psiDir = PsiDirectoryFactory.getInstance(myManager.getProject()).createDirectory(vFile);
  return ConcurrencyUtil.cacheOrGet(myVFileToPsiDirMap, vFile, psiDir);
}
项目:intellij-ce-playground    文件:CreateDirectoryOrPackageAction.java   
@Override
public void actionPerformed(AnActionEvent e) {
  IdeView view = e.getData(LangDataKeys.IDE_VIEW);
  Project project = e.getData(CommonDataKeys.PROJECT);

  if (view == null || project == null) {
    return;
  }
  PsiDirectory directory = DirectoryChooserUtil.getOrChooseDirectory(view);

  if (directory == null) return;
  boolean isDirectory = !PsiDirectoryFactory.getInstance(project).isPackage(directory);

  CreateDirectoryOrPackageHandler validator = new CreateDirectoryOrPackageHandler(project, directory, isDirectory,
                                                                                 isDirectory ? "\\/" : ".");
  Messages.showInputDialog(project, isDirectory
                                    ? IdeBundle.message("prompt.enter.new.directory.name")
                                    : IdeBundle.message("prompt.enter.new.package.name"),
                                    isDirectory ? IdeBundle.message("title.new.directory") : IdeBundle.message("title.new.package"),
                                    Messages.getQuestionIcon(), "", validator);

  final PsiElement result = validator.getCreatedElement();
  if (result != null) {
    view.selectElement(result);
  }
}
项目:svgtoandroid    文件:ModulesUtil.java   
public Set<String> getModules() {
    Set<String> modules = new HashSet<String>();
    PsiDirectory baseDir = PsiDirectoryFactory.getInstance(project).createDirectory(project.getBaseDir());
    if (isAndroidProject(baseDir)) {
        Logger.debug(project.getName() + " is an Android project");
        PsiDirectory[] dirs = baseDir.getSubdirectories();
        for (PsiDirectory dir : dirs) {
            if (!dir.getName().equals("build") && !dir.getName().equals("gradle")) {
                if (isModule(dir)) {
                    Logger.debug(dir.getName() + " is a Module");
                    modules.add(dir.getName());
                }
            }
        }
    }
    Logger.debug(modules.toString());
    return modules;
}
项目:svgtoandroid    文件:ModulesUtil.java   
public PsiDirectory getResDir(String moduleName) {
    PsiDirectory baseDir = PsiDirectoryFactory.getInstance(project).createDirectory(project.getBaseDir());
    PsiDirectory moduleDir = baseDir.findSubdirectory(moduleName);
    if (moduleDir != null && moduleDir.isDirectory()) {
        PsiDirectory srcDir = moduleDir.findSubdirectory("src");
        if (srcDir != null && srcDir.isDirectory()) {
            PsiDirectory mainDir = srcDir.findSubdirectory("main");
            if (mainDir != null && mainDir.isDirectory()) {
                PsiDirectory resDir = mainDir.findSubdirectory("res");
                if (resDir != null && resDir.isDirectory()) {
                    return resDir;
                }
            }
        }
    }
    return null;
}
项目:tools-idea    文件:PsiPackageRenameValidator.java   
@Nullable
@Override
public String getErrorMessage(String newName, Project project) {
  if (FileTypeManager.getInstance().isFileIgnored(newName)) {
    return "Trying to create a package with ignored name, result will not be visible";
  }
  if (newName.length() > 0) {
    if (!PsiDirectoryFactory.getInstance(project).isValidPackageName(newName)) {
      return "Not a valid package name";
    }
    if (!JavaPsiFacade.getInstance(project).getNameHelper().isIdentifier(newName)) {
      return "Not a valid identifier name";
    }
  }
  return null;
}
项目:tools-idea    文件:CreateDirectoryOrPackageAction.java   
@Override
public void actionPerformed(AnActionEvent e) {
  IdeView view = e.getData(LangDataKeys.IDE_VIEW);
  Project project = e.getData(PlatformDataKeys.PROJECT);

  if (view == null || project == null) {
    return;
  }
  PsiDirectory directory = DirectoryChooserUtil.getOrChooseDirectory(view);

  if (directory == null) return;
  boolean isDirectory = !PsiDirectoryFactory.getInstance(project).isPackage(directory);

  CreateDirectoryOrPackageHandler validator = new CreateDirectoryOrPackageHandler(project, directory, isDirectory,
                                                                                 isDirectory ? "\\/" : ".");
  Messages.showInputDialog(project, isDirectory
                                    ? IdeBundle.message("prompt.enter.new.directory.name")
                                    : IdeBundle.message("prompt.enter.new.package.name"),
                                    isDirectory ? IdeBundle.message("title.new.directory") : IdeBundle.message("title.new.package"),
                                    Messages.getQuestionIcon(), "", validator);

  final PsiElement result = validator.getCreatedElement();
  if (result != null) {
    view.selectElement(result);
  }
}
项目:Specflow.Rider    文件:SpecflowGenerateCodeTest.java   
@Test
public void actionAnalyzesFile() throws IOException {

    AnActionEvent action = mock(AnActionEvent.class);
    ISpecflowAnalyzer lexer = mock(ISpecflowAnalyzer.class);
    PsiFileFactory psiFileFactory = mock(PsiFileFactory.class);
    PsiDirectoryFactory psiDirectoryFactory = mock(PsiDirectoryFactory.class);
    FileFactory fileFactory = mock(FileFactory.class);
    DirectoryFactory directoryFactory = mock(DirectoryFactory.class);
    VirtualFile file = mock(VirtualFile.class);
    VirtualFile directoryFile = mock(VirtualFile.class);
    PsiDirectory directory = mock(PsiDirectory.class);
    Project project = mock(Project.class);
    PsiFile contentFile = mock(PsiFile.class);
    PsiFile stepsFile = mock(PsiFile.class);
    String fileContent = Faker.getRandomString();
    String projectName = Faker.getRandomString();

    when(action.getData(PlatformDataKeys.VIRTUAL_FILE)).thenReturn(file);
    when(file.contentsToByteArray()).thenReturn(fileContent.getBytes());
    when(file.getParent()).thenReturn(directoryFile);
    when(action.getProject()).thenReturn(project);
    when(project.getName()).thenReturn(projectName);
    when(fileFactory.getInstance(project)).thenReturn(psiFileFactory);
    when(directoryFactory.getInstance(project)).thenReturn(psiDirectoryFactory);
    when(psiDirectoryFactory.createDirectory(file.getParent())).thenReturn(directory);
    SpecflowFileContents content = new SpecflowFileContents(Faker.getRandomString(), Faker.getRandomString());
    when(lexer.analyze(fileContent,projectName)).thenReturn(content);
    when(psiFileFactory.createFileFromText(file.getName()+"Feature.cs",content.feature)).thenReturn(contentFile);
    when(psiFileFactory.createFileFromText(file.getName()+"Steps.cs",content.steps)).thenReturn(stepsFile);

    SpecflowGenerateCode generator = new SpecflowGenerateCode(lexer, fileFactory, directoryFactory);
    generator.actionPerformed(action);
    verify(directory).add(contentFile);
    verify(directory).add(stepsFile);
    verify(lexer).analyze(fileContent, projectName);
}
项目:Android-ORM-ASPlugin    文件:Utils.java   
public static String getJavaPkgName(PsiJavaDirectoryImpl dir) {
    PsiDirectoryFactory factory = PsiJavaDirectoryFactory.getInstance(dir.getProject());
    if (factory.isPackage(dir)) {
        String n = factory.getQualifiedName(dir, true);
        return factory.getQualifiedName(dir, false);
    }
    return null;
}
项目:Android-ORM-ASPlugin    文件:Utils.java   
public static String getPkgName(Project project, VirtualFile vf) {
    PsiFile psiFile = PsiManager.getInstance(project).findFile(vf);
    if (psiFile instanceof PsiJavaFile) {
        PsiJavaFile javaFile = (PsiJavaFile) psiFile;
        return javaFile.getPackageName();
    } else if (psiFile instanceof PsiJavaDirectoryImpl) {
        PsiJavaDirectoryImpl dir = (PsiJavaDirectoryImpl) psiFile;
        PsiDirectoryFactory factory = PsiJavaDirectoryFactory.getInstance(project);
        if (factory.isPackage(dir)) {
            String n = factory.getQualifiedName(dir, true);
            return factory.getQualifiedName(dir, false);
        }
    }
    return null;
}
项目:Android-ORM-ASPlugin    文件:Utils.java   
public static PsiDirectory getModuleBase(Project project, VirtualFile vf) {
    Module module = ModuleUtilCore.findModuleForFile(vf, project);
    ModuleFileIndex fileIndex = ModuleRootManager.getInstance(module).getFileIndex();
    PsiDirectory baseDir = PsiDirectoryFactory.getInstance(project).createDirectory(project.getBaseDir());
    PsiDirectory moduleDir = baseDir.findSubdirectory(module.getName());
    if (moduleDir == null) {
        return baseDir;
    }
    return moduleDir;
}
项目:CodeGen    文件:DefaultProviderImpl.java   
@Override
public void create(CodeTemplate template, CodeContext context, Map<String, Object> extraMap){

    VelocityContext velocityContext = new VelocityContext(BuilderUtil.transBean2Map(context));
    velocityContext.put("serialVersionUID", BuilderUtil.computeDefaultSUID(context.getModel(), context.getFields()));
    // $!dateFormatUtils.format($!now,'yyyy-MM-dd')
    velocityContext.put("dateFormatUtils", new org.apache.commons.lang.time.DateFormatUtils());
    if (extraMap != null && extraMap.size() > 0) {
        for (Map.Entry<String, Object> entry: extraMap.entrySet()) {
            velocityContext.put(entry.getKey(), entry.getValue());
        }
    }

    String fileName = VelocityUtil.evaluate(velocityContext, template.getFilename());
    String temp = VelocityUtil.evaluate(velocityContext, template.getTemplate());

    WriteCommandAction.runWriteCommandAction(this.project, () -> {
        try {
            VirtualFile vFile = VfsUtil.createDirectoryIfMissing(outputPath);
            PsiDirectory psiDirectory = PsiDirectoryFactory.getInstance(this.project).createDirectory(vFile);
            PsiDirectory directory = subDirectory(psiDirectory, template.getSubPath(), template.getResources());
            if (JavaFileType.INSTANCE == this.languageFileType) {
                PsiPackage psiPackage = JavaDirectoryService.getInstance().getPackage(directory);
                if (!StringUtils.isEmpty(psiPackage.getQualifiedName())) {
                    extraMap.put(fileName, new StringBuilder(psiPackage.getQualifiedName()).append(".").append(fileName));
                }
            }
            createFile(project, directory, new StringBuilder(fileName).append(".").append(this.languageFileType.getDefaultExtension()).toString(), temp, this.languageFileType);
        } catch (Exception e) {
            LOGGER.error(StringUtils.getStackTraceAsString(e));
        }
    });
}
项目:intellij-ce-playground    文件:PsiPackageRenameValidator.java   
@Nullable
@Override
public String getErrorMessage(String newName, Project project) {
  if (FileTypeManager.getInstance().isFileIgnored(newName)) {
    return "Trying to create a package with ignored name, result will not be visible";
  }
  if (newName.length() > 0) {
    if (!PsiDirectoryFactory.getInstance(project).isValidPackageName(newName)) {
      return "Not a valid package name";
    }
  }
  return null;
}
项目:intellij-ce-playground    文件:TestFileStructure.java   
public static PsiDirectory createDirectory(@NotNull Project project, @NotNull final VirtualFile parent, @NotNull final String name) throws IOException {
  final VirtualFile[] dir = new VirtualFile[1];
  ApplicationManager.getApplication().runWriteAction(new Runnable() {
    @Override
    public void run() {
      try {
        dir[0] = parent.createChildDirectory(null, name);
      }
      catch (IOException e) {
        e.printStackTrace();
      }
    }
  });
  return PsiDirectoryFactory.getInstance(project).createDirectory(dir[0]);
}
项目:intellij-ce-playground    文件:CoreProjectEnvironment.java   
public CoreProjectEnvironment(@NotNull Disposable parentDisposable, @NotNull CoreApplicationEnvironment applicationEnvironment) {
  myParentDisposable = parentDisposable;
  myEnvironment = applicationEnvironment;
  myProject = createProject(myEnvironment.getApplication().getPicoContainer(), myParentDisposable);

  preregisterServices();

  myFileIndexFacade = createFileIndexFacade();
  myMessageBus = MessageBusFactory.newMessageBus("CoreProjectEnvironment");

  PsiModificationTrackerImpl modificationTracker = new PsiModificationTrackerImpl(myProject);
  myProject.registerService(PsiModificationTracker.class, modificationTracker);
  myProject.registerService(FileIndexFacade.class, myFileIndexFacade);
  myProject.registerService(ResolveCache.class, new ResolveCache(myMessageBus));

  myPsiManager = new PsiManagerImpl(myProject, null, null, myFileIndexFacade, myMessageBus, modificationTracker);
  ((FileManagerImpl) myPsiManager.getFileManager()).markInitialized();
  registerProjectComponent(PsiManager.class, myPsiManager);
  myProject.registerService(SmartPointerManager.class, SmartPointerManagerImpl.class);
  registerProjectComponent(PsiDocumentManager.class, new CorePsiDocumentManager(myProject, myPsiManager,
                                                                                myMessageBus,
                                                                                new MockDocumentCommitProcessor()));

  myProject.registerService(ResolveScopeManager.class, createResolveScopeManager(myPsiManager));

  myProject.registerService(PsiFileFactory.class, new PsiFileFactoryImpl(myPsiManager));
  myProject.registerService(CachedValuesManager.class, new CachedValuesManagerImpl(myProject, new PsiCachedValuesFactory(myPsiManager)));
  myProject.registerService(PsiDirectoryFactory.class, new PsiDirectoryFactoryImpl(myPsiManager));
  myProject.registerService(ProjectScopeBuilder.class, createProjectScopeBuilder());
  myProject.registerService(DumbService.class, new MockDumbService(myProject));
  myProject.registerService(CoreEncodingProjectManager.class, CoreEncodingProjectManager.class);
}
项目:intellij-ce-playground    文件:ExportToHTMLManager.java   
private static String constructOutputDirectory(@NotNull final PsiDirectory directory, final String outputDirectoryName) {
  String qualifiedName = PsiDirectoryFactory.getInstance(directory.getProject()).getQualifiedName(directory, false);
  String dirName = outputDirectoryName;
  if(qualifiedName.length() > 0) {
    dirName += File.separator + qualifiedName.replace('.', File.separatorChar);
  }
  File dir = new File(dirName);
  dir.mkdirs();
  return dirName;
}
项目:intellij-ce-playground    文件:ExportToHTMLManager.java   
@SuppressWarnings({"HardCodedStringLiteral"})
private static void generateIndexHtml(final PsiDirectory psiDirectory, final boolean recursive, final String outputDirectoryName)
  throws FileNotFoundException {
  String indexHtmlName = constructOutputDirectory(psiDirectory, outputDirectoryName) + File.separator + "index.html";
  OutputStreamWriter writer = new OutputStreamWriter(new FileOutputStream(indexHtmlName), CharsetToolkit.UTF8_CHARSET);
  final String title = PsiDirectoryFactory.getInstance(psiDirectory.getProject()).getQualifiedName(psiDirectory, true);
  try {
    writer.write("<html><head><title>" + title + "</title></head><body>");
    if (recursive) {
      PsiDirectory[] directories = psiDirectory.getSubdirectories();
      for(PsiDirectory directory: directories) {
        writer.write("<a href=\"" + directory.getName() + "/index.html\"><b>" + directory.getName() + "</b></a><br />");
      }
    }
    PsiFile[] files = psiDirectory.getFiles();
    for(PsiFile file: files) {
      if (!(file instanceof PsiBinaryFile)) {
        writer.write("<a href=\"" + getHTMLFileName(file) + "\">" + file.getVirtualFile().getName() + "</a><br />");
      }
    }
    writer.write("</body></html>");
    writer.close();
  }
  catch (IOException e) {
    LOG.error(e);
  }
}
项目:intellij-ce-playground    文件:HTMLTextPainter.java   
private int writeReferenceTag(Writer writer, PsiReference ref) throws IOException {
  PsiElement refClass = ref.resolve();

  PsiFile refFile = refClass.getContainingFile();
  String refPackageName = PsiDirectoryFactory.getInstance(myProject).getQualifiedName(refFile.getContainingDirectory(), false);
  String psiPackageName = PsiDirectoryFactory.getInstance(myProject).getQualifiedName(myPsiFile.getContainingDirectory(), false);

  StringBuffer fileName = new StringBuffer();
  if (!psiPackageName.equals(refPackageName)) {
    StringTokenizer tokens = new StringTokenizer(psiPackageName, ".");
    while(tokens.hasMoreTokens()) {
      tokens.nextToken();
      fileName.append("../");
    }

    StringTokenizer refTokens = new StringTokenizer(refPackageName, ".");
    while(refTokens.hasMoreTokens()) {
      String token = refTokens.nextToken();
      fileName.append(token);
      fileName.append('/');
    }
  }
  fileName.append(ExportToHTMLManager.getHTMLFileName(refFile));
  //noinspection HardCodedStringLiteral
  writer.write("<a href=\""+fileName+"\">");
  return ref.getElement().getTextRange().getEndOffset();
}
项目:intellij-ce-playground    文件:UsageViewLongNameLocation.java   
@Override
public String getElementDescription(@NotNull final PsiElement element, @NotNull final ElementDescriptionLocation location) {
  if (location instanceof UsageViewLongNameLocation) {
    if (element instanceof PsiDirectory) {
      return PsiDirectoryFactory.getInstance(element.getProject()).getQualifiedName((PsiDirectory)element, true);
    }
    return "";
  }
  return null;
}
项目:intellij-ce-playground    文件:ProjectViewImpl.java   
@NotNull
private PsiElement[] getElementsToDelete() {
  final AbstractProjectViewPane viewPane = getCurrentProjectViewPane();
  PsiElement[] elements = viewPane.getSelectedPSIElements();
  for (int idx = 0; idx < elements.length; idx++) {
    final PsiElement element = elements[idx];
    if (element instanceof PsiDirectory) {
      PsiDirectory directory = (PsiDirectory)element;
      final ProjectViewDirectoryHelper directoryHelper = ProjectViewDirectoryHelper.getInstance(myProject);
      if (isHideEmptyMiddlePackages(viewPane.getId()) && directory.getChildren().length == 0 && !directoryHelper.skipDirectory(directory)) {
        while (true) {
          PsiDirectory parent = directory.getParentDirectory();
          if (parent == null) break;
          if (directoryHelper.skipDirectory(parent) || PsiDirectoryFactory.getInstance(myProject).getQualifiedName(parent, false).length() == 0) break;
          PsiElement[] children = parent.getChildren();
          if (children.length == 0 || children.length == 1 && children[0] == directory) {
            directory = parent;
          }
          else {
            break;
          }
        }
        elements[idx] = directory;
      }
      final VirtualFile virtualFile = directory.getVirtualFile();
      final String path = virtualFile.getPath();
      if (path.endsWith(JarFileSystem.JAR_SEPARATOR)) { // if is jar-file root
        final VirtualFile vFile =
          LocalFileSystem.getInstance().findFileByPath(path.substring(0, path.length() - JarFileSystem.JAR_SEPARATOR.length()));
        if (vFile != null) {
          final PsiFile psiFile = PsiManager.getInstance(myProject).findFile(vFile);
          if (psiFile != null) {
            elements[idx] = psiFile;
          }
        }
      }
    }
  }
  return elements;
}
项目:intellij-ce-playground    文件:PsiDirectoryNode.java   
@Override
public String getTitle() {
  final PsiDirectory directory = getValue();
  if (directory != null) {
    return PsiDirectoryFactory.getInstance(getProject()).getQualifiedName(directory, true);
  }
  return super.getTitle();
}
项目:intellij-ce-playground    文件:CopyFilesOrDirectoriesHandler.java   
@Nullable
protected static PsiDirectory resolveDirectory(@NotNull PsiDirectory defaultTargetDirectory) {
  final Project project = defaultTargetDirectory.getProject();
  final Boolean showDirsChooser = defaultTargetDirectory.getCopyableUserData(CopyPasteDelegator.SHOW_CHOOSER_KEY);
  if (showDirsChooser != null && showDirsChooser.booleanValue()) {
    final PsiDirectoryContainer directoryContainer =
      PsiDirectoryFactory.getInstance(project).getDirectoryContainer(defaultTargetDirectory);
    if (directoryContainer == null) {
      return defaultTargetDirectory;
    }
    return MoveFilesOrDirectoriesUtil.resolveToDirectory(project, directoryContainer);
  }
  return defaultTargetDirectory;
}
项目:intellij-ce-playground    文件:DefaultNonCodeSearchElementDescriptionProvider.java   
@Override
public String getElementDescription(@NotNull final PsiElement element, @NotNull final ElementDescriptionLocation location) {
  if (!(location instanceof NonCodeSearchDescriptionLocation)) return null;
  final NonCodeSearchDescriptionLocation ncdLocation = (NonCodeSearchDescriptionLocation)location;

  if (element instanceof PsiDirectory) {
    if (ncdLocation.isNonJava()) {
      final String qName = PsiDirectoryFactory.getInstance(element.getProject()).getQualifiedName((PsiDirectory)element, false);
      if (qName.length() > 0) return qName;
      return null;
    }
    return ((PsiDirectory) element).getName();
  }

  if (element instanceof PsiMetaOwner) {
    final PsiMetaOwner psiMetaOwner = (PsiMetaOwner)element;
    final PsiMetaData metaData = psiMetaOwner.getMetaData();
    if (metaData != null) {
      return metaData.getName();
    }
  }
  if (element instanceof PsiNamedElement) {
    return ((PsiNamedElement)element).getName();
  }
  else {
   // LOG.error("Unknown element type: " + element);
    return null;
  }
}
项目:svgtoandroid    文件:ModulesUtil.java   
public @Nullable String getCurrentModule() {
    Editor editor = FileEditorManager.getInstance(project).getSelectedTextEditor();
    String path = FileDocumentManager.getInstance().getFile(editor.getDocument()).getPath();
    VirtualFile virtualFile = LocalFileSystem.getInstance().refreshAndFindFileByPath(path.substring(0,path.indexOf("/src")));
    if (virtualFile!= null && virtualFile.isDirectory()) {
        PsiDirectory directory = PsiDirectoryFactory.getInstance(project).createDirectory(virtualFile);
        if (isModule(directory)) {
            return directory.getName();
        }
    }
    return null;
}
项目:svgtoandroid    文件:ModulesUtil.java   
public PsiDirectory getOrCreateDrawableDir(String moduleName,String dirName) {
    PsiDirectory baseDir = PsiDirectoryFactory.getInstance(project).createDirectory(project.getBaseDir());
    PsiDirectory moduleDir = baseDir.findSubdirectory(moduleName);
    if (moduleDir != null) {
        PsiDirectory srcDir = moduleDir.findSubdirectory("src");
        if (srcDir == null) {
            srcDir = moduleDir.createSubdirectory("src");
            Logger.debug("Creating dir :" + srcDir.getName());
        }

        PsiDirectory mainDir = srcDir.findSubdirectory("main");
        if (mainDir == null) {
            mainDir = srcDir.createSubdirectory("main");
            Logger.debug("Creating dir :" + mainDir.getName());
        }

        PsiDirectory resDir = mainDir.findSubdirectory("res");
        if (resDir == null) {
            resDir = mainDir.createSubdirectory("res");
            Logger.debug("Creating dir :" + resDir.getName());
        }

        PsiDirectory drawableDir = resDir.findSubdirectory(dirName);
        if (drawableDir == null) {
            drawableDir = resDir.createSubdirectory(dirName);
            Logger.debug("Creating dir :" + drawableDir.getName());
        }
        return drawableDir;
    }
    return null;
}
项目:JsonModelGenerator    文件:GeneratorForm.java   
private void showFileChoicer() {
    FileChooserDescriptor descriptor = new FileChooserDescriptor(false, true, false, false, false, false);
    VirtualFile virtualFile = FileChooser.chooseFile(descriptor, WindowManager.getInstance().findVisibleFrame(), project, null);
    if (virtualFile != null) {
        PsiDirectory directory = PsiDirectoryFactory.getInstance(project).createDirectory(virtualFile);
        mainClassName = directory.getName();

        char[] chars = mainClassName.toCharArray();
        chars[0] = Character.toUpperCase(chars[0]);
        rootName.setText(String.valueOf(chars));

        parser.reset(project, directory);
        String path = virtualFile.getPath();
        String pkg = "";
        dirPath.setText(path);
        if (path.contains("java")) {
            pkg = path.split("java/")[1].replaceAll("/", ".");
        } else if (path.contains("src")) {
            pkg = path.split("src/")[1].replaceAll("/", ".");
        }
        basePath = path + "/";
        pkgText.setText(pkg);

        Logger.info("Target path " + path);
    } else {
        Logger.warn("Empty target path!");
    }
    frame.setAlwaysOnTop(true);
    frame.setVisible(true);
}
项目:tools-idea    文件:FileManagerImpl.java   
@Nullable
private PsiDirectory findDirectoryImpl(final VirtualFile vFile) {
  PsiDirectory psiDir = myVFileToPsiDirMap.get(vFile);
  if (psiDir != null) return psiDir;

  if (myFileIndex.isExcludedFile(vFile)) return null;

  VirtualFile parent = vFile.getParent();
  if (parent != null) { //?
    findDirectoryImpl(parent);// need to cache parent directory - used for firing events
  }

  psiDir = PsiDirectoryFactory.getInstance(myManager.getProject()).createDirectory(vFile);
  return ConcurrencyUtil.cacheOrGet(myVFileToPsiDirMap, vFile, psiDir);
}
项目:tools-idea    文件:CoreProjectEnvironment.java   
public CoreProjectEnvironment(Disposable parentDisposable, CoreApplicationEnvironment applicationEnvironment) {
  myParentDisposable = parentDisposable;
  myEnvironment = applicationEnvironment;
  myProject = new MockProject(myEnvironment.getApplication().getPicoContainer(), myParentDisposable);

  preregisterServices();

  myFileIndexFacade = createFileIndexFacade();
  myMessageBus = new MessageBusImpl("CoreProjectEnvironment", null);

  PsiModificationTrackerImpl modificationTracker = new PsiModificationTrackerImpl(myProject);
  myProject.registerService(PsiModificationTracker.class, modificationTracker);
  myProject.registerService(FileIndexFacade.class, myFileIndexFacade);
  myProject.registerService(ResolveCache.class, new ResolveCache(myMessageBus));

  registerProjectExtensionPoint(PsiTreeChangePreprocessor.EP_NAME, PsiTreeChangePreprocessor.class);
  myPsiManager = new PsiManagerImpl(myProject, null, null, myFileIndexFacade, myMessageBus, modificationTracker);
  ((FileManagerImpl) myPsiManager.getFileManager()).markInitialized();
  registerProjectComponent(PsiManager.class, myPsiManager);

  myProject.registerService(ResolveScopeManager.class, createResolveScopeManager(myPsiManager));

  myProject.registerService(PsiFileFactory.class, new PsiFileFactoryImpl(myPsiManager));
  myProject.registerService(CachedValuesManager.class, new CachedValuesManagerImpl(myProject, new PsiCachedValuesFactory(myPsiManager)));
  myProject.registerService(PsiDirectoryFactory.class, new PsiDirectoryFactoryImpl(myPsiManager));
  myProject.registerService(ProjectScopeBuilder.class, createProjectScopeBuilder());
  myProject.registerService(DumbService.class, new MockDumbService(myProject));
}
项目:tools-idea    文件:ExportToHTMLManager.java   
private static String constructOutputDirectory(@NotNull final PsiDirectory directory, final String outputDirectoryName) {
  String qualifiedName = PsiDirectoryFactory.getInstance(directory.getProject()).getQualifiedName(directory, false);
  String dirName = outputDirectoryName;
  if(qualifiedName.length() > 0) {
    dirName += File.separator + qualifiedName.replace('.', File.separatorChar);
  }
  File dir = new File(dirName);
  dir.mkdirs();
  return dirName;
}
项目:tools-idea    文件:ExportToHTMLManager.java   
@SuppressWarnings({"HardCodedStringLiteral"})
private static void generateIndexHtml(final PsiDirectory psiDirectory, final boolean recursive, final String outputDirectoryName)
  throws FileNotFoundException {
  String indexHtmlName = constructOutputDirectory(psiDirectory, outputDirectoryName) + File.separator + "index.html";
  OutputStreamWriter writer = new OutputStreamWriter(new FileOutputStream(indexHtmlName), CharsetToolkit.UTF8_CHARSET);
  final String title = PsiDirectoryFactory.getInstance(psiDirectory.getProject()).getQualifiedName(psiDirectory, true);
  try {
    writer.write("<html><head><title>" + title + "</title></head><body>");
    if (recursive) {
      PsiDirectory[] directories = psiDirectory.getSubdirectories();
      for(PsiDirectory directory: directories) {
        writer.write("<a href=\"" + directory.getName() + "/index.html\"><b>" + directory.getName() + "</b></a><br />");
      }
    }
    PsiFile[] files = psiDirectory.getFiles();
    for(PsiFile file: files) {
      if (!(file instanceof PsiBinaryFile)) {
        writer.write("<a href=\"" + getHTMLFileName(file) + "\">" + file.getVirtualFile().getName() + "</a><br />");
      }
    }
    writer.write("</body></html>");
    writer.close();
  }
  catch (IOException e) {
    LOG.error(e);
  }
}
项目:tools-idea    文件:HTMLTextPainter.java   
private int writeReferenceTag(Writer writer, PsiReference ref) throws IOException {
  PsiElement refClass = ref.resolve();

  PsiFile refFile = refClass.getContainingFile();
  String refPackageName = PsiDirectoryFactory.getInstance(myProject).getQualifiedName(refFile.getContainingDirectory(), false);
  String psiPackageName = PsiDirectoryFactory.getInstance(myProject).getQualifiedName(myPsiFile.getContainingDirectory(), false);

  StringBuffer fileName = new StringBuffer();
  if (!psiPackageName.equals(refPackageName)) {
    StringTokenizer tokens = new StringTokenizer(psiPackageName, ".");
    while(tokens.hasMoreTokens()) {
      tokens.nextToken();
      fileName.append("../");
    }

    StringTokenizer refTokens = new StringTokenizer(refPackageName, ".");
    while(refTokens.hasMoreTokens()) {
      String token = refTokens.nextToken();
      fileName.append(token);
      fileName.append('/');
    }
  }
  fileName.append(ExportToHTMLManager.getHTMLFileName(refFile));
  //noinspection HardCodedStringLiteral
  writer.write("<a href=\""+fileName+"\">");
  return ref.getElement().getTextRange().getEndOffset();
}
项目:tools-idea    文件:UsageViewLongNameLocation.java   
@Override
public String getElementDescription(@NotNull final PsiElement element, @NotNull final ElementDescriptionLocation location) {
  if (location instanceof UsageViewLongNameLocation) {
    if (element instanceof PsiDirectory) {
      return PsiDirectoryFactory.getInstance(element.getProject()).getQualifiedName((PsiDirectory)element, true);
    }
    return "";
  }
  return null;
}
项目:tools-idea    文件:CreateDirectoryOrPackageHandler.java   
@Override
public String getErrorText(String inputString) {
  if (FileTypeManager.getInstance().isFileIgnored(inputString)) {
    return "Trying to create a " + (myIsDirectory ? "directory" : "package") + " with ignored name, result will not be visible";
  }
  if (!myIsDirectory && inputString.length() > 0 && !PsiDirectoryFactory.getInstance(myProject).isValidPackageName(inputString)) {
    return "Not a valid package name, it would be impossible to create a class inside";
  }
  return null;
}
项目:tools-idea    文件:ProjectViewImpl.java   
private PsiElement[] getElementsToDelete() {
  final AbstractProjectViewPane viewPane = getCurrentProjectViewPane();
  PsiElement[] elements = viewPane.getSelectedPSIElements();
  for (int idx = 0; idx < elements.length; idx++) {
    final PsiElement element = elements[idx];
    if (element instanceof PsiDirectory) {
      PsiDirectory directory = (PsiDirectory)element;
      final ProjectViewDirectoryHelper directoryHelper = ProjectViewDirectoryHelper.getInstance(myProject);
      if (isHideEmptyMiddlePackages(viewPane.getId()) && directory.getChildren().length == 0 && !directoryHelper.skipDirectory(directory)) {
        while (true) {
          PsiDirectory parent = directory.getParentDirectory();
          if (parent == null) break;
          if (directoryHelper.skipDirectory(parent) || PsiDirectoryFactory.getInstance(myProject).getQualifiedName(parent, false).length() == 0) break;
          PsiElement[] children = parent.getChildren();
          if (children.length == 0 || children.length == 1 && children[0] == directory) {
            directory = parent;
          }
          else {
            break;
          }
        }
        elements[idx] = directory;
      }
      final VirtualFile virtualFile = directory.getVirtualFile();
      final String path = virtualFile.getPath();
      if (path.endsWith(JarFileSystem.JAR_SEPARATOR)) { // if is jar-file root
        final VirtualFile vFile =
          LocalFileSystem.getInstance().findFileByPath(path.substring(0, path.length() - JarFileSystem.JAR_SEPARATOR.length()));
        if (vFile != null) {
          final PsiFile psiFile = PsiManager.getInstance(myProject).findFile(vFile);
          if (psiFile != null) {
            elements[idx] = psiFile;
          }
        }
      }
    }
  }
  return elements;
}
项目:tools-idea    文件:PsiDirectoryNode.java   
@Override
public String getTitle() {
  final PsiDirectory directory = getValue();
  if (directory != null) {
    return PsiDirectoryFactory.getInstance(getProject()).getQualifiedName(directory, true);
  }
  return super.getTitle();
}
项目:tools-idea    文件:CopyFilesOrDirectoriesHandler.java   
@Nullable
protected static PsiDirectory resolveDirectory(@NotNull PsiDirectory defaultTargetDirectory) {
  final Project project = defaultTargetDirectory.getProject();
  final Boolean showDirsChooser = defaultTargetDirectory.getCopyableUserData(CopyPasteDelegator.SHOW_CHOOSER_KEY);
  if (showDirsChooser != null && showDirsChooser.booleanValue()) {
    final PsiDirectoryContainer directoryContainer =
      PsiDirectoryFactory.getInstance(project).getDirectoryContainer(defaultTargetDirectory);
    if (directoryContainer == null) {
      return defaultTargetDirectory;
    }
    return MoveFilesOrDirectoriesUtil.resolveToDirectory(project, directoryContainer);
  }
  return defaultTargetDirectory;
}
项目:tools-idea    文件:DefaultNonCodeSearchElementDescriptionProvider.java   
@Override
public String getElementDescription(@NotNull final PsiElement element, @NotNull final ElementDescriptionLocation location) {
  if (!(location instanceof NonCodeSearchDescriptionLocation)) return null;
  final NonCodeSearchDescriptionLocation ncdLocation = (NonCodeSearchDescriptionLocation)location;

  if (element instanceof PsiDirectory) {
    if (ncdLocation.isNonJava()) {
      final String qName = PsiDirectoryFactory.getInstance(element.getProject()).getQualifiedName((PsiDirectory)element, false);
      if (qName.length() > 0) return qName;
      return null;
    }
    return ((PsiDirectory) element).getName();
  }

  if (element instanceof PsiMetaOwner) {
    final PsiMetaOwner psiMetaOwner = (PsiMetaOwner)element;
    final PsiMetaData metaData = psiMetaOwner.getMetaData();
    if (metaData != null) {
      return metaData.getName();
    }
  }
  if (element instanceof PsiNamedElement) {
    return ((PsiNamedElement)element).getName();
  }
  else {
   // LOG.error("Unknown element type: " + element);
    return null;
  }
}
项目:idea-php-symfony2-plugin    文件:PhpBundleFileFactory.java   
@NotNull
public static PsiElement createBundleFile(@NotNull PhpClass bundleClass, @NotNull String template, @NotNull String className, Map<String, String> vars) throws Exception {

    VirtualFile directory = bundleClass.getContainingFile().getContainingDirectory().getVirtualFile();
    if(fileExists(directory, new String[] {className})) {
        throw new Exception("File already exists");
    }

    String COMPILER_TEMPLATE = "/resources/fileTemplates/" + template + ".php";
    String fileTemplateContent = getFileTemplateContent(COMPILER_TEMPLATE);
    if(fileTemplateContent == null) {
        throw new Exception("Template content error");
    }

    String[] split = className.split("\\\\");

    String ns = bundleClass.getNamespaceName();
    String join = StringUtils.join(Arrays.copyOf(split, split.length - 1), "/");

    vars.put("ns", (ns.startsWith("\\") ? ns.substring(1) : ns) + join.replace("/", "\\"));
    vars.put("class", split[split.length - 1]);
    for (Map.Entry<String, String> entry : vars.entrySet()) {
        fileTemplateContent = fileTemplateContent.replace("{{ " + entry.getKey() + " }}", entry.getValue());
    }

    VirtualFile compilerDirectory = getAndCreateDirectory(directory, join);
    if(compilerDirectory == null) {
        throw new Exception("Directory creation failed");
    }

    Project project = bundleClass.getProject();
    PsiFile fileFromText = PsiFileFactory.getInstance(project).createFileFromText(split[split.length - 1] + ".php", PhpFileType.INSTANCE, fileTemplateContent);
    CodeStyleManager.getInstance(project).reformat(fileFromText);
    return PsiDirectoryFactory.getInstance(project).createDirectory(compilerDirectory).add(fileFromText);
}