com.intellij.openapi.module.ModuleUtil Java Examples

The following examples show how to use com.intellij.openapi.module.ModuleUtil. 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: ArmaPluginUserData.java    From arma-intellij-plugin with MIT License 6 votes vote down vote up
@Nullable
public XmlFile getStringTableXml(@NotNull PsiElement elementFromModule) {
	Module module = ModuleUtil.findModuleForPsiElement(elementFromModule);
	if (module == null) {
		return null;
	}
	ArmaPluginModuleData data = moduleMap.computeIfAbsent(module, module1 -> {
		return new ArmaPluginModuleData(module);
	});
	XmlFile f = data.getStringTableXmlFile();
	if (f == null) {
		VirtualFile virtFile = ArmaPluginUtil.getStringTableXmlFile(module);
		if (virtFile == null) {
			return null;
		}
		XmlFile file = (XmlFile) PsiManager.getInstance(elementFromModule.getProject()).findFile(virtFile);
		data.setStringTableXmlFile(file);
		return file;
	} else {
		if (!f.getVirtualFile().exists()) {
			data.setStringTableXmlFile(null);
			return null;
		}
		return f;
	}
}
 
Example #2
Source File: LogicalRootsManagerImpl.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Override
@Nullable
public LogicalRoot findLogicalRoot(@Nonnull final VirtualFile file) {
  final Module module = ModuleUtil.findModuleForFile(file, myProject);
  if (module == null) return null;

  LogicalRoot result = null;
  final List<LogicalRoot> list = getLogicalRoots(module);
  for (final LogicalRoot root : list) {
    final VirtualFile rootFile = root.getVirtualFile();
    if (rootFile != null && VfsUtil.isAncestor(rootFile, file, false)) {
      result = root;
      break;
    }
  }

  return result;
}
 
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: PsiPackageManagerImpl.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Nullable
private PsiPackage createPackageFromProviders(@Nonnull VirtualFile virtualFile,
                                              @Nonnull Class<? extends ModuleExtension> extensionClass,
                                              @Nonnull String qualifiedName) {
  final Module moduleForFile = ModuleUtil.findModuleForFile(virtualFile, myProject);
  if (moduleForFile == null) {
    return null;
  }

  ModuleRootManager moduleRootManager = ModuleRootManager.getInstance(moduleForFile);

  final ModuleExtension extension = moduleRootManager.getExtension(extensionClass);
  if (extension == null) {
    return null;
  }

  for (PsiPackageSupportProvider p : PsiPackageSupportProvider.EP_NAME.getExtensionList()) {
    if (p.isSupported(extension) && p.acceptVirtualFile(moduleForFile, virtualFile)) {
      return p.createPackage(myPsiManager, this, extensionClass, qualifiedName);
    }
  }
  return null;
}
 
Example #5
Source File: BazelRunConfig.java    From flutter-intellij with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@NotNull
@Override
public LaunchState getState(@NotNull Executor executor, @NotNull ExecutionEnvironment env) throws ExecutionException {
  final BazelFields launchFields = fields.copy();
  try {
    launchFields.checkRunnable(env.getProject());
  }
  catch (RuntimeConfigurationError e) {
    throw new ExecutionException(e);
  }

  final Workspace workspace = fields.getWorkspace(getProject());
  final VirtualFile workspaceRoot = workspace.getRoot();
  final RunMode mode = RunMode.fromEnv(env);
  final Module module = ModuleUtil.findModuleForFile(workspaceRoot, env.getProject());

  final LaunchState.CreateAppCallback createAppCallback = (@Nullable FlutterDevice device) -> {
    if (device == null) return null;

    final GeneralCommandLine command = getCommand(env, device);
    return FlutterApp.start(env, env.getProject(), module, mode, device, command,
                            StringUtil.capitalize(mode.mode()) + "BazelApp", "StopBazelApp");
  };

  return new LaunchState(env, workspaceRoot, workspaceRoot, this, createAppCallback);
}
 
Example #6
Source File: TestLaunchState.java    From flutter-intellij with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Nullable
@Override
protected ConsoleView createConsole(@NotNull Executor executor) throws ExecutionException {
  if (!testConsoleEnabled) {
    return super.createConsole(executor);
  }

  // Create a console showing a test tree.
  final Project project = getEnvironment().getProject();
  final DartUrlResolver resolver = DartUrlResolver.getInstance(project, testFileOrDir);
  final ConsoleProps props = ConsoleProps.forPub(config, executor, resolver);
  final BaseTestsOutputConsoleView console = SMTestRunnerConnectionUtil.createConsole(ConsoleProps.pubFrameworkName, props);

  final Module module = ModuleUtil.findModuleForFile(testFileOrDir, project);
  console.addMessageFilter(new DartConsoleFilter(project, getTestFileOrDir()));
  final String baseDir = getBaseDir();
  if (baseDir != null) {
    console.addMessageFilter(new DartRelativePathsConsoleFilter(project, baseDir));
  }
  console.addMessageFilter(new UrlFilter());

  return console;
}
 
Example #7
Source File: BazelRunConfig.java    From flutter-intellij with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@NotNull
@Override
public LaunchState getState(@NotNull Executor executor, @NotNull ExecutionEnvironment env) throws ExecutionException {
  final BazelFields launchFields = fields.copy();
  try {
    launchFields.checkRunnable(env.getProject());
  }
  catch (RuntimeConfigurationError e) {
    throw new ExecutionException(e);
  }

  final Workspace workspace = fields.getWorkspace(getProject());
  final VirtualFile workspaceRoot = workspace.getRoot();
  final RunMode mode = RunMode.fromEnv(env);
  final Module module = ModuleUtil.findModuleForFile(workspaceRoot, env.getProject());

  final LaunchState.CreateAppCallback createAppCallback = (@Nullable FlutterDevice device) -> {
    if (device == null) return null;

    final GeneralCommandLine command = getCommand(env, device);
    return FlutterApp.start(env, env.getProject(), module, mode, device, command,
                            StringUtil.capitalize(mode.mode()) + "BazelApp", "StopBazelApp");
  };

  return new LaunchState(env, workspaceRoot, workspaceRoot, this, createAppCallback);
}
 
Example #8
Source File: TestLaunchState.java    From flutter-intellij with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Nullable
@Override
protected ConsoleView createConsole(@NotNull Executor executor) throws ExecutionException {
  if (!testConsoleEnabled) {
    return super.createConsole(executor);
  }

  // Create a console showing a test tree.
  final Project project = getEnvironment().getProject();
  final DartUrlResolver resolver = DartUrlResolver.getInstance(project, testFileOrDir);
  final ConsoleProps props = ConsoleProps.forPub(config, executor, resolver);
  final BaseTestsOutputConsoleView console = SMTestRunnerConnectionUtil.createConsole(ConsoleProps.pubFrameworkName, props);

  final Module module = ModuleUtil.findModuleForFile(testFileOrDir, project);
  console.addMessageFilter(new DartConsoleFilter(project, getTestFileOrDir()));
  final String baseDir = getBaseDir();
  if (baseDir != null) {
    console.addMessageFilter(new DartRelativePathsConsoleFilter(project, baseDir));
  }
  console.addMessageFilter(new UrlFilter());

  return console;
}
 
Example #9
Source File: HaxeCompiler.java    From intellij-haxe with Apache License 2.0 6 votes vote down vote up
private static boolean compileModule(final CompileContext context,
                                     Module module,
                                     @NotNull final HaxeCommonCompilerUtil.CompilationContext compilationContext) {

  /*
  if ((skipBuildMap.get(module) != null) && (skipBuildMap.get(module).booleanValue())) {
    return false;
  }
  */

  if (!ModuleUtil.getModuleType(module).equals(HaxeModuleType.getInstance())) {
    return true;
  }

  boolean compiled = HaxeCommonCompilerUtil.compile(compilationContext);

  if (!compiled) {
    context.addMessage(CompilerMessageCategory.ERROR, "Compilation failed", null, 0, 0);
  }

  return compiled;
}
 
Example #10
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 #11
Source File: ArmaPluginUserData.java    From arma-intellij-plugin with MIT License 6 votes vote down vote up
@Nullable
public XmlFile getStringTableXml(@NotNull PsiElement elementFromModule) {
	Module module = ModuleUtil.findModuleForPsiElement(elementFromModule);
	if (module == null) {
		return null;
	}
	ArmaPluginModuleData data = moduleMap.computeIfAbsent(module, module1 -> {
		return new ArmaPluginModuleData(module);
	});
	XmlFile f = data.getStringTableXmlFile();
	if (f == null) {
		VirtualFile virtFile = ArmaPluginUtil.getStringTableXmlFile(module);
		if (virtFile == null) {
			return null;
		}
		XmlFile file = (XmlFile) PsiManager.getInstance(elementFromModule.getProject()).findFile(virtFile);
		data.setStringTableXmlFile(file);
		return file;
	} else {
		if (!f.getVirtualFile().exists()) {
			data.setStringTableXmlFile(null);
			return null;
		}
		return f;
	}
}
 
Example #12
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 #13
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 #14
Source File: VirtualFileTreeNode.java    From intellij-pants-plugin with Apache License 2.0 6 votes vote down vote up
@NotNull
@Override
public Collection<? extends AbstractTreeNode<?>> getChildren() {
  final PsiManager psiManager = PsiManager.getInstance(myProject);
  final VirtualFile virtualFile = getValue();
  return ContainerUtil.mapNotNull(
    virtualFile.isValid() && virtualFile.isDirectory() ? virtualFile.getChildren() : VirtualFile.EMPTY_ARRAY,
    new Function<VirtualFile, AbstractTreeNode<?>>() {
      @Override
      public AbstractTreeNode<?> fun(VirtualFile file) {
        final PsiElement psiElement = file.isDirectory() ? psiManager.findDirectory(file) : psiManager.findFile(file);
        if (psiElement instanceof PsiDirectory && ModuleUtil.findModuleForPsiElement(psiElement) != null) {
          // PsiDirectoryNode doesn't render files outside of a project
          // let's use PsiDirectoryNode only for folders in a modules
          return new PsiDirectoryNode(myProject, (PsiDirectory)psiElement, getSettings());
        }
        else if (psiElement instanceof PsiFile) {
          return new PsiFileNode(myProject, (PsiFile)psiElement, getSettings());
        }
        else {
          return shouldShow(file) ? new VirtualFileTreeNode(myProject, file, getSettings()) : null;
        }
      }
    }
  );
}
 
Example #15
Source File: ExtractSuperClassUtil.java    From intellij-haxe with Apache License 2.0 5 votes vote down vote up
public static void checkSuperAccessible(PsiDirectory targetDirectory, MultiMap<PsiElement, String> conflicts, final PsiClass subclass) {
  final VirtualFile virtualFile = subclass.getContainingFile().getVirtualFile();
  if (virtualFile != null) {
    final boolean inTestSourceContent = ProjectRootManager.getInstance(subclass.getProject()).getFileIndex().isInTestSourceContent(virtualFile);
    final Module module = ModuleUtil.findModuleForFile(virtualFile, subclass.getProject());
    if (targetDirectory != null &&
        module != null &&
        !GlobalSearchScope.moduleWithDependenciesAndLibrariesScope(module, inTestSourceContent).contains(targetDirectory.getVirtualFile())) {
      conflicts.putValue(subclass, "Superclass won't be accessible in subclass");
    }
  }
}
 
Example #16
Source File: Utils.java    From android-butterknife-zelezny with Apache License 2.0 5 votes vote down vote up
private static PsiFile resolveLayoutResourceFile(PsiElement element, Project project, String name) {
    // restricting the search to the current module - searching the whole project could return wrong layouts
    Module module = ModuleUtil.findModuleForPsiElement(element);
    PsiFile[] files = null;
    if (module != null) {
        // first omit libraries, it might cause issues like (#103)
        GlobalSearchScope moduleScope = module.getModuleWithDependenciesScope();
        files = FilenameIndex.getFilesByName(project, name, moduleScope);
        if (files == null || files.length <= 0) {
            // now let's do a fallback including the libraries
            moduleScope = module.getModuleWithDependenciesAndLibrariesScope(false);
            files = FilenameIndex.getFilesByName(project, name, moduleScope);
        }
    }
    if (files == null || files.length <= 0) {
        // fallback to search through the whole project
        // useful when the project is not properly configured - when the resource directory is not configured
        files = FilenameIndex.getFilesByName(project, name, new EverythingGlobalScope(project));
        if (files.length <= 0) {
            return null; //no matching files
        }
    }

    // TODO - we have a problem here - we still can have multiple layouts (some coming from a dependency)
    // we need to resolve R class properly and find the proper layout for the R class
    for (PsiFile file : files) {
        log.info("Resolved layout resource file for name [" + name + "]: " + file.getVirtualFile());
    }
    return files[0];
}
 
Example #17
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 #18
Source File: OneProjectItemCompileScope.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Nonnull
public Module[] getAffectedModules() {
  final Module module = ModuleUtil.findModuleForFile(myFile, myProject);
  if (module == null) {
    LOG.error("Module is null for file " + myFile.getPresentableUrl());
    return Module.EMPTY_ARRAY;
  }
  return new Module[] {module};
}
 
Example #19
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 #20
Source File: ModuleBasedConfiguration.java    From consulo with Apache License 2.0 5 votes vote down vote up
public void restoreOriginalModule(final Module originalModule) {
  if (originalModule == null) return;
  final Module[] classModules = getModules();
  final Set<Module> modules = new HashSet<Module>();
  for (Module classModule : classModules) {
    ModuleUtil.collectModulesDependsOn(classModule, modules);
  }
  if (modules.contains(originalModule)) setModule(originalModule);
}
 
Example #21
Source File: ModuleUtils.java    From EasyCode with MIT License 5 votes vote down vote up
/**
 * 获取模块的源代码文件夹,不存在
 *
 * @param module 模块对象
 * @return 文件夹路径
 */
public static VirtualFile getSourcePath(@NotNull Module module) {
    List<VirtualFile> virtualFileList = ModuleRootManager.getInstance(module).getSourceRoots(JavaSourceRootType.SOURCE);
    if (CollectionUtil.isEmpty(virtualFileList)) {
        return VirtualFileManager.getInstance().findFileByUrl(String.format("file://%s", ModuleUtil.getModuleDirPath(module)));
    }
    return virtualFileList.get(0);
}
 
Example #22
Source File: HaxelibProjectUpdater.java    From intellij-haxe with Apache License 2.0 5 votes vote down vote up
private void syncModuleClasspaths(final ProjectTracker tracker) {
  final HaxeDebugTimeLog timeLog = HaxeDebugTimeLog.startNew("syncModuleClasspaths");

  final Project project = tracker.getProject();

  //LOG.debug("Scanning project " + project.getName());
  timeLog.stamp("Scanning project " + project.getName());

  Collection<Module> modules = ModuleUtil.getModulesOfType(project, HaxeModuleType.getInstance());
  int i = 0;
  final int count = modules.size();
  for (final Module module : modules) {

    final int num = ++i;

    //LOG.debug("Scanning module " + (++i) + " of " + count + ": " + module.getName());
    timeLog.stamp("\nScanning module " + (num) + " of " + count + ": " + module.getName());

    if (myTestInForeground) {
      syncOneModule(tracker, module, timeLog);
    }
    else {
      // Running inside of a read action lets the UI run, and messes with the timing.
      doReadAction(new Runnable() {
        @Override
        public void run() {
          syncOneModule(tracker, module, timeLog);
        }
      });
    }
  }
  timeLog.stamp("Completed.");
  timeLog.print();
}
 
Example #23
Source File: FavoritesManager.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Override
public void beforePropertyChange(@Nonnull final PsiTreeChangeEvent event) {
  if (event.getPropertyName().equals(PsiTreeChangeEvent.PROP_FILE_NAME) || event.getPropertyName().equals(PsiTreeChangeEvent.PROP_DIRECTORY_NAME)) {
    final PsiElement psiElement = event.getChild();
    if (psiElement instanceof PsiFile || psiElement instanceof PsiDirectory) {
      final Module module = ModuleUtil.findModuleForPsiElement(psiElement);
      if (module == null) return;
      final String url = ((PsiDirectory)psiElement.getParent()).getVirtualFile().getUrl() + "/" + event.getNewValue();
      final AbstractUrl childUrl = psiElement instanceof PsiFile ? new PsiFileUrl(url) : new DirectoryUrl(url, module.getName());

      for (String listName : myName2FavoritesRoots.keySet()) {
        final List<TreeItem<Pair<AbstractUrl, String>>> roots = myName2FavoritesRoots.get(listName);
        iterateTreeItems(roots, new Consumer<TreeItem<Pair<AbstractUrl, String>>>() {
          @Override
          public void consume(TreeItem<Pair<AbstractUrl, String>> item) {
            final Pair<AbstractUrl, String> root = item.getData();
            final Object[] path = root.first.createPath(myProject);
            if (path == null || path.length < 1 || path[0] == null) {
              return;
            }
            final Object element = path[path.length - 1];
            if (element == psiElement && psiElement instanceof PsiFile) {
              item.setData(Pair.create(childUrl, root.second));
            }
            else {
              item.setData(root);
            }
          }
        });
      }
    }
  }
}
 
Example #24
Source File: GaugeUtil.java    From Intellij-Plugin with Apache License 2.0 5 votes vote down vote up
public static Module moduleForPsiElement(PsiElement element) {
    PsiFile file = element.getContainingFile();
    if (file == null) {
        return ModuleUtil.findModuleForPsiElement(element);
    }
    return ModuleUtil.findModuleForPsiElement(file);
}
 
Example #25
Source File: ExtractConceptRequest.java    From Intellij-Plugin with Apache License 2.0 5 votes vote down vote up
public Api.ExtractConceptResponse makeExtractConceptRequest(PsiElement element) {
    GaugeService gaugeService = Gauge.getGaugeService(ModuleUtil.findModuleForPsiElement(element), true);
    String message = "Cannot connect to gauge service.";
    if (gaugeService != null)
        try {
            return gaugeService.getGaugeConnection().sendGetExtractConceptRequest(steps, concept, refactorOtherUsages, fileName, textInfo);
        } catch (Exception ignored) {
            message = "Something went wrong during extract concept request.";
            LOG.debug(ignored);
        }
    return Api.ExtractConceptResponse.newBuilder().setIsSuccess(false).setError(message).build();
}
 
Example #26
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 #27
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 #28
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 #29
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 #30
Source File: ModuleRule.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Override
public Module getData(@Nonnull DataProvider dataProvider) {
  Module moduleContext = dataProvider.getDataUnchecked(LangDataKeys.MODULE_CONTEXT);
  if (moduleContext != null) {
    return moduleContext;
  }
  Project project = dataProvider.getDataUnchecked(CommonDataKeys.PROJECT);
  if (project == null) {
    PsiElement element = dataProvider.getDataUnchecked(LangDataKeys.PSI_ELEMENT);
    if (element == null || !element.isValid()) return null;
    project = element.getProject();
  }

  VirtualFile virtualFile = dataProvider.getDataUnchecked(PlatformDataKeys.VIRTUAL_FILE);
  if (virtualFile == null) {
    GetDataRule<VirtualFile> dataRule = ((BaseDataManager)DataManager.getInstance()).getDataRule(PlatformDataKeys.VIRTUAL_FILE);
    if (dataRule != null) {
      virtualFile = dataRule.getData(dataProvider);
    }
  }

  if (virtualFile == null) {
    return null;
  }

  return ModuleUtil.findModuleForFile(virtualFile, project);
}