Search in sources :

Example 31 with IAndroidTarget

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

the class ThemeEditorStyle method isPublic.

/**
   * Returns whether this style is public.
   */
public boolean isPublic() {
    if (!isFramework()) {
        return true;
    }
    IAndroidTarget target = myManager.getTarget();
    if (target == null) {
        LOG.error("Unable to get IAndroidTarget.");
        return false;
    }
    AndroidTargetData androidTargetData = AndroidTargetData.getTargetData(target, myManager.getModule());
    if (androidTargetData == null) {
        LOG.error("Unable to get AndroidTargetData.");
        return false;
    }
    return androidTargetData.isResourcePublic(ResourceType.STYLE.getName(), getName());
}
Also used : IAndroidTarget(com.android.sdklib.IAndroidTarget) AndroidTargetData(org.jetbrains.android.sdk.AndroidTargetData)

Example 32 with IAndroidTarget

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

the class ThemeEditorStyle method getValues.

/**
   * @param configuration FolderConfiguration of the style to lookup
   * @return all values defined in this style with a FolderConfiguration configuration
   */
@NotNull
public Collection<ItemResourceValue> getValues(@NotNull FolderConfiguration configuration) {
    if (isFramework()) {
        IAndroidTarget target = myManager.getHighestApiTarget();
        assert target != null;
        com.android.ide.common.resources.ResourceItem styleItem = myManager.getResolverCache().getFrameworkResources(new FolderConfiguration(), target).getResourceItem(ResourceType.STYLE, getName());
        for (ResourceFile file : styleItem.getSourceFileList()) {
            if (file.getConfiguration().equals(configuration)) {
                StyleResourceValue style = (StyleResourceValue) file.getValue(ResourceType.STYLE, getName());
                return style.getValues();
            }
        }
        throw new IllegalArgumentException("bad folder config " + configuration);
    }
    for (final ResourceItem styleItem : getStyleResourceItems()) {
        if (configuration.equals(styleItem.getConfiguration())) {
            StyleResourceValue style = (StyleResourceValue) styleItem.getResourceValue(false);
            if (style == null) {
                // style might be null if the value fails to parse
                continue;
            }
            return style.getValues();
        }
    }
    throw new IllegalArgumentException("bad folder config " + configuration);
}
Also used : ResourceFile(com.android.ide.common.resources.ResourceFile) StyleResourceValue(com.android.ide.common.rendering.api.StyleResourceValue) IAndroidTarget(com.android.sdklib.IAndroidTarget) FolderConfiguration(com.android.ide.common.resources.configuration.FolderConfiguration) ResourceItem(com.android.ide.common.res2.ResourceItem) NotNull(org.jetbrains.annotations.NotNull)

Example 33 with IAndroidTarget

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

the class VariantItemListener method itemStateChanged.

@Override
public void itemStateChanged(ItemEvent e) {
    if (e.getStateChange() != ItemEvent.SELECTED) {
        return;
    }
    VariantsComboItem item = (VariantsComboItem) e.getItem();
    Configuration oldConfiguration = myContext.getConfiguration();
    ConfigurationManager manager = oldConfiguration.getConfigurationManager();
    Configuration newConfiguration = Configuration.create(manager, null, null, item.getRestrictedConfiguration());
    // Target and locale are global so we need to set them in the configuration manager when updated
    VersionQualifier newVersionQualifier = item.getRestrictedConfiguration().getVersionQualifier();
    if (newVersionQualifier != null) {
        IAndroidTarget realTarget = manager.getHighestApiTarget() != null ? manager.getHighestApiTarget() : manager.getTarget();
        assert realTarget != null;
        manager.setTarget(new CompatibilityRenderTarget(realTarget, newVersionQualifier.getVersion(), null));
    } else {
        manager.setTarget(null);
    }
    LocaleQualifier newLocaleQualifier = item.getRestrictedConfiguration().getLocaleQualifier();
    manager.setLocale(newLocaleQualifier != null ? Locale.create(newLocaleQualifier) : Locale.ANY);
    oldConfiguration.setDevice(null, false);
    Configuration.copyCompatible(newConfiguration, oldConfiguration);
    oldConfiguration.updated(ConfigurationListener.MASK_FOLDERCONFIG);
}
Also used : Configuration(com.android.tools.idea.configurations.Configuration) VersionQualifier(com.android.ide.common.resources.configuration.VersionQualifier) CompatibilityRenderTarget(com.android.tools.idea.rendering.multi.CompatibilityRenderTarget) IAndroidTarget(com.android.sdklib.IAndroidTarget) ConfigurationManager(com.android.tools.idea.configurations.ConfigurationManager) LocaleQualifier(com.android.ide.common.resources.configuration.LocaleQualifier)

Example 34 with IAndroidTarget

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

the class RenderService method createTask.

/**
   * Creates a new {@link RenderService} associated with the given editor.
   *
   * @return a {@link RenderService} which can perform rendering services
   */
@Nullable
public RenderTask createTask(@Nullable final PsiFile psiFile, @NotNull final Configuration configuration, @NotNull final RenderLogger logger, @Nullable final EditorDesignSurface surface) {
    Module module = myFacet.getModule();
    final Project project = module.getProject();
    AndroidPlatform platform = getPlatform(module, logger);
    if (platform == null) {
        return null;
    }
    IAndroidTarget target = configuration.getTarget();
    if (target == null) {
        logger.addMessage(RenderProblem.createPlain(ERROR, "No render target was chosen"));
        return null;
    }
    warnIfObsoleteLayoutLib(module, logger, surface, target);
    LayoutLibrary layoutLib;
    try {
        layoutLib = platform.getSdkData().getTargetData(target).getLayoutLibrary(project);
        if (layoutLib == null) {
            String message = AndroidBundle.message("android.layout.preview.cannot.load.library.error");
            logger.addMessage(RenderProblem.createPlain(ERROR, message));
            return null;
        }
    } catch (UnsupportedJavaRuntimeException e) {
        RenderProblem.Html javaVersionProblem = RenderProblem.create(ERROR);
        javaVersionProblem.getHtmlBuilder().add(e.getPresentableMessage()).newline().addLink("Install a supported JDK", JDK_INSTALL_URL);
        logger.addMessage(javaVersionProblem);
        return null;
    } catch (RenderingException e) {
        String message = e.getPresentableMessage();
        message = message != null ? message : AndroidBundle.message("android.layout.preview.default.error.message");
        logger.addMessage(RenderProblem.createPlain(ERROR, message, module.getProject(), logger.getLinkManager(), e));
        return null;
    } catch (IOException e) {
        final String message = e.getMessage();
        logger.error(null, "I/O error: " + (message != null ? ": " + message : ""), e);
        return null;
    }
    if (psiFile != null && TAG_PREFERENCE_SCREEN.equals(AndroidPsiUtils.getRootTagName(psiFile)) && !layoutLib.supports(Features.PREFERENCES_RENDERING)) {
        // This means that user is using an outdated version of layoutlib. A warning to update has already been
        // presented in warnIfObsoleteLayoutLib(). Just log a plain message asking users to update.
        logger.addMessage(RenderProblem.createPlain(ERROR, "This version of the rendering library does not support rendering Preferences. " + "Update it using the SDK Manager"));
        return null;
    }
    Device device = configuration.getDevice();
    if (device == null) {
        logger.addMessage(RenderProblem.createPlain(ERROR, "No device selected"));
        return null;
    }
    try {
        RenderTask task = new RenderTask(this, configuration, logger, layoutLib, device, myCredential, CrashReporter.getInstance());
        if (psiFile != null) {
            task.setPsiFile(psiFile);
        }
        task.setDesignSurface(surface);
        return task;
    } catch (IncorrectOperationException | AssertionError e) {
        // We can get this exception if the module/project is closed while we are updating the model. Ignore it.
        assert myFacet.isDisposed();
    }
    return null;
}
Also used : LayoutLibrary(com.android.ide.common.rendering.LayoutLibrary) Device(com.android.sdklib.devices.Device) UnsupportedJavaRuntimeException(com.android.tools.idea.layoutlib.UnsupportedJavaRuntimeException) RenderingException(com.android.tools.idea.layoutlib.RenderingException) AndroidPlatform(org.jetbrains.android.sdk.AndroidPlatform) IAndroidTarget(com.android.sdklib.IAndroidTarget) IOException(java.io.IOException) Project(com.intellij.openapi.project.Project) IncorrectOperationException(com.intellij.util.IncorrectOperationException) Module(com.intellij.openapi.module.Module) Nullable(org.jetbrains.annotations.Nullable)

Example 35 with IAndroidTarget

use of com.android.sdklib.IAndroidTarget 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)

Aggregations

IAndroidTarget (com.android.sdklib.IAndroidTarget)105 Nullable (org.jetbrains.annotations.Nullable)24 VirtualFile (com.intellij.openapi.vfs.VirtualFile)19 Module (com.intellij.openapi.module.Module)17 NotNull (org.jetbrains.annotations.NotNull)16 AndroidSdkData (org.jetbrains.android.sdk.AndroidSdkData)15 Sdk (com.intellij.openapi.projectRoots.Sdk)14 File (java.io.File)13 AndroidFacet (org.jetbrains.android.facet.AndroidFacet)13 AndroidPlatform (org.jetbrains.android.sdk.AndroidPlatform)13 AndroidVersion (com.android.sdklib.AndroidVersion)11 Device (com.android.sdklib.devices.Device)11 FolderConfiguration (com.android.ide.common.resources.configuration.FolderConfiguration)9 State (com.android.sdklib.devices.State)8 AndroidSdkAdditionalData (org.jetbrains.android.sdk.AndroidSdkAdditionalData)8 AndroidTargetData (org.jetbrains.android.sdk.AndroidTargetData)8 Configuration (com.android.tools.idea.configurations.Configuration)7 CompatibilityRenderTarget (com.android.tools.idea.rendering.multi.CompatibilityRenderTarget)7 CompilerMessage (org.jetbrains.jps.incremental.messages.CompilerMessage)7 ConfigurationManager (com.android.tools.idea.configurations.ConfigurationManager)6