Java Code Examples for com.intellij.psi.PsiDirectory#getProject()

The following examples show how to use com.intellij.psi.PsiDirectory#getProject() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: MultipleJavaClassesTestContextProvider.java    From intellij with Apache License 2.0 6 votes vote down vote up
/**
 * Returns a {@link RunConfigurationContext} future setting up the relevant test target pattern,
 * if one can be found.
 */
@Nullable
private static ListenableFuture<TargetInfo> getTargetContext(PsiDirectory dir) {
  Project project = dir.getProject();
  ProjectFileIndex index = ProjectFileIndex.SERVICE.getInstance(project);
  if (!index.isInTestSourceContent(dir.getVirtualFile())) {
    return null;
  }
  if (BlazePackage.isBlazePackage(dir)) {
    // this case is handled by a separate run config producer
    return null;
  }
  ListenableFuture<Set<PsiClass>> classes = findAllTestClassesBeneathDirectory(dir);
  if (classes == null) {
    return null;
  }
  return Futures.transformAsync(
      classes,
      set -> set == null ? null : ReadAction.compute(() -> getTestTargetIfUnique(project, set)),
      EXECUTOR);
}
 
Example 2
Source File: BashTemplatesFactory.java    From BashSupport with Apache License 2.0 6 votes vote down vote up
@NotNull
static PsiFile createFromTemplate(final PsiDirectory directory, String fileName, String templateName) throws IncorrectOperationException {
    Project project = directory.getProject();
    FileTemplateManager templateManager = FileTemplateManager.getInstance(project);
    FileTemplate template = templateManager.getInternalTemplate(templateName);

    Properties properties = new Properties(templateManager.getDefaultProperties());

    String templateText;
    try {
        templateText = template.getText(properties);
    } catch (IOException e) {
        throw new RuntimeException("Unable to load template for " + templateManager.internalTemplateToSubject(templateName), e);
    }

    PsiFile file = PsiFileFactory.getInstance(project).createFileFromText(fileName, BashFileType.BASH_FILE_TYPE, templateText);
    return (PsiFile) directory.add(file);
}
 
Example 3
Source File: AbstractFileProcessor.java    From consulo with Apache License 2.0 6 votes vote down vote up
private static void findFiles(List<PsiFile> files, PsiDirectory directory, boolean subdirs) {
  final Project project = directory.getProject();
  PsiFile[] locals = directory.getFiles();
  for (PsiFile local : locals) {
    CopyrightProfile opts = CopyrightManager.getInstance(project).getCopyrightOptions(local);
    if (opts != null && CopyrightUpdaters.hasExtension(local)) {
      files.add(local);
    }

  }

  if (subdirs) {
    PsiDirectory[] dirs = directory.getSubdirectories();
    for (PsiDirectory dir : dirs) {
      findFiles(files, dir, subdirs);
    }

  }
}
 
Example 4
Source File: MultipleJavaClassesTestContextProvider.java    From intellij with Apache License 2.0 5 votes vote down vote up
private static ListenableFuture<Set<PsiClass>> findAllTestClassesBeneathDirectory(
    PsiDirectory dir) {
  Project project = dir.getProject();
  WorkspaceFileFinder finder =
      WorkspaceFileFinder.Provider.getInstance(project).getWorkspaceFileFinder();
  if (finder == null || !relevantDirectory(finder, dir)) {
    return null;
  }
  return EXECUTOR.submit(
      () -> {
        Set<PsiClass> classes = new HashSet<>();
        ReadAction.run(() -> addClassesInDirectory(finder, dir, classes, /* currentDepth= */ 0));
        return classes;
      });
}
 
Example 5
Source File: CreateDirectoryOrPackageAction.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Nonnull
@RequiredUIAccess
private static Trinity<ContentFolderTypeProvider, PsiDirectory, ChildType> getInfo(PsiDirectory d) {
  Project project = d.getProject();
  ProjectFileIndex projectFileIndex = ProjectFileIndex.getInstance(project);

  Module moduleForPsiElement = ModuleUtilCore.findModuleForPsiElement(d);
  if (moduleForPsiElement != null) {
    boolean isPackageSupported = false;
    ModuleRootManager moduleRootManager = ModuleRootManager.getInstance(moduleForPsiElement);
    List<PsiPackageSupportProvider> extensions = PsiPackageSupportProvider.EP_NAME.getExtensionList();
    for (ModuleExtension moduleExtension : moduleRootManager.getExtensions()) {
      for (PsiPackageSupportProvider supportProvider : extensions) {
        if (supportProvider.isSupported(moduleExtension)) {
          isPackageSupported = true;
          break;
        }
      }
    }

    if (isPackageSupported) {
      ContentFolderTypeProvider contentFolderTypeForFile = projectFileIndex.getContentFolderTypeForFile(d.getVirtualFile());
      if (contentFolderTypeForFile != null) {
        Image childPackageIcon = contentFolderTypeForFile.getChildPackageIcon();
        return Trinity.create(contentFolderTypeForFile, d, childPackageIcon != null ? ChildType.Package : ChildType.Directory);
      }
    }
  }

  return Trinity.create(null, d, ChildType.Directory);
}
 
Example 6
Source File: CreateFileAction.java    From consulo with Apache License 2.0 5 votes vote down vote up
@RequiredUIAccess
@Override
public boolean canClose(final String inputString) {
  if (inputString.length() == 0) {
    return super.canClose(inputString);
  }

  final PsiDirectory psiDirectory = getDirectory();

  final Project project = psiDirectory.getProject();
  final boolean[] result = {false};
  FileTypeChooser.getKnownFileTypeOrAssociate(psiDirectory.getVirtualFile(), getFileName(inputString), project);
  result[0] = super.canClose(getFileName(inputString));
  return result[0];
}
 
Example 7
Source File: CreateFromTemplateActionBase.java    From consulo with Apache License 2.0 5 votes vote down vote up
@RequiredUIAccess
@Override
public final void actionPerformed(@Nonnull AnActionEvent e) {
  DataContext dataContext = e.getDataContext();
  IdeView view = dataContext.getData(LangDataKeys.IDE_VIEW);
  if (view == null) return;
  PsiDirectory dir = getTargetDirectory(dataContext, view);
  if (dir == null) return;
  Project project = dir.getProject();

  FileTemplate selectedTemplate = getTemplate(project, dir);
  if (selectedTemplate != null) {
    AnAction action = getReplacedAction(selectedTemplate);
    if (action != null) {
      action.actionPerformed(e);
    }
    else {
      FileTemplateManager.getInstance(project).addRecentName(selectedTemplate.getName());
      AttributesDefaults defaults = getAttributesDefaults(dataContext);
      Map<String, Object> properties = defaults != null ? defaults.getDefaultProperties() : null;
      CreateFromTemplateDialog dialog = new CreateFromTemplateDialog(dir, selectedTemplate, defaults, properties);
      PsiElement createdElement = dialog.create();
      if (createdElement != null) {
        elementCreated(dialog, createdElement);
        view.selectElement(createdElement);
        if (selectedTemplate.isLiveTemplateEnabled() && createdElement instanceof PsiFile) {
          Map<String, String> defaultValues = getLiveTemplateDefaults(dataContext, ((PsiFile)createdElement));
          startLiveTemplate((PsiFile)createdElement, notNull(defaultValues, Collections.emptyMap()));
        }
      }
    }
  }
}
 
Example 8
Source File: CreateFromTemplateDialog.java    From consulo with Apache License 2.0 5 votes vote down vote up
public CreateFromTemplateDialog(@Nonnull PsiDirectory directory,
                                @Nonnull FileTemplate template,
                                @Nullable final AttributesDefaults attributesDefaults,
                                @Nullable final Map<String, Object> defaultProperties) {
  super(directory.getProject(), true);
  myDirectory = directory;
  myProject = directory.getProject();
  myTemplate = template;
  setTitle(IdeBundle.message("title.new.from.template", template.getName()));

  myDefaultProperties = defaultProperties == null ? FileTemplateManager.getInstance(myProject).getDefaultVariables() : defaultProperties;
  FileTemplateUtil.fillDefaultProperties(myDefaultProperties, directory);
  boolean mustEnterName = FileTemplateUtil.findHandler(template).isNameRequired();
  if (attributesDefaults != null && attributesDefaults.isFixedName()) {
    myDefaultProperties.put(FileTemplate.ATTRIBUTE_NAME, attributesDefaults.getDefaultFileName());
    mustEnterName = false;
  }

  String[] unsetAttributes = null;
  try {
    unsetAttributes = myTemplate.getUnsetAttributes(myDefaultProperties, myProject);
  }
  catch (ParseException e) {
    showErrorDialog(e);
  }

  if (unsetAttributes != null) {
    myAttrPanel = new CreateFromTemplatePanel(unsetAttributes, mustEnterName, attributesDefaults);
    myAttrComponent = myAttrPanel.getComponent();
    init();
  }
  else {
    myAttrPanel = null;
    myAttrComponent = null;
  }
}
 
Example 9
Source File: UnityNamespaceGeneratePolicy.java    From consulo-unity3d with Apache License 2.0 4 votes vote down vote up
@RequiredReadAction
@Nullable
@Override
public String calculateDirtyNamespace(@Nonnull PsiDirectory psiDirectory)
{
	Project project = psiDirectory.getProject();
	VirtualFile baseDir = project.getBaseDir();
	if(baseDir == null)
	{
		return myNamespacePrefix;
	}

	VirtualFile currentDirectory = psiDirectory.getVirtualFile();

	VirtualFile assetsDirectory = baseDir.findChild(Unity3dProjectImportUtil.ASSETS_DIRECTORY);
	if(assetsDirectory != null)
	{
		VirtualFile targetDirectory = assetsDirectory;

		VirtualFile temp = currentDirectory;
		while(temp != null && !temp.equals(targetDirectory))
		{
			if("Editor".equals(temp.getName()))
			{
				targetDirectory = temp;
			}
			temp = temp.getParent();
		}

		// if path is not changed
		if(targetDirectory.equals(assetsDirectory))
		{
			temp = currentDirectory;
			while(temp != null && !temp.equals(targetDirectory))
			{
				if("Scripts".equals(temp.getName()))
				{
					targetDirectory = temp;
				}
				temp = temp.getParent();
			}
		}

		// if path is not changed
		if(targetDirectory.equals(assetsDirectory))
		{
			for(String path : Unity3dProjectImportUtil.FIRST_PASS_PATHS)
			{
				VirtualFile child = baseDir.findFileByRelativePath(path);
				if(child != null && VfsUtil.isAncestor(child, currentDirectory, false))
				{
					targetDirectory = child;
					break;
				}
			}
		}

		String relativePath = VfsUtil.getRelativePath(currentDirectory, targetDirectory, '.');
		if(relativePath != null)
		{
			if(!StringUtil.isEmpty(myNamespacePrefix))
			{
				if(StringUtil.isEmpty(relativePath))
				{
					return myNamespacePrefix;
				}
				return myNamespacePrefix + "." + relativePath;
			}
			return relativePath;
		}
	}
	return myNamespacePrefix;
}
 
Example 10
Source File: GlobalSearchScopesCore.java    From consulo with Apache License 2.0 4 votes vote down vote up
private DirectoryScope(@Nonnull PsiDirectory psiDirectory, final boolean withSubdirectories) {
  super(psiDirectory.getProject());
  myWithSubdirectories = withSubdirectories;
  myDirectory = psiDirectory.getVirtualFile();
}
 
Example 11
Source File: DirElementInfo.java    From consulo with Apache License 2.0 4 votes vote down vote up
DirElementInfo(@Nonnull PsiDirectory directory) {
  myProject = directory.getProject();
  myVirtualFile = directory.getVirtualFile();
}
 
Example 12
Source File: FileRecursiveIterator.java    From consulo with Apache License 2.0 4 votes vote down vote up
FileRecursiveIterator(@Nonnull PsiDirectory directory) {
  this(directory.getProject(), Collections.singletonList(directory.getVirtualFile()));
}
 
Example 13
Source File: FileTemplateUtil.java    From consulo with Apache License 2.0 4 votes vote down vote up
public static PsiElement createFromTemplate(@Nonnull final FileTemplate template,
                                            @NonNls @Nullable String fileName,
                                            @Nullable Map<String, Object> additionalProperties,
                                            @Nonnull final PsiDirectory directory,
                                            @Nullable ClassLoader classLoader) throws Exception {
  final Project project = directory.getProject();

  Map<String, Object> properties = new THashMap<>();
  FileTemplateManager.getInstance(project).fillDefaultVariables(properties);

  if(additionalProperties != null) {
    properties.putAll(additionalProperties);
  }

  FileTemplateManager.getInstance(project).addRecentName(template.getName());
  fillDefaultProperties(properties, directory);

  final CreateFromTemplateHandler handler = findHandler(template);
  if (fileName != null && properties.get(FileTemplate.ATTRIBUTE_NAME) == null) {
    properties.put(FileTemplate.ATTRIBUTE_NAME, fileName);
  }
  else if (fileName == null && handler.isNameRequired()) {
    fileName = (String)properties.get(FileTemplate.ATTRIBUTE_NAME);
    if (fileName == null) {
      throw new Exception("File name must be specified");
    }
  }

  //Set escaped references to dummy values to remove leading "\" (if not already explicitely set)
  String[] dummyRefs = calculateAttributes(template.getText(), properties, true, project);
  for (String dummyRef : dummyRefs) {
    properties.put(dummyRef, "");
  }

  handler.prepareProperties(properties);

  final String fileName_ = fileName;
  String mergedText =
          ClassLoaderUtil.runWithClassLoader(classLoader != null ? classLoader : FileTemplateUtil.class.getClassLoader(), (ThrowableComputable<String, IOException>)() -> template.getText(properties));
  final String templateText = StringUtil.convertLineSeparators(mergedText);
  final Exception[] commandException = new Exception[1];
  final PsiElement[] result = new PsiElement[1];
  CommandProcessor.getInstance().executeCommand(project, () -> ApplicationManager.getApplication().runWriteAction(() -> {
    try {
      result[0] = handler.createFromTemplate(project, directory, fileName_, template, templateText, properties);
    }
    catch (Exception ex) {
      commandException[0] = ex;
    }
  }), handler.commandName(template), null);
  if (commandException[0] != null) {
    throw commandException[0];
  }
  return result[0];
}
 
Example 14
Source File: DirectoryUrl.java    From consulo with Apache License 2.0 4 votes vote down vote up
public static DirectoryUrl create(PsiDirectory directory) {
  Project project = directory.getProject();
  final VirtualFile virtualFile = directory.getVirtualFile();
  final Module module = ModuleUtil.findModuleForFile(virtualFile, project);
  return new DirectoryUrl(virtualFile.getUrl(), module != null ? module.getName() : null);
}
 
Example 15
Source File: VueTemplatesFactory.java    From vue-for-idea with BSD 3-Clause "New" or "Revised" License 3 votes vote down vote up
public static PsiFile createFromTemplate(final PsiDirectory directory, final String name,
                                         String fileName, String templateName,
                                         @NonNls String... parameters) throws IncorrectOperationException {

    final FileTemplate template = FileTemplateManager.getDefaultInstance().getTemplate(templateName);

    Properties properties = new Properties(FileTemplateManager.getDefaultInstance().getDefaultProperties());

    Project project = directory.getProject();
    properties.setProperty("PROJECT_NAME", project.getName());
    properties.setProperty("NAME", fileName);


    String text;

    try {
        text = template.getText(properties);
    } catch (Exception e) {
        throw new RuntimeException("Unable to load template for " +
                FileTemplateManager.getInstance().internalTemplateToSubject(templateName), e);
    }

    final PsiFileFactory factory = PsiFileFactory.getInstance(directory.getProject());

    final PsiFile file = factory.createFileFromText(fileName, VueFileType.INSTANCE, text);

    return (PsiFile) directory.add(file);
}