Search in sources :

Example 51 with AndroidVersion

use of com.android.sdklib.AndroidVersion in project android by JetBrains.

the class ManifestInfo method getMergedManifest.

@NotNull
static MergingReport getMergedManifest(@NotNull AndroidFacet facet, @NotNull VirtualFile primaryManifestFile, @NotNull List<VirtualFile> flavorAndBuildTypeManifests, @NotNull List<VirtualFile> libManifests) throws ManifestMerger2.MergeFailureException {
    ApplicationManager.getApplication().assertReadAccessAllowed();
    final File mainManifestFile = VfsUtilCore.virtualToIoFile(primaryManifestFile);
    ILogger logger = NullLogger.getLogger();
    ManifestMerger2.MergeType mergeType = facet.isAppProject() ? ManifestMerger2.MergeType.APPLICATION : ManifestMerger2.MergeType.LIBRARY;
    AndroidModel androidModel = facet.getAndroidModel();
    AndroidModuleModel gradleModel = AndroidModuleModel.get(facet);
    ManifestMerger2.Invoker manifestMergerInvoker = ManifestMerger2.newMerger(mainManifestFile, logger, mergeType);
    manifestMergerInvoker.withFeatures(ManifestMerger2.Invoker.Feature.SKIP_BLAME, ManifestMerger2.Invoker.Feature.SKIP_XML_STRING);
    manifestMergerInvoker.addFlavorAndBuildTypeManifests(VfsUtilCore.virtualToIoFiles(flavorAndBuildTypeManifests).toArray(new File[0]));
    List<Pair<String, File>> libraryManifests = new ArrayList<>();
    for (VirtualFile file : libManifests) {
        libraryManifests.add(Pair.of(file.getName(), VfsUtilCore.virtualToIoFile(file)));
    }
    manifestMergerInvoker.addBundleManifests(libraryManifests);
    if (androidModel != null) {
        AndroidVersion minSdkVersion = androidModel.getMinSdkVersion();
        if (minSdkVersion != null) {
            manifestMergerInvoker.setOverride(ManifestSystemProperty.MIN_SDK_VERSION, minSdkVersion.getApiString());
        }
        AndroidVersion targetSdkVersion = androidModel.getTargetSdkVersion();
        if (targetSdkVersion != null) {
            manifestMergerInvoker.setOverride(ManifestSystemProperty.TARGET_SDK_VERSION, targetSdkVersion.getApiString());
        }
        Integer versionCode = androidModel.getVersionCode();
        if (versionCode != null && versionCode > 0) {
            manifestMergerInvoker.setOverride(ManifestSystemProperty.VERSION_CODE, String.valueOf(versionCode));
        }
        String packageOverride = androidModel.getApplicationId();
        if (!Strings.isNullOrEmpty(packageOverride)) {
            manifestMergerInvoker.setOverride(ManifestSystemProperty.PACKAGE, packageOverride);
        }
    }
    if (gradleModel != null) {
        BuildTypeContainer buildTypeContainer = gradleModel.findBuildType(gradleModel.getSelectedVariant().getBuildType());
        assert buildTypeContainer != null;
        BuildType buildType = buildTypeContainer.getBuildType();
        ProductFlavor mergedProductFlavor = gradleModel.getSelectedVariant().getMergedFlavor();
        // copy-paste from {@link VariantConfiguration#getManifestPlaceholders()}
        Map<String, Object> placeHolders = new HashMap<>(mergedProductFlavor.getManifestPlaceholders());
        placeHolders.putAll(buildType.getManifestPlaceholders());
        manifestMergerInvoker.setPlaceHolderValues(placeHolders);
        // @deprecated maxSdkVersion has been ignored since Android 2.1 (API level 7)
        Integer maxSdkVersion = mergedProductFlavor.getMaxSdkVersion();
        if (maxSdkVersion != null) {
            manifestMergerInvoker.setOverride(ManifestSystemProperty.MAX_SDK_VERSION, maxSdkVersion.toString());
        }
        // TODO we should have version Name for non-gradle projects
        // copy-paste from {@link VariantConfiguration#getVersionName()}
        String versionName = mergedProductFlavor.getVersionName();
        String flavorVersionNameSuffix = null;
        if (gradleModel.getFeatures().isProductFlavorVersionSuffixSupported()) {
            flavorVersionNameSuffix = getVersionNameSuffix(mergedProductFlavor);
        }
        String versionNameSuffix = Joiner.on("").skipNulls().join(flavorVersionNameSuffix, getVersionNameSuffix(buildType));
        if (!Strings.isNullOrEmpty(versionName) || !Strings.isNullOrEmpty(versionNameSuffix)) {
            if (Strings.isNullOrEmpty(versionName)) {
                Manifest manifest = facet.getManifest();
                if (manifest != null) {
                    versionName = manifest.getXmlTag().getAttributeValue(SdkConstants.ATTR_VERSION_NAME, ANDROID_URI);
                }
            }
            if (!Strings.isNullOrEmpty(versionNameSuffix)) {
                versionName = Strings.nullToEmpty(versionName) + versionNameSuffix;
            }
            manifestMergerInvoker.setOverride(ManifestSystemProperty.VERSION_NAME, versionName);
        }
    }
    if (mergeType == ManifestMerger2.MergeType.APPLICATION) {
        manifestMergerInvoker.withFeatures(ManifestMerger2.Invoker.Feature.REMOVE_TOOLS_DECLARATIONS);
    }
    final Module module = facet.getModule();
    final Project project = module.getProject();
    manifestMergerInvoker.withFileStreamProvider(new ManifestMerger2.FileStreamProvider() {

        @Override
        protected InputStream getInputStream(@NotNull File file) throws FileNotFoundException {
            VirtualFile vFile;
            if (file == mainManifestFile) {
                // Some tests use VirtualFile files (e.g. temp:///src/AndroidManifest.xml) for the main manifest
                vFile = primaryManifestFile;
            } else {
                vFile = VfsUtil.findFileByIoFile(file, false);
            }
            assert vFile != null : file;
            // findModuleForFile does not work for other build systems (e.g. bazel)
            if (!libManifests.isEmpty()) {
                Module moduleContainingManifest = getAndroidModuleForManifest(vFile);
                if (moduleContainingManifest != null && !module.equals(moduleContainingManifest)) {
                    MergedManifest manifest = MergedManifest.get(moduleContainingManifest);
                    Document document = manifest.getDocument();
                    if (document != null) {
                        // normally the case, but can fail on merge fail
                        // This is not very efficient. Consider enhancing the manifest merger API
                        // such that I can pass back a fully merged DOM document instead of
                        // an XML string since it will need to turn around and parse it anyway.
                        String text = XmlUtils.toXml(document);
                        return new ByteArrayInputStream(text.getBytes(Charsets.UTF_8));
                    }
                }
            }
            try {
                PsiFile psiFile = PsiManager.getInstance(project).findFile(vFile);
                if (psiFile != null) {
                    String text = psiFile.getText();
                    return new ByteArrayInputStream(text.getBytes(Charsets.UTF_8));
                }
            } catch (ProcessCanceledException ignore) {
            // During startup we may receive a progress canceled exception here,
            // but we don't *need* to read from PSI; we can read directly from
            // disk. PSI is useful when the file has been modified, but that's not
            // the case in the typical scenario where we hit process canceled.
            }
            return super.getInputStream(file);
        }

        @Nullable
        private Module getAndroidModuleForManifest(@NotNull VirtualFile vFile) {
            // project and look at their source providers
            for (Module m : ModuleManager.getInstance(project).getModules()) {
                AndroidFacet androidFacet = AndroidFacet.getInstance(m);
                if (androidFacet == null) {
                    continue;
                }
                List<VirtualFile> manifestFiles = IdeaSourceProvider.getManifestFiles(androidFacet);
                for (VirtualFile manifestFile : manifestFiles) {
                    if (vFile.equals(manifestFile)) {
                        return m;
                    }
                }
            }
            return null;
        }
    });
    return manifestMergerInvoker.merge();
}
Also used : VirtualFile(com.intellij.openapi.vfs.VirtualFile) FileNotFoundException(java.io.FileNotFoundException) Document(org.w3c.dom.Document) ILogger(com.android.utils.ILogger) PsiFile(com.intellij.psi.PsiFile) ImmutableList(com.google.common.collect.ImmutableList) Pair(com.android.utils.Pair) ProcessCanceledException(com.intellij.openapi.progress.ProcessCanceledException) ByteArrayInputStream(java.io.ByteArrayInputStream) InputStream(java.io.InputStream) AndroidVersion(com.android.sdklib.AndroidVersion) Manifest(org.jetbrains.android.dom.manifest.Manifest) AndroidFacet(org.jetbrains.android.facet.AndroidFacet) Project(com.intellij.openapi.project.Project) ByteArrayInputStream(java.io.ByteArrayInputStream) AndroidModuleModel(com.android.tools.idea.gradle.project.model.AndroidModuleModel) Module(com.intellij.openapi.module.Module) VirtualFile(com.intellij.openapi.vfs.VirtualFile) PsiFile(com.intellij.psi.PsiFile) File(java.io.File) Nullable(org.jetbrains.annotations.Nullable) NotNull(org.jetbrains.annotations.NotNull)

Example 52 with AndroidVersion

use of com.android.sdklib.AndroidVersion in project android by JetBrains.

the class Platform method getLatestPlatform.

@Nullable
private static Platform getLatestPlatform(@NotNull ScopedStateStore store, @Nullable Map<String, RemotePackage> remotePackages, boolean installUpdates) {
    RemotePackage latest = InstallComponentsPath.findLatestPlatform(remotePackages);
    if (latest != null) {
        AndroidVersion version = ((DetailsTypes.PlatformDetailsType) latest.getTypeDetails()).getAndroidVersion();
        String versionName = SdkVersionInfo.getAndroidName(version.getFeatureLevel());
        final String description = "Android platform libraries for targeting " + versionName + " platform";
        return new Platform(store, versionName, description, version, !version.isPreview(), installUpdates);
    }
    return null;
}
Also used : AndroidVersion(com.android.sdklib.AndroidVersion) RemotePackage(com.android.repository.api.RemotePackage) Nullable(org.jetbrains.annotations.Nullable)

Example 53 with AndroidVersion

use of com.android.sdklib.AndroidVersion in project android by JetBrains.

the class InstallComponentsPath method findLatestPlatform.

@Nullable
public static RemotePackage findLatestPlatform(@Nullable Map<String, RemotePackage> remotePackages) {
    if (remotePackages == null) {
        return null;
    }
    AndroidVersion max = null;
    RemotePackage latest = null;
    for (RemotePackage pkg : remotePackages.values()) {
        TypeDetails details = pkg.getTypeDetails();
        if (!(details instanceof DetailsTypes.PlatformDetailsType)) {
            continue;
        }
        DetailsTypes.PlatformDetailsType platformDetails = (DetailsTypes.PlatformDetailsType) details;
        AndroidVersion version = platformDetails.getAndroidVersion();
        if (version.isPreview()) {
            // We only want stable platforms
            continue;
        }
        if (max == null || version.compareTo(max) > 0) {
            latest = pkg;
            max = version;
        }
    }
    return latest;
}
Also used : TypeDetails(com.android.repository.impl.meta.TypeDetails) DetailsTypes(com.android.sdklib.repository.meta.DetailsTypes) AndroidVersion(com.android.sdklib.AndroidVersion) RemotePackage(com.android.repository.api.RemotePackage) Nullable(org.jetbrains.annotations.Nullable)

Example 54 with AndroidVersion

use of com.android.sdklib.AndroidVersion in project android by JetBrains.

the class TargetMenuAction method addRealTargets.

private void addRealTargets(@NotNull DefaultActionGroup group) {
    Configuration configuration = myRenderContext.getConfiguration();
    assert configuration != null;
    IAndroidTarget current = configuration.getTarget();
    IAndroidTarget[] targets = configuration.getConfigurationManager().getTargets();
    boolean haveRecent = false;
    int minSdk = getMinSdkVersion();
    for (int i = targets.length - 1; i >= 0; i--) {
        IAndroidTarget target = targets[i];
        if (!ConfigurationManager.isLayoutLibTarget(target)) {
            continue;
        }
        if (!switchToTargetAllowed(configuration, target)) {
            continue;
        }
        AndroidVersion version = target.getVersion();
        if (version.getFeatureLevel() < minSdk) {
            continue;
        }
        if (version.getApiLevel() >= SHOW_FROM_API_LEVEL) {
            haveRecent = true;
        } else if (haveRecent) {
            // (unless of course all you have are ancient targets)
            break;
        }
        String title = getRenderingTargetLabel(target, false);
        boolean select = current == target;
        group.add(new SetTargetAction(myRenderContext, title, target, select));
    }
}
Also used : IAndroidTarget(com.android.sdklib.IAndroidTarget) AndroidVersion(com.android.sdklib.AndroidVersion)

Example 55 with AndroidVersion

use of com.android.sdklib.AndroidVersion in project android by JetBrains.

the class GradleImport method createModuleBuildGradle.

private void createModuleBuildGradle(@NonNull File file, ImportModule module) throws IOException {
    StringBuilder sb = new StringBuilder(500);
    if (module.isApp() || module.isAndroidLibrary()) {
        //noinspection PointlessBooleanExpression,ConstantConditions
        if (myPerModuleRepositories) {
            appendRepositories(sb, true);
        }
        if (module.isApp()) {
            sb.append("apply plugin: 'com.android.application'").append(NL);
        } else {
            assert module.isAndroidLibrary();
            sb.append("apply plugin: 'com.android.library'").append(NL);
        }
        sb.append(NL);
        //noinspection PointlessBooleanExpression,ConstantConditions
        if (myPerModuleRepositories) {
            sb.append("repositories {").append(NL);
            sb.append("    ").append(MAVEN_REPOSITORY).append(NL);
            sb.append("}").append(NL);
            sb.append(NL);
        }
        sb.append("android {").append(NL);
        AndroidVersion compileSdkVersion = module.getCompileSdkVersion();
        AndroidVersion minSdkVersion = module.getMinSdkVersion();
        AndroidVersion targetSdkVersion = module.getTargetSdkVersion();
        String compileSdkVersionString = compileSdkVersion.isPreview() ? '\'' + AndroidTargetHash.getPlatformHashString(compileSdkVersion) + '\'' : Integer.toString(compileSdkVersion.getApiLevel());
        String addOn = module.getAddOn();
        if (addOn != null) {
            compileSdkVersionString = '\'' + addOn + '\'';
        }
        String minSdkVersionString = minSdkVersion.isPreview() ? '\'' + module.getMinSdkVersion().getCodename() + '\'' : Integer.toString(module.getMinSdkVersion().getApiLevel());
        String targetSdkVersionString = targetSdkVersion.isPreview() ? '\'' + module.getTargetSdkVersion().getCodename() + '\'' : Integer.toString(module.getTargetSdkVersion().getApiLevel());
        sb.append("    compileSdkVersion ").append(compileSdkVersionString).append(NL);
        sb.append("    buildToolsVersion \"").append(getBuildToolsVersion()).append("\"").append(NL);
        sb.append(NL);
        sb.append("    defaultConfig {").append(NL);
        if (module.getPackage() != null && module.isApp()) {
            sb.append("        applicationId \"").append(module.getPackage()).append('"').append(NL);
        }
        if (minSdkVersion.getApiLevel() > 1) {
            sb.append("        minSdkVersion ").append(minSdkVersionString).append(NL);
        }
        if (targetSdkVersion.getApiLevel() > 1 && compileSdkVersion.getApiLevel() > 3) {
            sb.append("        targetSdkVersion ").append(targetSdkVersionString).append(NL);
        }
        String languageLevel = module.getLanguageLevel();
        if (!languageLevel.equals(EclipseProject.DEFAULT_LANGUAGE_LEVEL)) {
            sb.append("        compileOptions {").append(NL);
            // 1.6 => 1_6
            String level = languageLevel.replace('.', '_');
            sb.append("            sourceCompatibility JavaVersion.VERSION_").append(level).append(NL);
            sb.append("            targetCompatibility JavaVersion.VERSION_").append(level).append(NL);
            sb.append("        }").append(NL);
        }
        if (module.isNdkProject() && module.getNativeModuleName() != null) {
            sb.append(NL);
            sb.append("        ndk {").append(NL);
            sb.append("            moduleName \"").append(module.getNativeModuleName()).append("\"").append(NL);
            sb.append("        }").append(NL);
        }
        if (module.getInstrumentationDir() != null) {
            sb.append(NL);
            File manifestFile = new File(module.getInstrumentationDir(), ANDROID_MANIFEST_XML);
            assert manifestFile.exists() : manifestFile;
            Document manifest = getXmlDocument(manifestFile, true);
            if (manifest != null && manifest.getDocumentElement() != null) {
                String pkg = manifest.getDocumentElement().getAttribute(ATTR_PACKAGE);
                if (pkg != null && !pkg.isEmpty()) {
                    sb.append("        testApplicationId \"").append(pkg).append("\"").append(NL);
                }
                NodeList list = manifest.getElementsByTagName(NODE_INSTRUMENTATION);
                if (list.getLength() > 0) {
                    Element tag = (Element) list.item(0);
                    String runner = tag.getAttributeNS(ANDROID_URI, ATTR_NAME);
                    if (runner != null && !runner.isEmpty()) {
                        sb.append("        testInstrumentationRunner \"").append(runner).append("\"").append(NL);
                    }
                    Attr attr = tag.getAttributeNodeNS(ANDROID_URI, "functionalTest");
                    if (attr != null) {
                        sb.append("        testFunctionalTest ").append(attr.getValue()).append(NL);
                    }
                    attr = tag.getAttributeNodeNS(ANDROID_URI, "handleProfiling");
                    if (attr != null) {
                        sb.append("        testHandlingProfiling ").append(attr.getValue()).append(NL);
                    }
                }
            }
        }
        sb.append("    }").append(NL);
        sb.append(NL);
        List<File> localRules = module.getLocalProguardFiles();
        List<File> sdkRules = module.getSdkProguardFiles();
        if (!localRules.isEmpty() || !sdkRules.isEmpty()) {
            // User specified ProGuard rules; replicate exactly
            sb.append("    buildTypes {").append(NL);
            sb.append("        release {").append(NL);
            sb.append("            minifyEnabled true").append(NL);
            sb.append("            proguardFiles ");
            sb.append(generateProguardFileList(localRules, sdkRules)).append(NL);
            sb.append("        }").append(NL);
            sb.append("    }").append(NL);
        } else {
            // User didn't specify ProGuard rules; put in defaults (but off)
            sb.append("    buildTypes {").append(NL);
            sb.append("        release {").append(NL);
            sb.append("            minifyEnabled false").append(NL);
            sb.append("            proguardFiles getDefaultProguardFile('proguard-" + "android.txt'), 'proguard-rules.txt'").append(NL);
            sb.append("        }").append(NL);
            sb.append("    }").append(NL);
        }
        sb.append("}").append(NL);
        appendDependencies(sb, module);
    } else if (module.isJavaLibrary()) {
        //noinspection PointlessBooleanExpression,ConstantConditions
        if (myPerModuleRepositories) {
            appendRepositories(sb, false);
        }
        sb.append("apply plugin: 'java'").append(NL);
        String languageLevel = module.getLanguageLevel();
        if (!languageLevel.equals(EclipseProject.DEFAULT_LANGUAGE_LEVEL)) {
            sb.append(NL);
            sb.append("sourceCompatibility = \"");
            sb.append(languageLevel);
            sb.append("\"").append(NL);
            sb.append("targetCompatibility = \"");
            sb.append(languageLevel);
            sb.append("\"").append(NL);
        }
        appendDependencies(sb, module);
    } else {
        assert false : module;
    }
    Files.write(sb.toString(), file, UTF_8);
}
Also used : NodeList(org.w3c.dom.NodeList) Element(org.w3c.dom.Element) AndroidVersion(com.android.sdklib.AndroidVersion) Document(org.w3c.dom.Document) File(java.io.File) Attr(org.w3c.dom.Attr)

Aggregations

AndroidVersion (com.android.sdklib.AndroidVersion)89 Test (org.junit.Test)21 NotNull (org.jetbrains.annotations.NotNull)14 IAndroidTarget (com.android.sdklib.IAndroidTarget)12 IDevice (com.android.ddmlib.IDevice)11 Nullable (org.jetbrains.annotations.Nullable)9 MockPlatformTarget (com.android.sdklib.internal.androidTarget.MockPlatformTarget)8 Module (com.intellij.openapi.module.Module)8 File (java.io.File)8 AndroidFacet (org.jetbrains.android.facet.AndroidFacet)8 AndroidPlatform (org.jetbrains.android.sdk.AndroidPlatform)8 DetailsTypes (com.android.sdklib.repository.meta.DetailsTypes)6 Project (com.intellij.openapi.project.Project)5 Abi (com.android.sdklib.devices.Abi)4 InstantRunGradleSupport (com.android.tools.idea.fd.gradle.InstantRunGradleSupport)4 AndroidModuleModel (com.android.tools.idea.gradle.project.model.AndroidModuleModel)4 OutputFile (com.android.build.OutputFile)3 TypeDetails (com.android.repository.impl.meta.TypeDetails)3 AvdInfo (com.android.sdklib.internal.avd.AvdInfo)3 ModelWizardDialog (com.android.tools.idea.wizard.model.ModelWizardDialog)3