Ejemplo n.º 1
0
 public void setupLoadOnly(String deobfFileName, boolean loadAll) {
   try {
     File mapData = new File(deobfFileName);
     LZMAInputSupplier zis = new LZMAInputSupplier(new FileInputStream(mapData));
     InputSupplier<InputStreamReader> srgSupplier =
         CharStreams.newReaderSupplier(zis, Charsets.UTF_8);
     List<String> srgList = CharStreams.readLines(srgSupplier);
     rawMethodMaps = Maps.newHashMap();
     rawFieldMaps = Maps.newHashMap();
     Builder<String, String> builder = ImmutableBiMap.<String, String>builder();
     Builder<String, String> mcpBuilder = ImmutableBiMap.<String, String>builder();
     Splitter splitter = Splitter.on(CharMatcher.anyOf(": ")).omitEmptyStrings().trimResults();
     for (String line : srgList) {
       String[] parts = Iterables.toArray(splitter.split(line), String.class);
       String typ = parts[0];
       if ("CL".equals(typ)) {
         parseClass(builder, parts);
         parseMCPClass(mcpBuilder, parts);
       } else if ("MD".equals(typ) && loadAll) {
         parseMethod(parts);
       } else if ("FD".equals(typ) && loadAll) {
         parseField(parts);
       }
     }
     classNameBiMap = builder.build();
     mcpNameBiMap = mcpBuilder.build();
   } catch (IOException ioe) {
     FMLRelaunchLog.log(Level.ERROR, "An error occurred loading the deobfuscation map data", ioe);
   }
   methodNameMaps = Maps.newHashMapWithExpectedSize(rawMethodMaps.size());
   fieldNameMaps = Maps.newHashMapWithExpectedSize(rawFieldMaps.size());
 }
Ejemplo n.º 2
0
  public RuleNames(Grammar grammar, boolean installAdapter) {
    this.contextGrammar = grammar;
    Adapter adapter = new Adapter(this);
    if (installAdapter) {
      installAdapterIfMissing(adapter, grammar);
    }
    List<AbstractRule> allRules = GrammarUtil.allRules(grammar);
    ImmutableListMultimap.Builder<String, AbstractRule> simpleNameToRulesBuilder =
        ImmutableListMultimap.builder();
    ImmutableMap.Builder<String, AbstractRule> qualifiedNameToRuleBuilder = ImmutableMap.builder();
    ImmutableBiMap.Builder<String, AbstractRule> uniqueNameToRuleBuilder = ImmutableBiMap.builder();
    ImmutableBiMap.Builder<String, AbstractRule> antlrNameToRuleBuilder = ImmutableBiMap.builder();

    Map<String, AbstractRule> names = Maps.newHashMap();
    Set<String> usedAntlrNames = Sets.newHashSet();
    Set<String> usedUniqueNames = Sets.newHashSet();
    for (AbstractRule rule : allRules) {
      String name = rule.getName();
      simpleNameToRulesBuilder.put(name, rule);
      String qualifiedName = getQualifiedName(rule);
      qualifiedNameToRuleBuilder.put(qualifiedName, rule);
      String uniqueName = name;
      String antlrRuleName;
      if (names.containsKey(name)) {
        name = qualifiedName;
        uniqueName = getInheritedUniqueName(rule, usedUniqueNames);
        antlrRuleName = getInheritedAntlrRuleName(rule, usedAntlrNames);
      } else {
        antlrRuleName = getDefaultAntlrRuleName(rule);
      }
      names.put(name, rule);
      if (!usedUniqueNames.add(uniqueName)) {
        throw new IllegalStateException(uniqueName);
      }
      uniqueNameToRuleBuilder.put(uniqueName, rule);
      if (!usedAntlrNames.add(antlrRuleName)) {
        throw new IllegalStateException(antlrRuleName);
      }
      antlrNameToRuleBuilder.put(antlrRuleName, rule);
      if (installAdapter) {
        installAdapterIfMissing(adapter, rule);
      }
    }
    simpleNameToRules = simpleNameToRulesBuilder.build();
    qualifiedNameToRule = qualifiedNameToRuleBuilder.build();
    nameToRule = ImmutableBiMap.copyOf(names);
    uniqueNameToRule = uniqueNameToRuleBuilder.build();
    antlrNameToRule = antlrNameToRuleBuilder.build();
    this.allRules = ImmutableList.copyOf(allRules);
  }
Ejemplo n.º 3
0
 static {
   //noinspection ConstantConditions
   COAL_MAP =
       ImmutableBiMap.<CoalType, Integer>builder()
           .put(CoalTypes.COAL, 0)
           .put(CoalTypes.CHARCOAL, 1)
           .build();
   //noinspection ConstantConditions
   COOKED_FISH_MAP =
       ImmutableBiMap.<CookedFish, Integer>builder()
           .put(CookedFishes.COD, 0)
           .put(CookedFishes.SALMON, 1)
           .build();
   //noinspection deprecation, ConstantConditions
   DYE_MAP =
       ImmutableBiMap.<DyeColor, Integer>builder()
           .put(DyeColors.BLACK, (int) org.bukkit.DyeColor.BLACK.getDyeData())
           .put(DyeColors.RED, (int) org.bukkit.DyeColor.RED.getDyeData())
           .put(DyeColors.GREEN, (int) org.bukkit.DyeColor.GREEN.getDyeData())
           .put(DyeColors.BROWN, (int) org.bukkit.DyeColor.BROWN.getDyeData())
           .put(DyeColors.BLUE, (int) org.bukkit.DyeColor.BLUE.getDyeData())
           .put(DyeColors.PURPLE, (int) org.bukkit.DyeColor.PURPLE.getDyeData())
           .put(DyeColors.CYAN, (int) org.bukkit.DyeColor.CYAN.getDyeData())
           .put(DyeColors.SILVER, (int) org.bukkit.DyeColor.SILVER.getDyeData())
           .put(DyeColors.GRAY, (int) org.bukkit.DyeColor.GRAY.getDyeData())
           .put(DyeColors.PINK, (int) org.bukkit.DyeColor.PINK.getDyeData())
           .put(DyeColors.LIME, (int) org.bukkit.DyeColor.LIME.getDyeData())
           .put(DyeColors.YELLOW, (int) org.bukkit.DyeColor.YELLOW.getDyeData())
           .put(DyeColors.LIGHT_BLUE, (int) org.bukkit.DyeColor.LIGHT_BLUE.getDyeData())
           .put(DyeColors.MAGENTA, (int) org.bukkit.DyeColor.MAGENTA.getDyeData())
           .put(DyeColors.ORANGE, (int) org.bukkit.DyeColor.ORANGE.getDyeData())
           .put(DyeColors.WHITE, (int) org.bukkit.DyeColor.WHITE.getDyeData())
           .build();
   //noinspection ConstantConditions
   FISH_MAP =
       ImmutableBiMap.<Fish, Integer>builder()
           .put(Fishes.COD, 0)
           .put(Fishes.SALMON, 1)
           .put(Fishes.CLOWNFISH, 2)
           .put(Fishes.PUFFERFISH, 3)
           .build();
   //noinspection ConstantConditions
   GOLDEN_APPLE_MAP =
       ImmutableBiMap.<GoldenApple, Integer>builder()
           .put(GoldenApples.GOLDEN_APPLE, 0)
           .put(GoldenApples.ENCHANTED_GOLDEN_APPLE, 1)
           .build();
 }
 @Override
 public void fromBinary(final byte[] bytes) {
   final ByteBuffer buf = ByteBuffer.wrap(bytes);
   final int numSfcs = buf.getInt();
   final int numDimensions = buf.getInt();
   final int mappingSize = buf.getInt();
   maxEstimatedDuplicateIds = buf.getLong();
   maxEstimatedDuplicateIdsBigInteger = BigInteger.valueOf(maxEstimatedDuplicateIds);
   orderedSfcs = new SpaceFillingCurve[numSfcs];
   baseDefinitions = new NumericDimensionDefinition[numDimensions];
   for (int i = 0; i < numSfcs; i++) {
     final byte[] sfc = new byte[buf.getInt()];
     buf.get(sfc);
     orderedSfcs[i] = PersistenceUtils.fromBinary(sfc, SpaceFillingCurve.class);
   }
   for (int i = 0; i < numDimensions; i++) {
     final byte[] dim = new byte[buf.getInt()];
     buf.get(dim);
     baseDefinitions[i] = PersistenceUtils.fromBinary(dim, NumericDimensionDefinition.class);
   }
   final Builder<Integer, Byte> bimapBuilder = ImmutableBiMap.builder();
   for (int i = 0; i < mappingSize; i++) {
     bimapBuilder.put(Byte.valueOf(buf.get()).intValue(), buf.get());
   }
   orderedSfcIndexToTierId = bimapBuilder.build();
 }
Ejemplo n.º 5
0
  public ResponseLinking copyWithFilteredResponses(final Predicate<Response> toKeepCondition) {
    final Set<Response> newIncompletes = Sets.filter(incompleteResponses(), toKeepCondition);
    final ImmutableSet.Builder<ResponseSet> newResponseSetsB = ImmutableSet.builder();
    final ImmutableBiMap.Builder<String, ResponseSet> responseSetsIdB = ImmutableBiMap.builder();
    // to account for ResponseSets merging due to lost annotation
    final Set<ResponseSet> alreadyAdded = Sets.newHashSet();
    for (final ResponseSet responseSet : responseSets()) {
      final ImmutableSet<Response> okResponses =
          FluentIterable.from(responseSet.asSet()).filter(toKeepCondition).toSet();
      if (!okResponses.isEmpty()) {
        final ResponseSet newResponseSet = ResponseSet.from(okResponses);
        if (alreadyAdded.contains(newResponseSet)) {
          continue;
        }
        alreadyAdded.add(newResponseSet);
        newResponseSetsB.add(newResponseSet);
        if (responseSetIds().isPresent()) {
          responseSetsIdB.put(responseSetIds().get().inverse().get(responseSet), newResponseSet);
        }
      }
    }

    final ImmutableSet<ResponseSet> newResponseSets = newResponseSetsB.build();
    final ResponseLinking.Builder ret =
        ResponseLinking.builder()
            .docID(docID())
            .responseSets(newResponseSets)
            .incompleteResponses(newIncompletes);
    if (responseSetIds().isPresent()) {
      ret.responseSetIds(responseSetsIdB.build());
    }
    return ret.build();
  }
Ejemplo n.º 6
0
  static {
    ImmutableBiMap<String, String> mapping =
        ImmutableBiMap.<String, String>builder()
            .put(Constants.Metrics.Tag.NAMESPACE, "namespace")
            .put(Constants.Metrics.Tag.RUN_ID, "run")
            .put(Constants.Metrics.Tag.INSTANCE_ID, "instance")
            .put(Constants.Metrics.Tag.COMPONENT, "component")
            .put(Constants.Metrics.Tag.HANDLER, "handler")
            .put(Constants.Metrics.Tag.METHOD, "method")
            .put(Constants.Metrics.Tag.STREAM, "stream")
            .put(Constants.Metrics.Tag.DATASET, "dataset")
            .put(Constants.Metrics.Tag.APP, "app")
            .put(Constants.Metrics.Tag.ADAPTER, "adapter")
            .put(Constants.Metrics.Tag.SERVICE, "service")
            // SERVICE_HANDLER is the same HANDLER

            .put(Constants.Metrics.Tag.WORKER, "worker")
            .put(Constants.Metrics.Tag.FLOW, "flow")
            .put(Constants.Metrics.Tag.FLOWLET, "flowlet")
            .put(Constants.Metrics.Tag.FLOWLET_QUEUE, "queue")
            .put(Constants.Metrics.Tag.PRODUCER, "producer")
            .put(Constants.Metrics.Tag.CONSUMER, "consumer")
            .put(Constants.Metrics.Tag.MAPREDUCE, "mapreduce")
            .put(Constants.Metrics.Tag.MR_TASK_TYPE, "tasktype")
            .put(Constants.Metrics.Tag.WORKFLOW, "workflow")
            .put(Constants.Metrics.Tag.SPARK, "spark")
            .build();

    tagNameToHuman = mapping;
    humanToTagName = mapping.inverse();
  }
Ejemplo n.º 7
0
 public C4AtomApi(ChannelResolver channelResolver) {
   channelMap =
       ImmutableBiMap.<String, Channel>builder()
           .put("C4", channelResolver.fromUri("http://www.channel4.com").requireValue())
           .put("M4", channelResolver.fromUri("http://www.channel4.com/more4").requireValue())
           .put("F4", channelResolver.fromUri("http://film4.com").requireValue())
           .put("E4", channelResolver.fromUri("http://www.e4.com").requireValue())
           .put("4M", channelResolver.fromUri("http://www.4music.com").requireValue())
           .put("4S", channelResolver.fromUri("http://www.channel4.com/4seven").requireValue())
           .build();
 }
Ejemplo n.º 8
0
 public void testBuilder() {
   ImmutableBiMap<String, Integer> map =
       ImmutableBiMap.<String, Integer>builder()
           .put("one", 1)
           .put("two", 2)
           .put("three", 3)
           .put("four", 4)
           .put("five", 5)
           .build();
   assertMapEquals(map, "one", 1, "two", 2, "three", 3, "four", 4, "five", 5);
   assertMapEquals(map.inverse(), 1, "one", 2, "two", 3, "three", 4, "four", 5, "five");
 }
Ejemplo n.º 9
0
 public void setup(File mcDir, LaunchClassLoader classLoader, String deobfFileName) {
   this.classLoader = classLoader;
   try {
     InputStream classData = getClass().getResourceAsStream(deobfFileName);
     LZMAInputSupplier zis = new LZMAInputSupplier(classData);
     InputSupplier<InputStreamReader> srgSupplier =
         CharStreams.newReaderSupplier(zis, Charsets.UTF_8);
     List<String> srgList = CharStreams.readLines(srgSupplier);
     rawMethodMaps = Maps.newHashMap();
     rawFieldMaps = Maps.newHashMap();
     Builder<String, String> builder = ImmutableBiMap.<String, String>builder();
     Builder<String, String> mcpBuilder = ImmutableBiMap.<String, String>builder();
     Splitter splitter = Splitter.on(CharMatcher.anyOf(": ")).omitEmptyStrings().trimResults();
     for (String line : srgList) {
       String[] parts = Iterables.toArray(splitter.split(line), String.class);
       String typ = parts[0];
       if ("CL".equals(typ)) {
         parseClass(builder, parts);
         parseMCPClass(mcpBuilder, parts);
       } else if ("MD".equals(typ)) {
         parseMethod(parts);
       } else if ("FD".equals(typ)) {
         parseField(parts);
       }
     }
     classNameBiMap = builder.build();
     // Special case some mappings for modloader mods
     mcpBuilder.put("BaseMod", "net/minecraft/src/BaseMod");
     mcpBuilder.put("ModLoader", "net/minecraft/src/ModLoader");
     mcpBuilder.put("EntityRendererProxy", "net/minecraft/src/EntityRendererProxy");
     mcpBuilder.put("MLProp", "net/minecraft/src/MLProp");
     mcpBuilder.put("TradeEntry", "net/minecraft/src/TradeEntry");
     mcpNameBiMap = mcpBuilder.build();
   } catch (IOException ioe) {
     FMLRelaunchLog.log(Level.ERROR, ioe, "An error occurred loading the deobfuscation map data");
   }
   methodNameMaps = Maps.newHashMapWithExpectedSize(rawMethodMaps.size());
   fieldNameMaps = Maps.newHashMapWithExpectedSize(rawFieldMaps.size());
 }
Ejemplo n.º 10
0
  static {
    ImmutableBiMap.Builder<Integer, Class<? extends ImmunPacket>> builder =
        ImmutableBiMap.builder();

    builder.put(Integer.valueOf(0), Packet1Disease.class);
    builder.put(Integer.valueOf(1), Packet2RemoveDisease.class);
    builder.put(Integer.valueOf(2), Packet3Particle.class);
    builder.put(Integer.valueOf(3), Packet4SideEffect.class);
    builder.put(Integer.valueOf(4), Packet5RemoveSideEffect.class);
    builder.put(Integer.valueOf(5), Packet6Cure.class);
    builder.put(Integer.valueOf(6), Packet7Book.class);
    idMap = builder.build();
  }
Ejemplo n.º 11
0
 public ImmutableBiMap<ModContainer, Object> buildModObjectList() {
   ImmutableBiMap.Builder<ModContainer, Object> builder =
       ImmutableBiMap.<ModContainer, Object>builder();
   for (ModContainer mc : activeModList) {
     if (!mc.isImmutable() && mc.getMod() != null) {
       builder.put(mc, mc.getMod());
     }
     if (mc.getMod() == null && !mc.isImmutable() && state != LoaderState.CONSTRUCTING) {
       FMLLog.severe(
           "There is a severe problem with %s - it appears not to have constructed correctly",
           mc.getModId());
       if (state != LoaderState.CONSTRUCTING) {
         this.errorOccurred(mc, new RuntimeException());
       }
     }
   }
   return builder.build();
 }
Ejemplo n.º 12
0
  static {
    ImmutableBiMap.Builder<ChatColor, String> builder = ImmutableBiMap.builder();
    for (ChatColor style : ChatColor.values()) {
      if (!style.isFormat()) {
        continue;
      }

      String styleName;
      switch (style) {
        case MAGIC:
          styleName = "obfuscated";
          break;
        case UNDERLINE:
          styleName = "underlined";
          break;
        default:
          styleName = style.name().toLowerCase();
          break;
      }

      builder.put(style, styleName);
    }
    stylesToNames = builder.build();
  }
Ejemplo n.º 13
0
public class UriRecord implements ParsedRecord {

  // private static final String TAG = "UriRecord";

  public static final String RECORD_TYPE = "UriRecord";
  private static final BiMap<Byte, String> URI_PREFIX_MAP =
      ImmutableBiMap.<Byte, String>builder()
          .put((byte) 0x00, "")
          .put((byte) 0x01, "http://www.")
          .put((byte) 0x02, "https://www.")
          .put((byte) 0x03, "http://")
          .put((byte) 0x04, "https://")
          .put((byte) 0x05, "tel:")
          .put((byte) 0x06, "mailto:")
          .put((byte) 0x07, "ftp://*****:*****@")
          .put((byte) 0x08, "ftp://ftp.")
          .put((byte) 0x09, "ftps://")
          .put((byte) 0x0A, "sftp://")
          .put((byte) 0x0B, "smb://")
          .put((byte) 0x0C, "nfs://")
          .put((byte) 0x0D, "ftp://")
          .put((byte) 0x0E, "dav://")
          .put((byte) 0x0F, "news:")
          .put((byte) 0x10, "telnet://")
          .put((byte) 0x11, "imap:")
          .put((byte) 0x12, "rtsp://")
          .put((byte) 0x13, "urn:")
          .put((byte) 0x14, "pop:")
          .put((byte) 0x15, "sip:")
          .put((byte) 0x16, "sips:")
          .put((byte) 0x17, "tftp:")
          .put((byte) 0x18, "btspp://")
          .put((byte) 0x19, "btl2cap://")
          .put((byte) 0x1A, "btgoep://")
          .put((byte) 0x1B, "tcpobex://")
          .put((byte) 0x1C, "irdaobex://")
          .put((byte) 0x1D, "file://")
          .put((byte) 0x1E, "urn:epc:id:")
          .put((byte) 0x1F, "urn:epc:tag:")
          .put((byte) 0x20, "urn:epc:pat:")
          .put((byte) 0x21, "urn:epc:raw:")
          .put((byte) 0x22, "urn:epc:")
          .put((byte) 0x23, "urn:nfc:")
          .build();

  private final Uri mUri;

  private UriRecord(Uri uri) {
    this.mUri = Preconditions.checkNotNull(uri);
  }

  public int getType() {
    return ParsedRecord.TYPE_URI;
  }

  public Uri getUri() {
    return mUri;
  }

  public static UriRecord parse(NdefRecord record) {
    short tnf = record.getTnf();
    if (tnf == NdefRecord.TNF_WELL_KNOWN) {
      return parseWellKnown(record);
    } else if (tnf == NdefRecord.TNF_ABSOLUTE_URI) {
      return parseAbsolute(record);
    }
    throw new IllegalArgumentException("Unknown TNF " + tnf);
  }

  private static UriRecord parseAbsolute(NdefRecord record) {
    byte[] payload = record.getPayload();
    Uri uri = Uri.parse(new String(payload, Charset.forName("UTF-8")));
    return new UriRecord(uri);
  }

  /** Parse an well known URI record */
  private static UriRecord parseWellKnown(NdefRecord record) {
    Preconditions.checkArgument(Arrays.equals(record.getType(), NdefRecord.RTD_URI));
    byte[] payload = record.getPayload();

    String prefix = URI_PREFIX_MAP.get(payload[0]);
    byte[] fullUri =
        Bytes.concat(
            prefix.getBytes(Charset.forName("UTF-8")),
            Arrays.copyOfRange(payload, 1, payload.length));
    Uri uri = Uri.parse(new String(fullUri, Charset.forName("UTF-8")));
    return new UriRecord(uri);
  }

  public static boolean isUri(NdefRecord record) {
    try {
      parse(record);
      return true;
    } catch (IllegalArgumentException e) {
      return false;
    }
  }
}
Ejemplo n.º 14
0
public class FMLModContainer implements ModContainer {
  private Mod modDescriptor;
  private Object modInstance;
  private File source;
  private ModMetadata modMetadata;
  private String className;
  private Map<String, Object> descriptor;
  private boolean enabled = true;
  private String internalVersion;
  private boolean overridesMetadata;
  private EventBus eventBus;
  private LoadController controller;
  private DefaultArtifactVersion processedVersion;
  private boolean isNetworkMod;

  @SuppressWarnings("deprecation")
  private static final BiMap<Class<? extends FMLEvent>, Class<? extends Annotation>>
      modAnnotationTypes =
          ImmutableBiMap.<Class<? extends FMLEvent>, Class<? extends Annotation>>builder()
              .put(FMLPreInitializationEvent.class, Mod.PreInit.class)
              .put(FMLInitializationEvent.class, Mod.Init.class)
              .put(FMLPostInitializationEvent.class, Mod.PostInit.class)
              .put(FMLServerAboutToStartEvent.class, Mod.ServerAboutToStart.class)
              .put(FMLServerStartingEvent.class, Mod.ServerStarting.class)
              .put(FMLServerStartedEvent.class, Mod.ServerStarted.class)
              .put(FMLServerStoppingEvent.class, Mod.ServerStopping.class)
              .put(FMLServerStoppedEvent.class, Mod.ServerStopped.class)
              .put(IMCEvent.class, Mod.IMCCallback.class)
              .put(FMLFingerprintViolationEvent.class, Mod.FingerprintWarning.class)
              .build();

  private static final BiMap<Class<? extends Annotation>, Class<? extends FMLEvent>>
      modTypeAnnotations = modAnnotationTypes.inverse();
  private String annotationDependencies;
  private VersionRange minecraftAccepted;
  private boolean fingerprintNotPresent;
  private Set<String> sourceFingerprints;
  private Certificate certificate;
  private String modLanguage;
  private ILanguageAdapter languageAdapter;
  private ListMultimap<Class<? extends FMLEvent>, Method> eventMethods;
  private Map<String, String> customModProperties;
  private ModCandidate candidate;

  public FMLModContainer(
      String className, ModCandidate container, Map<String, Object> modDescriptor) {
    this.className = className;
    this.source = container.getModContainer();
    this.candidate = container;
    this.descriptor = modDescriptor;
    this.modLanguage = (String) modDescriptor.get("modLanguage");
    this.languageAdapter =
        "scala".equals(modLanguage)
            ? new ILanguageAdapter.ScalaAdapter()
            : new ILanguageAdapter.JavaAdapter();
    this.eventMethods = ArrayListMultimap.create();
  }

  private ILanguageAdapter getLanguageAdapter() {
    return languageAdapter;
  }

  @Override
  public String getModId() {
    return (String) descriptor.get("modid");
  }

  @Override
  public String getName() {
    return modMetadata.name;
  }

  @Override
  public String getVersion() {
    return internalVersion;
  }

  @Override
  public File getSource() {
    return source;
  }

  @Override
  public ModMetadata getMetadata() {
    return modMetadata;
  }

  @Override
  public void bindMetadata(MetadataCollection mc) {
    modMetadata = mc.getMetadataForId(getModId(), descriptor);

    if (descriptor.containsKey("useMetadata")) {
      overridesMetadata = !((Boolean) descriptor.get("useMetadata")).booleanValue();
    }

    if (overridesMetadata || !modMetadata.useDependencyInformation) {
      Set<ArtifactVersion> requirements = Sets.newHashSet();
      List<ArtifactVersion> dependencies = Lists.newArrayList();
      List<ArtifactVersion> dependants = Lists.newArrayList();
      annotationDependencies = (String) descriptor.get("dependencies");
      Loader.instance()
          .computeDependencies(annotationDependencies, requirements, dependencies, dependants);
      modMetadata.requiredMods = requirements;
      modMetadata.dependencies = dependencies;
      modMetadata.dependants = dependants;
      FMLLog.log(
          getModId(),
          Level.FINEST,
          "Parsed dependency info : %s %s %s",
          requirements,
          dependencies,
          dependants);
    } else {
      FMLLog.log(
          getModId(),
          Level.FINEST,
          "Using mcmod dependency info : %s %s %s",
          modMetadata.requiredMods,
          modMetadata.dependencies,
          modMetadata.dependants);
    }
    if (Strings.isNullOrEmpty(modMetadata.name)) {
      FMLLog.log(
          getModId(),
          Level.INFO,
          "Mod %s is missing the required element 'name'. Substituting %s",
          getModId(),
          getModId());
      modMetadata.name = getModId();
    }
    internalVersion = (String) descriptor.get("version");
    if (Strings.isNullOrEmpty(internalVersion)) {
      Properties versionProps = searchForVersionProperties();
      if (versionProps != null) {
        internalVersion = versionProps.getProperty(getModId() + ".version");
        FMLLog.log(
            getModId(),
            Level.FINE,
            "Found version %s for mod %s in version.properties, using",
            internalVersion,
            getModId());
      }
    }
    if (Strings.isNullOrEmpty(internalVersion) && !Strings.isNullOrEmpty(modMetadata.version)) {
      FMLLog.log(
          getModId(),
          Level.WARNING,
          "Mod %s is missing the required element 'version' and a version.properties file could not be found. Falling back to metadata version %s",
          getModId(),
          modMetadata.version);
      internalVersion = modMetadata.version;
    }
    if (Strings.isNullOrEmpty(internalVersion)) {
      FMLLog.log(
          getModId(),
          Level.WARNING,
          "Mod %s is missing the required element 'version' and no fallback can be found. Substituting '1.0'.",
          getModId());
      modMetadata.version = internalVersion = "1.0";
    }

    String mcVersionString = (String) descriptor.get("acceptedMinecraftVersions");
    if (!Strings.isNullOrEmpty(mcVersionString)) {
      minecraftAccepted = VersionParser.parseRange(mcVersionString);
    } else {
      minecraftAccepted = Loader.instance().getMinecraftModContainer().getStaticVersionRange();
    }
  }

  public Properties searchForVersionProperties() {
    try {
      FMLLog.log(
          getModId(),
          Level.FINE,
          "Attempting to load the file version.properties from %s to locate a version number for %s",
          getSource().getName(),
          getModId());
      Properties version = null;
      if (getSource().isFile()) {
        ZipFile source = new ZipFile(getSource());
        ZipEntry versionFile = source.getEntry("version.properties");
        if (versionFile != null) {
          version = new Properties();
          version.load(source.getInputStream(versionFile));
        }
        source.close();
      } else if (getSource().isDirectory()) {
        File propsFile = new File(getSource(), "version.properties");
        if (propsFile.exists() && propsFile.isFile()) {
          version = new Properties();
          FileInputStream fis = new FileInputStream(propsFile);
          version.load(fis);
          fis.close();
        }
      }
      return version;
    } catch (Exception e) {
      Throwables.propagateIfPossible(e);
      FMLLog.log(getModId(), Level.FINEST, "Failed to find a usable version.properties file");
      return null;
    }
  }

  @Override
  public void setEnabledState(boolean enabled) {
    this.enabled = enabled;
  }

  @Override
  public Set<ArtifactVersion> getRequirements() {
    return modMetadata.requiredMods;
  }

  @Override
  public List<ArtifactVersion> getDependencies() {
    return modMetadata.dependencies;
  }

  @Override
  public List<ArtifactVersion> getDependants() {
    return modMetadata.dependants;
  }

  @Override
  public String getSortingRules() {
    return ((overridesMetadata || !modMetadata.useDependencyInformation)
        ? Strings.nullToEmpty(annotationDependencies)
        : modMetadata.printableSortingRules());
  }

  @Override
  public boolean matches(Object mod) {
    return mod == modInstance;
  }

  @Override
  public Object getMod() {
    return modInstance;
  }

  @Override
  public boolean registerBus(EventBus bus, LoadController controller) {
    if (this.enabled) {
      FMLLog.log(getModId(), Level.FINE, "Enabling mod %s", getModId());
      this.eventBus = bus;
      this.controller = controller;
      eventBus.register(this);
      return true;
    } else {
      return false;
    }
  }

  private Method gatherAnnotations(Class<?> clazz) throws Exception {
    Method factoryMethod = null;
    for (Method m : clazz.getDeclaredMethods()) {
      for (Annotation a : m.getAnnotations()) {
        if (modTypeAnnotations.containsKey(a.annotationType())) {
          Class<?>[] paramTypes = new Class[] {modTypeAnnotations.get(a.annotationType())};
          if (Arrays.equals(m.getParameterTypes(), paramTypes)) {
            m.setAccessible(true);
            eventMethods.put(modTypeAnnotations.get(a.annotationType()), m);
          } else {
            FMLLog.log(
                getModId(),
                Level.SEVERE,
                "The mod %s appears to have an invalid method annotation %s. This annotation can only apply to methods with argument types %s -it will not be called",
                getModId(),
                a.annotationType().getSimpleName(),
                Arrays.toString(paramTypes));
          }
        } else if (a.annotationType().equals(Mod.EventHandler.class)) {
          if (m.getParameterTypes().length == 1
              && modAnnotationTypes.containsKey(m.getParameterTypes()[0])) {
            m.setAccessible(true);
            eventMethods.put((Class<? extends FMLEvent>) m.getParameterTypes()[0], m);
          } else {
            FMLLog.log(
                getModId(),
                Level.SEVERE,
                "The mod %s appears to have an invalid event annotation %s. This annotation can only apply to methods with recognized event arguments - it will not be called",
                getModId(),
                a.annotationType().getSimpleName());
          }
        } else if (a.annotationType().equals(Mod.InstanceFactory.class)) {
          if (Modifier.isStatic(m.getModifiers())
              && m.getParameterTypes().length == 0
              && factoryMethod == null) {
            m.setAccessible(true);
            factoryMethod = m;
          } else if (!(Modifier.isStatic(m.getModifiers()) && m.getParameterTypes().length == 0)) {
            FMLLog.log(
                getModId(),
                Level.SEVERE,
                "The InstanceFactory annotation can only apply to a static method, taking zero arguments - it will be ignored on %s(%s)",
                m.getName(),
                Arrays.asList(m.getParameterTypes()));
          } else if (factoryMethod != null) {
            FMLLog.log(
                getModId(),
                Level.SEVERE,
                "The InstanceFactory annotation can only be used once, the application to %s(%s) will be ignored",
                m.getName(),
                Arrays.asList(m.getParameterTypes()));
          }
        }
      }
    }
    return factoryMethod;
  }

  private void processFieldAnnotations(ASMDataTable asmDataTable) throws Exception {
    SetMultimap<String, ASMData> annotations = asmDataTable.getAnnotationsFor(this);

    parseSimpleFieldAnnotation(
        annotations,
        Instance.class.getName(),
        new Function<ModContainer, Object>() {
          public Object apply(ModContainer mc) {
            return mc.getMod();
          }
        });
    parseSimpleFieldAnnotation(
        annotations,
        Metadata.class.getName(),
        new Function<ModContainer, Object>() {
          public Object apply(ModContainer mc) {
            return mc.getMetadata();
          }
        });
  }

  private void parseSimpleFieldAnnotation(
      SetMultimap<String, ASMData> annotations,
      String annotationClassName,
      Function<ModContainer, Object> retreiver)
      throws IllegalAccessException {
    String[] annName = annotationClassName.split("\\.");
    String annotationName = annName[annName.length - 1];
    for (ASMData targets : annotations.get(annotationClassName)) {
      String targetMod = (String) targets.getAnnotationInfo().get("value");
      Field f = null;
      Object injectedMod = null;
      ModContainer mc = this;
      boolean isStatic = false;
      Class<?> clz = modInstance.getClass();
      if (!Strings.isNullOrEmpty(targetMod)) {
        if (Loader.isModLoaded(targetMod)) {
          mc = Loader.instance().getIndexedModList().get(targetMod);
        } else {
          mc = null;
        }
      }
      if (mc != null) {
        try {
          clz = Class.forName(targets.getClassName(), true, Loader.instance().getModClassLoader());
          f = clz.getDeclaredField(targets.getObjectName());
          f.setAccessible(true);
          isStatic = Modifier.isStatic(f.getModifiers());
          injectedMod = retreiver.apply(mc);
        } catch (Exception e) {
          Throwables.propagateIfPossible(e);
          FMLLog.log(
              getModId(),
              Level.WARNING,
              e,
              "Attempting to load @%s in class %s for %s and failing",
              annotationName,
              targets.getClassName(),
              mc.getModId());
        }
      }
      if (f != null) {
        Object target = null;
        if (!isStatic) {
          target = modInstance;
          if (!modInstance.getClass().equals(clz)) {
            FMLLog.log(
                getModId(),
                Level.WARNING,
                "Unable to inject @%s in non-static field %s.%s for %s as it is NOT the primary mod instance",
                annotationName,
                targets.getClassName(),
                targets.getObjectName(),
                mc.getModId());
            continue;
          }
        }
        f.set(target, injectedMod);
      }
    }
  }

  @Subscribe
  public void constructMod(FMLConstructionEvent event) {
    try {
      ModClassLoader modClassLoader = event.getModClassLoader();
      modClassLoader.addFile(source);
      modClassLoader.clearNegativeCacheFor(candidate.getClassList());
      Class<?> clazz = Class.forName(className, true, modClassLoader);

      Certificate[] certificates = clazz.getProtectionDomain().getCodeSource().getCertificates();
      int len = 0;
      if (certificates != null) {
        len = certificates.length;
      }
      Builder<String> certBuilder = ImmutableList.<String>builder();
      for (int i = 0; i < len; i++) {
        certBuilder.add(CertificateHelper.getFingerprint(certificates[i]));
      }

      ImmutableList<String> certList = certBuilder.build();
      sourceFingerprints = ImmutableSet.copyOf(certList);

      String expectedFingerprint = (String) descriptor.get("certificateFingerprint");

      fingerprintNotPresent = true;

      if (expectedFingerprint != null && !expectedFingerprint.isEmpty()) {
        if (!sourceFingerprints.contains(expectedFingerprint)) {
          Level warnLevel = Level.SEVERE;
          if (source.isDirectory()) {
            warnLevel = Level.FINER;
          }
          FMLLog.log(
              getModId(),
              warnLevel,
              "The mod %s is expecting signature %s for source %s, however there is no signature matching that description",
              getModId(),
              expectedFingerprint,
              source.getName());
        } else {
          certificate = certificates[certList.indexOf(expectedFingerprint)];
          fingerprintNotPresent = false;
        }
      }

      CustomProperty[] props = (CustomProperty[]) descriptor.get("customProperties");
      if (props != null && props.length > 0) {
        com.google.common.collect.ImmutableMap.Builder<String, String> builder =
            ImmutableMap.<String, String>builder();
        for (CustomProperty p : props) {
          builder.put(p.k(), p.v());
        }
        customModProperties = builder.build();
      } else {
        customModProperties = EMPTY_PROPERTIES;
      }

      Method factoryMethod = gatherAnnotations(clazz);
      modInstance = getLanguageAdapter().getNewInstance(this, clazz, modClassLoader, factoryMethod);
      isNetworkMod =
          FMLNetworkHandler.instance().registerNetworkMod(this, clazz, event.getASMHarvestedData());
      if (fingerprintNotPresent) {
        eventBus.post(
            new FMLFingerprintViolationEvent(
                source.isDirectory(),
                source,
                ImmutableSet.copyOf(this.sourceFingerprints),
                expectedFingerprint));
      }
      ProxyInjector.inject(
          this,
          event.getASMHarvestedData(),
          FMLCommonHandler.instance().getSide(),
          getLanguageAdapter());
      processFieldAnnotations(event.getASMHarvestedData());
    } catch (Throwable e) {
      controller.errorOccurred(this, e);
      Throwables.propagateIfPossible(e);
    }
  }

  @Subscribe
  public void handleModStateEvent(FMLEvent event) {
    if (!eventMethods.containsKey(event.getClass())) {
      return;
    }
    try {
      for (Method m : eventMethods.get(event.getClass())) {
        m.invoke(modInstance, event);
      }
    } catch (Throwable t) {
      controller.errorOccurred(this, t);
    }
  }

  @Override
  public ArtifactVersion getProcessedVersion() {
    if (processedVersion == null) {
      processedVersion = new DefaultArtifactVersion(getModId(), getVersion());
    }
    return processedVersion;
  }

  @Override
  public boolean isImmutable() {
    return false;
  }

  @Override
  public boolean isNetworkMod() {
    return isNetworkMod;
  }

  @Override
  public String getDisplayVersion() {
    return modMetadata.version;
  }

  @Override
  public VersionRange acceptableMinecraftVersionRange() {
    return minecraftAccepted;
  }

  @Override
  public Certificate getSigningCertificate() {
    return certificate;
  }

  @Override
  public String toString() {
    return "FMLMod:" + getModId() + "{" + getVersion() + "}";
  }

  @Override
  public Map<String, String> getCustomModProperties() {
    return customModProperties;
  }

  @Override
  public Class<?> getCustomResourcePackClass() {
    try {
      return getSource().isDirectory()
          ? Class.forName(
              "cpw.mods.fml.client.FMLFolderResourcePack", true, getClass().getClassLoader())
          : Class.forName(
              "cpw.mods.fml.client.FMLFileResourcePack", true, getClass().getClassLoader());
    } catch (ClassNotFoundException e) {
      return null;
    }
  }

  @Override
  public Map<String, String> getSharedModDescriptor() {
    Map<String, String> descriptor = Maps.newHashMap();
    descriptor.put("modsystem", "FML");
    descriptor.put("id", getModId());
    descriptor.put("version", getDisplayVersion());
    descriptor.put("name", getName());
    descriptor.put("url", modMetadata.url);
    descriptor.put("authors", modMetadata.getAuthorList());
    descriptor.put("description", modMetadata.description);
    return descriptor;
  }
}
Ejemplo n.º 15
0
 private ImmutableBiMap<Path, Path> getAllPathsWork(Path workingDir) {
   ImmutableBiMap.Builder<Path, Path> builder = ImmutableBiMap.builder();
   builder.put(workingDir, compilationDirectory);
   builder.putAll(other);
   return builder.build();
 }
/** @author Immortius */
public class NetworkEntitySerializer {
  private static final Logger logger = LoggerFactory.getLogger(NetworkEntitySerializer.class);

  private ComponentSerializeCheck componentSerializeCheck =
      ComponentSerializeCheck.NullCheck.create();
  private EngineEntityManager entityManager;
  private ComponentLibrary componentLibrary;
  private TypeSerializationLibrary typeSerializationLibrary;
  private ProtobufSerializationContext serializationContext;
  private ProtobufDeserializationContext deserializationContext;
  private BiMap<Class<? extends Component>, Integer> idTable =
      ImmutableBiMap.<Class<? extends Component>, Integer>builder().build();

  public NetworkEntitySerializer(
      EngineEntityManager entityManager,
      ComponentLibrary componentLibrary,
      TypeSerializationLibrary typeSerializationLibrary) {
    this.entityManager = entityManager;
    this.componentLibrary = componentLibrary;
    this.typeSerializationLibrary = typeSerializationLibrary;
    this.serializationContext = new ProtobufSerializationContext(typeSerializationLibrary);
    this.deserializationContext = new ProtobufDeserializationContext(typeSerializationLibrary);
  }

  public void setComponentSerializeCheck(ComponentSerializeCheck componentSerializeCheck) {
    this.componentSerializeCheck = componentSerializeCheck;
  }

  public ComponentLibrary getComponentLibrary() {
    return componentLibrary;
  }

  public Map<Class<? extends Component>, Integer> getIdMapping() {
    return ImmutableMap.copyOf(idTable);
  }

  public void setIdMapping(Map<Class<? extends Component>, Integer> componentIdMapping) {
    this.idTable = ImmutableBiMap.copyOf(componentIdMapping);
  }

  public EntityData.PackedEntity.Builder serialize(
      EntityRef entity, boolean deltaAgainstPrefab, FieldSerializeCheck<Component> fieldCheck) {
    Prefab prefab = entity.getParentPrefab();
    if (prefab != null && deltaAgainstPrefab) {
      return serializeEntityDelta(entity, prefab, fieldCheck);
    } else {
      return serializeEntityFull(entity, fieldCheck);
    }
  }

  private EntityData.PackedEntity.Builder serializeEntityFull(
      EntityRef entityRef, FieldSerializeCheck<Component> fieldCheck) {
    EntityData.PackedEntity.Builder entity = EntityData.PackedEntity.newBuilder();
    ByteString.Output fieldIds = ByteString.newOutput();
    ByteString.Output componentFieldCounts = ByteString.newOutput();
    for (Component component : entityRef.iterateComponents()) {
      if (!componentSerializeCheck.serialize(componentLibrary.getMetadata(component.getClass()))) {
        continue;
      }

      serializeComponentFull(
          component, false, fieldCheck, entity, fieldIds, componentFieldCounts, true);
    }
    entity.setFieldIds(fieldIds.toByteString());
    entity.setComponentFieldCounts(componentFieldCounts.toByteString());

    return entity;
  }

  private EntityData.PackedEntity.Builder serializeEntityDelta(
      EntityRef entityRef, Prefab prefab, FieldSerializeCheck<Component> fieldCheck) {
    EntityData.PackedEntity.Builder entity = EntityData.PackedEntity.newBuilder();
    entity.setParentPrefabUri(prefab.getName());
    Set<Class<? extends Component>> presentClasses = Sets.newHashSet();

    ByteString.Output fieldIds = ByteString.newOutput();
    ByteString.Output componentFieldCounts = ByteString.newOutput();
    for (Component component : entityRef.iterateComponents()) {
      if (!componentSerializeCheck.serialize(componentLibrary.getMetadata(component.getClass()))) {
        continue;
      }

      presentClasses.add(component.getClass());

      Component prefabComponent = prefab.getComponent(component.getClass());

      if (prefabComponent == null) {
        serializeComponentFull(
            component, false, fieldCheck, entity, fieldIds, componentFieldCounts, true);
      } else {
        serializeComponentDelta(
            prefabComponent, component, fieldCheck, entity, fieldIds, componentFieldCounts, true);
      }
    }
    entity.setFieldIds(fieldIds.toByteString());
    entity.setComponentFieldCounts(componentFieldCounts.toByteString());

    for (Component prefabComponent : prefab.iterateComponents()) {
      if (!presentClasses.contains(prefabComponent.getClass())
          && componentSerializeCheck.serialize(
              componentLibrary.getMetadata(prefabComponent.getClass()))) {
        entity.addRemovedComponent(idTable.get(prefabComponent.getClass()));
      }
    }
    return entity;
  }

  private void serializeComponentDelta(
      Component oldComponent,
      Component newComponent,
      FieldSerializeCheck<Component> fieldCheck,
      EntityData.PackedEntity.Builder entityData,
      ByteString.Output entityFieldIds,
      ByteString.Output componentFieldCounts,
      boolean componentInitial) {
    ComponentMetadata<?> componentMetadata = componentLibrary.getMetadata(oldComponent.getClass());
    if (componentMetadata == null) {
      logger.error("Unregistered component type: {}", oldComponent.getClass());
      return;
    }

    byte fieldCount = 0;
    Serializer serializer = typeSerializationLibrary.getSerializerFor(componentMetadata);
    for (ReplicatedFieldMetadata field : componentMetadata.getFields()) {
      if (fieldCheck.shouldSerializeField(field, newComponent, componentInitial)) {
        Object oldValue = field.getValue(oldComponent);
        Object newValue = field.getValue(newComponent);
        if (!Objects.equal(oldValue, newValue)) {
          PersistedData data = serializer.serializeValue(field, newValue, serializationContext);
          if (!data.isNull()) {
            entityFieldIds.write(field.getId());
            entityData.addFieldValue(((ProtobufPersistedData) data).getValue());
            fieldCount++;
          } else {
            logger.error(
                "Exception serializing component type: {}, field: {} - returned null",
                componentMetadata,
                field);
          }
        }
      }
    }

    if (fieldCount > 0) {
      entityData.addComponentId(idTable.get(newComponent.getClass()));
      componentFieldCounts.write(fieldCount);
    }
  }

  private void serializeComponentFull(
      Component component,
      boolean ignoreIfNoFields,
      FieldSerializeCheck<Component> fieldCheck,
      EntityData.PackedEntity.Builder entityData,
      ByteString.Output entityFieldIds,
      ByteString.Output componentFieldCounts,
      boolean componentInitial) {
    ComponentMetadata<?> componentMetadata = componentLibrary.getMetadata(component.getClass());
    if (componentMetadata == null) {
      logger.error("Unregistered component type: {}", component.getClass());
      return;
    }

    Serializer serializer = typeSerializationLibrary.getSerializerFor(componentMetadata);
    byte fieldCount = 0;
    for (ReplicatedFieldMetadata field : componentMetadata.getFields()) {
      if (fieldCheck.shouldSerializeField(field, component, componentInitial)) {
        PersistedData fieldValue = serializer.serialize(field, component, serializationContext);
        if (!fieldValue.isNull()) {
          entityFieldIds.write(field.getId());

          entityData.addFieldValue(((ProtobufPersistedData) fieldValue).getValue());
          fieldCount++;
        }
      }
    }

    if (fieldCount != 0 || !ignoreIfNoFields) {
      entityData.addComponentId(idTable.get(component.getClass()));
      componentFieldCounts.write(fieldCount);
    }
  }

  public void deserializeOnto(
      MutableComponentContainer entity, EntityData.PackedEntity entityData) {
    deserializeOnto(entity, entityData, FieldSerializeCheck.NullCheck.<Component>newInstance());
  }

  public void deserializeOnto(
      MutableComponentContainer entity,
      EntityData.PackedEntity entityData,
      FieldSerializeCheck<Component> fieldCheck) {
    int fieldPos = 0;
    for (int componentIndex = 0;
        componentIndex < entityData.getComponentIdCount();
        ++componentIndex) {
      Class<? extends Component> componentClass =
          idTable.inverse().get((Integer) entityData.getComponentId(componentIndex));
      ComponentMetadata<?> metadata = componentLibrary.getMetadata(componentClass);
      if (metadata == null) {
        logger.warn("Skipping unknown component {}", entityData.getComponentId(componentIndex));
        fieldPos +=
            UnsignedBytes.toInt(entityData.getComponentFieldCounts().byteAt(componentIndex));
        continue;
      }
      if (!componentSerializeCheck.serialize(metadata)) {
        fieldPos +=
            UnsignedBytes.toInt(entityData.getComponentFieldCounts().byteAt(componentIndex));
        continue;
      }

      Component component = entity.getComponent(metadata.getType());
      boolean createdNewComponent = false;
      if (component == null) {
        createdNewComponent = true;
        component = metadata.newInstance();
      }
      Serializer serializer = typeSerializationLibrary.getSerializerFor(metadata);
      for (int fieldIndex = 0;
          fieldIndex
              < UnsignedBytes.toInt(entityData.getComponentFieldCounts().byteAt(componentIndex));
          ++fieldIndex) {
        byte fieldId = entityData.getFieldIds().byteAt(fieldPos);
        ReplicatedFieldMetadata fieldMetadata = metadata.getField(fieldId);
        if (fieldMetadata != null && fieldCheck.shouldDeserialize(metadata, fieldMetadata)) {
          logger.trace(
              "Deserializing field {} of component {} as value {}",
              fieldMetadata,
              metadata,
              entityData.getFieldValue(fieldPos));
          serializer.deserializeOnto(
              component,
              fieldMetadata,
              new ProtobufPersistedData(entityData.getFieldValue(fieldPos)),
              deserializationContext);
        }
        fieldPos++;
      }
      if (createdNewComponent) {
        entity.addComponent(component);
      } else {
        entity.saveComponent(component);
      }
    }

    for (int componentId : entityData.getRemovedComponentList()) {
      Class<? extends Component> componentClass = idTable.inverse().get(componentId);
      ComponentMetadata<?> metadata = componentLibrary.getMetadata(componentClass);
      if (componentSerializeCheck.serialize(metadata)) {
        entity.removeComponent(metadata.getType());
      }
    }
  }

  public EntityRef deserialize(EntityData.PackedEntity entityData) {
    EntityBuilder target;
    if (entityData.hasParentPrefabUri()) {
      target = entityManager.newBuilder(entityData.getParentPrefabUri());
    } else {
      target = entityManager.newBuilder();
    }
    deserializeOnto(target, entityData);
    if (entityData.hasId()) {
      return entityManager.createEntityWithId(entityData.getId(), target.iterateComponents());
    } else {
      return target.build();
    }
  }

  public EntityData.PackedEntity serialize(
      EntityRef entityRef,
      Set<Class<? extends Component>> added,
      Set<Class<? extends Component>> changed,
      Set<Class<? extends Component>> removed,
      FieldSerializeCheck<Component> fieldCheck) {
    EntityData.PackedEntity.Builder entity = EntityData.PackedEntity.newBuilder();

    ByteString.Output fieldIds = ByteString.newOutput();
    ByteString.Output componentFieldCounts = ByteString.newOutput();
    for (Class<? extends Component> componentType : added) {
      Component component = entityRef.getComponent(componentType);
      if (component == null) {
        logger.error("Non-existent component marked as added: {}", componentType);
      }
      serializeComponentFull(
          entityRef.getComponent(componentType),
          false,
          fieldCheck,
          entity,
          fieldIds,
          componentFieldCounts,
          true);
    }
    for (Class<? extends Component> componentType : changed) {
      Component comp = entityRef.getComponent(componentType);
      if (comp != null) {
        serializeComponentFull(
            comp, true, fieldCheck, entity, fieldIds, componentFieldCounts, false);
      } else {
        logger.error("Non-existent component marked as changed: {}", componentType);
      }
    }
    for (Class<? extends Component> componentType : removed) {
      entity.addRemovedComponent(idTable.get(componentType));
    }
    entity.setFieldIds(fieldIds.toByteString());
    entity.setComponentFieldCounts(componentFieldCounts.toByteString());
    if (entity.getFieldIds().isEmpty() && entity.getRemovedComponentCount() == 0) {
      return null;
    } else {
      return entity.build();
    }
  }
}
Ejemplo n.º 17
0
  @VisibleForTesting
  static AppleCxxPlatform buildWithExecutableChecker(
      AppleSdk targetSdk,
      String minVersion,
      String targetArchitecture,
      AppleSdkPaths sdkPaths,
      BuckConfig buckConfig,
      ExecutableFinder executableFinder) {

    ImmutableList.Builder<Path> toolSearchPathsBuilder = ImmutableList.builder();
    // Search for tools from most specific to least specific.
    toolSearchPathsBuilder
        .add(sdkPaths.getSdkPath().resolve(USR_BIN))
        .add(sdkPaths.getSdkPath().resolve("Developer").resolve(USR_BIN))
        .add(sdkPaths.getPlatformPath().resolve("Developer").resolve(USR_BIN));
    for (Path toolchainPath : sdkPaths.getToolchainPaths()) {
      toolSearchPathsBuilder.add(toolchainPath.resolve(USR_BIN));
    }
    if (sdkPaths.getDeveloperPath().isPresent()) {
      toolSearchPathsBuilder.add(sdkPaths.getDeveloperPath().get().resolve(USR_BIN));
      toolSearchPathsBuilder.add(sdkPaths.getDeveloperPath().get().resolve("Tools"));
    }
    ImmutableList<Path> toolSearchPaths = toolSearchPathsBuilder.build();

    // TODO(user): Add more and better cflags.
    ImmutableList.Builder<String> cflagsBuilder = ImmutableList.builder();
    cflagsBuilder.add("-isysroot", sdkPaths.getSdkPath().toString());
    cflagsBuilder.add("-arch", targetArchitecture);
    switch (targetSdk.getApplePlatform().getName()) {
      case ApplePlatform.Name.IPHONEOS:
        cflagsBuilder.add("-mios-version-min=" + minVersion);
        break;
      case ApplePlatform.Name.IPHONESIMULATOR:
        cflagsBuilder.add("-mios-simulator-version-min=" + minVersion);
        break;
      default:
        // For Mac builds, -mmacosx-version-min=<version>.
        cflagsBuilder.add(
            "-m" + targetSdk.getApplePlatform().getName() + "-version-min=" + minVersion);
        break;
    }

    ImmutableList<String> ldflags = ImmutableList.of("-sdk_version", targetSdk.getVersion());

    ImmutableList.Builder<String> versionsBuilder = ImmutableList.builder();
    versionsBuilder.add(targetSdk.getVersion());
    for (AppleToolchain toolchain : targetSdk.getToolchains()) {
      versionsBuilder.add(toolchain.getVersion());
    }
    String version = Joiner.on(':').join(versionsBuilder.build());

    Tool clangPath =
        new VersionedTool(
            getToolPath("clang", toolSearchPaths, executableFinder),
            ImmutableList.<String>of(),
            "apple-clang",
            version);

    Tool clangXxPath =
        new VersionedTool(
            getToolPath("clang++", toolSearchPaths, executableFinder),
            ImmutableList.<String>of(),
            "apple-clang++",
            version);

    Tool ar =
        new VersionedTool(
            getToolPath("ar", toolSearchPaths, executableFinder),
            ImmutableList.<String>of(),
            "apple-ar",
            version);

    Tool actool =
        new VersionedTool(
            getToolPath("actool", toolSearchPaths, executableFinder),
            ImmutableList.<String>of(),
            "apple-actool",
            version);

    Tool ibtool =
        new VersionedTool(
            getToolPath("ibtool", toolSearchPaths, executableFinder),
            ImmutableList.<String>of(),
            "apple-ibtool",
            version);

    Tool xctest =
        new VersionedTool(
            getToolPath("xctest", toolSearchPaths, executableFinder),
            ImmutableList.<String>of(),
            "apple-xctest",
            version);

    Optional<Tool> otest = getOptionalTool("otest", toolSearchPaths, executableFinder, version);

    Tool dsymutil =
        new VersionedTool(
            getToolPath("dsymutil", toolSearchPaths, executableFinder),
            ImmutableList.<String>of(),
            "apple-dsymutil",
            version);

    CxxBuckConfig config = new CxxBuckConfig(buckConfig);

    ImmutableFlavor targetFlavor =
        ImmutableFlavor.of(
            ImmutableFlavor.replaceInvalidCharacters(
                targetSdk.getName() + "-" + targetArchitecture));

    ImmutableBiMap.Builder<Path, Path> sanitizerPaths = ImmutableBiMap.builder();
    sanitizerPaths.put(sdkPaths.getSdkPath(), Paths.get("APPLE_SDKROOT"));
    sanitizerPaths.put(sdkPaths.getPlatformPath(), Paths.get("APPLE_PLATFORM_DIR"));
    if (sdkPaths.getDeveloperPath().isPresent()) {
      sanitizerPaths.put(sdkPaths.getDeveloperPath().get(), Paths.get("APPLE_DEVELOPER_DIR"));
    }

    DebugPathSanitizer debugPathSanitizer =
        new DebugPathSanitizer(250, File.separatorChar, Paths.get("."), sanitizerPaths.build());

    ImmutableList<String> cflags = cflagsBuilder.build();

    CxxPlatform cxxPlatform =
        CxxPlatforms.build(
            targetFlavor,
            Platform.MACOS,
            config,
            clangPath,
            clangPath,
            new ClangCompiler(clangPath),
            new ClangCompiler(clangXxPath),
            clangPath,
            clangXxPath,
            clangXxPath,
            Optional.of(CxxPlatform.LinkerType.DARWIN),
            clangXxPath,
            ldflags,
            new BsdArchiver(ar),
            cflags,
            ImmutableList.<String>of(),
            getOptionalTool("lex", toolSearchPaths, executableFinder, version),
            getOptionalTool("yacc", toolSearchPaths, executableFinder, version),
            Optional.of(debugPathSanitizer));

    return AppleCxxPlatform.builder()
        .setCxxPlatform(cxxPlatform)
        .setAppleSdk(targetSdk)
        .setAppleSdkPaths(sdkPaths)
        .setActool(actool)
        .setIbtool(ibtool)
        .setXctest(xctest)
        .setOtest(otest)
        .setDsymutil(dsymutil)
        .build();
  }