private void appendChosenAnnotationsRoot(
     @NotNull final OrderEntry entry, @NotNull final VirtualFile vFile) {
   if (entry instanceof LibraryOrderEntry) {
     Library library = ((LibraryOrderEntry) entry).getLibrary();
     LOG.assertTrue(library != null);
     final ModifiableRootModel rootModel =
         ModuleRootManager.getInstance(entry.getOwnerModule()).getModifiableModel();
     final Library.ModifiableModel model = library.getModifiableModel();
     model.addRoot(vFile, AnnotationOrderRootType.getInstance());
     model.commit();
     rootModel.commit();
   } else if (entry instanceof ModuleSourceOrderEntry) {
     final ModifiableRootModel model =
         ModuleRootManager.getInstance(entry.getOwnerModule()).getModifiableModel();
     final JavaModuleExternalPaths extension =
         model.getModuleExtension(JavaModuleExternalPaths.class);
     extension.setExternalAnnotationUrls(
         ArrayUtil.mergeArrays(extension.getExternalAnnotationsUrls(), vFile.getUrl()));
     model.commit();
   } else if (entry instanceof JdkOrderEntry) {
     final SdkModificator sdkModificator = ((JdkOrderEntry) entry).getJdk().getSdkModificator();
     sdkModificator.addRoot(vFile, AnnotationOrderRootType.getInstance());
     sdkModificator.commitChanges();
   }
   myExternalAnnotations.clear();
 }
  public void testRemoveSourceRoot() {
    final VirtualFile root = ModuleRootManager.getInstance(myModule).getContentRoots()[0];

    PsiTodoSearchHelper.SERVICE
        .getInstance(myProject)
        .findFilesWithTodoItems(); // to initialize caches

    new WriteCommandAction.Simple(getProject()) {
      @Override
      protected void run() throws Throwable {
        VirtualFile newFile = createChildData(root, "New.java");
        setFileText(newFile, "class A{ Exception e;} //todo");
      }
    }.execute().throwException();

    PsiDocumentManager.getInstance(myProject).commitAllDocuments();

    PsiTodoSearchHelper.SERVICE.getInstance(myProject).findFilesWithTodoItems(); // to update caches

    VirtualFile[] sourceRoots = ModuleRootManager.getInstance(myModule).getSourceRoots();
    LOG.assertTrue(sourceRoots.length == 1);
    PsiTestUtil.removeSourceRoot(myModule, sourceRoots[0]);

    PsiClass exceptionClass =
        myJavaFacade.findClass("java.lang.Exception", GlobalSearchScope.allScope(getProject()));
    assertNotNull(exceptionClass);
    // currently it actually finds usages by FQN due to Java PSI enabled for out-of-source java
    // files
    // so the following check is disabled
    // checkUsages(exceptionClass, new String[]{});
    checkTodos(new String[] {"2.java", "New.java"});
  }
Example #3
0
 @Override
 @NotNull
 public Collection<AbstractTreeNode> getChildren() {
   Module module = getValue().getModule();
   final ModuleRootManager moduleRootManager = ModuleRootManager.getInstance(module);
   final List<AbstractTreeNode> children = new ArrayList<AbstractTreeNode>();
   final OrderEntry[] orderEntries = moduleRootManager.getOrderEntries();
   for (final OrderEntry orderEntry : orderEntries) {
     if (orderEntry instanceof LibraryOrderEntry) {
       final LibraryOrderEntry libraryOrderEntry = (LibraryOrderEntry) orderEntry;
       final Library library = libraryOrderEntry.getLibrary();
       if (library == null) {
         continue;
       }
       final String libraryName = library.getName();
       if (libraryName == null || libraryName.length() == 0) {
         addLibraryChildren(libraryOrderEntry, children, getProject(), this);
       } else {
         children.add(
             new NamedLibraryElementNode(
                 getProject(), new NamedLibraryElement(module, libraryOrderEntry), getSettings()));
       }
     } else if (orderEntry instanceof SdkOrderEntry) {
       final SdkOrderEntry sdkOrderEntry = (SdkOrderEntry) orderEntry;
       final Sdk jdk = sdkOrderEntry.getSdk();
       if (jdk != null) {
         children.add(
             new NamedLibraryElementNode(
                 getProject(), new NamedLibraryElement(module, sdkOrderEntry), getSettings()));
       }
     }
   }
   return children;
 }
  public static boolean checkSourceRootsConfigured(
      final Module module, final boolean askUserToSetupSourceRoots) {
    List<VirtualFile> sourceRoots =
        ModuleRootManager.getInstance(module).getSourceRoots(JavaModuleSourceRootTypes.SOURCES);
    if (sourceRoots.isEmpty()) {
      if (!askUserToSetupSourceRoots) {
        return false;
      }

      Project project = module.getProject();
      Messages.showErrorDialog(
          project,
          ProjectBundle.message("module.source.roots.not.configured.error", module.getName()),
          ProjectBundle.message("module.source.roots.not.configured.title"));

      ProjectSettingsService.getInstance(project)
          .showModuleConfigurationDialog(module.getName(), CommonContentEntriesEditor.NAME);

      sourceRoots =
          ModuleRootManager.getInstance(module).getSourceRoots(JavaModuleSourceRootTypes.SOURCES);
      if (sourceRoots.isEmpty()) {
        return false;
      }
    }
    return true;
  }
  protected void setupRootModel(
      final String testDir, final VirtualFile[] sourceDir, final String sdkName) {
    VirtualFile projectDir =
        LocalFileSystem.getInstance().refreshAndFindFileByIoFile(new File(testDir));
    assertNotNull("could not find project dir " + testDir, projectDir);
    sourceDir[0] = projectDir.findChild("src");
    if (sourceDir[0] == null) {
      sourceDir[0] = projectDir;
    }
    final ModuleRootManager rootManager = ModuleRootManager.getInstance(myModule);
    final ModifiableRootModel rootModel = rootManager.getModifiableModel();
    rootModel.clear();
    // configure source and output path
    final ContentEntry contentEntry = rootModel.addContentEntry(projectDir);
    contentEntry.addSourceFolder(sourceDir[0], false);
    ext_src =
        LocalFileSystem.getInstance().refreshAndFindFileByIoFile(new File(testDir + "/ext_src"));
    if (ext_src != null) {
      contentEntry.addSourceFolder(ext_src, false);
    }

    // IMPORTANT! The jdk must be obtained in a way it is obtained in the normal program!
    // ProjectJdkEx jdk = ProjectJdkTable.getInstance().getInternalJdk();

    rootModel.setSdk(getTestProjectSdk());

    rootModel.commit();
  }
  @NotNull
  public static Collection<String> collectPythonPath(
      @Nullable Module module, boolean addContentRoots, boolean addSourceRoots) {
    Collection<String> pythonPathList = Sets.newLinkedHashSet();
    if (module != null) {
      Set<Module> dependencies = new HashSet<Module>();
      ModuleUtilCore.getDependencies(module, dependencies);

      if (addContentRoots) {
        addRoots(pythonPathList, ModuleRootManager.getInstance(module).getContentRoots());
        for (Module dependency : dependencies) {
          addRoots(pythonPathList, ModuleRootManager.getInstance(dependency).getContentRoots());
        }
      }
      if (addSourceRoots) {
        addRoots(pythonPathList, ModuleRootManager.getInstance(module).getSourceRoots());
        for (Module dependency : dependencies) {
          addRoots(pythonPathList, ModuleRootManager.getInstance(dependency).getSourceRoots());
        }
      }

      addLibrariesFromModule(module, pythonPathList);
      addRootsFromModule(module, pythonPathList);
      for (Module dependency : dependencies) {
        addLibrariesFromModule(dependency, pythonPathList);
        addRootsFromModule(dependency, pythonPathList);
      }
    }
    return pythonPathList;
  }
  @NotNull
  public List<? extends LocalQuickFix> registerFixes(final FileReference reference) {
    final PsiElement element = reference.getElement();
    if (!(reference instanceof JSFlexFileReference)
        || !(element instanceof JSAttributeNameValuePair)) return Collections.emptyList();

    final PsiElement parent = element.getParent();
    if (!(parent instanceof JSAttribute)
        || !FlexAnnotationNames.EMBED.equals(((JSAttribute) parent).getName())) {
      return Collections.emptyList();
    }

    final String value = ((JSAttributeNameValuePair) element).getSimpleValue();
    if (value.startsWith("/")) return Collections.emptyList();

    final Module module = ModuleUtil.findModuleForPsiElement(element);
    if (module == null) return Collections.emptyList();

    final ModuleRootManager rootManager = ModuleRootManager.getInstance(module);
    final VirtualFile virtualFile = element.getContainingFile().getVirtualFile();
    final boolean testSourceRoot =
        virtualFile != null && rootManager.getFileIndex().isInTestSourceContent(virtualFile);

    for (VirtualFile sourceRoot : rootManager.getSourceRoots(testSourceRoot)) {
      if (sourceRoot.findFileByRelativePath(value) != null) {
        return Collections.singletonList(
            new AddLeadingSlashFix((JSAttributeNameValuePair) element));
      }
    }

    return Collections.emptyList();
  }
 @Nullable
 private Sdk getSdk() {
   if (myModule == null) {
     return ProjectRootManager.getInstance(myProject).getProjectSdk();
   }
   final ModuleRootManager rootManager = ModuleRootManager.getInstance(myModule);
   return rootManager.getSdk();
 }
  @NotNull
  private Map<VirtualFile, OrderEntry[]> getOrderEntries() {
    Map<VirtualFile, OrderEntry[]> result = myOrderEntries;
    if (result != null) return result;

    MultiMap<VirtualFile, OrderEntry> libClassRootEntries = MultiMap.createSmart();
    MultiMap<VirtualFile, OrderEntry> libSourceRootEntries = MultiMap.createSmart();
    MultiMap<VirtualFile, OrderEntry> depEntries = MultiMap.createSmart();

    for (final Module module : ModuleManager.getInstance(myProject).getModules()) {
      final ModuleRootManager moduleRootManager = ModuleRootManager.getInstance(module);
      for (OrderEntry orderEntry : moduleRootManager.getOrderEntries()) {
        if (orderEntry instanceof ModuleOrderEntry) {
          final Module depModule = ((ModuleOrderEntry) orderEntry).getModule();
          if (depModule != null) {
            VirtualFile[] importedClassRoots =
                OrderEnumerator.orderEntries(depModule)
                    .exportedOnly()
                    .recursively()
                    .classes()
                    .usingCache()
                    .getRoots();
            for (VirtualFile importedClassRoot : importedClassRoots) {
              depEntries.putValue(importedClassRoot, orderEntry);
            }
          }
          for (VirtualFile sourceRoot : orderEntry.getFiles(OrderRootType.SOURCES)) {
            depEntries.putValue(sourceRoot, orderEntry);
          }
        } else if (orderEntry instanceof LibraryOrSdkOrderEntry) {
          final LibraryOrSdkOrderEntry entry = (LibraryOrSdkOrderEntry) orderEntry;
          for (final VirtualFile sourceRoot : entry.getRootFiles(OrderRootType.SOURCES)) {
            libSourceRootEntries.putValue(sourceRoot, orderEntry);
          }
          for (final VirtualFile classRoot : entry.getRootFiles(OrderRootType.CLASSES)) {
            libClassRootEntries.putValue(classRoot, orderEntry);
          }
        }
      }
    }

    RootInfo rootInfo = buildRootInfo(myProject);
    result = ContainerUtil.newHashMap();
    Set<VirtualFile> allRoots = rootInfo.getAllRoots();
    for (VirtualFile file : allRoots) {
      List<VirtualFile> hierarchy = getHierarchy(file, allRoots, rootInfo);
      result.put(
          file,
          hierarchy == null
              ? OrderEntry.EMPTY_ARRAY
              : calcOrderEntries(
                  rootInfo, depEntries, libClassRootEntries, libSourceRootEntries, hierarchy));
    }
    myOrderEntries = result;
    return result;
  }
 private static boolean isTestDirectory(final Module module, final PsiElement element) {
   final PsiDirectory dir = (PsiDirectory) element;
   final ModuleRootManager manager = ModuleRootManager.getInstance(module);
   final ContentEntry[] entries = manager.getContentEntries();
   for (ContentEntry entry : entries) {
     for (SourceFolder folder : entry.getSourceFolders()) {
       if (folder.isTestSource() && folder.getFile() == dir.getVirtualFile()) {
         return true;
       }
     }
   }
   return false;
 }
  @Nullable
  private Pair<Set<String>, Set<String>> getAllRoots(boolean includeSourceRoots) {
    if (myProject.isDefault()) return null;

    final Set<String> recursive = new HashSet<String>();
    final Set<String> flat = new HashSet<String>();

    final String projectFilePath = myProject.getProjectFilePath();
    final File projectDirFile = new File(projectFilePath).getParentFile();
    if (projectDirFile != null && projectDirFile.getName().equals(Project.DIRECTORY_STORE_FOLDER)) {
      recursive.add(projectDirFile.getAbsolutePath());
    } else {
      flat.add(projectFilePath);
      final VirtualFile workspaceFile = myProject.getWorkspaceFile();
      if (workspaceFile != null) {
        flat.add(workspaceFile.getPath());
      }
    }

    for (WatchedRootsProvider extension :
        Extensions.getExtensions(WatchedRootsProvider.EP_NAME, myProject)) {
      recursive.addAll(extension.getRootsToWatch());
    }

    final Module[] modules = ModuleManager.getInstance(myProject).getModules();
    for (Module module : modules) {
      flat.add(module.getModuleFilePath());

      final ModuleRootManager moduleRootManager = ModuleRootManager.getInstance(module);

      addRootsToTrack(moduleRootManager.getContentRootUrls(), recursive, flat);

      if (includeSourceRoots) {
        addRootsToTrack(moduleRootManager.getSourceRootUrls(), recursive, flat);
      }

      final OrderEntry[] orderEntries = moduleRootManager.getOrderEntries();
      for (OrderEntry entry : orderEntries) {
        if (entry instanceof LibraryOrSdkOrderEntry) {
          final LibraryOrSdkOrderEntry libSdkEntry = (LibraryOrSdkOrderEntry) entry;
          for (OrderRootType orderRootType : OrderRootType.getAllTypes()) {
            addRootsToTrack(libSdkEntry.getRootUrls(orderRootType), recursive, flat);
          }
        }
      }
    }

    return Pair.create(recursive, flat);
  }
  public int compare(@NotNull VirtualFile file1, @NotNull VirtualFile file2) {
    List<OrderEntry> entries1 = myProjectFileIndex.getOrderEntriesForFile(file1);
    List<OrderEntry> entries2 = myProjectFileIndex.getOrderEntriesForFile(file2);
    if (entries1.size() != entries2.size()) return 0;

    int res = 0;
    for (OrderEntry entry1 : entries1) {
      Module module = entry1.getOwnerModule();
      ModuleFileIndex moduleFileIndex = ModuleRootManager.getInstance(module).getFileIndex();
      OrderEntry entry2 = moduleFileIndex.getOrderEntryForFile(file2);
      if (entry2 == null) {
        return 0;
      } else {
        int aRes = entry2.compareTo(entry1);
        if (aRes == 0) return 0;
        if (res == 0) {
          res = aRes;
        } else if (res != aRes) {
          return 0;
        }
      }
    }

    return res;
  }
 private void buildScopeModulesSet(Module module) {
   ModuleRootManager.getInstance(module)
       .orderEntries()
       .recursively()
       .compileOnly()
       .forEachModule(new CommonProcessors.CollectProcessor<Module>(myScopeModules));
 }
 @Override
 @NotNull
 public Collection<PsiFileSystemItem> getRoots(@NotNull final Module module) {
   return ContainerUtil.mapNotNull(
       ModuleRootManager.getInstance(module).getContentRoots(),
       virtualFile -> PsiManager.getInstance(module.getProject()).findDirectory(virtualFile));
 }
  private void buildEntries(
      @NotNull final Module module,
      @NotNull final Set<Module> processedModules,
      @NotNull final Set<Library> processedLibraries,
      @NotNull final Set<Sdk> processedSdk,
      Condition<OrderEntry> condition) {
    if (!processedModules.add(module)) return;

    ModuleRootManager.getInstance(module)
        .orderEntries()
        .recursively()
        .satisfying(condition)
        .process(
            new RootPolicy<LinkedHashSet<VirtualFile>>() {
              @Override
              public LinkedHashSet<VirtualFile> visitLibraryOrderEntry(
                  final LibraryOrderEntry libraryOrderEntry,
                  final LinkedHashSet<VirtualFile> value) {
                final Library library = libraryOrderEntry.getLibrary();
                if (library != null && processedLibraries.add(library)) {
                  ContainerUtil.addAll(
                      value, libraryOrderEntry.getFiles(BinariesOrderRootType.getInstance()));
                }
                return value;
              }

              @Override
              public LinkedHashSet<VirtualFile> visitModuleSourceOrderEntry(
                  final ModuleSourceOrderEntry moduleSourceOrderEntry,
                  final LinkedHashSet<VirtualFile> value) {
                processedModules.add(moduleSourceOrderEntry.getOwnerModule());
                ContainerUtil.addAll(value, moduleSourceOrderEntry.getRootModel().getSourceRoots());
                return value;
              }

              @Override
              public LinkedHashSet<VirtualFile> visitModuleOrderEntry(
                  ModuleOrderEntry moduleOrderEntry, LinkedHashSet<VirtualFile> value) {
                final Module depModule = moduleOrderEntry.getModule();
                if (depModule != null) {
                  ContainerUtil.addAll(
                      value, ModuleRootManager.getInstance(depModule).getSourceRoots());
                }
                return value;
              }

              @Override
              public LinkedHashSet<VirtualFile> visitModuleExtensionSdkOrderEntry(
                  final ModuleExtensionWithSdkOrderEntry sdkOrderEntry,
                  final LinkedHashSet<VirtualFile> value) {
                final Sdk jdk = sdkOrderEntry.getSdk();
                if (jdk != null && processedSdk.add(jdk)) {
                  ContainerUtil.addAll(
                      value, sdkOrderEntry.getFiles(BinariesOrderRootType.getInstance()));
                }
                return value;
              }
            },
            myEntries);
  }
  @Override
  public VirtualFile[] getSourceRoots(Module module) {
    VirtualFile[] cachedRoots = myModuleToRootsCache.get(module);
    if (cachedRoots != null) {
      if (areFilesValid(cachedRoots)) {
        return cachedRoots;
      } else {
        myModuleToRootsCache.remove(
            module); // clear cache for this module and rebuild list of roots
      }
    }

    Set<VirtualFile> additionalRoots = myModuleToRootsMap.get(module);
    VirtualFile[] moduleRoots = ModuleRootManager.getInstance(module).getSourceRoots();
    if (additionalRoots == null || additionalRoots.isEmpty()) {
      myModuleToRootsCache.put(module, moduleRoots);
      return moduleRoots;
    }

    final VirtualFile[] allRoots = new VirtualFile[additionalRoots.size() + moduleRoots.length];
    System.arraycopy(moduleRoots, 0, allRoots, 0, moduleRoots.length);
    int index = moduleRoots.length;
    for (final VirtualFile additionalRoot : additionalRoots) {
      allRoots[index++] = additionalRoot;
    }
    myModuleToRootsCache.put(module, allRoots);
    return allRoots;
  }
  public boolean tryToSetUpGroovyFacetOnTheFly(final Module module) {
    final Project project = module.getProject();
    final Library[] libraries = getAllSDKLibraries(project);
    if (libraries.length > 0) {
      final Library library = libraries[0];
      int result =
          Messages.showOkCancelDialog(
              GroovyBundle.message(
                  "groovy.like.library.found.text",
                  module.getName(),
                  library.getName(),
                  getSDKLibVersion(library)),
              GroovyBundle.message("groovy.like.library.found"),
              JetgroovyIcons.Groovy.Groovy_32x32);
      if (result == Messages.OK) {
        AccessToken accessToken = WriteAction.start();

        try {
          ModifiableRootModel model = ModuleRootManager.getInstance(module).getModifiableModel();
          LibraryOrderEntry entry = model.addLibraryEntry(libraries[0]);
          LibrariesUtil.placeEntryToCorrectPlace(model, entry);
          model.commit();
          return true;
        } finally {
          accessToken.finish();
        }
      }
    }
    return false;
  }
Example #18
0
  public void collectCommonPluginRoots(
      Map<String, VirtualFile> result, @NotNull Module module, boolean refresh) {
    if (isCommonPluginsModule(module)) {
      for (VirtualFile root : ModuleRootManager.getInstance(module).getContentRoots()) {
        String pluginName = getInstalledPluginNameByPath(module.getProject(), root);
        if (pluginName != null) {
          result.put(pluginName, root);
        }
      }
    } else {
      VirtualFile root = findAppRoot(module);
      if (root == null) return;

      extractPlugins(
          module.getProject(), root.findChild(MvcModuleStructureUtil.PLUGINS_DIRECTORY), result);
      extractPlugins(
          module.getProject(),
          MvcModuleStructureUtil.findFile(getCommonPluginsDir(module), refresh),
          result);
      extractPlugins(
          module.getProject(),
          MvcModuleStructureUtil.findFile(getGlobalPluginsDir(module), refresh),
          result);
    }
  }
  private Set<VirtualFile> enumerateGroovyFiles(final Module module) {
    final Set<VirtualFile> moduleClasses = new THashSet<VirtualFile>();
    ModuleRootManager.getInstance(module)
        .getFileIndex()
        .iterateContent(
            new ContentIterator() {
              public boolean processFile(final VirtualFile vfile) {
                if (!vfile.isDirectory()
                    && GroovyFileType.GROOVY_FILE_TYPE.equals(vfile.getFileType())) {

                  AccessToken accessToken =
                      ApplicationManager.getApplication().acquireReadActionLock();

                  try {
                    if (PsiManager.getInstance(myProject).findFile(vfile) instanceof GroovyFile) {
                      moduleClasses.add(vfile);
                    }
                  } finally {
                    accessToken.finish();
                  }
                }
                return true;
              }
            });
    return moduleClasses;
  }
  private void initPubListPackageDirsMap(final @NotNull VirtualFile contextFile) {
    final Module module = ModuleUtilCore.findModuleForFile(contextFile, myProject);

    final List<OrderEntry> orderEntries =
        module != null
            ? Arrays.asList(ModuleRootManager.getInstance(module).getOrderEntries())
            : ProjectRootManager.getInstance(myProject)
                .getFileIndex()
                .getOrderEntriesForFile(contextFile);
    for (OrderEntry orderEntry : orderEntries) {
      if (orderEntry instanceof LibraryOrderEntry
          && LibraryTablesRegistrar.PROJECT_LEVEL.equals(
              ((LibraryOrderEntry) orderEntry).getLibraryLevel())
          && PubListPackageDirsAction.PUB_LIST_PACKAGE_DIRS_LIB_NAME.equals(
              ((LibraryOrderEntry) orderEntry).getLibraryName())) {
        final LibraryEx library = (LibraryEx) ((LibraryOrderEntry) orderEntry).getLibrary();
        final LibraryProperties properties = library == null ? null : library.getProperties();

        if (properties instanceof DartListPackageDirsLibraryProperties) {
          myPubListPackageDirsMap.putAll(
              ((DartListPackageDirsLibraryProperties) properties).getPackageNameToDirsMap());
          return;
        }
      }
    }
  }
  @NotNull
  private static String getPresentableElementPosition(
      @NotNull final CodeInsightTestFixture fixture, final @Nullable PsiElement element) {
    if (element == null) return "";

    final StringBuilder buf = new StringBuilder(element.getText());
    DartComponent component = PsiTreeUtil.getParentOfType(element, DartComponent.class);
    while (component != null) {
      final DartComponentName componentName = component.getComponentName();
      if (componentName != null && componentName != element) {
        buf.insert(0, component.getName() + " -> ");
      }
      component = PsiTreeUtil.getParentOfType(component, DartComponent.class);
    }
    String path =
        element instanceof PsiDirectoryImpl
            ? ((PsiDirectoryImpl) element).getVirtualFile().getPath()
            : element.getContainingFile().getVirtualFile().getPath();

    final String contentRoot =
        ModuleRootManager.getInstance(fixture.getModule()).getContentRoots()[0].getPath();
    if (path.equals(contentRoot)) path = "[content root]";

    final String contentRootWithSlash = contentRoot + "/";
    if (path.startsWith(contentRootWithSlash)) path = path.substring(contentRootWithSlash.length());

    final DartSdk sdk = DartSdk.getDartSdk(element.getProject());
    if (sdk != null && path.startsWith(sdk.getHomePath()))
      path = "[Dart SDK]" + path.substring(sdk.getHomePath().length());

    if (buf.length() > 0) buf.insert(0, " -> ");
    buf.insert(0, path);

    return buf.toString();
  }
Example #22
0
  public boolean isEnabled(AnActionEvent e) {
    PsiElement psiElement = e.getData(LangDataKeys.PSI_ELEMENT);
    if (psiElement == null || !(psiElement instanceof PsiDirectory)) {
      // Can be used only on package
      return false;
    }
    VirtualFile targetDir = ((PsiDirectory) psiElement).getVirtualFile();

    boolean isUnderSourceRoot = false;
    if (psiElement instanceof MPSPsiModel) {
      isUnderSourceRoot = true;
    } else {
      Module m = e.getData(LangDataKeys.MODULE);
      VirtualFile[] sourceRoots = ModuleRootManager.getInstance(m).getSourceRoots(true);
      for (VirtualFile root : sourceRoots) {
        if (targetDir.getPath().equals(root.getPath())) {
          // Can't be source or test folder
          return false;
        }
        isUnderSourceRoot =
            isUnderSourceRoot || FileUtil.isSubPath(root.getPath(), targetDir.getPath());
      }
    }

    return isUnderSourceRoot
        && myOperationContext != null
        && (myModelDescriptor != null || myNewModel)
        && myProject != null;
  }
 @Nullable
 protected VirtualFile findClassFile(String className) {
   final CompilerModuleExtension extension =
       ModuleRootManager.getInstance(myModule).getModuleExtension(CompilerModuleExtension.class);
   //noinspection ConstantConditions
   return extension.getCompilerOutputPath().findChild(className + ".class");
 }
Example #24
0
  @Override
  public Iterable<SDependency> getDeclaredDependencies() {
    if (myDependencies == null) {
      myDependencies = new ArrayList<SDependency>();

      ArrayList<Module> usedModules =
          new ArrayList<Module>(
              Arrays.asList(ModuleRootManager.getInstance(myModule).getDependencies()));
      for (Module usedModule : usedModules) {
        MPSFacet usedModuleMPSFacet =
            FacetManager.getInstance(usedModule).getFacetByType(MPSFacetType.ID);
        if (usedModuleMPSFacet != null && usedModuleMPSFacet.wasInitialized()) {
          myDependencies.add(
              new SDependencyImpl(
                  usedModuleMPSFacet.getSolution(), SDependencyScope.DEFAULT, false));
        }
      }

      addUsedSdk(myDependencies);
      addUsedLibraries(myDependencies);

      // adding JDK module to a set of dependencies
      // why, oh, why are we doing it?
      // FIXME, PLEASE!
      //      Solution jdkSolution = StubSolutionIdea.getJdkSolution();
      //      if (jdkSolution != null) {
      //        myDependencies.add(new Dependency(jdkSolution.getModuleReference(), false));
      //      }
    }
    return myDependencies;
  }
 public OrderEntry[] getOrderEntries() {
   if (myModifiableRootModel == null) { // do not clone all model if not necessary
     return ModuleRootManager.getInstance(getModule()).getOrderEntries();
   } else {
     return myModifiableRootModel.getOrderEntries();
   }
 }
  private void createTreeModel() {
    final PsiManager psiManager = PsiManager.getInstance(myProject);
    final FileIndex fileIndex =
        myModule != null
            ? ModuleRootManager.getInstance(myModule).getFileIndex()
            : ProjectRootManager.getInstance(myProject).getFileIndex();
    fileIndex.iterateContent(
        new ContentIterator() {
          public boolean processFile(VirtualFile fileOrDir) {
            if (fileOrDir.isDirectory() && fileIndex.isInSourceContent(fileOrDir)) {
              final PsiDirectory psiDirectory = psiManager.findDirectory(fileOrDir);
              LOG.assertTrue(psiDirectory != null);
              PsiPackage aPackage = JavaDirectoryService.getInstance().getPackage(psiDirectory);
              if (aPackage != null) {
                addPackage(aPackage);
              }
            }
            return true;
          }
        });

    TreeUtil.sort(
        myModel,
        new Comparator() {
          public int compare(Object o1, Object o2) {
            DefaultMutableTreeNode n1 = (DefaultMutableTreeNode) o1;
            DefaultMutableTreeNode n2 = (DefaultMutableTreeNode) o2;
            PsiNamedElement element1 = (PsiNamedElement) n1.getUserObject();
            PsiNamedElement element2 = (PsiNamedElement) n2.getUserObject();
            return element1.getName().compareToIgnoreCase(element2.getName());
          }
        });
  }
  public AddModuleDependencyFix(
      Module currentModule, VirtualFile classVFile, PsiClass[] classes, PsiReference reference) {
    final PsiElement psiElement = reference.getElement();
    final Project project = psiElement.getProject();
    final JavaPsiFacade facade = JavaPsiFacade.getInstance(project);
    final ProjectFileIndex fileIndex = ProjectRootManager.getInstance(project).getFileIndex();

    for (PsiClass aClass : classes) {
      if (!facade.getResolveHelper().isAccessible(aClass, psiElement, aClass)) continue;
      PsiFile psiFile = aClass.getContainingFile();
      if (psiFile == null) continue;
      VirtualFile virtualFile = psiFile.getVirtualFile();
      if (virtualFile == null) continue;
      final Module classModule = fileIndex.getModuleForFile(virtualFile);
      if (classModule != null
          && classModule != currentModule
          && !ModuleRootManager.getInstance(currentModule).isDependsOn(classModule)) {
        myModules.add(classModule);
      }
    }
    myCurrentModule = currentModule;
    myClassVFile = classVFile;
    myClasses = classes;
    myReference = reference;
  }
 private static String setCompilerOutput(Module module, String path, boolean testOutput) {
   VirtualFile output =
       ModuleRootManager.getInstance(module).getContentEntries()[0].getFile().findChild(path);
   assertNotNull(output);
   PsiTestUtil.setCompilerOutputPath(module, output.getUrl(), testOutput);
   return output.getPath().replace('/', File.separatorChar);
 }
  private void attachLibraries(
      @NotNull Collection<VirtualFile> libraryRoots, Set<VirtualFile> exclusions) {
    ApplicationManager.getApplication().assertIsDispatchThread();

    if (!libraryRoots.isEmpty()) {
      ApplicationManager.getApplication()
          .runWriteAction(
              () -> {
                ModuleRootManager model = ModuleRootManager.getInstance(myModule);
                LibraryOrderEntry goLibraryEntry =
                    OrderEntryUtil.findLibraryOrderEntry(model, getLibraryName());

                if (goLibraryEntry != null && goLibraryEntry.isValid()) {
                  Library library = goLibraryEntry.getLibrary();
                  if (library != null && !((LibraryEx) library).isDisposed()) {
                    fillLibrary(library, libraryRoots, exclusions);
                  }
                } else {
                  LibraryTable libraryTable =
                      LibraryTablesRegistrar.getInstance().getLibraryTable(myModule.getProject());
                  Library library = libraryTable.createLibrary(getLibraryName());
                  fillLibrary(library, libraryRoots, exclusions);
                  ModuleRootModificationUtil.addDependency(myModule, library);
                }
              });
      showNotification(myModule.getProject());
    } else {
      removeLibraryIfNeeded();
    }
  }
  private void calculateRoots() {
    final ModuleManager moduleManager = ModuleManager.getInstance(myProject);
    // assertion for read access inside
    final Module[] modules =
        ApplicationManager.getApplication()
            .runReadAction(
                new Computable<Module[]>() {
                  public Module[] compute() {
                    return moduleManager.getModules();
                  }
                });

    final TreeSet<VirtualFile> checkSet =
        new TreeSet<VirtualFile>(FilePathComparator.getInstance());
    myRoots = new HashSet<VirtualFile>();
    myRoots.addAll(myInitialRoots);
    checkSet.addAll(myInitialRoots);
    for (Module module : modules) {
      final VirtualFile[] files = ModuleRootManager.getInstance(module).getContentRoots();
      for (VirtualFile file : files) {
        final VirtualFile floor = checkSet.floor(file);
        if (floor != null) {
          myModulesSet.put(file, module.getName());
          myRoots.add(file);
        }
      }
    }
  }