Search in sources :

Example 6 with ResourceResolver

use of com.android.ide.common.resources.ResourceResolver in project android by JetBrains.

the class ConfiguredThemeEditorStyle method getParent.

/**
   * @param themeResolver theme resolver that would be used to look up parent theme by name
   *                      Pass null if you don't care about resulting ThemeEditorStyle source module (which would be null in that case)
   * @return the style parent
   */
@Nullable
public /*if this is a root style*/
ConfiguredThemeEditorStyle getParent(@Nullable ThemeResolver themeResolver) {
    ResourceResolver resolver = myConfiguration.getResourceResolver();
    assert resolver != null;
    StyleResourceValue parent = resolver.getParent(getStyleResourceValue());
    if (parent == null) {
        return null;
    }
    if (themeResolver == null) {
        return ResolutionUtils.getStyle(myConfiguration, ResolutionUtils.getQualifiedStyleName(parent), null);
    } else {
        return themeResolver.getTheme(ResolutionUtils.getQualifiedStyleName(parent));
    }
}
Also used : StyleResourceValue(com.android.ide.common.rendering.api.StyleResourceValue) ResourceResolver(com.android.ide.common.resources.ResourceResolver) Nullable(org.jetbrains.annotations.Nullable)

Example 7 with ResourceResolver

use of com.android.ide.common.resources.ResourceResolver 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 8 with ResourceResolver

use of com.android.ide.common.resources.ResourceResolver in project android by JetBrains.

the class RenderTask method measure.

@Nullable
private RenderSession measure(ILayoutPullParser parser) {
    ResourceResolver resolver = getResourceResolver();
    if (resolver == null) {
        // Abort the rendering if the resources are not found.
        return null;
    }
    myLayoutlibCallback.reset();
    HardwareConfig hardwareConfig = myHardwareConfigHelper.getConfig();
    Module module = myRenderService.getModule();
    final SessionParams params = new SessionParams(parser, RenderingMode.NORMAL, module, /* projectKey */
    hardwareConfig, resolver, myLayoutlibCallback, myMinSdkVersion.getApiLevel(), myTargetSdkVersion.getApiLevel(), myLogger);
    params.setLayoutOnly();
    params.setForceNoDecor();
    params.setExtendedViewInfoMode(true);
    params.setLocale(myLocale.toLocaleId());
    params.setAssetRepository(myAssetRepository);
    params.setFlag(RenderParamsFlags.FLAG_KEY_RECYCLER_VIEW_SUPPORT, true);
    MergedManifest manifestInfo = MergedManifest.get(module);
    try {
        params.setRtlSupport(manifestInfo.isRtlSupported());
    } catch (Exception e) {
    // ignore.
    }
    try {
        myLayoutlibCallback.setLogger(myLogger);
        myLayoutlibCallback.setResourceResolver(resolver);
        return ApplicationManager.getApplication().runReadAction(new Computable<RenderSession>() {

            @Nullable
            @Override
            public RenderSession compute() {
                int retries = 0;
                while (retries < 10) {
                    RenderSession 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++;
                            session.dispose();
                            continue;
                        }
                        return session;
                    }
                    retries++;
                }
                return null;
            }
        });
    } 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) ResourceResolver(com.android.ide.common.resources.ResourceResolver) Module(com.intellij.openapi.module.Module) XmlPullParserException(org.xmlpull.v1.XmlPullParserException) IOException(java.io.IOException) Nullable(org.jetbrains.annotations.Nullable) Nullable(org.jetbrains.annotations.Nullable)

Example 9 with ResourceResolver

use of com.android.ide.common.resources.ResourceResolver in project android by JetBrains.

the class ThemeHelper method hasActionBar.

public static Boolean hasActionBar(@NotNull Configuration configuration, @NotNull String themeName) {
    StyleResourceValue theme = getStyleResource(configuration, themeName);
    if (theme == null) {
        return null;
    }
    ResourceResolver resolver = configuration.getResourceResolver();
    assert resolver != null;
    ResourceValue value = resolver.findItemInStyle(theme, "windowActionBar", theme.isFramework());
    if (value == null || value.getValue() == null) {
        return true;
    }
    return SdkConstants.VALUE_TRUE.equals(value.getValue());
}
Also used : StyleResourceValue(com.android.ide.common.rendering.api.StyleResourceValue) ResourceResolver(com.android.ide.common.resources.ResourceResolver) ResourceValue(com.android.ide.common.rendering.api.ResourceValue) StyleResourceValue(com.android.ide.common.rendering.api.StyleResourceValue)

Example 10 with ResourceResolver

use of com.android.ide.common.resources.ResourceResolver in project android by JetBrains.

the class ThemeHelper method getStyleResource.

@Nullable
private static StyleResourceValue getStyleResource(@NotNull Configuration configuration, @NotNull String themeName) {
    configuration.setTheme(themeName);
    ResourceResolver resolver = configuration.getResourceResolver();
    assert resolver != null;
    boolean isFramework = themeName.startsWith(SdkConstants.PREFIX_ANDROID);
    if (isFramework) {
        themeName = themeName.substring(SdkConstants.PREFIX_ANDROID.length());
    }
    return resolver.getStyle(themeName, isFramework);
}
Also used : ResourceResolver(com.android.ide.common.resources.ResourceResolver) Nullable(org.jetbrains.annotations.Nullable)

Aggregations

ResourceResolver (com.android.ide.common.resources.ResourceResolver)43 Configuration (com.android.tools.idea.configurations.Configuration)16 ResourceValue (com.android.ide.common.rendering.api.ResourceValue)13 NotNull (org.jetbrains.annotations.NotNull)11 FolderConfiguration (com.android.ide.common.resources.configuration.FolderConfiguration)8 ItemResourceValue (com.android.ide.common.rendering.api.ItemResourceValue)6 Nullable (org.jetbrains.annotations.Nullable)6 SessionParams (com.android.ide.common.rendering.api.SessionParams)5 StyleResourceValue (com.android.ide.common.rendering.api.StyleResourceValue)5 ConfiguredThemeEditorStyle (com.android.tools.idea.editors.theme.datamodels.ConfiguredThemeEditorStyle)5 Module (com.intellij.openapi.module.Module)5 VirtualFile (com.intellij.openapi.vfs.VirtualFile)5 IAndroidTarget (com.android.sdklib.IAndroidTarget)4 Project (com.intellij.openapi.project.Project)4 ResourceType (com.android.resources.ResourceType)3 CompatibilityRenderTarget (com.android.tools.idea.rendering.multi.CompatibilityRenderTarget)3 XmlFile (com.intellij.psi.xml.XmlFile)3 ResourceRepository (com.android.ide.common.resources.ResourceRepository)2 Device (com.android.sdklib.devices.Device)2 ConfigurationManager (com.android.tools.idea.configurations.ConfigurationManager)2