Java Code Examples for org.jetbrains.android.facet.AndroidFacet#getInstance()

The following examples show how to use org.jetbrains.android.facet.AndroidFacet#getInstance() . 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: FolivoraDomExtender.java    From Folivora with Apache License 2.0 6 votes vote down vote up
@Override
public void registerExtensions(@Nonnull AndroidDomElement element,
                               @Nonnull final DomExtensionsRegistrar registrar) {
  final AndroidFacet facet = AndroidFacet.getInstance(element);

  if (facet == null) {
    return;
  }

  AttributeProcessingUtil.AttributeProcessor callback = (xmlName, attrDef, parentStyleableName)
    -> {
    Set<?> formats = attrDef.getFormats();
    Class valueClass = formats.size() == 1 ? getValueClass(formats.iterator().next()) : String
      .class;
    registrar.registerAttributeChildExtension(xmlName, GenericAttributeValue.class);
    return registrar.registerGenericAttributeValueChildExtension(xmlName, valueClass);
  };

  try {
    FolivoraAttrProcessing.registerFolivoraAttributes(facet, element, callback);
  } catch (Exception ignore) {}
}
 
Example 2
Source File: BlazeNativeAndroidDebugger.java    From intellij with Apache License 2.0 6 votes vote down vote up
@VisibleForTesting
@Override
@Nullable
public Module findModuleForProcess(Project project, String packageName) {
  for (Module module : ModuleManager.getInstance(project).getModules()) {
    if (AndroidFacet.getInstance(module) == null) {
      continue; // A module must have an attached AndroidFacet to have a package name.
    }

    BlazeModuleSystem moduleSystem = BlazeModuleSystem.getInstance(module);
    String modulePackageName = ReadAction.compute(() -> moduleSystem.getPackageName());
    if (modulePackageName != null && modulePackageName.equals(packageName)) {
      return module;
    }
  }
  return null;
}
 
Example 3
Source File: BlazeNativeAndroidDebugger.java    From intellij with Apache License 2.0 6 votes vote down vote up
@VisibleForTesting
@Override
@Nullable
public Module findModuleForProcess(Project project, String packageName) {
  for (Module module : ModuleManager.getInstance(project).getModules()) {
    if (AndroidFacet.getInstance(module) == null) {
      continue; // A module must have an attached AndroidFacet to have a package name.
    }

    BlazeModuleSystem moduleSystem = BlazeModuleSystem.getInstance(module);
    String modulePackageName = ReadAction.compute(() -> moduleSystem.getPackageName());
    if (modulePackageName != null && modulePackageName.equals(packageName)) {
      return module;
    }
  }
  return null;
}
 
Example 4
Source File: BlazeSampleDataDirectoryProvider.java    From intellij with Apache License 2.0 6 votes vote down vote up
@Override
@Nullable
public PathString getSampleDataDirectory() {
  // If this isn't a resource module then it doesn't have any layouts
  // that we could open in the layout editor anyway, so there's no
  // reason for a sample data directory.
  if (!isResourceModule) {
    return null;
  }

  AndroidFacet facet = AndroidFacet.getInstance(module);
  VirtualFile mainContentRoot = facet != null ? AndroidRootUtil.getMainContentRoot(facet) : null;
  if (mainContentRoot == null) {
    return null;
  }

  // The main content root of a resource module is its res folder.
  // Instead, we'll use the res folder's parent directory so that the
  // sample data directory and the res folder sit parallel to one another.
  VirtualFile parentDir = getSampleDataDirectoryHomeForResFolder(mainContentRoot);
  if (parentDir == null) {
    return null;
  }

  return toPathString(parentDir).resolve(FD_SAMPLE_DATA);
}
 
Example 5
Source File: BlazeAndroidSyncPlugin.java    From intellij with Apache License 2.0 6 votes vote down vote up
@Override
public boolean validate(
    Project project, BlazeContext context, BlazeProjectData blazeProjectData) {
  if (!isAndroidWorkspace(blazeProjectData.getWorkspaceLanguageSettings())) {
    return true;
  }

  boolean valid = true;
  for (Module module : ModuleManager.getInstance(project).getModules()) {
    AndroidFacet facet = AndroidFacet.getInstance(module);
    if (BlazeAndroidSyncPluginCompat.facetHasAndroidModel(facet)) {
      IssueOutput.error("Android model missing for module: " + module.getName()).submit(context);
      valid = false;
    }
  }
  return valid;
}
 
Example 6
Source File: AndroidFacetModuleCustomizer.java    From intellij with Apache License 2.0 6 votes vote down vote up
public static void createAndroidFacet(Module module, boolean isApp) {
  AndroidFacet facet = AndroidFacet.getInstance(module);
  if (facet != null) {
    configureFacet(facet, isApp);
  } else {
    // Module does not have Android facet. Create one and add it.
    FacetManager facetManager = FacetManager.getInstance(module);
    ModifiableFacetModel model = facetManager.createModifiableModel();
    try {
      facet = facetManager.createFacet(AndroidFacet.getFacetType(), AndroidFacet.NAME, null);
      model.addFacet(facet);
      configureFacet(facet, isApp);
    } finally {
      model.commit();
    }
  }
}
 
Example 7
Source File: FlutterProjectCreator.java    From flutter-intellij with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public static void disableUserConfig(Project project) {
  if (FlutterModuleUtils.declaresFlutter(project)) {
    for (Module module : ModuleManager.getInstance(project).getModules()) {
      final AndroidFacet facet = AndroidFacet.getInstance(module);
      if (facet == null) {
        continue;
      }
      facet.getProperties().ALLOW_USER_CONFIGURATION = false;
    }
  }
}
 
Example 8
Source File: BlazeAndroidTestRunConfigurationHandler.java    From intellij with Apache License 2.0 5 votes vote down vote up
/**
 * We collect errors rather than throwing to avoid missing fatal errors by exiting early for a
 * warning. We use a separate method for the collection so the compiler prevents us from
 * accidentally throwing.
 */
private List<ValidationError> validate() {
  List<ValidationError> errors = Lists.newArrayList();
  Module module = getModule();
  errors.addAll(BlazeAndroidRunConfigurationValidationUtil.validateModule(module));
  AndroidFacet facet = null;
  if (module != null) {
    facet = AndroidFacet.getInstance(module);
    errors.addAll(BlazeAndroidRunConfigurationValidationUtil.validateFacet(facet, module));
  }
  errors.addAll(configState.validate(facet));
  return errors;
}
 
Example 9
Source File: BlazeAndroidBinaryRunConfigurationHandler.java    From intellij with Apache License 2.0 5 votes vote down vote up
/**
 * We collect errors rather than throwing to avoid missing fatal errors by exiting early for a
 * warning. We use a separate method for the collection so the compiler prevents us from
 * accidentally throwing.
 */
private List<ValidationError> validate() {
  List<ValidationError> errors = Lists.newArrayList();
  Module module = getModule();
  errors.addAll(BlazeAndroidRunConfigurationValidationUtil.validateModule(module));
  AndroidFacet facet = null;
  if (module != null) {
    facet = AndroidFacet.getInstance(module);
    errors.addAll(BlazeAndroidRunConfigurationValidationUtil.validateFacet(facet, module));
  }
  errors.addAll(configState.validate(facet));
  return errors;
}
 
Example 10
Source File: AdbWifiConnect.java    From ADBWIFI with Apache License 2.0 5 votes vote down vote up
private static List<AndroidFacet> getApplicationFacets(Project project) {

        List<AndroidFacet> facetList = AndroidUtils.getApplicationFacets(project);
        Module[] modules = ModuleManager.getInstance(project).getModules();
        for (Module module : modules) {
            AndroidFacet androidFacet = AndroidFacet.getInstance(module);
            if (androidFacet != null) {
                facetList.add(androidFacet);
            }
        }

        return facetList;
    }
 
Example 11
Source File: BlazeAndroidModuleTemplate.java    From intellij with Apache License 2.0 5 votes vote down vote up
public static List<NamedModuleTemplate> getTemplates(
    Module module, @Nullable VirtualFile targetDirectory) {
  AndroidFacet androidFacet = AndroidFacet.getInstance(module);
  if (androidFacet == null) {
    return Collections.emptyList();
  }
  return getTemplates(androidFacet, targetDirectory);
}
 
Example 12
Source File: AndroidFacetModuleCustomizer.java    From intellij with Apache License 2.0 5 votes vote down vote up
public static void removeAndroidFacet(Module module) {
  AndroidFacet facet = AndroidFacet.getInstance(module);
  if (facet != null) {
    ModifiableFacetModel facetModel = FacetManager.getInstance(module).createModifiableModel();
    facetModel.removeFacet(facet);
    facetModel.commit();
  }
}
 
Example 13
Source File: BlazeLightResourceClassService.java    From intellij with Apache License 2.0 5 votes vote down vote up
@Nullable
private BlazeRClass getRClassForWorkspace(String qualifiedName, GlobalSearchScope scope) {
  if (!workspaceResourcesFeature.isEnabled() || !workspaceRClassNames.contains(qualifiedName)) {
    return null;
  }

  BlazeRClass rClass = workspaceRClasses.get(qualifiedName);
  if (rClass != null) {
    if (scope.isSearchInModuleContent(rClass.getModule())) {
      return rClass;
    } else {
      return null;
    }
  }

  Module workspaceModule =
      ModuleManager.getInstance(project).findModuleByName(BlazeDataStorage.WORKSPACE_MODULE_NAME);
  if (workspaceModule == null || !scope.isSearchInModuleContent(workspaceModule)) {
    return null;
  }

  // Remove the .R suffix
  String packageName = qualifiedName.substring(0, qualifiedName.length() - 2);
  AndroidFacet workspaceFacet = AndroidFacet.getInstance(workspaceModule);
  if (workspaceFacet == null) {
    return null;
  }

  rClass = new BlazeRClass(psiManager, workspaceFacet, packageName);
  workspaceRClasses.put(qualifiedName, rClass);
  allRClasses.add(rClass);
  return rClass;
}
 
Example 14
Source File: BlazeLightResourceClassService.java    From intellij with Apache License 2.0 5 votes vote down vote up
public void addRClass(String resourceJavaPackage, Module module) {
  AndroidFacet androidFacet = AndroidFacet.getInstance(module);
  if (androidFacet == null) {
    return; // Do not register R class if android facet is not present.
  }
  BlazeRClass rClass = new BlazeRClass(psiManager, androidFacet, resourceJavaPackage);
  rClassMap.put(getQualifiedRClassName(resourceJavaPackage), rClass);
  rClassByModuleMap.put(module, rClass);
  if (createStubResourcePackages.getValue()) {
    addStubPackages(resourceJavaPackage);
  }
}
 
Example 15
Source File: IdeaFrameFixture.java    From flutter-intellij with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@NotNull
public AndroidModuleModel getAndroidProjectForModule(@NotNull String name) {
  Module module = getModule(name);
  AndroidFacet facet = AndroidFacet.getInstance(module);
  if (facet != null && AndroidModel.isRequired(facet)) {
    // TODO: Resolve direct AndroidGradleModel dep (b/22596984)
    AndroidModuleModel androidModel = AndroidModuleModel.get(facet);
    if (androidModel != null) {
      return androidModel;
    }
  }
  throw new AssertionError("Unable to find AndroidGradleModel for module '" + name + "'");
}
 
Example 16
Source File: FlutterProjectCreator.java    From flutter-intellij with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public static void disableUserConfig(Project project) {
  if (FlutterModuleUtils.declaresFlutter(project)) {
    for (Module module : ModuleManager.getInstance(project).getModules()) {
      final AndroidFacet facet = AndroidFacet.getInstance(module);
      if (facet == null) {
        continue;
      }
      facet.getProperties().ALLOW_USER_CONFIGURATION = false;
    }
  }
}
 
Example 17
Source File: BlazeAndroidProjectStructureSyncer.java    From intellij with Apache License 2.0 4 votes vote down vote up
private static void updateModuleFacetInMemoryState(
    Project project,
    @Nullable BlazeContext context,
    AndroidSdkPlatform androidSdkPlatform,
    Module module,
    File moduleDirectory,
    @Nullable File manifestFile,
    String resourceJavaPackage,
    Collection<File> resources,
    boolean configAndroidJava8Libs,
    @Nullable ManifestParsingStatCollector manifestParsingStatCollector) {
  List<PathString> manifests =
      manifestFile == null
          ? ImmutableList.of()
          : ImmutableList.of(PathStringUtil.toPathString(manifestFile));
  SourceSet sourceSet =
      new SourceSet(
          ImmutableMap.of(
              AndroidPathType.RES,
              PathStringUtil.toPathStrings(resources),
              AndroidPathType.MANIFEST,
              manifests));
  SourceProvider sourceProvider =
      SourceProviderUtil.toSourceProvider(sourceSet, module.getName());

  String applicationId =
      getApplicationIdFromManifestOrDefault(
          project, context, manifestFile, resourceJavaPackage, manifestParsingStatCollector);

  BlazeAndroidModel androidModel =
      new BlazeAndroidModel(
          project,
          moduleDirectory,
          sourceProvider,
          applicationId,
          androidSdkPlatform.androidMinSdkLevel,
          configAndroidJava8Libs);
  AndroidFacet facet = AndroidFacet.getInstance(module);
  if (facet != null) {
    BlazeAndroidProjectStructureSyncerCompat.updateAndroidFacetWithSourceAndModel(
        facet, sourceProvider, androidModel);
  }
}
 
Example 18
Source File: BlazeAndroidTestRunConfigurationHandler.java    From intellij with Apache License 2.0 4 votes vote down vote up
@Override
public BlazeCommandRunConfigurationRunner createRunner(
    Executor executor, ExecutionEnvironment env) throws ExecutionException {
  Project project = env.getProject();

  // This is a workaround for b/134587683
  // Due to the way blaze run configuration editors update the underlying configuration state,
  // it's possible for the configuration referenced in this handler to be out of date. This can
  // cause tricky side-effects such as incorrect build target and target validation settings.
  // Fortunately, the only field that can come out of sync is the target label and it's target
  // kind. The handlers are designed to only handle their supported target kinds, so we can
  // safely ignore all fields other than target label itself and extract an up to date target
  // label from the execution environment.
  // Validation of the updated target label is not needed here because:
  // 1. The target kind is guaranteed to be an android binary kind or else this
  //    specific handler will not be used.
  // 2. Any other validation is done during edit-time of the run configuration before saving.
  BlazeCommandRunConfiguration configFromEnv =
      BlazeAndroidRunConfigurationHandler.getCommandConfig(env);
  configuration.setTarget(configFromEnv.getSingleTarget());

  Module module = getModule();
  AndroidFacet facet = module != null ? AndroidFacet.getInstance(module) : null;
  ProjectViewSet projectViewSet = ProjectViewManager.getInstance(project).getProjectViewSet();
  BlazeAndroidRunConfigurationValidationUtil.validateExecution(module, facet, projectViewSet);

  ImmutableList<String> blazeFlags =
      configState
          .getCommonState()
          .getExpandedBuildFlags(
              project,
              projectViewSet,
              BlazeCommandName.TEST,
              BlazeInvocationContext.runConfigContext(
                  ExecutorType.fromExecutor(env.getExecutor()), configuration.getType(), false));
  ImmutableList<String> exeFlags =
      ImmutableList.copyOf(
          configState.getCommonState().getExeFlagsState().getFlagsForExternalProcesses());
  BlazeAndroidRunContext runContext = createRunContext(project, facet, env, blazeFlags, exeFlags);

  EventLoggingService.getInstance()
      .logEvent(
          BlazeAndroidTestRunConfigurationHandler.class,
          "BlazeAndroidTestRun",
          ImmutableMap.of(
              "launchMethod",
              configState.getLaunchMethod().name(),
              "executorId",
              env.getExecutor().getId()));

  return new BlazeAndroidRunConfigurationRunner(
      module,
      runContext,
      getCommonState().getDeployTargetManager(),
      getCommonState().getDebuggerManager(),
      configuration);
}
 
Example 19
Source File: BlazeAndroidIntegrationTestCase.java    From intellij with Apache License 2.0 4 votes vote down vote up
protected AndroidFacet getFacet(String moduleName) {
  AndroidFacet facet = AndroidFacet.getInstance(getModule(moduleName));
  assertThat(facet).isNotNull();
  return facet;
}
 
Example 20
Source File: BlazeClassJarProviderIntegrationTest.java    From intellij with Apache License 2.0 4 votes vote down vote up
@Test
public void testGetModuleExternalLibraries() {
  // Need AndroidFact for LocalResourceRepository.
  ApplicationManager.getApplication()
      .runWriteAction(
          () -> {
            ModifiableFacetModel model = FacetManager.getInstance(module).createModifiableModel();
            model.addFacet(new MockAndroidFacet(module));
            model.commit();
          });

  List<File> externalLibraries = classJarProvider.getModuleExternalLibraries(module);
  assertThat(externalLibraries)
      .containsExactly(
          VfsUtilCore.virtualToIoFile(fileSystem.findFile("com/google/example/libimport.jar")),
          VfsUtilCore.virtualToIoFile(
              fileSystem.findFile("com/google/example/transitive/libimport.jar")),
          VfsUtilCore.virtualToIoFile(
              fileSystem.findFile("com/google/example/transitive/libimport2.jar")));

  // Make sure we can generate dynamic classes from all resource packages in dependencies.
  ResourceClassRegistry registry = ResourceClassRegistry.get(getProject());
  AndroidFacet facet = AndroidFacet.getInstance(module);
  assertThat(facet).isNotNull();
  ResourceRepositoryManager repositoryManager = ResourceRepositoryManager.getInstance(facet);
  assertThat(repositoryManager).isNotNull();
  assertThat(registry.findClassDefinition("com.google.example.resource.R", repositoryManager))
      .isNotNull();
  assertThat(
          registry.findClassDefinition("com.google.example.resource.R$string", repositoryManager))
      .isNotNull();
  assertThat(registry.findClassDefinition("com.google.example.resource2.R", repositoryManager))
      .isNotNull();
  assertThat(
          registry.findClassDefinition(
              "com.google.example.resource2.R$layout", repositoryManager))
      .isNotNull();
  assertThat(
          registry.findClassDefinition(
              "com.google.example.transitive.resource.R", repositoryManager))
      .isNotNull();
  assertThat(
          registry.findClassDefinition(
              "com.google.example.transitive.resource.R$style", repositoryManager))
      .isNotNull();

  // And nothing else.
  assertThat(
          registry.findClassDefinition("com.google.example.main.MainActivity", repositoryManager))
      .isNull();
  assertThat(registry.findClassDefinition("com.google.example.resource.Bogus", repositoryManager))
      .isNull();
  assertThat(registry.findClassDefinition("com.google.example.main.R", repositoryManager))
      .isNull();
  assertThat(registry.findClassDefinition("com.google.example.main.R$string", repositoryManager))
      .isNull();
  assertThat(registry.findClassDefinition("com.google.example.java.Java", repositoryManager))
      .isNull();
  assertThat(registry.findClassDefinition("com.google.unrelated.R", repositoryManager)).isNull();
  assertThat(registry.findClassDefinition("com.google.unrelated.R$layout", repositoryManager))
      .isNull();
}