Java Code Examples for com.intellij.openapi.module.ModuleUtil#findModuleForPsiElement()

The following examples show how to use com.intellij.openapi.module.ModuleUtil#findModuleForPsiElement() . 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: AddPythonFacetQuickFix.java    From intellij-pants-plugin with Apache License 2.0 6 votes vote down vote up
@Nullable
private Sdk resolveSdk(Project project, PsiFile file) {
  final AtomicReference<Sdk> pythonSdk = new AtomicReference<>();
  final ProjectJdkTable jdkTable = ProjectJdkTable.getInstance();
  List<Sdk> sdks = jdkTable.getSdksOfType(PythonSdkType.getInstance());

  if (sdks.isEmpty()) {
    final Module module = ModuleUtil.findModuleForPsiElement(file);
    PyAddSdkDialog.show(project, module, sdks, pythonSdk::set);
    if (pythonSdk.get() != null) {
      ApplicationManager.getApplication().runWriteAction(() -> {
        jdkTable.addJdk(pythonSdk.get());
      });
    }

    return pythonSdk.get();
  }
  else {
    return sdks.get(0);
  }
}
 
Example 2
Source File: PythonFacetInspection.java    From intellij-pants-plugin with Apache License 2.0 6 votes vote down vote up
private boolean shouldAddPythonSdk(@NotNull PsiFile file) {
  if (!PantsUtil.isPantsProject(file.getProject())) {
    return false;
  }

  if (!PantsUtil.isBUILDFileName(file.getName())) {
    return false;
  }

  final Module module = ModuleUtil.findModuleForPsiElement(file);
  if (module == null) {
    return false;
  }

  return PantsPythonSdkUtil.hasNoPythonSdk(module);
}
 
Example 3
Source File: PsiDirectoryNode.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Override
@RequiredUIAccess
public void navigate(final boolean requestFocus) {
  Module module = ModuleUtil.findModuleForPsiElement(getValue());
  if (module != null) {
    final VirtualFile file = getVirtualFile();
    final Project project = getProject();
    ProjectSettingsService service = ProjectSettingsService.getInstance(myProject);
    if (ProjectRootsUtil.isModuleContentRoot(file, project)) {
      service.openModuleSettings(module);
    }
    else if (ProjectRootsUtil.isLibraryRoot(file, project)) {
      final OrderEntry orderEntry = LibraryUtil.findLibraryEntry(file, module.getProject());
      if (orderEntry != null) {
        service.openLibraryOrSdkSettings(orderEntry);
      }
    }
    else {
      service.openContentEntriesSettings(module);
    }
  }
}
 
Example 4
Source File: MongoScriptRunConfigurationProducer.java    From nosql4idea with Apache License 2.0 6 votes vote down vote up
@Nullable
@Override
protected RunnerAndConfigurationSettings createConfigurationByElement(Location location, ConfigurationContext configurationContext) {
    sourceFile = location.getPsiElement().getContainingFile();
    if (sourceFile != null && sourceFile.getFileType().getName().toLowerCase().contains("javascript")) {
        Project project = sourceFile.getProject();

        VirtualFile file = sourceFile.getVirtualFile();

        RunnerAndConfigurationSettings settings = cloneTemplateConfiguration(project, configurationContext);

        MongoRunConfiguration runConfiguration = (MongoRunConfiguration) settings.getConfiguration();
        runConfiguration.setName(file.getName());

        runConfiguration.setScriptPath(file.getPath());

        Module module = ModuleUtil.findModuleForPsiElement(location.getPsiElement());
        if (module != null) {
            runConfiguration.setModule(module);
        }

        return settings;
    }
    return null;
}
 
Example 5
Source File: PsiElementModuleRenderer.java    From consulo with Apache License 2.0 5 votes vote down vote up
protected void customizeCellRenderer(
  Object value,
  int index,
  boolean selected,
  boolean hasFocus
) {
  myText = "";
  if (value instanceof PsiElement) {
    PsiElement element = (PsiElement)value;
    if (element.isValid()) {
      PsiFile psiFile = element.getContainingFile();
      Module module = ModuleUtil.findModuleForPsiElement(element);
      final ProjectFileIndex fileIndex = ProjectRootManager.getInstance(element.getProject()).getFileIndex();
      boolean isInLibraries = false;
      if (psiFile != null) {
        VirtualFile vFile = psiFile.getVirtualFile();
        if (vFile != null) {
          isInLibraries = fileIndex.isInLibrarySource(vFile) || fileIndex.isInLibraryClasses(vFile);
          if (isInLibraries){
            showLibraryLocation(fileIndex, vFile);
          }
        }
      }
      if (module != null && !isInLibraries) {
        showProjectLocation(psiFile, module, fileIndex);
      }
    }
  }

  setText(myText);
  setBorder(BorderFactory.createEmptyBorder(0, 0, 0, UIUtil.getListCellHPadding()));
  setHorizontalTextPosition(SwingConstants.LEFT);
  setBackground(selected ? UIUtil.getListSelectionBackground() : UIUtil.getListBackground());
  setForeground(selected ? UIUtil.getListSelectionForeground() : UIUtil.getInactiveTextColor());

  if (UIUtil.isUnderNimbusLookAndFeel()) {
    setOpaque(false);
  }
}
 
Example 6
Source File: AddPantsTargetDependencyFix.java    From intellij-pants-plugin with Apache License 2.0 5 votes vote down vote up
@Override
public void invoke(@NotNull Project project, @Nullable Editor editor, @NotNull PsiFile psiFile) throws IncorrectOperationException {
  final Module module = ModuleUtil.findModuleForPsiElement(psiFile);
  final VirtualFile buildFile = module != null ? PantsUtil.findBUILDFileForModule(module).orElse(null) : null;
  final PsiFile psiBuildFile = buildFile != null ? PsiManager.getInstance(project).findFile(buildFile) : null;
  if (psiBuildFile != null && StringUtil.isNotEmpty(myAddress.getTargetName())) {
    doInsert(psiBuildFile, myAddress.getTargetName(), myAddressToAdd);
  }
}
 
Example 7
Source File: UsageFavoriteNodeProvider.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Override
public String getElementModuleName(Object element) {
  if (element instanceof UsageInfo) {
    Module module = ModuleUtil.findModuleForPsiElement(((UsageInfo)element).getElement());
    return module != null ? module.getName() : null;
  }
  return null;
}
 
Example 8
Source File: SQFReferenceContributor.java    From arma-intellij-plugin with MIT License 5 votes vote down vote up
/**
 * Adds all {@link SQFVariable}s in the current module that is equal to findVar into a list and returns it
 * <p>
 * If findVar is a local variable, the list returned will be empty.
 *
 * @param project project
 * @param findVar variable
 * @return list
 */
@NotNull
public static List<SQFVariable> findGlobalVariables(@NotNull Project project, @NotNull SQFVariable findVar) {
	List<SQFVariable> result = new ArrayList<>();
	if (findVar.isLocal()) {
		return result;
	}
	Module m = ModuleUtil.findModuleForPsiElement(findVar);
	if (m == null) {
		return result;
	}
	GlobalSearchScope searchScope = m.getModuleContentScope();
	Collection<VirtualFile> files = FileTypeIndex.getFiles(SQFFileType.INSTANCE, searchScope);
	for (VirtualFile virtualFile : files) {
		PsiFile file = PsiManager.getInstance(project).findFile(virtualFile);
		if (!(file instanceof SQFFile)) {
			continue;
		}
		SQFFile sqfFile = (SQFFile) file;
		PsiUtil.traverseBreadthFirstSearch(sqfFile.getNode(), astNode -> {
			PsiElement nodeAsElement = astNode.getPsi();
			if (nodeAsElement instanceof SQFVariable) {
				SQFVariable var = (SQFVariable) nodeAsElement;
				if (var.isLocal()) {
					return false;
				}
				if (SQFVariableName.nameEquals(var.getVarName(), findVar.getVarName())) {
					result.add(var);
				}
			}
			return false;
		});
	}
	return result;
}
 
Example 9
Source File: SQFReferenceContributor.java    From arma-intellij-plugin with MIT License 5 votes vote down vote up
/**
 * Adds all {@link SQFCommand} instances in the current module that is equal to findCommand into a list and returns it
 *
 * @param project     project
 * @param findCommand the command
 * @return list
 */
@NotNull
public static List<SQFCommand> findAllCommandInstances(@NotNull Project project, @NotNull SQFCommand findCommand) {
	List<SQFCommand> result = new ArrayList<>();
	Module m = ModuleUtil.findModuleForPsiElement(findCommand);
	if (m == null) {
		return result;
	}
	GlobalSearchScope searchScope = m.getModuleContentScope();
	Collection<VirtualFile> files = FileTypeIndex.getFiles(SQFFileType.INSTANCE, searchScope);
	for (VirtualFile virtualFile : files) {
		PsiFile file = PsiManager.getInstance(project).findFile(virtualFile);
		if (!(file instanceof SQFFile)) {
			continue;
		}
		SQFFile sqfFile = (SQFFile) file;
		PsiUtil.traverseBreadthFirstSearch(sqfFile.getNode(), astNode -> {
			PsiElement nodeAsElement = astNode.getPsi();
			if (nodeAsElement instanceof SQFCommand) {
				SQFCommand command = (SQFCommand) nodeAsElement;
				if (command.commandNameEquals(findCommand.getCommandName())) {
					result.add(command);
				}
			}
			return false;
		});
	}
	return result;
}
 
Example 10
Source File: Utils.java    From android-butterknife-zelezny with Apache License 2.0 5 votes vote down vote up
/**
 * Check whether classpath of a module that corresponds to a {@link PsiElement} contains given class.
 *
 * @param project    Project
 * @param psiElement Element for which we check the class
 * @param className  Class name of the searched class
 * @return True if the class is present on the classpath
 * @since 1.3
 */
public static boolean isClassAvailableForPsiFile(@NotNull Project project, @NotNull PsiElement psiElement, @NotNull String className) {
    Module module = ModuleUtil.findModuleForPsiElement(psiElement);
    if (module == null) {
        return false;
    }
    GlobalSearchScope moduleScope = module.getModuleWithDependenciesAndLibrariesScope(false);
    PsiClass classInModule = JavaPsiFacade.getInstance(project).findClass(className, moduleScope);
    return classInModule != null;
}
 
Example 11
Source File: PantsUnresolvedReferenceFixFinder.java    From intellij-pants-plugin with Apache License 2.0 5 votes vote down vote up
@NotNull
public static List<PantsQuickFix> findMissingDependencies(@NotNull String referenceName, @NotNull PsiFile containingFile) {
  final VirtualFile containingClassFile = containingFile.getVirtualFile();
  if (containingClassFile == null) return Collections.emptyList();

  final Project project = containingFile.getProject();

  final ProjectFileIndex fileIndex = ProjectRootManager.getInstance(project).getFileIndex();
  final Module containingModule = fileIndex.getModuleForFile(containingClassFile);

  final List<PantsTargetAddress> addresses = PantsUtil.getTargetAddressesFromModule(containingModule);
  if (addresses.size() != 1) return Collections.emptyList();

  final PantsTargetAddress currentAddress = addresses.iterator().next();

  final PsiClass[] classes = PsiShortNamesCache.getInstance(project).getClassesByName(referenceName, GlobalSearchScope.allScope(project));
  final List<PsiClass> allowedDependencies = filterAllowedDependencies(containingFile, classes);
  final List<PantsQuickFix> result = new ArrayList<>();
  for (PsiClass dependency : allowedDependencies) {
    final Module module = ModuleUtil.findModuleForPsiElement(dependency);
    for (PantsTargetAddress addressToAdd : PantsUtil.getTargetAddressesFromModule(module)) {
      result.add(new AddPantsTargetDependencyFix(currentAddress, addressToAdd));
    }
    // todo(fkoroktov): handle jars
  }
  return result;
}
 
Example 12
Source File: ArmaPluginUtil.java    From arma-intellij-plugin with MIT License 5 votes vote down vote up
/**
 * Invokes {@link #getConfigVirtualFiles(Module)} by first getting a {@link Module} instance for the the provided PsiElement.
 *
 * @param elementFromModule a PsiElement used to determine what module the root config file is located in
 * @return a list of VirtualFile instances, or an empty list
 */
@NotNull
public static List<VirtualFile> getConfigVirtualFiles(@NotNull PsiElement elementFromModule) {
	Module module = ModuleUtil.findModuleForPsiElement(elementFromModule);
	if (module == null) {
		return Collections.emptyList();
	}
	return getConfigVirtualFiles(module);
}
 
Example 13
Source File: SQFReferenceContributor.java    From arma-intellij-plugin with MIT License 5 votes vote down vote up
/**
 * Adds all {@link SQFVariable}s in the current module that is equal to findVar into a list and returns it
 * <p>
 * If findVar is a local variable, the list returned will be empty.
 *
 * @param project project
 * @param findVar variable
 * @return list
 */
@NotNull
public static List<SQFVariable> findGlobalVariables(@NotNull Project project, @NotNull SQFVariable findVar) {
	List<SQFVariable> result = new ArrayList<>();
	if (findVar.isLocal()) {
		return result;
	}
	Module m = ModuleUtil.findModuleForPsiElement(findVar);
	if (m == null) {
		return result;
	}
	GlobalSearchScope searchScope = m.getModuleContentScope();
	Collection<VirtualFile> files = FileTypeIndex.getFiles(SQFFileType.INSTANCE, searchScope);
	for (VirtualFile virtualFile : files) {
		PsiFile file = PsiManager.getInstance(project).findFile(virtualFile);
		if (!(file instanceof SQFFile)) {
			continue;
		}
		SQFFile sqfFile = (SQFFile) file;
		PsiUtil.traverseBreadthFirstSearch(sqfFile.getNode(), astNode -> {
			PsiElement nodeAsElement = astNode.getPsi();
			if (nodeAsElement instanceof SQFVariable) {
				SQFVariable var = (SQFVariable) nodeAsElement;
				if (var.isLocal()) {
					return false;
				}
				if (SQFVariableName.nameEquals(var.getVarName(), findVar.getVarName())) {
					result.add(var);
				}
			}
			return false;
		});
	}
	return result;
}
 
Example 14
Source File: ArmaPluginUserData.java    From arma-intellij-plugin with MIT License 5 votes vote down vote up
/**
 * Invoke when the root config file ({@link #parseAndGetConfigHeaderFiles(PsiElement)}) or included files for it has been edited.
 * Note that this doesn't do any reparsing and instead tells {@link #parseAndGetConfigHeaderFiles(PsiElement)} that it's cached
 * {@link HeaderFile} is no longer valid and it should reparse.
 */
public void reparseConfigs(@NotNull PsiFile fileFromModule) {
	Module module = ModuleUtil.findModuleForPsiElement(fileFromModule);
	if (module == null) {
		return;
	}
	ArmaPluginModuleData moduleData = moduleMap.computeIfAbsent(module, module1 -> {
		return new ArmaPluginModuleData(module);
	});
	moduleData.setReparseConfigHeaderFiles(true);
}
 
Example 15
Source File: ArmaPluginUserData.java    From arma-intellij-plugin with MIT License 5 votes vote down vote up
@Nullable
private ArmaPluginModuleData getModuleData(@NotNull PsiElement elementFromModule) {
	Module module = ModuleUtil.findModuleForPsiElement(elementFromModule);
	if (module == null) {
		return null;
	}
	return getModuleData(module);
}
 
Example 16
Source File: SameModuleWeigher.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Override
public Comparable weigh(@Nonnull final PsiElement element, @Nonnull final ProximityLocation location) {
  final Module elementModule = ModuleUtil.findModuleForPsiElement(element);
  if (location.getPositionModule() == elementModule) {
    return 2;
  }

  if (elementModule != null) {
    return 1; // in project => still not bad
  }

  return 0;
}
 
Example 17
Source File: MuleSchemaProvider.java    From mule-intellij-plugins with Apache License 2.0 5 votes vote down vote up
@Override
public Set<String> getLocations(@NotNull @NonNls final String namespace, @NotNull final XmlFile context) throws ProcessCanceledException {
    Set<String> locations = new HashSet<>();
    final Module module = ModuleUtil.findModuleForPsiElement(context);
    if (module == null) {
        return null;
    }
    try {
        final Map<String, XmlFile> schemas = getSchemas(module);
        for (Map.Entry<String, XmlFile> entry : schemas.entrySet()) {
            final String s = getNamespace(entry.getValue(), context.getProject());
            if (s != null && s.equals(namespace)) {
                if (!entry.getKey().contains("mule-httpn.xsd")) {
                    locations.add(entry.getKey()); //Observe the formatting rules
                    XmlFile schemaFile = entry.getValue();
                    try {
                        String url = schemaFile.getVirtualFile().getUrl();
                        if (url != null) {
                            if (url.startsWith("jar://"))
                                url = url.substring(6);
                            ExternalResourceManager.getInstance().addResource(namespace, url);
                        }
                    } catch (Throwable ex) {
                        Notifications.Bus.notify(new Notification("Schema Provider", "Schema Provider", ex.toString(),
                                NotificationType.ERROR));
                    }
                }
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return locations;
}
 
Example 18
Source File: MuleSchemaProvider.java    From mule-intellij-plugins with Apache License 2.0 5 votes vote down vote up
@Override
@NotNull
public Set<String> getAvailableNamespaces(@NotNull XmlFile file, @Nullable String tagName) {
    final Module module = ModuleUtil.findModuleForPsiElement(file);
    Map<String, XmlFile> schemas = getSchemas(module);
    Set<String> namespaces = new HashSet<>();

    try {
        for (XmlFile xsd : schemas.values()) {
            final XmlDocument document = xsd.getDocument();
            if (document != null) {
                final PsiMetaData metaData = document.getMetaData();
                if (metaData instanceof XmlNSDescriptorImpl) {
                    XmlNSDescriptorImpl descriptor = (XmlNSDescriptorImpl) metaData;
                    String defaultNamespace = descriptor.getDefaultNamespace();

                    //Stupid HTTP module XSD weirdo
                    if (xsd.getName().contains("mule-httpn"))
                        defaultNamespace = "http://www.mulesoft.org/schema/mule/http";
                    /////

                    if (StringUtils.isNotEmpty(defaultNamespace)) {
                        if (StringUtils.isNotEmpty(tagName)) {
                            XmlElementDescriptor elementDescriptor = descriptor.getElementDescriptor(tagName, defaultNamespace);
                            if (elementDescriptor != null) {
                                namespaces.add(defaultNamespace);
                            }
                        } else {
                            namespaces.add(defaultNamespace);
                        }
                    }
                }
            }
        }
    } catch (Exception e) {
        //e.printStackTrace();
    }
    return namespaces;
}
 
Example 19
Source File: CSharpDocumentationProvider.java    From consulo-csharp with Apache License 2.0 4 votes vote down vote up
@RequiredReadAction
private static String generateQuickTypeDeclarationInfo(DotNetTypeDeclaration element, boolean isFullDocumentation)
{
	StringBuilder builder = new StringBuilder();

	if(isFullDocumentation)
	{
		PsiFile containingFile = element.getContainingFile();
		final ProjectFileIndex fileIndex = ProjectRootManager.getInstance(element.getProject()).getFileIndex();
		VirtualFile vFile = containingFile == null ? null : containingFile.getVirtualFile();
		if(vFile != null && (fileIndex.isInLibrarySource(vFile) || fileIndex.isInLibraryClasses(vFile)))
		{
			final List<OrderEntry> orderEntries = fileIndex.getOrderEntriesForFile(vFile);
			if(orderEntries.size() > 0)
			{
				final OrderEntry orderEntry = orderEntries.get(0);
				builder.append("[").append(StringUtil.escapeXml(orderEntry.getPresentableName())).append("] ");
			}
		}
		else
		{
			final Module module = containingFile == null ? null : ModuleUtil.findModuleForPsiElement(containingFile);
			if(module != null)
			{
				builder.append('[').append(module.getName()).append("] ");
			}
		}
	}

	String presentableParentQName = element.getPresentableParentQName();
	if(!StringUtil.isEmpty(presentableParentQName))
	{
		builder.append(presentableParentQName);
	}

	if(builder.length() > 0)
	{
		builder.append("<br>");
	}

	appendModifiers(element, builder);

	appendTypeDeclarationType(element, builder);

	builder.append(" ");

	appendName(element, builder, isFullDocumentation);

	return builder.toString();
}
 
Example 20
Source File: AddPantsTargetDependencyFix.java    From intellij-pants-plugin with Apache License 2.0 4 votes vote down vote up
@Override
public boolean isAvailable(@NotNull Project project, Editor editor, PsiFile file) {
  final Module module = ModuleUtil.findModuleForPsiElement(file);
  return module != null && PantsUtil.findBUILDFileForModule(module) != null;
}