LoadableFile.java 14.8 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533
/*
 * This file is part of LiteLoader.
 * Copyright (C) 2012-16 Adam Mummery-Smith
 * All Rights Reserved.
 */
package com.mumfrey.liteloader.interfaces;

import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.jar.Attributes;
import java.util.jar.JarFile;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;

import org.spongepowered.asm.util.Constants.ManifestAttributes;

import com.google.common.io.Files;
import com.google.common.primitives.Ints;
import com.mumfrey.liteloader.core.api.LoadableModFile;
import com.mumfrey.liteloader.launch.ClassPathUtilities;
import com.mumfrey.liteloader.launch.InjectionStrategy;
import com.mumfrey.liteloader.launch.LiteLoaderTweaker;
import com.mumfrey.liteloader.launch.LoaderEnvironment;
import com.mumfrey.liteloader.util.log.LiteLoaderLogger;

import net.minecraft.launchwrapper.LaunchClassLoader;

public class LoadableFile extends File implements TweakContainer<File>
{
    public static final String MFATT_MODTYPE = "ModType";
    public static final String MFATT_TWEAK_CLASS = "TweakClass";
    public static final String MFATT_CLASS_PATH = "Class-Path";
    public static final String MFATT_TWEAK_ORDER = "TweakOrder";
    public static final String MFATT_IMPLEMENTATION_TITLE = "Implementation-Title";
    public static final String MFATT_TWEAK_NAME = "TweakName";
    public static final String MFATT_IMPLEMENTATION_VERSION = "Implementation-Version";
    public static final String MFATT_TWEAK_VERSION = "TweakVersion";
    public static final String MFATT_IMPLEMENTATION_VENDOR = "Implementation-Vendor";
    public static final String MFATT_TWEAK_AUTHOR = "TweakAuthor";
    public static final String MFATT_MIXIN_CONFIGS = ManifestAttributes.MIXINCONFIGS;
    public static final String MFATT_INJECTION_STRATEGY = "TweakInjectionStrategy";

    private static final Pattern versionPattern = Pattern.compile("([0-9]+\\.)+[0-9]+([_A-Z0-9]+)?");

    private static final long serialVersionUID = 1L;

    /**
     * True once this file has been injected into the class path 
     */
    protected boolean injected;

    protected boolean forceInjection;

    /**
     * Position to inject the mod file at in the class path, if blank injects at
     * the bottom as usual, alternatively the developer can specify "top" to
     * inject at the top, "base" to inject above the game jar, or "above: name"
     * to inject above a specified other library matching "name".
     */
    protected InjectionStrategy injectionStrategy = null;

    protected Set<String> modSystems = new HashSet<String>();

    /**
     * Name of the tweak class
     */
    protected String tweakClassName;

    /**
     * Priority for this tweaker 
     */
    protected int tweakPriority = 1000;

    /**
     * Class path entries read from jar metadata
     */
    protected String[] classPathEntries = null;

    protected String displayName;

    protected String version = "Unknown";

    protected String author = "Unknown";

    protected boolean hasEventTransformers;

    /**
     * Mixin config resource names
     */
    protected Set<String> mixinConfigs = new HashSet<String>();
    
    /**
     * Mixin errors 
     */
    protected List<Throwable> mixinErrors = new ArrayList<Throwable>();

    /**
     * Create a new tweak container wrapping the specified file
     */
    public LoadableFile(File parent)
    {
        super(parent.getAbsolutePath());
        this.displayName = this.getName();
        this.guessVersionFromName();
        this.readJarMetaData();
    }

    /**
     * ctor for subclasses
     */
    protected LoadableFile(LoadableFile file)
    {
        super(file.getAbsolutePath());
        this.displayName = this.getName();
        this.forceInjection = file.forceInjection;
        this.assignJarMetaData(file);
    }

    /**
     * ctor for subclasses
     */
    protected LoadableFile(String pathname)
    {
        super(pathname);
        this.displayName = this.getName();
        this.readJarMetaData();
    }

    private void guessVersionFromName()
    {
        Matcher versionPatternMatcher = LoadableFile.versionPattern.matcher(this.getName());
        while (versionPatternMatcher.find())
        {
            this.version = versionPatternMatcher.group();
        }
    }

    protected void assignJarMetaData(LoadableFile file)
    {
        this.modSystems        = file.modSystems;
        this.tweakClassName    = file.tweakClassName;
        this.classPathEntries  = file.classPathEntries;
        this.tweakPriority     = file.tweakPriority;
        this.displayName       = file.displayName;
        this.version           = file.version;
        this.author            = file.author;
        this.injectionStrategy = file.injectionStrategy;
    }

    /**
     * Search for tweaks in this file
     */
    protected void readJarMetaData()
    {
        JarFile jar = null;

        if (this.isDirectory())
        {
            return;
        }

        try
        {
            jar = new JarFile(this);
            if (jar.getManifest() != null)
            {
                LiteLoaderLogger.info("Inspecting jar metadata in '%s'", this.getName());
                Attributes mfAttributes = jar.getManifest().getMainAttributes();

                String mfAttmodSystemList     = mfAttributes.getValue(LoadableFile.MFATT_MODTYPE);
                String mfAttTweakClass        = mfAttributes.getValue(LoadableFile.MFATT_TWEAK_CLASS);
                String mfAttClassPath         = mfAttributes.getValue(LoadableFile.MFATT_CLASS_PATH);
                String mfAttTweakOrder        = mfAttributes.getValue(LoadableFile.MFATT_TWEAK_ORDER);
                String mfAttDisplayName       = mfAttributes.getValue(LoadableFile.MFATT_IMPLEMENTATION_TITLE);
                String mfAttTweakName         = mfAttributes.getValue(LoadableFile.MFATT_TWEAK_NAME);
                String mfAttVersion           = mfAttributes.getValue(LoadableFile.MFATT_IMPLEMENTATION_VERSION);
                String mfAttTweakVersion      = mfAttributes.getValue(LoadableFile.MFATT_TWEAK_VERSION);
                String mfAttAuthor            = mfAttributes.getValue(LoadableFile.MFATT_IMPLEMENTATION_VENDOR);
                String mfAttTweakAuthor       = mfAttributes.getValue(LoadableFile.MFATT_TWEAK_AUTHOR);
                String mfAttMixinConfigs      = mfAttributes.getValue(LoadableFile.MFATT_MIXIN_CONFIGS);
                String mfAttInjectionStrategy = mfAttributes.getValue(LoadableFile.MFATT_INJECTION_STRATEGY);
                
                if (mfAttmodSystemList != null)
                {
                    for (String modSystem : mfAttmodSystemList.split(","))
                    {
                        modSystem = modSystem.trim();
                        if (modSystem.length() > 0)
                        {
                            this.modSystems.add(modSystem);
                        }
                    }
                }

                this.tweakClassName = mfAttTweakClass;
                if (this.tweakClassName != null && mfAttClassPath != null)
                {
                    this.classPathEntries = mfAttClassPath.split(" ");
                }

                if (mfAttTweakOrder != null)
                {
                    Integer tweakOrder = Ints.tryParse(mfAttTweakOrder);
                    if (tweakOrder != null)
                    {
                        this.tweakPriority = tweakOrder.intValue();
                    }
                }

                if (mfAttDisplayName  != null) this.displayName = mfAttDisplayName;
                if (mfAttTweakName    != null) this.displayName = mfAttTweakName;
                if (mfAttVersion      != null) this.version     = mfAttVersion;
                if (mfAttTweakVersion != null) this.version     = mfAttTweakVersion;
                if (mfAttAuthor       != null) this.author      = mfAttAuthor;
                if (mfAttTweakAuthor  != null) this.author      = mfAttTweakAuthor;
                
                if (mfAttMixinConfigs != null)
                {
                    for (String config : mfAttMixinConfigs.split(","))
                    {
                        this.mixinConfigs.add(config);
                    }
                }

                this.injectionStrategy = InjectionStrategy.parseStrategy(mfAttInjectionStrategy, InjectionStrategy.TOP);
            }
        }
        catch (Exception ex)
        {
            LiteLoaderLogger.warning("Could not parse jar metadata in '%s'", this);
        }
        finally
        {
            try
            {
                if (jar != null) jar.close();
            }
            catch (IOException ex) {}
        }
    }

    public Set<String> getModSystems()
    {
        return Collections.unmodifiableSet(this.modSystems);
    }

    @Override
    public File getTarget()
    {
        return this;
    }

    @Override
    public File toFile()
    {
        return this;
    }

    @Override
    public String getLocation()
    {
        return this.getAbsolutePath();
    }

    @Override
    public URL getURL() throws MalformedURLException
    {
        return this.toURI().toURL();
    }

    @Override
    public String getIdentifier()
    {
        return this.getName().toLowerCase();
    }

    /* (non-Javadoc)
     * @see com.mumfrey.liteloader.core.ITweakContainer#hasTweakClass()
     */
    @Override
    public boolean hasTweakClass()
    {
        return this.tweakClassName != null;
    }

    /* (non-Javadoc)
     * @see com.mumfrey.liteloader.core.ITweakContainer#getTweakClassName()
     */
    @Override
    public String getTweakClassName()
    {
        return this.tweakClassName;
    }

    /* (non-Javadoc)
     * @see com.mumfrey.liteloader.core.TweakContainer#getTweakPriority()
     */
    @Override
    public int getTweakPriority()
    {
        return this.tweakPriority;
    }

    /* (non-Javadoc)
     * @see com.mumfrey.liteloader.core.ITweakContainer#getClassPathEntries()
     */
    @Override
    public String[] getClassPathEntries()
    {
        return this.classPathEntries;
    }

    /* (non-Javadoc)
     * @see com.mumfrey.liteloader.core.ITweakContainer#hasClassTransformers()
     */
    @Override
    public boolean hasClassTransformers()
    {
        return false;
    }

    /* (non-Javadoc)
     * @see com.mumfrey.liteloader.core.ITweakContainer
     *      #getClassTransformerClassNames()
     */
    @Override
    public List<String> getClassTransformerClassNames()
    {
        return Collections.<String>emptyList();
    }
    
    @Override
    public boolean hasMixins()
    {
        return this.mixinConfigs.size() > 0;
    }
    
    @Override
    public Set<String> getMixinConfigs()
    {
        return this.mixinConfigs;
    }
    
    @Override
    public void registerMixinError(Throwable th)
    {
        this.mixinErrors.add(th);
    }
    
    @Override
    public Collection<Throwable> getMixinErrors()
    {
        return this.mixinErrors;
    }

    @Override
    public boolean hasEventTransformers()
    {
        return this.hasEventTransformers;
    }

    public void onEventsInjected()
    {
        this.hasEventTransformers = true;
    }

    public boolean isInjectionForced()
    {
        return this.forceInjection;
    }

    public void setForceInjection(boolean forceInjection)
    {
        this.forceInjection = forceInjection;
    }
    
    @Override
    public boolean requiresPreInitInjection()
    {
        return this.hasTweakClass() || this.hasClassTransformers() || this.hasMixins();
    }

    @Override
    public boolean isInjected()
    {
        return this.injected;
    }

    @Override
    public boolean injectIntoClassPath(LaunchClassLoader classLoader, boolean injectIntoParent) throws MalformedURLException
    {
        if (!this.injected)
        {
            this.injected = true;

            boolean isOnClassPath = ClassPathUtilities.isJarOnClassPath(this, classLoader);
            if (!this.forceInjection && isOnClassPath)
            {
                LiteLoaderLogger.info("%s already exists on the classpath, skipping injection", this);
                return false;
            }

            ClassPathUtilities.injectIntoClassPath(classLoader, this.getURL(), this.getInjectionStrategy());

            if (injectIntoParent)
            {
                LiteLoaderTweaker.addURLToParentClassLoader(this.getURL());
            }

            return true;

        }

        return false;
    }

    @Override
    public InjectionStrategy getInjectionStrategy()
    {
        return this.injectionStrategy;
    }

    @Override
    public String getDisplayName()
    {
        return this.displayName != null ? this.displayName : this.getName();
    }

    @Override
    public String getVersion()
    {
        return this.version;
    }

    @Override
    public String getAuthor()
    {
        return this.author;
    }

    @Override
    public String getDescription(String key)
    {
        return "";
    }

    @Override
    public boolean isExternalJar()
    {
        return true;
    }

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

    @Override
    public boolean isEnabled(LoaderEnvironment environment)
    {
        return environment.getEnabledModsList().isEnabled(environment.getProfile(), this.getIdentifier());
    }

    @Override
    public String toString()
    {
        return this.getLocation();
    }

    /**
     * @param name
     * @param charset
     */
    public String getFileContents(String name, Charset charset)
    {
        return LoadableFile.getFileContents(this, name, charset);
    }

    /**
     * @param parent
     * @param name
     * @param charset
     */
    public static String getFileContents(File parent, String name, Charset charset)
    {
        try
        {
            if (parent.isDirectory())
            {
                File file = new File(parent, name);
                if (file.isFile())
                {
                    return Files.toString(file, charset);
                }
            }
            else
            {
                String content = null;
                ZipFile zipFile = new ZipFile(parent);
                ZipEntry zipEntry = zipFile.getEntry(name);
                if (zipEntry != null)
                {
                    try
                    {
                        content = LoadableModFile.zipEntryToString(zipFile, zipEntry);
                    }
                    catch (IOException ex) {}
                }

                zipFile.close();
                return content;
            }
        }
        catch (IOException ex)
        {
            ex.printStackTrace();
        }

        return null;
    }
}