Search in sources :

Example 1 with ActivityAttributes

use of com.android.tools.idea.model.MergedManifest.ActivityAttributes in project android by JetBrains.

the class RenderTask method createRenderSession.

/**
   * Renders the model and returns the result as a {@link com.android.ide.common.rendering.api.RenderSession}.
   *
   * @param factory Factory for images which would be used to render layouts to.
   * @return the {@link RenderResult resulting from rendering the current model
   */
@Nullable
private RenderResult createRenderSession(@NotNull IImageFactory factory) {
    if (myPsiFile == null) {
        throw new IllegalStateException("createRenderSession shouldn't be called on RenderTask without PsiFile");
    }
    ResourceResolver resolver = ResourceResolver.copy(getResourceResolver());
    if (resolver == null) {
        // Abort the rendering if the resources are not found.
        return null;
    }
    ILayoutPullParser modelParser = LayoutPullParserFactory.create(this);
    if (modelParser == null) {
        return null;
    }
    if (modelParser instanceof LayoutPsiPullParser) {
        // For regular layouts, if we use appcompat, we have to emulat the app:srcCompat attribute behaviour
        AndroidModuleModel androidModel = AndroidModuleModel.get(myRenderService.getFacet());
        boolean useSrcCompat = androidModel != null && GradleUtil.dependsOn(androidModel, APPCOMPAT_LIB_ARTIFACT);
        ((LayoutPsiPullParser) modelParser).setUseSrcCompat(useSrcCompat);
    }
    myLayoutlibCallback.reset();
    ILayoutPullParser includingParser = getIncludingLayoutParser(resolver, modelParser);
    if (includingParser != null) {
        modelParser = includingParser;
    }
    IAndroidTarget target = myConfiguration.getTarget();
    int simulatedPlatform = target instanceof CompatibilityRenderTarget ? target.getVersion().getApiLevel() : 0;
    Module module = myRenderService.getModule();
    HardwareConfig hardwareConfig = myHardwareConfigHelper.getConfig();
    final SessionParams params = new SessionParams(modelParser, myRenderingMode, module, /* projectKey */
    hardwareConfig, resolver, myLayoutlibCallback, myMinSdkVersion.getApiLevel(), myTargetSdkVersion.getApiLevel(), myLogger, simulatedPlatform);
    params.setAssetRepository(myAssetRepository);
    params.setFlag(RenderParamsFlags.FLAG_KEY_ROOT_TAG, AndroidPsiUtils.getRootTagName(myPsiFile));
    params.setFlag(RenderParamsFlags.FLAG_KEY_RECYCLER_VIEW_SUPPORT, true);
    params.setFlag(RenderParamsFlags.FLAG_KEY_DISABLE_BITMAP_CACHING, true);
    params.setFlag(RenderParamsFlags.FLAG_DO_NOT_RENDER_ON_CREATE, true);
    // Request margin and baseline information.
    // TODO: Be smarter about setting this; start without it, and on the first request
    // for an extended view info, re-render in the same session, and then set a flag
    // which will cause this to create extended view info each time from then on in the
    // same session
    params.setExtendedViewInfoMode(true);
    MergedManifest manifestInfo = MergedManifest.get(module);
    LayoutDirectionQualifier qualifier = myConfiguration.getFullConfig().getLayoutDirectionQualifier();
    if (qualifier != null && qualifier.getValue() == LayoutDirection.RTL && !getLayoutLib().isRtl(myLocale.toLocaleId())) {
        // We don't have a flag to force RTL regardless of locale, so just pick a RTL locale (note that
        // this is decoupled from resource lookup)
        params.setLocale("ur");
    } else {
        params.setLocale(myLocale.toLocaleId());
    }
    try {
        params.setRtlSupport(manifestInfo.isRtlSupported());
    } catch (Exception e) {
    // ignore.
    }
    // Don't show navigation buttons on older platforms
    Device device = myConfiguration.getDevice();
    if (!myShowDecorations || HardwareConfigHelper.isWear(device)) {
        params.setForceNoDecor();
    } else {
        try {
            params.setAppLabel(manifestInfo.getApplicationLabel());
            params.setAppIcon(manifestInfo.getApplicationIcon());
            String activity = myConfiguration.getActivity();
            if (activity != null) {
                params.setActivityName(activity);
                ActivityAttributes attributes = manifestInfo.getActivityAttributes(activity);
                if (attributes != null) {
                    if (attributes.getLabel() != null) {
                        params.setAppLabel(attributes.getLabel());
                    }
                    if (attributes.getIcon() != null) {
                        params.setAppIcon(attributes.getIcon());
                    }
                }
            }
        } catch (Exception e) {
        // ignore.
        }
    }
    if (myOverrideBgColor != null) {
        params.setOverrideBgColor(myOverrideBgColor.intValue());
    } else if (requiresTransparency()) {
        params.setOverrideBgColor(0);
    }
    params.setImageFactory(factory);
    if (myTimeout > 0) {
        params.setTimeout(myTimeout);
    }
    try {
        myLayoutlibCallback.setLogger(myLogger);
        myLayoutlibCallback.setResourceResolver(resolver);
        RenderResult result = ApplicationManager.getApplication().runReadAction(new Computable<RenderResult>() {

            @NotNull
            @Override
            public RenderResult compute() {
                Module module = myRenderService.getModule();
                RenderSecurityManager securityManager = isSecurityManagerEnabled ? RenderSecurityManagerFactory.create(module, getPlatform()) : null;
                if (securityManager != null) {
                    securityManager.setActive(true, myCredential);
                }
                try {
                    int retries = 0;
                    RenderSession session = null;
                    while (retries < 10) {
                        if (session != null) {
                            session.dispose();
                        }
                        session = myLayoutLib.createSession(params);
                        Result result = session.getResult();
                        if (result.getStatus() != Result.Status.ERROR_TIMEOUT) {
                            // Sometimes happens at startup; treat it as a timeout; typically a retry fixes it
                            if (!result.isSuccess() && "The main Looper has already been prepared.".equals(result.getErrorMessage())) {
                                retries++;
                                continue;
                            }
                            break;
                        }
                        retries++;
                    }
                    if (session.getResult().isSuccess()) {
                        // Advance the frame time to display the material progress bars
                        // TODO: Expose this through the RenderTask API to allow callers to customize this value
                        long now = System.nanoTime();
                        session.setSystemBootTimeNanos(now);
                        session.setSystemTimeNanos(now);
                        session.setElapsedFrameTimeNanos(TimeUnit.MILLISECONDS.toNanos(500));
                    }
                    RenderResult result = RenderResult.create(RenderTask.this, session, myPsiFile, myLogger, myImagePool.copyOf(session.getImage()));
                    myRenderSession = session;
                    return result;
                } finally {
                    if (securityManager != null) {
                        securityManager.dispose(myCredential);
                    }
                }
            }
        });
        addDiagnostics(result.getRenderResult());
        return result;
    } catch (RuntimeException t) {
        // Exceptions from the bridge
        myLogger.error(null, t.getLocalizedMessage(), t, null);
        throw t;
    }
}
Also used : MergedManifest(com.android.tools.idea.model.MergedManifest) ActivityAttributes(com.android.tools.idea.model.MergedManifest.ActivityAttributes) NotNull(org.jetbrains.annotations.NotNull) Device(com.android.sdklib.devices.Device) IAndroidTarget(com.android.sdklib.IAndroidTarget) XmlPullParserException(org.xmlpull.v1.XmlPullParserException) IOException(java.io.IOException) CompatibilityRenderTarget(com.android.tools.idea.rendering.multi.CompatibilityRenderTarget) ResourceResolver(com.android.ide.common.resources.ResourceResolver) AndroidModuleModel(com.android.tools.idea.gradle.project.model.AndroidModuleModel) LayoutDirectionQualifier(com.android.ide.common.resources.configuration.LayoutDirectionQualifier) Module(com.intellij.openapi.module.Module) Nullable(org.jetbrains.annotations.Nullable)

Example 2 with ActivityAttributes

use of com.android.tools.idea.model.MergedManifest.ActivityAttributes in project android by JetBrains.

the class MergedManifestTest method testGetActivityThemes6.

public void testGetActivityThemes6() throws Exception {
    // Ensures that when the *rendering* target is less than version 11, we don't
    // use Holo even though the manifest SDK version calls for it.
    MergedManifest info = getMergedManifest("<manifest xmlns:android='http://schemas.android.com/apk/res/android'\n" + "    package='com.android.unittest'>\n" + "    <uses-sdk android:minSdkVersion='3' android:targetSdkVersion='11'/>\n" + "</manifest>\n");
    Map<String, ActivityAttributes> map = info.getActivityAttributesMap();
    assertEquals(map.toString(), 0, map.size());
    assertEquals("com.android.unittest", info.getPackage());
    assertEquals("Theme.Holo", ResourceHelper.styleToTheme(info.getDefaultTheme(null, XLARGE, null)));
    // Here's the check
    IAndroidTarget olderVersion = new TestAndroidTarget(4);
    assertEquals("Theme", ResourceHelper.styleToTheme(info.getDefaultTheme(olderVersion, XLARGE, null)));
}
Also used : ActivityAttributes(com.android.tools.idea.model.MergedManifest.ActivityAttributes) IAndroidTarget(com.android.sdklib.IAndroidTarget)

Example 3 with ActivityAttributes

use of com.android.tools.idea.model.MergedManifest.ActivityAttributes in project android by JetBrains.

the class ConfigurationManager method computePreferredTheme.

/**
   * Returns the preferred theme
   */
@NotNull
public String computePreferredTheme(@NotNull Configuration configuration) {
    MergedManifest manifest = MergedManifest.get(myModule);
    // TODO: If we are rendering a layout in included context, pick the theme
    // from the outer layout instead
    String activity = configuration.getActivity();
    if (activity != null) {
        String activityFqcn = activity;
        if (activity.startsWith(".")) {
            String pkg = StringUtil.notNullize(manifest.getPackage());
            activityFqcn = pkg + activity;
        }
        ActivityAttributes attributes = manifest.getActivityAttributes(activityFqcn);
        if (attributes != null) {
            String theme = attributes.getTheme();
            // Check that the theme looks like a reference
            if (theme != null && theme.startsWith(SdkConstants.PREFIX_RESOURCE_REF)) {
                return theme;
            }
        }
        // Try with the package name from the manifest.
        attributes = manifest.getActivityAttributes(activity);
        if (attributes != null) {
            String theme = attributes.getTheme();
            // Check that the theme looks like a reference
            if (theme != null && theme.startsWith(SdkConstants.PREFIX_RESOURCE_REF)) {
                return theme;
            }
        }
    }
    // in the manifest)
    return manifest.getDefaultTheme(configuration.getTarget(), configuration.getScreenSize(), configuration.getDevice());
}
Also used : MergedManifest(com.android.tools.idea.model.MergedManifest) ActivityAttributes(com.android.tools.idea.model.MergedManifest.ActivityAttributes) NotNull(org.jetbrains.annotations.NotNull)

Aggregations

ActivityAttributes (com.android.tools.idea.model.MergedManifest.ActivityAttributes)3 IAndroidTarget (com.android.sdklib.IAndroidTarget)2 MergedManifest (com.android.tools.idea.model.MergedManifest)2 NotNull (org.jetbrains.annotations.NotNull)2 ResourceResolver (com.android.ide.common.resources.ResourceResolver)1 LayoutDirectionQualifier (com.android.ide.common.resources.configuration.LayoutDirectionQualifier)1 Device (com.android.sdklib.devices.Device)1 AndroidModuleModel (com.android.tools.idea.gradle.project.model.AndroidModuleModel)1 CompatibilityRenderTarget (com.android.tools.idea.rendering.multi.CompatibilityRenderTarget)1 Module (com.intellij.openapi.module.Module)1 IOException (java.io.IOException)1 Nullable (org.jetbrains.annotations.Nullable)1 XmlPullParserException (org.xmlpull.v1.XmlPullParserException)1