Java Code Examples for org.jetbrains.android.facet.AndroidFacet

The following examples show how to use org.jetbrains.android.facet.AndroidFacet. These examples are extracted from open source projects. 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 Project: Folivora   Source File: FolivoraAttrProcessing.java    License: Apache License 2.0 6 votes vote down vote up
private static void registerAttributes(/*NotNull*/ AndroidFacet facet,
  /*NotNull*/ DomElement element,
  /*NotNull*/ String styleableName,
  /*NotNull*/ AttributeProcessingUtil.AttributeProcessor callback) {

  ResourceManager manager = AndroidFacetCompat.getAppResourceManager(facet);
  if (manager == null) {
    return;
  }

  AttributeDefinitions attrDefs = manager.getAttributeDefinitions();
  if (attrDefs == null) {
    return;
  }

  String namespace = getNamespaceUriByResourcePackage(facet, null);
  StyleableDefinition styleable = attrDefs.getStyleableByName(styleableName);
  if (styleable != null) {
    registerStyleableAttributes(element, styleable, namespace, callback);
  }
  // It's a good idea to add a warning when styleable not found, to make sure that code doesn't
  // try to use attributes that don't exist. However, current AndroidDomExtender code relies on
  // a lot of "heuristics" that fail quite a lot (like adding a bunch of suffixes to short
  // class names)
  // TODO: add a warning when rest of the code of AndroidDomExtender is cleaned up
}
 
Example 2
Source Project: Folivora   Source File: FolivoraDomExtender.java    License: 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 3
Source Project: ADB-Duang   Source File: DeviceChooserDialog.java    License: MIT License 6 votes vote down vote up
public DeviceChooserDialog(@NotNull final AndroidFacet facet) {
    super(facet.getModule().getProject(), true);
    setTitle(AndroidBundle.message("choose.device.dialog.title"));

    myProject = facet.getModule().getProject();
    final PropertiesComponent properties = PropertiesComponent.getInstance(myProject);

    getOKAction().setEnabled(false);

    myDeviceChooser = new MyDeviceChooser(false, getOKAction(), facet, facet.getConfiguration().getAndroidTarget(), null);
    Disposer.register(myDisposable, myDeviceChooser);
    myDeviceChooser.addListener(new DeviceChooserListener() {
        @Override
        public void selectedDevicesChanged() {
            updateOkButton();
        }
    });
    myDeviceChooserWrapper.add(myDeviceChooser.getPanel());
    final String[] selectedSerials = getSelectedSerialsFromPreferences(properties);
    myDeviceChooser.init(selectedSerials);
    init();
    updateEnabled();
}
 
Example 4
private void updateAndroidModuleLibraryDependencies(Module flutterModule) {
  for (final Module module : ModuleManager.getInstance(getProject()).getModules()) {
    if (module != flutterModule) {
      if (null != FacetManager.getInstance(module).findFacet(AndroidFacet.ID, "Android")) {
        Object circularModules = CircularModuleDependenciesDetector.addingDependencyFormsCircularity(module, flutterModule);
        if (circularModules == null) {
          ModuleRootManager rootManager = ModuleRootManager.getInstance(module);
          if (!rootManager.isDependsOn(flutterModule)) {
            JavaProjectModelModifier[] modifiers = JavaProjectModelModifier.EP_NAME.getExtensions(getProject());
            for (JavaProjectModelModifier modifier : modifiers) {
              if (modifier instanceof IdeaProjectModelModifier) {
                modifier.addModuleDependency(module, flutterModule, DependencyScope.COMPILE, false);
              }
            }
          }
        }
      }
    }
  }
}
 
Example 5
private void updateAndroidModuleLibraryDependencies(Module flutterModule) {
  for (final Module module : ModuleManager.getInstance(getProject()).getModules()) {
    if (module != flutterModule) {
      if (null != FacetManager.getInstance(module).findFacet(AndroidFacet.ID, "Android")) {
        Object circularModules = CircularModuleDependenciesDetector.addingDependencyFormsCircularity(module, flutterModule);
        if (circularModules == null) {
          ModuleRootManager rootManager = ModuleRootManager.getInstance(module);
          if (!rootManager.isDependsOn(flutterModule)) {
            JavaProjectModelModifier[] modifiers = JavaProjectModelModifier.EP_NAME.getExtensions(getProject());
            for (JavaProjectModelModifier modifier : modifiers) {
              if (modifier instanceof IdeaProjectModelModifier) {
                modifier.addModuleDependency(module, flutterModule, DependencyScope.COMPILE, false);
              }
            }
          }
        }
      }
    }
  }
}
 
Example 6
Source Project: intellij   Source File: BlazeNativeAndroidDebugger.java    License: 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 7
Source Project: intellij   Source File: BlazeNativeAndroidDebugger.java    License: 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 8
Source Project: intellij   Source File: PackageNameUtils.java    License: Apache License 2.0 6 votes vote down vote up
@Nullable
private static String getRawPackageNameFromIndex(AndroidFacet facet) {
  VirtualFile primaryManifest = SourceProviderManager.getInstance(facet).getMainManifestFile();
  if (primaryManifest == null) {
    return null;
  }
  Project project = facet.getModule().getProject();
  try {
    AndroidManifestRawText manifestRawText =
        DumbService.getInstance(project)
            .runReadActionInSmartMode(
                () -> AndroidManifestIndex.getDataForManifestFile(project, primaryManifest));
    return manifestRawText == null ? null : manifestRawText.getPackageName();
  } catch (IndexNotReadyException e) {
    // TODO(142681129): runReadActionInSmartMode doesn't work if we already have read access.
    //  We need to refactor the callers of AndroidManifestUtils#getPackage to require a *smart*
    //  read action, at which point we can remove this try-catch.
    return null;
  }
}
 
Example 9
Source Project: intellij   Source File: BlazeSampleDataDirectoryProvider.java    License: 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 10
Source Project: intellij   Source File: BlazeProjectSystem.java    License: Apache License 2.0 6 votes vote down vote up
@NotNull
@Override
public SourceProvidersFactory getSourceProvidersFactory() {
  return new SourceProvidersFactory() {
    @Nullable
    @Override
    public SourceProviders createSourceProvidersFor(@NotNull AndroidFacet facet) {
      BlazeAndroidModel model = ((BlazeAndroidModel) AndroidModel.get(facet));
      if (model != null) {
        NamedIdeaSourceProvider mainSourceProvider =
            createIdeaSourceProviderFromModelSourceProvider(model.getDefaultSourceProvider());
        return new SourceProvidersImpl(
            mainSourceProvider,
            ImmutableList.of(mainSourceProvider),
            ImmutableList.of(mainSourceProvider),
            ImmutableList.of(mainSourceProvider),
            ImmutableList.of(mainSourceProvider),
            ImmutableList.of(mainSourceProvider));
      } else {
        return createSourceProvidersForLegacyModule(facet);
      }
    }
  };
}
 
Example 11
Source Project: intellij   Source File: BlazeProjectSystem.java    License: Apache License 2.0 6 votes vote down vote up
@NotNull
// #api41 @Override
public Collection<AndroidFacet> getAndroidFacetsWithPackageName(
    @NotNull Project project, @NotNull String packageName, @NotNull GlobalSearchScope scope) {
  List<AndroidFacet> facets = ProjectFacetManager.getInstance(project).getFacets(AndroidFacet.ID);
  return facets.stream()
      .filter(facet -> hasPackageName(facet, packageName))
      .filter(
          facet -> {
            VirtualFile file = SourceProviderManager.getInstance(facet).getMainManifestFile();
            if (file == null) {
              return false;
            } else {
              return scope.contains(file);
            }
          })
      .collect(Collectors.toList());
}
 
Example 12
Source Project: intellij   Source File: BlazeNewResourceCreationHandler.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public CreateResourceFileDialogBase createNewResourceFileDialog(
    AndroidFacet facet,
    Collection<CreateTypedResourceFileAction> actions,
    @Nullable ResourceFolderType folderType,
    @Nullable String filename,
    @Nullable String rootElement,
    @Nullable FolderConfiguration folderConfiguration,
    boolean chooseFileName,
    boolean chooseModule,
    @Nullable PsiDirectory resDirectory,
    @Nullable DataContext dataContext,
    CreateResourceFileDialogBase.ValidatorFactory validatorFactory) {
  return new BlazeCreateResourceFileDialog(
      facet,
      actions,
      folderType,
      filename,
      rootElement,
      folderConfiguration,
      chooseFileName,
      chooseModule,
      resDirectory,
      dataContext,
      validatorFactory);
}
 
Example 13
Source Project: intellij   Source File: BlazeAndroidSyncPlugin.java    License: 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 14
Source Project: intellij   Source File: AndroidFacetModuleCustomizer.java    License: 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 15
public static void validateExecution(
    @Nullable Module module,
    @Nullable AndroidFacet facet,
    @Nullable ProjectViewSet projectViewSet)
    throws ExecutionException {
  List<ValidationError> errors = Lists.newArrayList();
  errors.addAll(validateModule(module));
  if (module != null) {
    errors.addAll(validateFacet(facet, module));
  }
  if (projectViewSet == null) {
    errors.add(ValidationError.fatal("Could not load project view. Please resync project"));
  }

  if (errors.isEmpty()) {
    return;
  }
  ValidationError topError = Ordering.natural().max(errors);
  if (topError.isFatal()) {
    throw new ExecutionException(topError.getMessage());
  }
}
 
Example 16
private BlazeAndroidRunContext createRunContext(
    Project project,
    AndroidFacet facet,
    ExecutionEnvironment env,
    ImmutableList<String> blazeFlags,
    ImmutableList<String> exeFlags) {
  switch (configState.getLaunchMethod()) {
    case NON_BLAZE:
      if (!maybeShowMobileInstallOptIn(project, configuration)) {
        return new BlazeAndroidBinaryNormalBuildRunContext(
            project, facet, configuration, env, configState, getLabel(), blazeFlags);
      }
      // fall through
    case MOBILE_INSTALL_V2:
      // Standardize on a single mobile-install launch method
      configState.setLaunchMethod(AndroidBinaryLaunchMethod.MOBILE_INSTALL);
      // fall through
    case MOBILE_INSTALL:
      return new BlazeAndroidBinaryMobileInstallRunContext(
          project, facet, configuration, env, configState, getLabel(), blazeFlags, exeFlags);
  }
  throw new AssertionError();
}
 
Example 17
BlazeAndroidBinaryNormalBuildRunContextBase(
    Project project,
    AndroidFacet facet,
    RunConfiguration runConfiguration,
    ExecutionEnvironment env,
    BlazeAndroidBinaryRunConfigurationState configState,
    Label label,
    ImmutableList<String> blazeFlags) {
  this.project = project;
  this.facet = facet;
  this.runConfiguration = runConfiguration;
  this.env = env;
  this.configState = configState;
  this.consoleProvider = new BlazeAndroidBinaryConsoleProvider(project);
  this.buildStep = new BlazeApkBuildStepNormalBuild(project, label, blazeFlags);
  this.apkProvider = new BlazeApkProvider(project, buildStep);
  this.applicationIdProvider = new BlazeAndroidBinaryApplicationIdProvider(buildStep);
}
 
Example 18
public BlazeAndroidBinaryMobileInstallRunContextBase(
    Project project,
    AndroidFacet facet,
    RunConfiguration runConfiguration,
    ExecutionEnvironment env,
    BlazeAndroidBinaryRunConfigurationState configState,
    Label label,
    ImmutableList<String> blazeFlags,
    ImmutableList<String> exeFlags) {
  this.project = project;
  this.facet = facet;
  this.runConfiguration = runConfiguration;
  this.env = env;
  this.configState = configState;
  this.consoleProvider = new BlazeAndroidBinaryConsoleProvider(project);
  this.buildStep = new BlazeApkBuildStepMobileInstall(project, label, blazeFlags, exeFlags);
  this.applicationIdProvider = new BlazeAndroidBinaryApplicationIdProvider(buildStep);
}
 
Example 19
private static String canDebug(
    DeviceFutures deviceFutures, AndroidFacet facet, String moduleName) {
  // If we are debugging on a device, then the app needs to be debuggable
  for (ListenableFuture<IDevice> future : deviceFutures.get()) {
    if (!future.isDone()) {
      // this is an emulator, and we assume that all emulators are debuggable
      continue;
    }
    IDevice device = Futures.getUnchecked(future);
    if (!LaunchUtils.canDebugAppOnDevice(facet, device)) {
      return AndroidBundle.message(
          "android.cannot.debug.noDebugPermissions", moduleName, device.getName());
    }
  }
  return null;
}
 
Example 20
Source Project: Folivora   Source File: AndroidFacetCompat.java    License: Apache License 2.0 5 votes vote down vote up
static ResourceManager getAppResourceManager(AndroidFacet facet) {
  ResourceManager manager = null;
  if (sModuleResourceManagerExists) {
    try {
      manager = ModuleResourceManagers.getInstance(facet).getResourceManager(null);
    } catch (Throwable ignore) {
      sModuleResourceManagerExists = false;
    }
  }
  if (!sModuleResourceManagerExists) {
    manager = LocalResourceManager.getInstance(facet.getModule());
  }
  return manager;
}
 
Example 21
Source Project: ADBWIFI   Source File: AdbUtil.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Computes the project's package while preserving backward compatibility between android studio 0.4.3 and 0.4.4
 */
public static String computePackageName(AndroidFacet facet) {
    try {
        Object androidModuleInfo = facet.getClass().getMethod("getAndroidModuleInfo").invoke(facet);
        return (String) androidModuleInfo.getClass().getMethod("getPackage").invoke(androidModuleInfo);
    } catch (Exception e) {
        e.printStackTrace();
    }

    return null;
}
 
Example 22
Source Project: Folivora   Source File: AndroidFacetCompat.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Added for android studio 4.0 canary release
 */
static boolean requiresAndroidModel(AndroidFacet facet) {
  Boolean value = invoke(AndroidModel.class, "isRequired", null, new Class[]{AndroidFacet.class}, new Object[]{facet}, new Callable<Boolean>() {
    @Override
    public Boolean call() throws Exception {
      return facet.requiresAndroidModel();
    }
  });
  return value != null && value;
}
 
Example 23
Source Project: Folivora   Source File: AndroidFacetCompat.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Added for android studio 4.0 canary release
 */
static Manifest getManifest(AndroidFacet facet) {
  return invoke(AndroidFacet.class, "getManifest", facet, null, null, new Callable<Manifest>() {
    @Override
    public Manifest call() throws Exception {
      return Manifest.getMainManifest(facet);
    }
  });
}
 
Example 24
Source Project: Folivora   Source File: FolivoraAttrProcessing.java    License: Apache License 2.0 5 votes vote down vote up
static void registerFolivoraAttributes(AndroidFacet facet,
                                       AndroidDomElement element,
                                       AttributeProcessingUtil.AttributeProcessor callback) {
  if (!(element instanceof LayoutElement)) return;
  if (element instanceof DataBindingElement) return;
  XmlTag tag = element.getXmlTag();
  if (tag == null) return;
  if (isInvalidTagName(tag.getName())) return;
  List<String> styleableNames = getStyleablesToRegister(tag.getAttributes());
  for (String styleableName : styleableNames) {
    if (styleableName != null && styleableName.length() > 0) {
      registerAttributes(facet, element, styleableName, callback);
    }
  }
}
 
Example 25
Source Project: ADBWIFI   Source File: AdbWifiConnect.java    License: 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 26
Source Project: ADBWIFI   Source File: DeviceChooserDialog.java    License: Apache License 2.0 5 votes vote down vote up
public DeviceChooserDialog(@NotNull final AndroidFacet facet) {
    super(facet.getModule().getProject(), true);
    setTitle(AndroidBundle.message("choose.device.dialog.title"));

    myProject = facet.getModule().getProject();
    final PropertiesComponent properties = PropertiesComponent.getInstance(myProject);

    getOKAction().setEnabled(false);

    myDeviceChooser = new MyDeviceChooser(true, getOKAction(), facet, facet.getConfiguration().getAndroidTarget(), null);
    Disposer.register(myDisposable, myDeviceChooser);
    myDeviceChooser.addListener(new DeviceChooserListener() {
        @Override
        public void selectedDevicesChanged() {
                updateOkButton();
        }
    });

    myDeviceChooserWrapper.add(myDeviceChooser.getPanel());

    final String[] selectedSerials = getSelectedSerialsFromPreferences(properties);
    myDeviceChooser.init(selectedSerials);

    init();

    updateEnabled();
}
 
Example 27
Source Project: ADBWIFI   Source File: ModuleChooserDialogHelper.java    License: Apache License 2.0 5 votes vote down vote up
public static AndroidFacet showDialogForFacets(Project project, List<AndroidFacet> facets) {
    List<Module> modules = Lists.newArrayList();
    String previousModuleName = getPreviousModuleName(project);
    List<Module> previousSelectedModule = null;
    for (AndroidFacet facet : facets) {
        Module module = facet.getModule();
        modules.add(module);
        if (module.getName().equals(previousModuleName)) {
            previousSelectedModule = Lists.newArrayList(module);
        }
    }

    ChooseModulesDialog dialog = new ChooseModulesDialog(project, modules, "Choose Module", "");
    dialog.setSingleSelectionMode();
    if (previousSelectedModule != null) {
        dialog.selectElements(previousSelectedModule);
    }
    dialog.show();

    List<Module> chosenElements = dialog.getChosenElements();
    if (chosenElements.isEmpty()) {
        return null;
    }

    Module chosenModule = chosenElements.get(0);
    saveModuleName(project, chosenModule.getName());
    int chosenModuleIndex = modules.indexOf(chosenModule);
    return facets.get(chosenModuleIndex);
}
 
Example 28
@NotNull
@SuppressWarnings("override")
public Collection<AndroidFacet> getAndroidFacetsWithPackageName(@NotNull Project project,
                                                                @NotNull String packageName,
                                                                @NotNull GlobalSearchScope scope) {
  return gradleProjectSystem.getAndroidFacetsWithPackageName(project, packageName, scope);
}
 
Example 29
Source Project: intellij   Source File: AswbMergedManifestTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void manifestBelongsToResourceModule() {
  ManifestFixture manifest = manifestFactory.fromPackage("com.example.target");
  setTargetMap(android_binary("//java/com/example/target:target").manifest(manifest).res("res"));
  runFullBlazeSync();
  AndroidFacet targetFacet = getFacet("java.com.example.target.target");

  // Verify the mapping from resource module to manifest.
  assertThat(IdeaSourceProviderUtil.getManifestFiles(targetFacet))
      .containsExactly(manifest.file.getVirtualFile());
  // Verify the mapping from manifest back to resource module.
  assertThat(AndroidFacet.getInstance(manifest.file)).isEqualTo(targetFacet);
}
 
Example 30
@NotNull
@SuppressWarnings("override")
public Collection<AndroidFacet> getAndroidFacetsWithPackageName(@NotNull Project project,
                                                                @NotNull String packageName,
                                                                @NotNull GlobalSearchScope scope) {
  return gradleProjectSystem.getAndroidFacetsWithPackageName(project, packageName, scope);
}