private RenderResult createRenderSession()

in rendering/src/com/android/tools/rendering/RenderTask.java [681:870]


  private RenderResult createRenderSession(@NotNull IImageFactory factory) {
    RenderContext context = getContext();
    RenderModelModule module = context.getModule();
    if (module.isDisposed()) {
      return null;
    }

    RenderXmlFile xmlFile = getXmlFile();
    if (xmlFile == null) {
      throw new IllegalStateException("createRenderSession shouldn't be called on RenderTask without PsiFile");
    }
    if (isDisposed.get()) {
      return null;
    }

    Configuration configuration = context.getConfiguration();
    ResourceResolver resolver = ResourceResolver.copy(configuration.getResourceResolver());
    if (resolver == null) {
      // Abort the rendering if the resources are not found.
      return null;
    }

    ILayoutPullParser modelParser = LayoutPullParsers.create(this);
    if (modelParser == null) {
      return null;
    }

    myLayoutlibCallback.reset();

    if (modelParser instanceof LayoutRenderPullParser) {
      // For regular layouts, if we use appcompat, we have to emulat the app:srcCompat attribute behaviour.
      boolean useSrcCompat = context.getModule().getDependencies().dependsOn(GoogleMavenArtifactId.SUPPORT_APPCOMPAT_V7) ||
                             context.getModule().getDependencies().dependsOn(GoogleMavenArtifactId.ANDROIDX_APPCOMPAT);
      ((LayoutRenderPullParser)modelParser).setUseSrcCompat(useSrcCompat);
      myLayoutlibCallback.setAaptDeclaredResources(((LayoutRenderPullParser)modelParser).getAaptDeclaredAttrs());
    }

    ILayoutPullParser includingParser = getIncludingLayoutParser(resolver, modelParser);
    if (includingParser != null) {
      modelParser = includingParser;
    }

    IAndroidTarget target = configuration.getTarget();
    int simulatedPlatform = target instanceof CompatibilityRenderTarget ? target.getVersion().getApiLevel() : 0;

    HardwareConfig hardwareConfig = myHardwareConfigHelper.getConfig();
    SessionParams params =
      new SessionParams(modelParser, myRenderingMode, context.getModule().getModuleKey(), hardwareConfig, resolver,
                        myLayoutlibCallback, context.getMinSdkVersion().getApiLevel(), context.getTargetSdkVersion().getApiLevel(),
                        myLogger, simulatedPlatform);
    params.setAssetRepository(context.getModule().getAssetRepository());

    params.setFlag(RenderParamsFlags.FLAG_KEY_ROOT_TAG, getRootTagName(xmlFile));
    params.setFlag(RenderParamsFlags.FLAG_KEY_DISABLE_BITMAP_CACHING, true);
    params.setFlag(RenderParamsFlags.FLAG_DO_NOT_RENDER_ON_CREATE, true);
    params.setFlag(RenderParamsFlags.FLAG_KEY_RESULT_IMAGE_AUTO_SCALE, true);
    params.setFlag(RenderParamsFlags.FLAG_KEY_ADAPTIVE_ICON_MASK_PATH, configuration.getAdaptiveShape().getPathDescription());
    params.setFlag(RenderParamsFlags.FLAG_KEY_USE_THEMED_ICON, configuration.getUseThemedIcon());
    params.setFlag(RenderParamsFlags.FLAG_KEY_FORCE_MONOCHROME_ICON, myForceMonochromeIcon);
    params.setFlag(RenderParamsFlags.FLAG_KEY_WALLPAPER_PATH, configuration.getWallpaperPath());
    params.setFlag(RenderParamsFlags.FLAG_KEY_USE_GESTURE_NAV, configuration.isGestureNav());
    params.setFlag(RenderParamsFlags.FLAG_KEY_EDGE_TO_EDGE, configuration.isEdgeToEdge());
    params.setFlag(RenderParamsFlags.FLAG_KEY_SHOW_CUTOUT, true);

    params.setLayoutValidationChecker(() -> myEnableLayoutScanner);

    params.setCustomContentHierarchyParser(myCustomContentHierarchyParser);
    params.setImageTransformation(configuration.getImageTransformation());

    params.setAnimatorDurationScale(myAnimatorDurationScale);

    // 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);

    LayoutDirectionQualifier qualifier = configuration.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 {
      @Nullable RenderModelManifest manifestInfo = context.getModule().getManifest();
      params.setRtlSupport(manifestInfo != null && manifestInfo.isRtlSupported());
    }
    catch (Exception e) {
      // ignore.
    }

    // Don't show navigation buttons on older platforms.
    Device device = configuration.getDevice();
    if (!myShowDecorations || Device.isWear(device)) {
      params.setForceNoDecor();
    }
    else {
      try {
        @Nullable RenderModelManifest manifestInfo = context.getModule().getManifest();
        ResourceValue appLabel = manifestInfo != null
                                 ? manifestInfo.getApplicationLabel()
                                 : new ResourceValueImpl(ResourceNamespace.RES_AUTO, ResourceType.STRING, "appName", "");
        if (manifestInfo != null) {
          params.setAppIcon(manifestInfo.getApplicationIcon());
        }
        String activity = configuration.getActivity();
        if (activity != null) {
          params.setActivityName(activity);
          ActivityAttributesSnapshot attributes = manifestInfo != null ? manifestInfo.getActivityAttributes(activity) : null;
          if (attributes != null) {
            if (attributes.getLabel() != null) {
              appLabel = attributes.getLabel();
            }
            if (attributes.getIcon() != null) {
              params.setAppIcon(attributes.getIcon());
            }
          }
        }
        ResourceValue resource = params.getResources().resolveResValue(appLabel);
        if (resource != null) {
          params.setAppLabel(resource.getValue());
        }
      }
      catch (Exception ignored) {
      }
    }

    if (mySetTransparentBackground || requiresTransparency()) {
      params.setTransparentBackground();
    }

    params.setImageFactory(factory);

    if (myTimeout > 0) {
      params.setTimeout(myTimeout);
    }

    params.setFontScale(configuration.getFontScale());
    params.setUiMode(configuration.getUiModeFlagValue());

    try {
      myLayoutlibCallback.setLogger(myLogger);

      RenderSecurityManager securityManager =
        isSecurityManagerEnabled ?
        myContext.getModule().getEnvironment().createRenderSecurityManager(
          module.getProject().getBasePath(),
          context.getModule().getAndroidPlatform()
        ) : null;
      if (securityManager != null) {
        securityManager.setActive(true, myCredential);
      }

      try {
        RenderSession session = myLayoutLib.createSession(params);

        if (session.getResult().isSuccess()) {
          session.setSystemBootTimeNanos(0);
          session.setSystemTimeNanos(0);
          // Advance the frame time to display the material progress bars
          session.setElapsedFrameTimeNanos(TimeUnit.MILLISECONDS.toNanos(500));
        }
        BufferedImage resultImage = session.getImage();

        RenderResult result = RenderResult.create(context, session, xmlFile, myLogger, toPooledImage(resultImage), myLayoutlibCallback.isUsed());
        RenderSession oldRenderSession = myRenderSession;
        myRenderSession = session;
        RenderTaskPatcher.enableComposeHotReloadMode(myModuleClassLoaderReference.getClassLoader());
        if (oldRenderSession != null) {
          disposeRenderSession(oldRenderSession);
        }
        addDiagnostics(result.getRenderResult());
        return result;
      }
      finally {
        if (securityManager != null) {
          securityManager.dispose(myCredential);
        }
      }
    }
    catch (RuntimeException t) {
      // Exceptions from the bridge
      myLogger.error(null, t.getLocalizedMessage(), t, null, null);
      throw t;
    }
  }