com.intellij.openapi.roots.ex.ProjectRootManagerEx Java Examples

The following examples show how to use com.intellij.openapi.roots.ex.ProjectRootManagerEx. 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: UnindexedFilesUpdater.java    From consulo with Apache License 2.0 6 votes vote down vote up
private void scheduleInitialVfsRefresh() {
  ProjectRootManagerEx.getInstanceEx(myProject).markRootsForRefresh();

  Application app = ApplicationManager.getApplication();
  if (!app.isCommandLine()) {
    long sessionId = VirtualFileManager.getInstance().asyncRefresh(null);
    MessageBusConnection connection = app.getMessageBus().connect();
    connection.subscribe(ProjectManager.TOPIC, new ProjectManagerListener() {
      @Override
      public void projectClosed(@Nonnull Project project, @Nonnull UIAccess uiAccess) {
        if (project == myProject) {
          RefreshQueue.getInstance().cancelSession(sessionId);
          connection.disconnect();
        }
      }
    });
  }
  else {
    VirtualFileManager.getInstance().syncRefresh();
  }
}
 
Example #2
Source File: EnforcedPlainTextFileTypeManager.java    From consulo with Apache License 2.0 6 votes vote down vote up
private static void fireRootsChanged(final Collection<VirtualFile> files, final boolean isAdded) {
  ApplicationManager.getApplication().runWriteAction(new Runnable() {
    @Override
    public void run() {
      for (Project project : ProjectManager.getInstance().getOpenProjects()) {
        ProjectRootManagerEx.getInstanceEx(project).makeRootsChange(EmptyRunnable.getInstance(), false, true);
        ProjectPlainTextFileTypeManager projectPlainTextFileTypeManager = ProjectPlainTextFileTypeManager.getInstance(project);
        for (VirtualFile file : files) {
          if (projectPlainTextFileTypeManager.hasProjectContaining(file)) {
            if (isAdded) {
              projectPlainTextFileTypeManager.addFile(file);
            }
            else {
              projectPlainTextFileTypeManager.removeFile(file);
            }
          }
        }
      }
    }
  });
}
 
Example #3
Source File: BlazeAndroidSyncPlugin.java    From intellij with Apache License 2.0 6 votes vote down vote up
private static void setProjectSdkAndLanguageLevel(
    final Project project, final Sdk sdk, final LanguageLevel javaLanguageLevel) {
  UIUtil.invokeAndWaitIfNeeded(
      (Runnable)
          () ->
              ApplicationManager.getApplication()
                  .runWriteAction(
                      () -> {
                        ProjectRootManagerEx rootManager =
                            ProjectRootManagerEx.getInstanceEx(project);
                        rootManager.setProjectSdk(sdk);
                        LanguageLevelProjectExtension ext =
                            LanguageLevelProjectExtension.getInstance(project);
                        ext.setLanguageLevel(javaLanguageLevel);
                      }));
}
 
Example #4
Source File: BlazeAndroidSyncPluginTest.java    From intellij with Apache License 2.0 6 votes vote down vote up
@Test
public void testUpdateProjectSdkWithoutSyncData() {
  // Setup.
  BlazeProjectData blazeProjectData =
      MockBlazeProjectDataBuilder.builder(workspaceRoot)
          .setWorkspaceLanguageSettings(
              new WorkspaceLanguageSettings(WorkspaceType.ANDROID, ImmutableSet.of()))
          .build();

  // Perform.
  syncPlugin.updateProjectSdk(project, context, projectViewSet, null, blazeProjectData);

  // Verify.
  ProjectRootManagerEx rootManager = ProjectRootManagerEx.getInstanceEx(project);
  LanguageLevel languageLevel =
      LanguageLevelProjectExtension.getInstance(project).getLanguageLevel();

  // Even when sync data is null, the project sdk should still be available.
  assertThat(rootManager.getProjectSdk().getName()).isEqualTo("android-sdk-28");
  assertThat(languageLevel).isEqualTo(LanguageLevel.JDK_1_8);
}
 
Example #5
Source File: BlazeAndroidSyncPluginTest.java    From intellij with Apache License 2.0 6 votes vote down vote up
@Test
public void testUpdateProjectSdkWithoutSyncDataDoesNotOverrideSdkIfOneAlreadyExists() {
  // Setup.
  BlazeProjectData blazeProjectData =
      MockBlazeProjectDataBuilder.builder(workspaceRoot)
          .setWorkspaceLanguageSettings(
              new WorkspaceLanguageSettings(WorkspaceType.ANDROID, ImmutableSet.of()))
          .build();
  ProjectRootManagerEx.getInstanceEx(project)
      .setProjectSdk(BlazeSdkProvider.getInstance().findSdk(MOCK_ANDROID_SDK_TARGET_HASH_26));

  // Perform.
  syncPlugin.updateProjectSdk(project, context, projectViewSet, null, blazeProjectData);

  // Verify.
  ProjectRootManagerEx rootManager = ProjectRootManagerEx.getInstanceEx(project);
  LanguageLevel languageLevel =
      LanguageLevelProjectExtension.getInstance(project).getLanguageLevel();

  // Even when sync data is null, the project sdk should still be available.  In this case
  // an sdk is already available, so it's not reset from project view.
  assertThat(rootManager.getProjectSdk().getName()).isEqualTo("android-sdk-26");
  assertThat(languageLevel).isNull();
}
 
Example #6
Source File: ExternalSystemAutoImporter.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Override
public void onSuccess(@javax.annotation.Nullable final DataNode<ProjectData> externalProject) {
  if (externalProject != null) {
    ExternalSystemApiUtil.executeProjectChangeAction(new DisposeAwareProjectChange(myProject) {
      @RequiredUIAccess
      @Override
      public void execute() {
        ProjectRootManagerEx.getInstanceEx(myProject).mergeRootsChangesDuring(new Runnable() {
          @Override
          public void run() {
            myProjectDataManager.importData(externalProject.getKey(), Collections.singleton(externalProject), myProject, true);
          }
        });
      }
    });
  }
}
 
Example #7
Source File: PantsSdkUtil.java    From intellij-pants-plugin with Apache License 2.0 6 votes vote down vote up
public static void refreshJdk(Project project, Sdk originalSdk, Disposable disposable) {
  String pantsExecutable = PantsUtil.findPantsExecutable(project)
    .map(VirtualFile::getPath)
    .orElse(null);

  if (pantsExecutable == null) {
    return;
  }

  if (originalSdk != null && originalSdk.getName().endsWith(pantsExecutable)) {
    PantsSdkUtil.createPantsJdk(pantsExecutable)
      .ifPresent(newSdk -> PantsSdkUtil.updateJdk(originalSdk, newSdk));
  }
  else {
    PantsSdkUtil.getDefaultJavaSdk(pantsExecutable, disposable)
      .ifPresent(defaultSdk -> {
        ApplicationManager.getApplication().invokeAndWait(() -> {
          ApplicationManager.getApplication().runWriteAction(() -> {
            ProjectRootManagerEx.getInstanceEx(project).setProjectSdk(defaultSdk);
          });
        });
      });
  }
}
 
Example #8
Source File: DeviceService.java    From flutter-intellij with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
private DeviceService(@NotNull final Project project) {
  this.project = project;

  deviceDaemon.setDisposeParent(project);
  deviceDaemon.subscribe(this::refreshDeviceSelection);
  refreshDeviceDaemon();

  // Watch for Flutter SDK changes.
  final FlutterSdkManager.Listener sdkListener = new FlutterSdkManager.Listener() {
    @Override
    public void flutterSdkAdded() {
      refreshDeviceDaemon();
    }

    @Override
    public void flutterSdkRemoved() {
      refreshDeviceDaemon();
    }
  };
  FlutterSdkManager.getInstance(project).addListener(sdkListener);
  Disposer.register(project, () -> FlutterSdkManager.getInstance(project).removeListener(sdkListener));

  // Watch for Bazel workspace changes.
  WorkspaceCache.getInstance(project).subscribe(this::refreshDeviceDaemon);

  // Watch for Java SDK changes. (Used to get the value of ANDROID_HOME.)
  ProjectRootManagerEx.getInstanceEx(project).addProjectJdkListener(this::refreshDeviceDaemon);
}
 
Example #9
Source File: ExternalSystemUtil.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Override
public void onSuccess(@Nullable final DataNode<ProjectData> externalProject) {
  if (externalProject == null) {
    return;
  }
  Collection<DataNode<ModuleData>> moduleNodes = ExternalSystemApiUtil.findAll(externalProject, ProjectKeys.MODULE);
  for (DataNode<ModuleData> node : moduleNodes) {
    myExternalModulePaths.add(node.getData().getLinkedExternalProjectPath());
  }
  ExternalSystemApiUtil.executeProjectChangeAction(true, new DisposeAwareProjectChange(myProject) {
    @RequiredUIAccess
    @Override
    public void execute() {
      ProjectRootManagerEx.getInstanceEx(myProject).mergeRootsChangesDuring(new Runnable() {
        @Override
        public void run() {
          myProjectDataManager.importData(externalProject.getKey(), Collections.singleton(externalProject), myProject, true);
        }
      });

      processOrphanProjectLibraries();
    }
  });
  if (--myCounter[0] <= 0) {
    processOrphanModules();
  }
}
 
Example #10
Source File: AbstractExternalModuleImportProvider.java    From consulo with Apache License 2.0 5 votes vote down vote up
/**
 * The whole import sequence looks like below:
 * <p>
 * <pre>
 * <ol>
 *   <li>Get project view from the gradle tooling api without resolving dependencies (downloading libraries);</li>
 *   <li>Allow to adjust project settings before importing;</li>
 *   <li>Create IJ project and modules;</li>
 *   <li>Ask gradle tooling api to resolve library dependencies (download the if necessary);</li>
 *   <li>Configure libraries used by the gradle project at intellij;</li>
 *   <li>Configure library dependencies;</li>
 * </ol>
 * </pre>
 * <p>
 *
 * @param projectWithResolvedLibraries gradle project with resolved libraries (libraries have already been downloaded and
 *                                     are available at file system under gradle service directory)
 * @param project                      current intellij project which should be configured by libraries and module library
 *                                     dependencies information available at the given gradle project
 */
private void setupLibraries(@Nonnull final DataNode<ProjectData> projectWithResolvedLibraries, final Project project) {
  ExternalSystemApiUtil.executeProjectChangeAction(new DisposeAwareProjectChange(project) {
    @RequiredUIAccess
    @Override
    public void execute() {
      ProjectRootManagerEx.getInstanceEx(project).mergeRootsChangesDuring(new Runnable() {
        @Override
        public void run() {
          if (ExternalSystemApiUtil.isNewProjectConstruction()) {
            // Clean existing libraries (if any).
            LibraryTable projectLibraryTable = ProjectLibraryTable.getInstance(project);
            if (projectLibraryTable == null) {
              LOG.warn("Can't resolve external dependencies of the target gradle project (" + project + "). Reason: project " + "library table is undefined");
              return;
            }
            LibraryTable.ModifiableModel model = projectLibraryTable.getModifiableModel();
            try {
              for (Library library : model.getLibraries()) {
                model.removeLibrary(library);
              }
            }
            finally {
              model.commit();
            }
          }

          // Register libraries.
          myProjectDataManager.importData(Collections.<DataNode<?>>singletonList(projectWithResolvedLibraries), project, false);
        }
      });
    }
  });
}
 
Example #11
Source File: BlazeJavaSyncPlugin.java    From intellij with Apache License 2.0 5 votes vote down vote up
private static void setProjectSdkAndLanguageLevel(
    final Project project, final Sdk sdk, final LanguageLevel javaLanguageLevel) {
  Transactions.submitWriteActionTransactionAndWait(
      () -> {
        ProjectRootManagerEx rootManager = ProjectRootManagerEx.getInstanceEx(project);
        rootManager.setProjectSdk(sdk);
        LanguageLevelProjectExtension ext = LanguageLevelProjectExtension.getInstance(project);
        ext.setLanguageLevel(javaLanguageLevel);
      });
}
 
Example #12
Source File: BlazeAndroidSyncPluginTest.java    From intellij with Apache License 2.0 5 votes vote down vote up
@Test
public void testUpdateProjectSdkWithSyncData() {
  // Setup.
  SyncState syncStateWithAndroidSdk26AndJava9 =
      new SyncState.Builder()
          .put(new BlazeAndroidSyncData(null, new AndroidSdkPlatform("android-26", 0)))
          .put(
              new BlazeJavaSyncData(
                  BlazeJavaImportResult.builder()
                      .setContentEntries(ImmutableList.of())
                      .setLibraries(ImmutableMap.of())
                      .setBuildOutputJars(ImmutableList.of())
                      .setJavaSourceFiles(ImmutableSet.of())
                      .setSourceVersion("9")
                      .setEmptyJarTracker(EmptyJarTracker.builder().build())
                      .build(),
                  null))
          .build();

  BlazeProjectData blazeProjectData =
      MockBlazeProjectDataBuilder.builder(workspaceRoot)
          .setWorkspaceLanguageSettings(
              new WorkspaceLanguageSettings(WorkspaceType.ANDROID, ImmutableSet.of()))
          .setSyncState(syncStateWithAndroidSdk26AndJava9)
          .build();

  // Perform.
  syncPlugin.updateProjectSdk(project, context, projectViewSet, null, blazeProjectData);

  // Verify.
  ProjectRootManagerEx rootManager = ProjectRootManagerEx.getInstanceEx(project);
  LanguageLevel languageLevel =
      LanguageLevelProjectExtension.getInstance(project).getLanguageLevel();

  // Should return android-26 even though project view says android-28 because data returned from
  // sync takes higher priority.
  assertThat(rootManager.getProjectSdk().getName()).isEqualTo("android-sdk-26");
  // Defaults to JDK 1.8, but sync result specifies 1.9, which takes higher priority.
  assertThat(languageLevel).isEqualTo(LanguageLevel.JDK_1_9);
}
 
Example #13
Source File: BlazeAndroidSyncPlugin.java    From intellij with Apache License 2.0 5 votes vote down vote up
@Override
public void updateProjectSdk(
    Project project,
    BlazeContext context,
    ProjectViewSet projectViewSet,
    BlazeVersionData blazeVersionData,
    BlazeProjectData blazeProjectData) {
  if (!isAndroidWorkspace(blazeProjectData.getWorkspaceLanguageSettings())) {
    return;
  }
  AndroidSdkPlatform androidSdkPlatform = null;
  BlazeAndroidSyncData syncData = blazeProjectData.getSyncState().get(BlazeAndroidSyncData.class);
  if (syncData != null) {
    androidSdkPlatform = syncData.androidSdkPlatform;
  } else if (ProjectRootManagerEx.getInstanceEx(project).getProjectSdk() == null) {
    // If syncData is null then this could have been a directory only sync.  In this case,
    // calculate
    // the androidSdkPlatform directly from project view if the project SDK is not yet set.
    // This ensures the android SDK is available even if the initial project sync fails or simply
    // takes too long.
    androidSdkPlatform = AndroidSdkFromProjectView.getAndroidSdkPlatform(context, projectViewSet);
  }
  if (androidSdkPlatform == null) {
    return;
  }
  Sdk sdk = BlazeSdkProvider.getInstance().findSdk(androidSdkPlatform.androidSdk);
  if (sdk == null) {
    IssueOutput.error(
            String.format("Android platform '%s' not found.", androidSdkPlatform.androidSdk))
        .submit(context);
    return;
  }

  LanguageLevel javaLanguageLevel =
      JavaLanguageLevelHelper.getJavaLanguageLevel(
          projectViewSet, blazeProjectData, LanguageLevel.JDK_1_8);
  setProjectSdkAndLanguageLevel(project, sdk, javaLanguageLevel);
}
 
Example #14
Source File: DeviceService.java    From flutter-intellij with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
private DeviceService(@NotNull final Project project) {
  this.project = project;

  deviceDaemon.setDisposeParent(project);
  deviceDaemon.subscribe(this::refreshDeviceSelection);
  refreshDeviceDaemon();

  // Watch for Flutter SDK changes.
  final FlutterSdkManager.Listener sdkListener = new FlutterSdkManager.Listener() {
    @Override
    public void flutterSdkAdded() {
      refreshDeviceDaemon();
    }

    @Override
    public void flutterSdkRemoved() {
      refreshDeviceDaemon();
    }
  };
  FlutterSdkManager.getInstance(project).addListener(sdkListener);
  Disposer.register(project, () -> FlutterSdkManager.getInstance(project).removeListener(sdkListener));

  // Watch for Bazel workspace changes.
  WorkspaceCache.getInstance(project).subscribe(this::refreshDeviceDaemon);

  // Watch for Java SDK changes. (Used to get the value of ANDROID_HOME.)
  ProjectRootManagerEx.getInstanceEx(project).addProjectJdkListener(this::refreshDeviceDaemon);
}
 
Example #15
Source File: CompileDriver.java    From consulo with Apache License 2.0 4 votes vote down vote up
private void dropScopesCaches() {
  // hack to be sure the classpath will include the output directories
  ApplicationManager.getApplication().runReadAction(() -> {
    ((ProjectRootManagerEx)ProjectRootManager.getInstance(myProject)).clearScopesCachesForModules();
  });
}
 
Example #16
Source File: AbstractExternalModuleImportProvider.java    From consulo with Apache License 2.0 4 votes vote down vote up
@RequiredReadAction
@Override
public void process(@Nonnull ExternalModuleImportContext<C> context, @Nonnull final Project project, @Nonnull ModifiableModuleModel model, @Nonnull Consumer<Module> newModuleConsumer) {
  project.putUserData(ExternalSystemDataKeys.NEWLY_IMPORTED_PROJECT, Boolean.TRUE);
  final DataNode<ProjectData> externalProjectNode = getExternalProjectNode();
  if (externalProjectNode != null) {
    beforeCommit(externalProjectNode, project);
  }

  StartupManager.getInstance(project).runWhenProjectIsInitialized(new Runnable() {
    @SuppressWarnings("unchecked")
    @Override
    public void run() {
      AbstractExternalSystemSettings systemSettings = ExternalSystemApiUtil.getSettings(project, myExternalSystemId);
      final ExternalProjectSettings projectSettings = getCurrentExternalProjectSettings();
      Set<ExternalProjectSettings> projects = ContainerUtilRt.<ExternalProjectSettings>newHashSet(systemSettings.getLinkedProjectsSettings());
      // add current importing project settings to linked projects settings or replace if similar already exist
      projects.remove(projectSettings);
      projects.add(projectSettings);

      systemSettings.copyFrom(myControl.getSystemSettings());
      systemSettings.setLinkedProjectsSettings(projects);

      if (externalProjectNode != null) {
        ExternalSystemUtil.ensureToolWindowInitialized(project, myExternalSystemId);
        ExternalSystemApiUtil.executeProjectChangeAction(new DisposeAwareProjectChange(project) {
          @RequiredUIAccess
          @Override
          public void execute() {
            ProjectRootManagerEx.getInstanceEx(project).mergeRootsChangesDuring(new Runnable() {
              @Override
              public void run() {
                myProjectDataManager.importData(externalProjectNode.getKey(), Collections.singleton(externalProjectNode), project, true);
                myExternalProjectNode = null;
              }
            });
          }
        });

        final Runnable resolveDependenciesTask = new Runnable() {
          @Override
          public void run() {
            String progressText = ExternalSystemBundle.message("progress.resolve.libraries", myExternalSystemId.getReadableName());
            ProgressManager.getInstance().run(new Task.Backgroundable(project, progressText, false) {
              @Override
              public void run(@Nonnull final ProgressIndicator indicator) {
                if (project.isDisposed()) return;
                ExternalSystemResolveProjectTask task = new ExternalSystemResolveProjectTask(myExternalSystemId, project, projectSettings.getExternalProjectPath(), false);
                task.execute(indicator, ExternalSystemTaskNotificationListener.EP_NAME.getExtensions());
                DataNode<ProjectData> projectWithResolvedLibraries = task.getExternalProject();
                if (projectWithResolvedLibraries == null) {
                  return;
                }

                setupLibraries(projectWithResolvedLibraries, project);
              }
            });
          }
        };
        UIUtil.invokeLaterIfNeeded(resolveDependenciesTask);
      }
    }
  });
}
 
Example #17
Source File: ModuleRootManagerImpl.java    From consulo with Apache License 2.0 4 votes vote down vote up
void makeRootsChange(@Nonnull Runnable runnable) {
  ProjectRootManagerEx projectRootManagerEx = (ProjectRootManagerEx)ProjectRootManager.getInstance(myModule.getProject());
  // IMPORTANT: should be the first listener!
  projectRootManagerEx.makeRootsChange(runnable, false, isModuleAdded);
}
 
Example #18
Source File: ExternalSystemUtil.java    From consulo with Apache License 2.0 4 votes vote down vote up
/**
 * Tries to obtain external project info implied by the given settings and link that external project to the given ide project.
 *
 * @param externalSystemId        target external system
 * @param projectSettings         settings of the external project to link
 * @param project                 target ide project to link external project to
 * @param executionResultCallback it might take a while to resolve external project info, that's why it's possible to provide
 *                                a callback to be notified on processing result. It receives <code>true</code> if an external
 *                                project has been successfully linked to the given ide project;
 *                                <code>false</code> otherwise (note that corresponding notification with error details is expected
 *                                to be shown to the end-user then)
 * @param isPreviewMode           flag which identifies if missing external project binaries should be downloaded
 * @param progressExecutionMode   identifies how progress bar will be represented for the current processing
 */
@SuppressWarnings("UnusedDeclaration")
public static void linkExternalProject(@Nonnull final ProjectSystemId externalSystemId,
                                       @Nonnull final ExternalProjectSettings projectSettings,
                                       @Nonnull final Project project,
                                       @Nullable final Consumer<Boolean> executionResultCallback,
                                       boolean isPreviewMode,
                                       @Nonnull final ProgressExecutionMode progressExecutionMode) {
  ExternalProjectRefreshCallback callback = new ExternalProjectRefreshCallback() {
    @SuppressWarnings("unchecked")
    @Override
    public void onSuccess(@Nullable final DataNode<ProjectData> externalProject) {
      if (externalProject == null) {
        if (executionResultCallback != null) {
          executionResultCallback.consume(false);
        }
        return;
      }
      AbstractExternalSystemSettings systemSettings = ExternalSystemApiUtil.getSettings(project, externalSystemId);
      Set<ExternalProjectSettings> projects = ContainerUtilRt.<ExternalProjectSettings>newHashSet(systemSettings.getLinkedProjectsSettings());
      projects.add(projectSettings);
      systemSettings.setLinkedProjectsSettings(projects);
      ensureToolWindowInitialized(project, externalSystemId);
      ExternalSystemApiUtil.executeProjectChangeAction(new DisposeAwareProjectChange(project) {
        @RequiredUIAccess
        @Override
        public void execute() {
          ProjectRootManagerEx.getInstanceEx(project).mergeRootsChangesDuring(new Runnable() {
            @Override
            public void run() {
              ProjectDataManager dataManager = ServiceManager.getService(ProjectDataManager.class);
              dataManager.importData(externalProject.getKey(), Collections.singleton(externalProject), project, true);
            }
          });
        }
      });
      if (executionResultCallback != null) {
        executionResultCallback.consume(true);
      }
    }

    @Override
    public void onFailure(@Nonnull String errorMessage, @Nullable String errorDetails) {
      if (executionResultCallback != null) {
        executionResultCallback.consume(false);
      }
    }
  };
  refreshProject(project, externalSystemId, projectSettings.getExternalProjectPath(), callback, isPreviewMode, progressExecutionMode);
}