sdk-common

16:52:16.173 INFO  jd.cli.Main - Decompiling sdk-common.jar
package com.android.ide.common.internal;

import com.android.annotations.NonNull;
import com.android.annotations.Nullable;
import java.io.File;
import java.io.IOException;
import java.util.Map;

public class AaptRunner
{
  private final String mAaptLocation;
  private final CommandLineRunner mCommandLineRunner;
  
  public AaptRunner(@NonNull String aaptLocation, @NonNull CommandLineRunner commandLineRunner)
  {
    mAaptLocation = aaptLocation;
    mCommandLineRunner = commandLineRunner;
  }
  
  public void crunchPng(File from, File to)
    throws InterruptedException, LoggedErrorException, IOException
  {
    crunchPng(from, to, null);
  }
  
  public void crunchPng(File from, File to, @Nullable Map<String, String> envVariableMap)
    throws IOException, InterruptedException, LoggedErrorException
  {
    String[] command = { mAaptLocation, "s", "-i", from.getAbsolutePath(), "-o", to.getAbsolutePath() };
    
    mCommandLineRunner.runCmdLine(command, envVariableMap);
  }
}

/* Location:
 * Qualified Name:     com.android.ide.common.internal.AaptRunner
 * Java Class Version: 6 (50.0)
 * JD-Core Version:    0.7.1
 */
package com.android.ide.common.internal;

class CommandLineRunner$1 {}

/* Location:
 * Qualified Name:     com.android.ide.common.internal.CommandLineRunner.1
 * Java Class Version: 6 (50.0)
 * JD-Core Version:    0.7.1
 */
package com.android.ide.common.internal;

import com.android.annotations.Nullable;
import com.android.sdklib.util.GrabProcessOutput.IProcessOutput;
import com.android.utils.ILogger;
import com.google.common.collect.Lists;
import java.util.List;

class CommandLineRunner$OutputGrabber
  implements GrabProcessOutput.IProcessOutput
{
  private boolean mFoundError = false;
  private List<String> mErrors = Lists.newArrayList();
  
  private CommandLineRunner$OutputGrabber(CommandLineRunner paramCommandLineRunner) {}
  
  public void out(@Nullable String line)
  {
    if (line != null) {
      CommandLineRunner.access$000(this$0).info(line, new Object[0]);
    }
  }
  
  public void err(@Nullable String line)
  {
    if (line != null)
    {
      CommandLineRunner.access$000(this$0).error(null, line, new Object[0]);
      mErrors.add(line);
      mFoundError = true;
    }
  }
  
  private boolean foundError()
  {
    return mFoundError;
  }
}

/* Location:
 * Qualified Name:     com.android.ide.common.internal.CommandLineRunner.OutputGrabber
 * Java Class Version: 6 (50.0)
 * JD-Core Version:    0.7.1
 */
package com.android.ide.common.internal;

import com.android.annotations.NonNull;
import com.android.annotations.Nullable;
import com.android.sdklib.util.GrabProcessOutput;
import com.android.sdklib.util.GrabProcessOutput.IProcessOutput;
import com.android.sdklib.util.GrabProcessOutput.Wait;
import com.android.utils.ILogger;
import com.google.common.base.Joiner;
import com.google.common.collect.Lists;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

public class CommandLineRunner
{
  private final ILogger mLogger;
  
  private class OutputGrabber
    implements GrabProcessOutput.IProcessOutput
  {
    private boolean mFoundError = false;
    private List<String> mErrors = Lists.newArrayList();
    
    private OutputGrabber() {}
    
    public void out(@Nullable String line)
    {
      if (line != null) {
        mLogger.info(line, new Object[0]);
      }
    }
    
    public void err(@Nullable String line)
    {
      if (line != null)
      {
        mLogger.error(null, line, new Object[0]);
        mErrors.add(line);
        mFoundError = true;
      }
    }
    
    private boolean foundError()
    {
      return mFoundError;
    }
  }
  
  public CommandLineRunner(ILogger logger)
  {
    mLogger = logger;
  }
  
  public void runCmdLine(@NonNull List<String> command, @Nullable Map<String, String> envVariableMap)
    throws IOException, InterruptedException, LoggedErrorException
  {
    String[] cmdArray = (String[])command.toArray(new String[command.size()]);
    runCmdLine(cmdArray, envVariableMap);
  }
  
  public void runCmdLine(@NonNull String[] command, @Nullable Map<String, String> envVariableMap)
    throws IOException, InterruptedException, LoggedErrorException
  {
    printCommand(command);
    
    ProcessBuilder processBuilder = new ProcessBuilder(command);
    Map<String, String> env;
    if (envVariableMap != null)
    {
      env = processBuilder.environment();
      for (Map.Entry<String, String> entry : envVariableMap.entrySet()) {
        env.put(entry.getKey(), entry.getValue());
      }
    }
    Process process = processBuilder.start();
    
    OutputGrabber grabber = new OutputGrabber(null);
    
    int returnCode = GrabProcessOutput.grabProcessOutput(process, GrabProcessOutput.Wait.WAIT_FOR_READERS, grabber);
    if (returnCode != 0) {
      throw new LoggedErrorException(returnCode, mErrors, Joiner.on(' ').join(command));
    }
  }
  
  private void printCommand(String[] command)
  {
    mLogger.info("command: " + Joiner.on(' ').join(command), new Object[0]);
  }
}

/* Location:
 * Qualified Name:     com.android.ide.common.internal.CommandLineRunner
 * Java Class Version: 6 (50.0)
 * JD-Core Version:    0.7.1
 */
package com.android.ide.common.internal;

import com.android.annotations.NonNull;
import com.android.annotations.Nullable;
import java.util.List;

public class LoggedErrorException
  extends Exception
{
  private final int mCmdLineError;
  private final List<String> mOutput;
  private final String mCmdLine;
  
  public LoggedErrorException(int error, @NonNull List<String> output, @Nullable String cmdLine)
  {
    mCmdLineError = error;
    mOutput = output;
    mCmdLine = cmdLine;
  }
  
  public LoggedErrorException(@NonNull List<String> output)
  {
    this(0, output, null);
  }
  
  public int getCmdLineError()
  {
    return mCmdLineError;
  }
  
  @NonNull
  public List<String> getOutput()
  {
    return mOutput;
  }
  
  public String getCmdLine()
  {
    return mCmdLine;
  }
  
  public String getMessage()
  {
    StringBuilder sb = new StringBuilder();
    sb.append("Failed to run command:\n\t").append(mCmdLine).append('\n');
    sb.append("Error Code:\n\t").append(mCmdLineError).append('\n');
    if (!mOutput.isEmpty())
    {
      sb.append("Output:\n");
      for (String line : mOutput) {
        sb.append('\t').append(line).append('\n');
      }
    }
    return sb.toString();
  }
}

/* Location:
 * Qualified Name:     com.android.ide.common.internal.LoggedErrorException
 * Java Class Version: 6 (50.0)
 * JD-Core Version:    0.7.1
 */
package com.android.ide.common.internal;

public final class WaitableExecutor$TaskResult<T>
{
  public T value;
  public Throwable exception;
  
  static <T> TaskResult<T> withValue(T value)
  {
    TaskResult<T> result = new TaskResult(null);
    value = value;
    return result;
  }
  
  WaitableExecutor$TaskResult(Throwable cause)
  {
    exception = cause;
  }
}

/* Location:
 * Qualified Name:     com.android.ide.common.internal.WaitableExecutor.TaskResult
 * Java Class Version: 6 (50.0)
 * JD-Core Version:    0.7.1
 */
package com.android.ide.common.internal;

import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import java.util.List;
import java.util.Set;
import java.util.concurrent.Callable;
import java.util.concurrent.CompletionService;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorCompletionService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

public class WaitableExecutor<T>
{
  private final CompletionService<T> mCompletionService;
  private final Set<Future<T>> mFutureSet = Sets.newHashSet();
  
  public WaitableExecutor(int nThreads)
  {
    if (nThreads < 1) {
      mCompletionService = new ExecutorCompletionService(Executors.newCachedThreadPool());
    } else {
      mCompletionService = new ExecutorCompletionService(Executors.newFixedThreadPool(nThreads));
    }
  }
  
  public WaitableExecutor()
  {
    this(0);
  }
  
  public void execute(Callable<T> runnable)
  {
    mFutureSet.add(mCompletionService.submit(runnable));
  }
  
  public List<T> waitForTasksWithQuickFail(boolean cancelRemaining)
    throws InterruptedException, LoggedErrorException
  {
    List<T> results = Lists.newArrayListWithCapacity(mFutureSet.size());
    try
    {
      while (!mFutureSet.isEmpty())
      {
        Future<T> future = mCompletionService.take();
        
        assert (mFutureSet.contains(future));
        mFutureSet.remove(future);
        
        results.add(future.get());
      }
    }
    catch (ExecutionException e)
    {
      if (cancelRemaining) {
        cancelAllTasks();
      }
      Throwable cause = e.getCause();
      if ((cause instanceof LoggedErrorException)) {
        throw ((LoggedErrorException)cause);
      }
      throw new RuntimeException(cause);
    }
    return results;
  }
  
  public static final class TaskResult<T>
  {
    public T value;
    public Throwable exception;
    
    static <T> TaskResult<T> withValue(T value)
    {
      TaskResult<T> result = new TaskResult(null);
      value = value;
      return result;
    }
    
    TaskResult(Throwable cause)
    {
      exception = cause;
    }
  }
  
  public List<TaskResult<T>> waitForAllTasks()
    throws InterruptedException
  {
    List<TaskResult<T>> results = Lists.newArrayListWithCapacity(mFutureSet.size());
    while (!mFutureSet.isEmpty())
    {
      Future<T> future = mCompletionService.take();
      
      assert (mFutureSet.contains(future));
      mFutureSet.remove(future);
      try
      {
        results.add(TaskResult.withValue(future.get()));
      }
      catch (ExecutionException e)
      {
        Throwable cause = e.getCause();
        if (!(cause instanceof InterruptedException)) {
          results.add(new TaskResult(cause));
        }
      }
    }
    return results;
  }
  
  public void cancelAllTasks()
  {
    for (Future<T> future : mFutureSet) {
      future.cancel(true);
    }
  }
}

/* Location:
 * Qualified Name:     com.android.ide.common.internal.WaitableExecutor
 * Java Class Version: 6 (50.0)
 * JD-Core Version:    0.7.1
 */
package com.android.ide.common.packaging;

public class PackagingUtils
{
  public static boolean checkFolderForPackaging(String folderName)
  {
    return (!folderName.equalsIgnoreCase("CVS")) && (!folderName.equalsIgnoreCase(".svn")) && (!folderName.equalsIgnoreCase("SCCS")) && (!folderName.startsWith("_"));
  }
  
  public static boolean checkFileForPackaging(String fileName)
  {
    String[] fileSegments = fileName.split("\\.");
    String fileExt = "";
    if (fileSegments.length > 1) {
      fileExt = fileSegments[(fileSegments.length - 1)];
    }
    return checkFileForPackaging(fileName, fileExt);
  }
  
  public static boolean checkFileForPackaging(String fileName, String extension)
  {
    return (fileName.charAt(0) != '.') && (fileName.charAt(fileName.length() - 1) != '~') && (!"aidl".equalsIgnoreCase(extension)) && (!"rs".equalsIgnoreCase(extension)) && (!"fs".equalsIgnoreCase(extension)) && (!"rsh".equalsIgnoreCase(extension)) && (!"d".equalsIgnoreCase(extension)) && (!"java".equalsIgnoreCase(extension)) && (!"scala".equalsIgnoreCase(extension)) && (!"class".equalsIgnoreCase(extension)) && (!"scc".equalsIgnoreCase(extension)) && (!"swp".equalsIgnoreCase(extension)) && (!"thumbs.db".equalsIgnoreCase(fileName)) && (!"picasa.ini".equalsIgnoreCase(fileName)) && (!"about.html".equalsIgnoreCase(fileName)) && (!"package.html".equalsIgnoreCase(fileName)) && (!"overview.html".equalsIgnoreCase(fileName));
  }
}

/* Location:
 * Qualified Name:     com.android.ide.common.packaging.PackagingUtils
 * Java Class Version: 6 (50.0)
 * JD-Core Version:    0.7.1
 */
package com.android.ide.common.rendering;

import com.android.sdklib.devices.Device;
import java.util.Comparator;

final class HardwareConfigHelper$1
  implements Comparator<Device>
{
  public int compare(Device device1, Device device2)
  {
    return HardwareConfigHelper.nexusRank(device2) - HardwareConfigHelper.nexusRank(device1);
  }
}

/* Location:
 * Qualified Name:     com.android.ide.common.rendering.HardwareConfigHelper.1
 * Java Class Version: 6 (50.0)
 * JD-Core Version:    0.7.1
 */
package com.android.ide.common.rendering;

import com.android.annotations.NonNull;
import com.android.ide.common.rendering.api.HardwareConfig;
import com.android.resources.Density;
import com.android.resources.ScreenOrientation;
import com.android.sdklib.devices.ButtonType;
import com.android.sdklib.devices.Device;
import com.android.sdklib.devices.Hardware;
import com.android.sdklib.devices.Screen;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Locale;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class HardwareConfigHelper
{
  @NonNull
  private final Device mDevice;
  @NonNull
  private ScreenOrientation mScreenOrientation = ScreenOrientation.PORTRAIT;
  private int mMaxRenderWidth = -1;
  private int mMaxRenderHeight = -1;
  private int mOverrideRenderWidth = -1;
  private int mOverrideRenderHeight = -1;
  public static final String MANUFACTURER_GENERIC = "Generic";
  private static final String NEXUS = "Nexus";
  
  public HardwareConfigHelper(@NonNull Device device)
  {
    mDevice = device;
  }
  
  @NonNull
  public HardwareConfigHelper setOrientation(@NonNull ScreenOrientation screenOrientation)
  {
    mScreenOrientation = screenOrientation;
    return this;
  }
  
  @NonNull
  public HardwareConfigHelper setOverrideRenderSize(int overrideRenderWidth, int overrideRenderHeight)
  {
    mOverrideRenderWidth = overrideRenderWidth;
    mOverrideRenderHeight = overrideRenderHeight;
    return this;
  }
  
  @NonNull
  public HardwareConfigHelper setMaxRenderSize(int maxRenderWidth, int maxRenderHeight)
  {
    mMaxRenderWidth = maxRenderWidth;
    mMaxRenderHeight = maxRenderHeight;
    return this;
  }
  
  @NonNull
  public HardwareConfig getConfig()
  {
    Screen screen = mDevice.getDefaultHardware().getScreen();
    
    int x = screen.getXDimension();
    int y = screen.getYDimension();
    int height;
    int width;
    int height;
    if (x > y)
    {
      int height;
      if (mScreenOrientation == ScreenOrientation.LANDSCAPE)
      {
        int width = x;
        height = y;
      }
      else
      {
        int width = y;
        height = x;
      }
    }
    else
    {
      int height;
      if (mScreenOrientation == ScreenOrientation.LANDSCAPE)
      {
        int width = y;
        height = x;
      }
      else
      {
        width = x;
        height = y;
      }
    }
    if (mOverrideRenderHeight != -1) {
      width = mOverrideRenderWidth;
    }
    if (mOverrideRenderHeight != -1) {
      height = mOverrideRenderHeight;
    }
    if (mMaxRenderWidth != -1) {
      width = mMaxRenderWidth;
    }
    if (mMaxRenderHeight != -1) {
      height = mMaxRenderHeight;
    }
    return new HardwareConfig(width, height, screen.getPixelDensity(), (float)screen.getXdpi(), (float)screen.getYdpi(), screen.getSize(), mScreenOrientation, mDevice.getDefaultHardware().getButtonType() == ButtonType.SOFT);
  }
  
  private static final Pattern GENERIC_PATTERN = Pattern.compile("(\\d+\\.?\\d*)\" (.+?)( \\(.*Nexus.*\\))?");
  
  @NonNull
  public static String getNexusLabel(@NonNull Device device)
  {
    String name = device.getDisplayName();
    Screen screen = device.getDefaultHardware().getScreen();
    float length = (float)screen.getDiagonalLength();
    
    length = Math.round(10.0F * length) / 10.0F;
    return String.format(Locale.US, "%1$s (%3$s\", %2$s)", new Object[] { name, getResolutionString(device), Float.toString(length) });
  }
  
  @NonNull
  public static String getGenericLabel(@NonNull Device device)
  {
    String name = device.getDisplayName();
    Matcher matcher = GENERIC_PATTERN.matcher(name);
    if (matcher.matches())
    {
      String size = matcher.group(1);
      String n = matcher.group(2);
      int dot = size.indexOf('.');
      if (dot == -1)
      {
        size = size + ".0";
        dot = size.length() - 2;
      }
      for (int i = 0; i < 2 - dot; i++) {
        size = ' ' + size;
      }
      name = size + "\" " + n;
    }
    return String.format(Locale.US, "%1$s (%2$s)", new Object[] { name, getResolutionString(device) });
  }
  
  @NonNull
  public static String getResolutionString(@NonNull Device device)
  {
    Screen screen = device.getDefaultHardware().getScreen();
    return String.format(Locale.US, "%1$d � %2$d: %3$s", new Object[] { Integer.valueOf(screen.getXDimension()), Integer.valueOf(screen.getYDimension()), screen.getPixelDensity().getResourceValue() });
  }
  
  public static boolean isGeneric(@NonNull Device device)
  {
    return device.getManufacturer().equals("Generic");
  }
  
  public static boolean isNexus(@NonNull Device device)
  {
    return device.getId().contains("Nexus");
  }
  
  public static int nexusRank(Device device)
  {
    String id = device.getId();
    if (id.equals("Nexus One")) {
      return 1;
    }
    if (id.equals("Nexus S")) {
      return 2;
    }
    if (id.equals("Galaxy Nexus")) {
      return 3;
    }
    if (id.equals("Nexus 7")) {
      return 4;
    }
    if (id.equals("Nexus 10")) {
      return 5;
    }
    if (id.equals("Nexus 4")) {
      return 6;
    }
    if (id.equals("Nexus 7 2013")) {
      return 7;
    }
    if (id.equals("Nexus 5")) {
      return 8;
    }
    return 100;
  }
  
  public static void sortNexusList(@NonNull List<Device> list)
  {
    Collections.sort(list, new Comparator()
    {
      public int compare(Device device1, Device device2)
      {
        return HardwareConfigHelper.nexusRank(device2) - HardwareConfigHelper.nexusRank(device1);
      }
    });
  }
}

/* Location:
 * Qualified Name:     com.android.ide.common.rendering.HardwareConfigHelper
 * Java Class Version: 6 (50.0)
 * JD-Core Version:    0.7.1
 */
package com.android.ide.common.rendering;

import com.android.ide.common.rendering.api.LayoutLog;
import com.android.layoutlib.api.ILayoutLog;

class LayoutLibrary$1
  implements ILayoutLog
{
  LayoutLibrary$1(LayoutLibrary paramLayoutLibrary, LayoutLog paramLayoutLog) {}
  
  public void warning(String message)
  {
    val$log.warning(null, message, null);
  }
  
  public void error(Throwable t)
  {
    val$log.error(null, "error!", t, null);
  }
  
  public void error(String message)
  {
    val$log.error(null, message, null);
  }
}

/* Location:
 * Qualified Name:     com.android.ide.common.rendering.LayoutLibrary.1
 * Java Class Version: 6 (50.0)
 * JD-Core Version:    0.7.1
 */
package com.android.ide.common.rendering;

class LayoutLibrary$2 {}

/* Location:
 * Qualified Name:     com.android.ide.common.rendering.LayoutLibrary.2
 * Java Class Version: 6 (50.0)
 * JD-Core Version:    0.7.1
 */
package com.android.ide.common.rendering;

import com.android.ide.common.rendering.api.Bridge;
import com.android.ide.common.rendering.api.Capability;
import com.android.ide.common.rendering.api.DrawableParams;
import com.android.ide.common.rendering.api.LayoutLog;
import com.android.ide.common.rendering.api.RenderSession;
import com.android.ide.common.rendering.api.ResourceValue;
import com.android.ide.common.rendering.api.Result;
import com.android.ide.common.rendering.api.Result.Status;
import com.android.ide.common.rendering.api.SessionParams;
import com.android.ide.common.rendering.api.SessionParams.RenderingMode;
import com.android.ide.common.rendering.api.ViewInfo;
import com.android.ide.common.resources.ResourceResolver;
import com.android.ide.common.sdk.LoadStatus;
import com.android.layoutlib.api.ILayoutBridge;
import com.android.layoutlib.api.ILayoutLog;
import com.android.layoutlib.api.ILayoutResult;
import com.android.layoutlib.api.ILayoutResult.ILayoutViewInfo;
import com.android.layoutlib.api.IProjectCallback;
import com.android.layoutlib.api.IResourceValue;
import com.android.layoutlib.api.IXmlPullParser;
import com.android.resources.Density;
import com.android.resources.ResourceType;
import com.android.utils.ILogger;
import com.android.utils.SdkUtils;
import java.io.File;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.ArrayList;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

public class LayoutLibrary
{
  public static final String CLASS_BRIDGE = "com.android.layoutlib.bridge.Bridge";
  public static final String FN_ICU_JAR = "icu4j.jar";
  private final Bridge mBridge;
  private final ILayoutBridge mLegacyBridge;
  private final LoadStatus mStatus;
  private final String mLoadMessage;
  private final ClassLoader mClassLoader;
  private Method mViewGetParentMethod;
  private Method mViewGetBaselineMethod;
  private Method mViewParentIndexOfChildMethod;
  private Class<?> mMarginLayoutParamClass;
  private Field mLeftMarginField;
  private Field mTopMarginField;
  private Field mRightMarginField;
  private Field mBottomMarginField;
  
  public LoadStatus getStatus()
  {
    return mStatus;
  }
  
  public String getLoadMessage()
  {
    return mLoadMessage;
  }
  
  public ClassLoader getClassLoader()
  {
    return mClassLoader;
  }
  
  public static LayoutLibrary load(String layoutLibJarOsPath, ILogger log, String toolName)
  {
    LoadStatus status = LoadStatus.LOADING;
    String message = null;
    Bridge bridge = null;
    ILayoutBridge legacyBridge = null;
    ClassLoader classLoader = null;
    try
    {
      File f = new File(layoutLibJarOsPath);
      if (!f.isFile())
      {
        if (log != null) {
          log.error(null, "layoutlib.jar is missing!", new Object[0]);
        }
      }
      else
      {
        File icu4j = new File(f.getParent(), "icu4j.jar");
        URL[] urls;
        if (icu4j.isFile())
        {
          URL[] urls = new URL[2];
          urls[1] = SdkUtils.fileToUrl(icu4j);
        }
        else
        {
          urls = new URL[1];
        }
        urls[0] = SdkUtils.fileToUrl(f);
        
        classLoader = new URLClassLoader(urls, LayoutLibrary.class.getClassLoader());
        
        Class<?> clazz = classLoader.loadClass("com.android.layoutlib.bridge.Bridge");
        if (clazz != null)
        {
          Constructor<?> constructor = clazz.getConstructor(new Class[0]);
          if (constructor != null)
          {
            Object bridgeObject = constructor.newInstance(new Object[0]);
            if ((bridgeObject instanceof Bridge)) {
              bridge = (Bridge)bridgeObject;
            } else if ((bridgeObject instanceof ILayoutBridge)) {
              legacyBridge = (ILayoutBridge)bridgeObject;
            }
          }
        }
        if ((bridge == null) && (legacyBridge == null))
        {
          status = LoadStatus.FAILED;
          message = "Failed to load com.android.layoutlib.bridge.Bridge";
          if (log != null) {
            log.error(null, "Failed to load com.android.layoutlib.bridge.Bridge from " + layoutLibJarOsPath, new Object[0]);
          }
        }
        else
        {
          status = LoadStatus.LOADED;
          if (bridge != null)
          {
            int api = bridge.getApiLevel();
            if (api > 10)
            {
              status = LoadStatus.FAILED;
              message = String.format("This version of the rendering library is more recent than your version of %1$s. Please update %1$s", new Object[] { toolName });
            }
          }
        }
      }
    }
    catch (Throwable t)
    {
      status = LoadStatus.FAILED;
      Throwable cause = t;
      while (cause.getCause() != null) {
        cause = cause.getCause();
      }
      message = "Failed to load the LayoutLib: " + cause.getMessage();
      if (log != null) {
        log.error(t, message, new Object[0]);
      }
    }
    return new LayoutLibrary(bridge, legacyBridge, classLoader, status, message);
  }
  
  public int getApiLevel()
  {
    if (mBridge != null) {
      return mBridge.getApiLevel();
    }
    if (mLegacyBridge != null) {
      return getLegacyApiLevel();
    }
    return 0;
  }
  
  public int getRevision()
  {
    if (mBridge != null) {
      return mBridge.getRevision();
    }
    return 0;
  }
  
  public boolean supports(Capability capability)
  {
    if (mBridge != null) {
      return mBridge.getCapabilities().contains(capability);
    }
    if (mLegacyBridge != null) {
      switch (capability)
      {
      case UNBOUND_RENDERING: 
        return getLegacyApiLevel() == 4;
      }
    }
    return false;
  }
  
  public boolean init(Map<String, String> platformProperties, File fontLocation, Map<String, Map<String, Integer>> enumValueMap, LayoutLog log)
  {
    if (mBridge != null) {
      return mBridge.init(platformProperties, fontLocation, enumValueMap, log);
    }
    if (mLegacyBridge != null) {
      return mLegacyBridge.init(fontLocation.getAbsolutePath(), enumValueMap);
    }
    return false;
  }
  
  public boolean dispose()
  {
    if (mBridge != null) {
      return mBridge.dispose();
    }
    return true;
  }
  
  public RenderSession createSession(SessionParams params)
  {
    if (mBridge != null)
    {
      RenderSession session = mBridge.createSession(params);
      if ((params.getExtendedViewInfoMode()) && (!mBridge.getCapabilities().contains(Capability.EXTENDED_VIEWINFO)))
      {
        List<ViewInfo> infoList = session.getRootViews();
        if (infoList != null) {
          for (ViewInfo info : infoList) {
            addExtendedViewInfo(info);
          }
        }
      }
      return session;
    }
    if (mLegacyBridge != null) {
      return createLegacySession(params);
    }
    return null;
  }
  
  public Result renderDrawable(DrawableParams params)
  {
    if (mBridge != null) {
      return mBridge.renderDrawable(params);
    }
    return Result.Status.NOT_IMPLEMENTED.createResult();
  }
  
  public void clearCaches(Object projectKey)
  {
    if (mBridge != null) {
      mBridge.clearCaches(projectKey);
    } else if (mLegacyBridge != null) {
      mLegacyBridge.clearCaches(projectKey);
    }
  }
  
  public Result getViewParent(Object viewObject)
  {
    if (mBridge != null)
    {
      Result r = mBridge.getViewParent(viewObject);
      if (r.isSuccess()) {
        return r;
      }
    }
    return getViewParentWithReflection(viewObject);
  }
  
  public Result getViewIndex(Object viewObject)
  {
    if (mBridge != null)
    {
      Result r = mBridge.getViewIndex(viewObject);
      if (r.isSuccess()) {
        return r;
      }
    }
    return getViewIndexReflection(viewObject);
  }
  
  public boolean isRtl(String locale)
  {
    return supports(Capability.RTL) ? mBridge.isRtl(locale) : false;
  }
  
  private LayoutLibrary(Bridge bridge, ILayoutBridge legacyBridge, ClassLoader classLoader, LoadStatus status, String message)
  {
    mBridge = bridge;
    mLegacyBridge = legacyBridge;
    mClassLoader = classLoader;
    mStatus = status;
    mLoadMessage = message;
  }
  
  private int getLegacyApiLevel()
  {
    int apiLevel = 1;
    try
    {
      apiLevel = mLegacyBridge.getApiLevel();
    }
    catch (AbstractMethodError e) {}
    return apiLevel;
  }
  
  private RenderSession createLegacySession(SessionParams params)
  {
    if (!(params.getLayoutDescription() instanceof IXmlPullParser)) {
      throw new IllegalArgumentException("Parser must be of type ILegacyPullParser");
    }
    if (!(params.getProjectCallback() instanceof IProjectCallback)) {
      throw new IllegalArgumentException("Project callback must be of type ILegacyCallback");
    }
    if (!(params.getResources() instanceof ResourceResolver)) {
      throw new IllegalArgumentException("RenderResources object must be of type ResourceResolver");
    }
    ResourceResolver resources = (ResourceResolver)params.getResources();
    
    int apiLevel = getLegacyApiLevel();
    
    final LayoutLog log = params.getLog();
    ILayoutLog logWrapper = new ILayoutLog()
    {
      public void warning(String message)
      {
        log.warning(null, message, null);
      }
      
      public void error(Throwable t)
      {
        log.error(null, "error!", t, null);
      }
      
      public void error(String message)
      {
        log.error(null, message, null);
      }
    };
    Map<String, Map<String, IResourceValue>> projectMap = convertMap(resources.getProjectResources());
    
    Map<String, Map<String, IResourceValue>> frameworkMap = convertMap(resources.getFrameworkResources());
    
    ILayoutResult result = null;
    if (apiLevel == 4)
    {
      result = mLegacyBridge.computeLayout((IXmlPullParser)params.getLayoutDescription(), params.getProjectKey(), params.getScreenWidth(), params.getScreenHeight(), params.getRenderingMode() == SessionParams.RenderingMode.FULL_EXPAND, params.getDensity().getDpiValue(), params.getXdpi(), params.getYdpi(), resources.getThemeName(), resources.isProjectTheme(), projectMap, frameworkMap, (IProjectCallback)params.getProjectCallback(), logWrapper);
    }
    else if (apiLevel == 3)
    {
      result = mLegacyBridge.computeLayout((IXmlPullParser)params.getLayoutDescription(), params.getProjectKey(), params.getScreenWidth(), params.getScreenHeight(), params.getDensity().getDpiValue(), params.getXdpi(), params.getYdpi(), resources.getThemeName(), resources.isProjectTheme(), projectMap, frameworkMap, (IProjectCallback)params.getProjectCallback(), logWrapper);
    }
    else if (apiLevel == 2)
    {
      result = mLegacyBridge.computeLayout((IXmlPullParser)params.getLayoutDescription(), params.getProjectKey(), params.getScreenWidth(), params.getScreenHeight(), resources.getThemeName(), resources.isProjectTheme(), projectMap, frameworkMap, (IProjectCallback)params.getProjectCallback(), logWrapper);
    }
    else
    {
      String themeName = resources.getThemeName();
      if (resources.isProjectTheme()) {
        themeName = "*" + themeName;
      }
      result = mLegacyBridge.computeLayout((IXmlPullParser)params.getLayoutDescription(), params.getProjectKey(), params.getScreenWidth(), params.getScreenHeight(), themeName, projectMap, frameworkMap, (IProjectCallback)params.getProjectCallback(), logWrapper);
    }
    legacyCleanUp();
    
    return convertToScene(result);
  }
  
  private Map<String, Map<String, IResourceValue>> convertMap(Map<ResourceType, Map<String, ResourceValue>> map)
  {
    Map<String, Map<String, IResourceValue>> result = new HashMap();
    for (Map.Entry<ResourceType, Map<String, ResourceValue>> entry : map.entrySet()) {
      result.put(((ResourceType)entry.getKey()).getName(), (Map)entry.getValue());
    }
    return result;
  }
  
  private RenderSession convertToScene(ILayoutResult result)
  {
    ViewInfo rootViewInfo = null;
    Result sceneResult;
    if (result.getSuccess() == 0)
    {
      Result sceneResult = Result.Status.SUCCESS.createResult();
      ILayoutResult.ILayoutViewInfo oldRootView = result.getRootView();
      if (oldRootView != null) {
        rootViewInfo = convertToViewInfo(oldRootView);
      }
    }
    else
    {
      sceneResult = Result.Status.ERROR_UNKNOWN.createResult(result.getErrorMessage());
    }
    return new StaticRenderSession(sceneResult, rootViewInfo, result.getImage());
  }
  
  private ViewInfo convertToViewInfo(ILayoutResult.ILayoutViewInfo view)
  {
    ViewInfo viewInfo = new ViewInfo(view.getName(), view.getViewKey(), view.getLeft(), view.getTop(), view.getRight(), view.getBottom());
    
    ILayoutResult.ILayoutViewInfo[] children = view.getChildren();
    if (children != null)
    {
      ArrayList<ViewInfo> convertedChildren = new ArrayList(children.length);
      for (ILayoutResult.ILayoutViewInfo child : children) {
        convertedChildren.add(convertToViewInfo(child));
      }
      viewInfo.setChildren(convertedChildren);
    }
    return viewInfo;
  }
  
  private void legacyCleanUp()
  {
    try
    {
      Class<?> looperClass = mClassLoader.loadClass("android.os.Looper");
      Field threadLocalField = looperClass.getField("sThreadLocal");
      if (threadLocalField != null)
      {
        threadLocalField.setAccessible(true);
        
        ThreadLocal<?> threadLocal = (ThreadLocal)threadLocalField.get(null);
        if (threadLocal != null) {
          threadLocal.remove();
        }
      }
    }
    catch (Exception e) {}
  }
  
  private Result getViewParentWithReflection(Object viewObject)
  {
    try
    {
      if (mViewGetParentMethod == null)
      {
        Class<?> viewClass = Class.forName("android.view.View");
        mViewGetParentMethod = viewClass.getMethod("getParent", new Class[0]);
      }
      return Result.Status.SUCCESS.createResult(mViewGetParentMethod.invoke(viewObject, new Object[0]));
    }
    catch (Exception e)
    {
      return Result.Status.ERROR_REFLECTION.createResult(null, e);
    }
  }
  
  private Result getViewIndexReflection(Object viewObject)
  {
    try
    {
      Class<?> viewClass = Class.forName("android.view.View");
      if (mViewGetParentMethod == null) {
        mViewGetParentMethod = viewClass.getMethod("getParent", new Class[0]);
      }
      Object parentObject = mViewGetParentMethod.invoke(viewObject, new Object[0]);
      if (mViewParentIndexOfChildMethod == null)
      {
        Class<?> viewParentClass = Class.forName("android.view.ViewParent");
        mViewParentIndexOfChildMethod = viewParentClass.getMethod("indexOfChild", new Class[] { viewClass });
      }
      return Result.Status.SUCCESS.createResult(mViewParentIndexOfChildMethod.invoke(parentObject, new Object[] { viewObject }));
    }
    catch (Exception e)
    {
      return Result.Status.ERROR_REFLECTION.createResult(null, e);
    }
  }
  
  private void addExtendedViewInfo(ViewInfo info)
  {
    computeExtendedViewInfo(info);
    
    List<ViewInfo> children = info.getChildren();
    for (ViewInfo child : children) {
      addExtendedViewInfo(child);
    }
  }
  
  private void computeExtendedViewInfo(ViewInfo info)
  {
    Object viewObject = info.getViewObject();
    Object params = info.getLayoutParamsObject();
    
    int baseLine = getViewBaselineReflection(viewObject);
    int leftMargin = 0;
    int topMargin = 0;
    int rightMargin = 0;
    int bottomMargin = 0;
    try
    {
      if (mMarginLayoutParamClass == null)
      {
        mMarginLayoutParamClass = Class.forName("android.view.ViewGroup$MarginLayoutParams");
        
        mLeftMarginField = mMarginLayoutParamClass.getField("leftMargin");
        mTopMarginField = mMarginLayoutParamClass.getField("topMargin");
        mRightMarginField = mMarginLayoutParamClass.getField("rightMargin");
        mBottomMarginField = mMarginLayoutParamClass.getField("bottomMargin");
      }
      if (mMarginLayoutParamClass.isAssignableFrom(params.getClass()))
      {
        leftMargin = ((Integer)mLeftMarginField.get(params)).intValue();
        topMargin = ((Integer)mTopMarginField.get(params)).intValue();
        rightMargin = ((Integer)mRightMarginField.get(params)).intValue();
        bottomMargin = ((Integer)mBottomMarginField.get(params)).intValue();
      }
    }
    catch (Exception e)
    {
      leftMargin = Integer.MIN_VALUE;
      topMargin = Integer.MIN_VALUE;
      rightMargin = Integer.MIN_VALUE;
      bottomMargin = Integer.MIN_VALUE;
    }
    info.setExtendedInfo(baseLine, leftMargin, topMargin, rightMargin, bottomMargin);
  }
  
  private int getViewBaselineReflection(Object viewObject)
  {
    try
    {
      if (mViewGetBaselineMethod == null)
      {
        Class<?> viewClass = Class.forName("android.view.View");
        mViewGetBaselineMethod = viewClass.getMethod("getBaseline", new Class[0]);
      }
      Object result = mViewGetBaselineMethod.invoke(viewObject, new Object[0]);
      if ((result instanceof Integer)) {
        return ((Integer)result).intValue();
      }
    }
    catch (Exception e) {}
    return Integer.MIN_VALUE;
  }
}

/* Location:
 * Qualified Name:     com.android.ide.common.rendering.LayoutLibrary
 * Java Class Version: 6 (50.0)
 * JD-Core Version:    0.7.1
 */
package com.android.ide.common.rendering;

import com.android.annotations.NonNull;
import com.android.annotations.Nullable;

public class RenderSecurityException
  extends SecurityException
{
  private final String myMessage;
  
  private RenderSecurityException(@NonNull String message)
  {
    super(message);
    myMessage = message;
  }
  
  public String getMessage()
  {
    return myMessage;
  }
  
  public String toString()
  {
    return getMessage();
  }
  
  @NonNull
  public static RenderSecurityException create(@NonNull String resource, @Nullable String context)
  {
    return new RenderSecurityException(computeLabel(resource, context));
  }
  
  @NonNull
  public static RenderSecurityException create(@NonNull String message)
  {
    return new RenderSecurityException(message);
  }
  
  private static String computeLabel(@NonNull String resource, @Nullable String context)
  {
    StringBuilder sb = new StringBuilder(40);
    sb.append(resource);
    sb.append(" access not allowed during rendering");
    if (context != null) {
      sb.append(" (").append(context).append(")");
    }
    return sb.toString();
  }
}

/* Location:
 * Qualified Name:     com.android.ide.common.rendering.RenderSecurityException
 * Java Class Version: 6 (50.0)
 * JD-Core Version:    0.7.1
 */
package com.android.ide.common.rendering;

final class RenderSecurityManager$1
  extends InheritableThreadLocal<Boolean>
{
  protected synchronized Boolean initialValue()
  {
    return Boolean.FALSE;
  }
  
  protected synchronized Boolean childValue(Boolean parentValue)
  {
    return parentValue;
  }
}

/* Location:
 * Qualified Name:     com.android.ide.common.rendering.RenderSecurityManager.1
 * Java Class Version: 6 (50.0)
 * JD-Core Version:    0.7.1
 */
package com.android.ide.common.rendering;

import com.android.annotations.Nullable;
import com.android.utils.ILogger;
import java.io.File;
import java.io.FileDescriptor;
import java.io.FilePermission;
import java.io.IOException;
import java.net.InetAddress;
import java.security.Permission;
import java.util.PropertyPermission;

public class RenderSecurityManager
  extends SecurityManager
{
  public static final String ENABLED_PROPERTY = "android.render.sandbox";
  public static final boolean RESTRICT_READS = false;
  public static boolean sEnabled = !"false".equals(System.getProperty("android.render.sandbox"));
  private static ThreadLocal<Boolean> sIsRenderThread = new InheritableThreadLocal()
  {
    protected synchronized Boolean initialValue()
    {
      return Boolean.FALSE;
    }
    
    protected synchronized Boolean childValue(Boolean parentValue)
    {
      return parentValue;
    }
  };
  private static Object sCredential;
  private static String sLastFailedPath;
  private boolean mAllowSetSecurityManager;
  private boolean mDisabled;
  private String mSdkPath;
  private String mProjectPath;
  private String mTempDir;
  private String mNormalizedTempDir;
  private String mCanonicalTempDir;
  private SecurityManager myPreviousSecurityManager;
  private ILogger mLogger;
  
  @Nullable
  public static RenderSecurityManager getCurrent()
  {
    if (((Boolean)sIsRenderThread.get()).booleanValue())
    {
      SecurityManager securityManager = System.getSecurityManager();
      if ((securityManager instanceof RenderSecurityManager))
      {
        RenderSecurityManager manager = (RenderSecurityManager)securityManager;
        return manager.isRelevant() ? manager : null;
      }
    }
    return null;
  }
  
  public RenderSecurityManager(@Nullable String sdkPath, @Nullable String projectPath)
  {
    mSd
1 2 3 4 5 6 7 8 9 10 11 12

Further reading...

For more information on Java 1.5 Tiger, you may find Java 1.5 Tiger, A developer's Notebook by D. Flanagan and B. McLaughlin from O'Reilly of interest.

New!JAR listings


Copyright 2006-2017. Infinite Loop Ltd