diff --git a/.github/ISSUE_TEMPLATE/000-report-bug.yml b/.github/ISSUE_TEMPLATE/000-report-bug.yml index 265c999a8..e2a6af838 100644 --- a/.github/ISSUE_TEMPLATE/000-report-bug.yml +++ b/.github/ISSUE_TEMPLATE/000-report-bug.yml @@ -77,8 +77,6 @@ body: required: true - label: "I have installed [Fugue](https://www.curseforge.com/minecraft/mc-mods/fugue) and it didn't fix my issue." required: true - - label: "I have installed [Scalar Legacy](https://www.curseforge.com/minecraft/mc-mods/scalar-legacy) and it didn't fix my issue." - required: true - label: "I have switched my Forgelin and LibrarianLib to continuous versions(check readme for more detail)." required: true - label: "I am running a test build from Cleanroom Github Actions. (Or, if I've compiled it myself I plan to fix the issue)" diff --git a/README.md b/README.md index a4c37928f..600e64a7e 100644 --- a/README.md +++ b/README.md @@ -162,7 +162,7 @@ As for Cleanroom mods, before Cleanroom 1.0.0, no binary compatibility is guaran - The official template is [CleanroomModTemplate](https://github.com/CleanroomMC/CleanroomModTemplate). A porting guide is in the [Cleanroom wiki](https://cleanroommc.com/wiki/cleanroom-mod-development/introduction) (WIP). -- Scala 3 and Kotlin 2 are both usable for mod code, through Scalar and Forgelin-Continuous. +- Scala 2.11 and Scala 3 mods run on runtimes Cleanroom provides, Kotlin 2 is usable through Forgelin-Continuous. ## Development & Build System diff --git a/module/builtin/mixinbooter/src/main/java/zone/rong/mixinbooter/package-info.java b/module/builtin/mixinbooter/src/main/java/zone/rong/mixinbooter/package-info.java index 721c1dc0a..5a3b52b02 100644 --- a/module/builtin/mixinbooter/src/main/java/zone/rong/mixinbooter/package-info.java +++ b/module/builtin/mixinbooter/src/main/java/zone/rong/mixinbooter/package-info.java @@ -1,3 +1,13 @@ +/* + * Copyright (c) 2026 CleanroomMC contributors + * + * This file is licensed under the CleanroomMC License Version 1.0. + * See the applicable LICENSE file in this directory or a parent directory + * for the full licence terms. + * + * This is visible-source software and is not open-source software. + */ + @HideFromUserdev package zone.rong.mixinbooter; diff --git a/module/cleanroom/src/main/java/com/cleanroommc/client/modlist/ModListConfig.java b/module/cleanroom/src/main/java/com/cleanroommc/client/modlist/ModListConfig.java index a3613bfb7..925d7f99a 100644 --- a/module/cleanroom/src/main/java/com/cleanroommc/client/modlist/ModListConfig.java +++ b/module/cleanroom/src/main/java/com/cleanroommc/client/modlist/ModListConfig.java @@ -30,7 +30,6 @@ public final class ModListConfig { "configanytime", "mixinbooter", "fugue", - "scalar", "kirino_ecs", "kirino_engine", "kirino_gl" diff --git a/module/cleanroom/src/main/java/com/cleanroommc/common/PatchModPresentChecker.java b/module/cleanroom/src/main/java/com/cleanroommc/common/PatchModPresentChecker.java index d10ce9a16..14e78d677 100644 --- a/module/cleanroom/src/main/java/com/cleanroommc/common/PatchModPresentChecker.java +++ b/module/cleanroom/src/main/java/com/cleanroommc/common/PatchModPresentChecker.java @@ -17,10 +17,8 @@ public final class PatchModPresentChecker { private static final String FUGUE_COREMOD_CLASS = "com.cleanroommc.fugue.common.FugueLoadingPlugin"; - private static final String SCALAR_COREMOD_CLASS = "com.cleanroommc.scalar.ScalarLoadingPlugin"; private static boolean fuguePresent; - private static boolean scalarPresent; private static boolean checkPerformed; private PatchModPresentChecker() { } @@ -28,7 +26,6 @@ private PatchModPresentChecker() { } public static void performCheck() { if (ForgeEarlyConfig.DISABLE_PATCH_MOD_CHECK) { fuguePresent = true; - scalarPresent = true; return; } @@ -38,16 +35,8 @@ public static void performCheck() { checkPerformed = true; fuguePresent = Launch.classLoader.isClassExist(FUGUE_COREMOD_CLASS); - scalarPresent = Launch.classLoader.isClassExist(SCALAR_COREMOD_CLASS); - - if (!fuguePresent || !scalarPresent) { - FMLLog.log.warn("These mods are missing:"); - if (!fuguePresent) { - FMLLog.log.warn(" Fugue is missing"); - } - if (!scalarPresent) { - FMLLog.log.warn(" Scalar is missing"); - } + if (!fuguePresent) { + FMLLog.log.warn("Fugue is missing"); } } @@ -61,25 +50,17 @@ public static boolean isNotPresent() { if (!checkPerformed) { performCheck(); } - return !fuguePresent || !scalarPresent; + return !fuguePresent; } public static String getWarningMessage() { if (!checkPerformed) { performCheck(); } - if (fuguePresent && scalarPresent) { + if (fuguePresent) { return ""; } - String missing; - if (!fuguePresent && !scalarPresent) { - missing = "Fugue and Scalar are not installed"; - } else if (!fuguePresent) { - missing = "Fugue is not installed"; - } else { - missing = "Scalar is not installed"; - } - return "WARNING\n" + missing + "\n" + "Your pack may crash without these mods.\n" + + return "WARNING\nFugue is not installed\nYour pack may crash without it.\n" + "To disable this warning, check forge_early.cfg"; } diff --git a/module/cleanroom/src/main/java/com/cleanroommc/discovery/CleanroomModDiscoverer.java b/module/cleanroom/src/main/java/com/cleanroommc/discovery/CleanroomModDiscoverer.java index 662fd4c1c..93425f64a 100644 --- a/module/cleanroom/src/main/java/com/cleanroommc/discovery/CleanroomModDiscoverer.java +++ b/module/cleanroom/src/main/java/com/cleanroommc/discovery/CleanroomModDiscoverer.java @@ -16,6 +16,10 @@ import com.cleanroommc.common.CleanroomEnvironment; import com.cleanroommc.common.ConfigAnytimeContainer; import com.cleanroommc.kirino.KirinoCommonCore; +import com.cleanroommc.language.scala.ScalaProvider; +import com.cleanroommc.language.scala.ScalaScanner; +import com.cleanroommc.language.scala.ScalaUsage; +import com.cleanroommc.language.scala.ScalarContainer; import com.cleanroommc.util.CleanroomLog; import top.outlands.foundation.boot.ActualClassLoader; import zone.rong.mixinbooter.MixinBooterModContainer; @@ -147,8 +151,11 @@ public final class CleanroomModDiscoverer extends ModDiscoverer { private static final String FERMIUM_PLUGIN = "fermiumbooter.FermiumPlugin"; private static final String FILE_DIRECTOR = "net.jan.moddirector.core.ModDirector"; private static final String FILE_DIRECTOR_TWEAKER = "net.jan.moddirector.launchwrapper.ModDirectorTweaker"; + private static final String SCALAR_PLUGIN = "com.cleanroommc.scalar.ScalarLoadingPlugin"; - private final List builtInMods = List.of(new MixinBooterModContainer(), new ConfigAnytimeContainer()); + private final List builtInMods = List.of( + new MixinBooterModContainer(), new ConfigAnytimeContainer(), new ScalarContainer() + ); private final List builtInModIds = builtInMods.stream().map(ModContainer::getModId).toList(); private final SetMultimap modIdToFiles = HashMultimap.create(); private final SetMultimap fileToModIds = LinkedHashMultimap.create(); @@ -449,6 +456,7 @@ public void discoverCoreMods(File minecraftDirectory, LaunchClassLoader classLoa if (fileDirector != null) { discoverFileDirectorMods(minecraftDirectory, classLoader); } + provideScala(); CleanroomLog.get().debug("Discovering coremods"); File containedDepsDir = new File(new File(Launch.minecraftHome, "mods"), ForgeVersion.mcVersion); @@ -584,6 +592,20 @@ private void discoverFileDirectorMods(File gameDir, LaunchClassLoader classLoade } } + private void provideScala() { + ScalaProvider.provide(discoveredFiles.values(), mod -> { + File original = mod.scala().original(); + File rewritten = normalize(mod.file()); + discoveredFiles.remove(original); + discoveredFiles.put(rewritten, mod); + for (String modId : fileToModIds.removeAll(original)) { + fileToModIds.put(rewritten, modId); + modIdToFiles.remove(modId, original); + modIdToFiles.put(modId, rewritten); + } + }); + } + private void discover(Map files) { CleanroomLog.get().info("Discovering mods"); long startTime = System.nanoTime(); @@ -600,6 +622,14 @@ private void discover(Map files) { // Merged in discovery order, so jars declaring a built-in mod id are dropped as they were when scanned one by one mods: for (DiscoveredMod mod : runScans(scans)) { + if (SCALAR_PLUGIN.equals(mod.coremod())) { + CleanroomLog.get() + .warn( + "{} is no longer needed as Cleanroom provides Scala, it will not be loaded", + mod.file().getName() + ); + continue; + } for (String modId : mod.modIds()) { if (recordMod(modId, mod.file())) { continue mods; @@ -630,7 +660,7 @@ private DiscoveredMod scan(File absolute, boolean onClasspath, byte[][] descript if (!isArchive(absolute)) { return new DiscoveredMod( absolute, null, List.of(), Map.of(), Map.of(), List.of(), ManifestAttributes.CLEANROOMMODTYPE, false, - false, false, null, null, onClasspath, Map.of(), Set.of(), List.of() + false, false, null, null, onClasspath, Map.of(), Set.of(), List.of(), ScalaUsage.NONE ); } @@ -649,6 +679,7 @@ private DiscoveredMod scan(File absolute, boolean onClasspath, byte[][] descript boolean mixinTweakerForceMod = false; boolean coreModContainsMod = false; Map accessTransformers = Map.of(); + ScalaScanner scala = new ScalaScanner(); try (JarFile jarFile = new JarFile(absolute)) { attributes = readManifestAttributes(absolute, jarFile); @@ -681,7 +712,7 @@ private DiscoveredMod scan(File absolute, boolean onClasspath, byte[][] descript } scanModAnnotations( jarFile, descriptors, modIds, modNames, modVersions, dependencies, configurationClasses, - fermiumConfigClasses + fermiumConfigClasses, scala ); } String atList = attributes == null ? null : attributes.getValue(ModAccessTransformer.FMLAT); @@ -695,7 +726,7 @@ private DiscoveredMod scan(File absolute, boolean onClasspath, byte[][] descript return new DiscoveredMod( absolute, attributes, List.copyOf(modIds), modNames, modVersions, configurationClasses, modType, hasMixinManifestAttributes, mixinTweakerForceMod, coreModContainsMod, coremod, tweaker, onClasspath, - accessTransformers, dependencies, fermiumConfigClasses + accessTransformers, dependencies, fermiumConfigClasses, scala.result() ); } @@ -1007,13 +1038,15 @@ private void parseMcmodInfo( private void scanModAnnotations( JarFile jar, byte[][] descriptors, Set modIds, Map names, Map versions, - Set dependencies, List configurationClasses, List fermiumConfigClasses) { + Set dependencies, List configurationClasses, List fermiumConfigClasses, + ScalaScanner scala) { byte[] buffer = CLASS_BUFFER.get(); var entries = jar.entries(); entryLoop: while (entries.hasMoreElements()) { JarEntry entry = entries.nextElement(); String name = entry.getName(); + scala.entry(name); if (entry.isDirectory() || !name.endsWith(".class")) { continue; } @@ -1033,6 +1066,7 @@ private void scanModAnnotations( buffer = Arrays.copyOf(buffer, length << 1); } } + scala.scan(buffer, length); if (!namesAnnotation(buffer, descriptors)) { continue; } diff --git a/module/cleanroom/src/main/java/com/cleanroommc/discovery/DiscoveredMod.java b/module/cleanroom/src/main/java/com/cleanroommc/discovery/DiscoveredMod.java index dcdd724ad..787357206 100644 --- a/module/cleanroom/src/main/java/com/cleanroommc/discovery/DiscoveredMod.java +++ b/module/cleanroom/src/main/java/com/cleanroommc/discovery/DiscoveredMod.java @@ -10,6 +10,8 @@ package com.cleanroommc.discovery; +import com.cleanroommc.language.scala.ScalaUsage; + import java.io.File; import java.util.List; import java.util.Map; @@ -32,7 +34,8 @@ public record DiscoveredMod( boolean onClasspath, Map accessTransformers, Set dependencies, - List fermiumConfigClasses) { + List fermiumConfigClasses, + ScalaUsage scala) { public DiscoveredMod { file = file.getAbsoluteFile(); @@ -45,6 +48,14 @@ public record DiscoveredMod( fermiumConfigClasses = List.copyOf(fermiumConfigClasses); } + public DiscoveredMod withRewrittenFile(File rewritten) { + return new DiscoveredMod( + rewritten, attributes, modIds, modNames, modVersions, mixinConfigurationClasses, modType, + hasMixinManifestAttributes, mixinTweakerForceMod, coreModContainsMod, coremod, tweaker, onClasspath, + accessTransformers, dependencies, fermiumConfigClasses, new ScalaUsage(scala.kind(), scala.config(), file) + ); + } + public boolean isDirectoryBased() { return file.isDirectory(); } diff --git a/module/cleanroom/src/main/java/com/cleanroommc/language/scala/PickleRemapper.java b/module/cleanroom/src/main/java/com/cleanroommc/language/scala/PickleRemapper.java new file mode 100644 index 000000000..239a37021 --- /dev/null +++ b/module/cleanroom/src/main/java/com/cleanroommc/language/scala/PickleRemapper.java @@ -0,0 +1,285 @@ +/* + * Copyright (c) 2026 CleanroomMC contributors + * + * This file is licensed under the CleanroomMC License Version 1.0. + * See the applicable LICENSE file in this directory or a parent directory + * for the full licence terms. + * + * This is visible-source software and is not open-source software. + */ + +package com.cleanroommc.language.scala; + +import org.objectweb.asm.AnnotationVisitor; +import org.objectweb.asm.ClassVisitor; +import org.objectweb.asm.Opcodes; +import org.objectweb.asm.tree.AnnotationNode; + +import java.io.ByteArrayOutputStream; +import java.nio.charset.StandardCharsets; +import java.util.Arrays; +import java.util.List; + +/** + * Moves the top-level {@code scala} package inside Scala 2 pickles to {@code scala211}. + * Pickles must agree with the rewritten bytecode and the relocated runtime. + * Mods such as ForgeMultipart read their own pickles to find methods. + */ +public final class PickleRemapper extends ClassVisitor { + + private static final String SIGNATURE = "Lscala/reflect/ScalaSignature;"; + private static final String LONG_SIGNATURE = "Lscala/reflect/ScalaLongSignature;"; + private static final byte[] SCALA = "scala".getBytes(StandardCharsets.US_ASCII); + private static final byte[] SCALA_211 = "scala211".getBytes(StandardCharsets.US_ASCII); + private static final int TERM_NAME = 1; + private static final int TYPE_NAME = 2; + private static final int EXT_REF = 9; + private static final int EXT_MOD_CLASS_REF = 10; + private static final int MAX_STRING = 65535; + + private final ClassVisitor writer; + + /** + * @param next receives everything but the signature + * @param writer receives the signature, skipping the remapper so it never rewrites the encoded string + */ + PickleRemapper(ClassVisitor next, ClassVisitor writer) { + super(Opcodes.ASM9, next); + this.writer = writer; + } + + /** + * Inverse of scalac's {@code ByteCodecs.encode}, which packs bytes into 7-bit units, + * then shifts each unit by one so that none or {@code 0x7f} is zero. + */ + public static byte[] decode(String encoded) { + byte[] bytes = new byte[encoded.length() * 7 / 8]; + int buffer = 0; + int bits = 0; + int j = 0; + for (int i = 0; i < encoded.length(); i++) { + int unit = encoded.charAt(i); + buffer |= (unit == 0 ? 0x7F : unit - 1) << bits; + bits += 7; + if (bits >= 8) { + if (j < bytes.length) { + bytes[j++] = (byte) buffer; + } + buffer >>>= 8; + bits -= 8; + } + } + return bytes; + } + + public static String encode(byte[] bytes) { + StringBuilder out = new StringBuilder((bytes.length * 8 + 6) / 7); + int buffer = 0; + int bits = 0; + for (byte b : bytes) { + buffer |= (b & 0xFF) << bits; + bits += 8; + while (bits >= 7) { + out.append(unit(buffer & 0x7F)); + buffer >>>= 7; + bits -= 7; + } + } + if (bits > 0) { + out.append(unit(buffer & 0x7F)); + } + return out.toString(); + } + + /** + * Top-level packages are external references without an owner. + * Those named {@code scala} are pointed at new {@code scala211} name entries, + * leaving the original names to any other entry that uses them. + * + * @return the relocated pickle, or null when it has no {@code scala} package + */ + public static byte[] relocate(byte[] pickle) { + Reader in = new Reader(pickle); + int major = in.nat(); + int minor = in.nat(); + int count = in.nat(); + int[] tags = new int[count]; + int[] starts = new int[count]; + int[] ends = new int[count]; + for (int i = 0; i < count; i++) { + tags[i] = pickle[in.position++]; + int length = in.nat(); + starts[i] = in.position; + in.position += length; + ends[i] = in.position; + } + + int[] relocated = new int[count]; + Arrays.fill(relocated, -1); + int[] appended = new int[2]; + int added = 0; + int termName = -1; + int typeName = -1; + for (int i = 0; i < count; i++) { + if (tags[i] != EXT_REF && tags[i] != EXT_MOD_CLASS_REF) { + continue; + } + Reader data = new Reader(pickle); + data.position = starts[i]; + int name = data.nat(); + if (data.position != ends[i] || + name >= count || + !Arrays.equals(pickle, starts[name], ends[name], SCALA, 0, SCALA.length)) { + continue; + } + if (tags[name] == TERM_NAME) { + if (termName < 0) { + termName = count + added; + appended[added++] = TERM_NAME; + } + relocated[i] = termName; + } else if (tags[name] == TYPE_NAME) { + if (typeName < 0) { + typeName = count + added; + appended[added++] = TYPE_NAME; + } + relocated[i] = typeName; + } + } + if (added == 0) { + return null; + } + + ByteArrayOutputStream out = new ByteArrayOutputStream(pickle.length + 32); + writeNat(out, major); + writeNat(out, minor); + writeNat(out, count + added); + for (int i = 0; i < count; i++) { + if (relocated[i] >= 0) { + ByteArrayOutputStream data = new ByteArrayOutputStream(4); + writeNat(data, relocated[i]); + writeEntry(out, tags[i], data.toByteArray()); + } else { + writeEntry(out, tags[i], Arrays.copyOfRange(pickle, starts[i], ends[i])); + } + } + for (int i = 0; i < added; i++) { + writeEntry(out, appended[i], SCALA_211); + } + return out.toByteArray(); + } + + private static char unit(int seven) { + return (char) (seven == 0x7F ? 0 : seven + 1); + } + + private static void writeEntry(ByteArrayOutputStream out, int tag, byte[] data) { + out.write(tag); + writeNat(out, data.length); + out.writeBytes(data); + } + + // Big-endian 7-bit groups, with the high bit set on all but the last + private static void writeNat(ByteArrayOutputStream out, int value) { + int shift = 28; + while (shift > 0 && value >>> shift == 0) { + shift -= 7; + } + for (; shift > 0; shift -= 7) { + out.write(value >>> shift & 0x7F | 0x80); + } + out.write(value & 0x7F); + } + + private static int utf8Length(String value) { + int length = 0; + for (int i = 0; i < value.length(); i++) { + length += value.charAt(i) == 0 ? 2 : 1; + } + return length; + } + + @Override + public AnnotationVisitor visitAnnotation(String descriptor, boolean visible) { + if (!SIGNATURE.equals(descriptor) && !LONG_SIGNATURE.equals(descriptor)) { + return super.visitAnnotation(descriptor, visible); + } + return new AnnotationNode(Opcodes.ASM9, descriptor) { + + @Override + public void visitEnd() { + StringBuilder encoded = new StringBuilder(); + for (int i = 1; values != null && i < values.size(); i += 2) { + if (values.get(i) instanceof List chunks) { + chunks.forEach(encoded::append); + } else { + encoded.append(values.get(i)); + } + } + byte[] pickle; + try { + pickle = relocate(decode(encoded.toString())); + } catch (IndexOutOfBoundsException e) { + // Obfuscated? + pickle = null; + } + if (pickle != null) { + write(encode(pickle), visible); + } else { + String type = SIGNATURE.equals(desc) ? "ScalaSignature;" : "ScalaLongSignature;"; + accept(writer.visitAnnotation("L" + ScalaRemapper.LEGACY_PACKAGE + "reflect/" + type, visible)); + } + } + + }; + } + + private void write(String encoded, boolean visible) { + String reflect = "L" + ScalaRemapper.LEGACY_PACKAGE + "reflect/"; + if (utf8Length(encoded) <= MAX_STRING) { + AnnotationVisitor signature = writer.visitAnnotation(reflect + "ScalaSignature;", visible); + signature.visit("bytes", encoded); + signature.visitEnd(); + return; + } + AnnotationVisitor signature = writer.visitAnnotation(reflect + "ScalaLongSignature;", visible); + AnnotationVisitor chunks = signature.visitArray("bytes"); + int start = 0; + int length = 0; + for (int i = 0; i < encoded.length(); i++) { + int size = encoded.charAt(i) == 0 ? 2 : 1; + if (length + size > MAX_STRING) { + chunks.visit(null, encoded.substring(start, i)); + start = i; + length = 0; + } + length += size; + } + chunks.visit(null, encoded.substring(start)); + chunks.visitEnd(); + signature.visitEnd(); + } + + private static final class Reader { + + private final byte[] bytes; + + private int position; + + private Reader(byte[] bytes) { + this.bytes = bytes; + } + + private int nat() { + int value = 0; + int b; + do { + b = bytes[position++]; + value = (value << 7) + (b & 0x7F); + } while ((b & 0x80) != 0); + return value; + } + + } + +} diff --git a/module/cleanroom/src/main/java/com/cleanroommc/language/scala/ScalaAdapter.java b/module/cleanroom/src/main/java/com/cleanroommc/language/scala/ScalaAdapter.java new file mode 100644 index 000000000..d3fe99f67 --- /dev/null +++ b/module/cleanroom/src/main/java/com/cleanroommc/language/scala/ScalaAdapter.java @@ -0,0 +1,125 @@ +/* + * Copyright (c) 2026 CleanroomMC contributors + * + * This file is licensed under the CleanroomMC License Version 1.0. + * See the applicable LICENSE file in this directory or a parent directory + * for the full licence terms. + * + * This is visible-source software and is not open-source software. + */ + +package com.cleanroommc.language.scala; + +import com.cleanroommc.util.CleanroomLog; + +import net.minecraftforge.fml.common.FMLModContainer; +import net.minecraftforge.fml.common.ILanguageAdapter; +import net.minecraftforge.fml.common.LoaderException; +import net.minecraftforge.fml.common.ModContainer; +import net.minecraftforge.fml.common.SidedProxy; +import net.minecraftforge.fml.relauncher.Side; + +import java.lang.reflect.Field; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; + +/** + * Forge's adapter for {@code modLanguage = "scala"}. + * Scala singletons live in a {@code Name$} class whose instance sits in {@code MODULE$} + * with their fields being set through {@code name_$eq} setters. Scala 2 and 3 share both. + */ +public final class ScalaAdapter implements ILanguageAdapter { + + @Override + public Object getNewInstance( + FMLModContainer container, Class scalaObjectClass, ClassLoader classLoader, Method factoryMarkedAnnotation + ) throws Exception { + Class objectClass = Class.forName(scalaObjectClass.getName() + "$", true, classLoader); + return objectClass.getField("MODULE$").get(null); + } + + @Override + public boolean supportsStatics() { + return false; + } + + @Override + public void setProxy(Field target, Class proxyTarget, Object proxy) throws IllegalArgumentException, + IllegalAccessException, NoSuchFieldException, SecurityException { + if (!proxyTarget.getName().endsWith("$")) { + try { + proxyTarget = Class.forName(proxyTarget.getName() + "$", true, proxyTarget.getClassLoader()); + } catch (ClassNotFoundException e) { + CleanroomLog.get() + .info( + "An error occurred trying to load a proxy into {}.{}. Did you declare your mod as 'class' instead of 'object'?", + proxyTarget.getSimpleName(), target.getName(), e + ); + return; + } + } + Object targetInstance = proxyTarget.getField("MODULE$").get(null); + String setterName = target.getName() + "_$eq"; + try { + for (Method setter : proxyTarget.getMethods()) { + Class[] parameters = setter.getParameterTypes(); + if (setterName.equals(setter.getName()) && + parameters.length == 1 && + parameters[0].isAssignableFrom(proxy.getClass())) { + setter.invoke(targetInstance, proxy); + return; + } + } + } catch (InvocationTargetException e) { + CleanroomLog.get() + .error( + "An error occurred trying to load a proxy into {}.{}", proxyTarget.getSimpleName(), + target.getName(), e + ); + throw new LoaderException(e); + } + String message = String.format( + "Failed loading proxy into %s.%s, could not find setter function. Did you declare the field with 'val' instead of 'var'?", + proxyTarget.getSimpleName(), target.getName() + ); + CleanroomLog.get().error(message); + throw new LoaderException(message); + } + + @Override + public void setInternalProxies(ModContainer mod, Side side, ClassLoader loader) { + Class proxyTarget = mod.getMod().getClass(); + if (!proxyTarget.getName().endsWith("$")) { + return; + } + for (Field target : proxyTarget.getDeclaredFields()) { + SidedProxy sidedProxy = target.getAnnotation(SidedProxy.class); + if (sidedProxy == null) { + continue; + } + String targetType = side.isClient() ? sidedProxy.clientSide() : sidedProxy.serverSide(); + try { + Object proxy = Class.forName(targetType, true, loader).getConstructor().newInstance(); + if (!target.getType().isAssignableFrom(proxy.getClass())) { + String message = String.format( + "Attempted to load a proxy type %s into %s.%s, but the types don't match", targetType, + proxyTarget.getSimpleName(), target.getName() + ); + CleanroomLog.get().error(message); + throw new LoaderException(message); + } + setProxy(target, proxyTarget, proxy); + } catch (LoaderException e) { + throw e; + } catch (Exception e) { + CleanroomLog.get() + .error( + "An error occurred trying to load a proxy into {}.{}", proxyTarget.getSimpleName(), + target.getName(), e + ); + throw new LoaderException(e); + } + } + } + +} diff --git a/module/cleanroom/src/main/java/com/cleanroommc/language/scala/ScalaProvider.java b/module/cleanroom/src/main/java/com/cleanroommc/language/scala/ScalaProvider.java new file mode 100644 index 000000000..46e93bce1 --- /dev/null +++ b/module/cleanroom/src/main/java/com/cleanroommc/language/scala/ScalaProvider.java @@ -0,0 +1,229 @@ +/* + * Copyright (c) 2026 CleanroomMC contributors + * + * This file is licensed under the CleanroomMC License Version 1.0. + * See the applicable LICENSE file in this directory or a parent directory + * for the full licence terms. + * + * This is visible-source software and is not open-source software. + */ + +package com.cleanroommc.language.scala; + +import com.cleanroommc.cleanroom.cache.Cache; +import com.cleanroommc.discovery.CleanroomModDiscoverer; +import com.cleanroommc.discovery.DiscoveredMod; +import com.cleanroommc.language.scala.ScalaUsage.Kind; +import com.cleanroommc.util.CleanroomLog; + +import com.google.common.hash.Hashing; +import com.google.common.io.Files; + +import net.minecraft.launchwrapper.Launch; + +import java.io.File; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.net.MalformedURLException; +import java.net.URI; +import java.nio.file.Path; +import java.security.cert.Certificate; +import java.util.ArrayList; +import java.util.Collection; +import java.util.HashMap; +import java.util.HashSet; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import java.util.function.Consumer; +import java.util.jar.JarEntry; +import java.util.jar.JarFile; + +/** + * Provides Scala to mods without Scala mods of their own. Scala 2.11 lives in {@code scala211}, so mods written in it + * are rewritten to match, and Scala 3 keeps {@code scala} untouched. Both runtimes and the rewritten jars are cached. + */ +public final class ScalaProvider { + + // Bump when ScalaRemapper's output changes, so cached jars are rewritten again + private static final String REMAPPER_VERSION = "1"; + private static final String CENTRAL = "https://repo1.maven.org/maven2/"; + private static final Artifact SCALA_211 = new Artifact( + "https://maven.cleanroommc.com/com/cleanroommc/scala211/1.0.0/scala211-1.0.0.jar", + "99e99f89d3a36d354e48787d22a2ee57bb6c254ac856f29d54132a9f00685490" + ); + private static final List SCALA_3 = List.of( + new Artifact( + CENTRAL + "org/scala-lang/scala-library/3.10.0/scala-library-3.10.0.jar", + "b47befb29e02bbc08a10bbd387b35cf80ff9bf04fda8fdf3dda6c8ad6895f325" + ), + new Artifact( + CENTRAL + "org/scala-lang/modules/scala-parser-combinators_3/2.5.0/scala-parser-combinators_3-2.5.0.jar", + "b0bd92c899104db8ce82b675a6bc54cfd9da80b81a6ce4c15451819dfd5b12cc" + ) + ); + private static final Artifact CONFIG = new Artifact( + CENTRAL + "com/typesafe/config/1.2.1/config-1.2.1.jar", + "c160fbd78f51a0c2375a794e435ce2112524a6871f64d0331895e9e26ee8b9ee" + ); + + private ScalaProvider() { } + + /** + * Fetches the runtimes the mods need onto the classpath and rewrites the jars that link against Scala 2.11. + * Jars already on the classpath are left alone, as they cannot be swapped. + * + * @param onRewritten receives each rewritten mod as soon as its jar is ready + */ + public static void provide(Collection mods, Consumer onRewritten) { + List swappable = new ArrayList<>(); + Set modernMods = new HashSet<>(); + boolean legacy = false; + boolean modern = false; + boolean config = false; + for (DiscoveredMod mod : mods) { + Kind kind = mod.scala().kind(); + config |= mod.scala().config(); + if (kind == Kind.MODERN) { + modern = true; + modernMods.addAll(mod.modIds()); + } + // Development puts Scala and the mods being developed on the classpath itself + if (!mod.onClasspath() && !mod.isDirectoryBased()) { + swappable.add(mod); + legacy |= kind == Kind.LEGACY; + } + } + modern &= Launch.classLoader.findResource("scala/Predef.class") == null; + config &= Launch.classLoader.findResource("com/typesafe/config/Config.class") == null; + + Map rewrites = new HashMap<>(); + for (DiscoveredMod mod : swappable) { + Kind kind = mod.scala().kind(); + // Java addons follow the mods they were written against + boolean addsOnModern = kind == Kind.LINKED && mod.dependencies().stream().anyMatch(modernMods::contains); + if (kind == Kind.SHIM || kind == Kind.LEGACY || kind == Kind.LINKED && legacy && !addsOnModern) { + rewrites.put(mod, kind != Kind.SHIM); + } + } + List runtimes = new ArrayList<>(); + if (legacy) { + runtimes.add(SCALA_211); + } + if (modern) { + runtimes.addAll(SCALA_3); + } + if (config) { + runtimes.add(CONFIG); + } + if (runtimes.isEmpty() && rewrites.isEmpty()) { + return; + } + + long start = System.nanoTime(); + Cache cache = Cache.global().namespace("scala"); + int remapped = 0; + // Rewriting is CPU bound and virtual threads share one carrier per core, so at most one jar runs per core + try (ExecutorService executor = Executors.newVirtualThreadPerTaskExecutor()) { + Map> fetched = new LinkedHashMap<>(); + runtimes.forEach(runtime -> fetched.put(runtime, runtime.fetch(cache))); + Map> rewritten = new LinkedHashMap<>(); + rewrites.forEach((mod, toLegacy) -> rewritten.put( + mod, executor.submit(() -> rewrite(cache, mod.file(), toLegacy)) + )); + for (Map.Entry> entry : fetched.entrySet()) { + File runtime; + try { + runtime = join(entry.getValue()); + } catch (RuntimeException e) { + throw new RuntimeException("Failed to fetch Scala from " + entry.getKey().url(), e); + } + Launch.classLoader.addURL(runtime.toURI().toURL()); + } + for (Map.Entry> entry : rewritten.entrySet()) { + DiscoveredMod mod = entry.getKey(); + File file; + try { + file = join(entry.getValue()); + } catch (RuntimeException e) { + CleanroomLog.get() + .error("Failed to rewrite {} for Scala, loading it as is", mod.file().getName(), e); + continue; + } + onRewritten.accept(mod.withRewrittenFile(file)); + remapped++; + } + } catch (MalformedURLException e) { + throw new RuntimeException("Failed to add Scala to the classpath", e); + } + CleanroomLog.get() + .info( + "Provided Scala in {} ms. Scala 2.11: {}, Scala 3: {}, rewritten jars: {}", + (System.nanoTime() - start) / 1_000_000L, legacy, modern, remapped + ); + } + + /** + * Rewritten jars carry no signatures, so mods expecting a fingerprint get the certificates of the original jar. + */ + public static Certificate[] certificates(Class clazz, File source) { + Certificate[] certificates = clazz.getProtectionDomain().getCodeSource().getCertificates(); + DiscoveredMod mod = CleanroomModDiscoverer.instance().discoveredMod(source); + File original = mod == null ? null : mod.scala().original(); + if (certificates != null || original == null) { + return certificates; + } + try (JarFile jar = new JarFile(original, true)) { + JarEntry entry = jar.getJarEntry(clazz.getName().replace('.', '/') + ".class"); + if (entry == null) { + return null; + } + // Certificates are only known once the entry has been read through + try (InputStream in = jar.getInputStream(entry)) { + in.transferTo(OutputStream.nullOutputStream()); + } + return entry.getCertificates(); + } catch (IOException | SecurityException e) { + CleanroomLog.get().warn("Failed to read the certificates of {}", original.getName(), e); + return null; + } + } + + private static File rewrite(Cache cache, File jar, boolean legacy) throws IOException { + String hash = Files.asByteSource(jar).hash(Hashing.sha256()).toString(); + return cache.fromBytes(() -> ScalaRemapper.remap(jar, legacy)) + .version(REMAPPER_VERSION) + .get((legacy ? "legacy/" : "shim/") + hash + "/" + jar.getName()) + .toFile(); + } + + private static T join(Future future) { + try { + return future.get(); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + throw new RuntimeException(e); + } catch (ExecutionException e) { + throw new RuntimeException(e.getCause()); + } + } + + private record Artifact(String url, String sha256) { + + private CompletableFuture fetch(Cache cache) { + return cache.fromUrl(URI.create(url)) + .expectSha256(sha256) + .getAsync(url.substring(url.lastIndexOf('/') + 1)) + .thenApply(Path::toFile); + } + + } + +} diff --git a/module/cleanroom/src/main/java/com/cleanroommc/language/scala/ScalaRemapper.java b/module/cleanroom/src/main/java/com/cleanroommc/language/scala/ScalaRemapper.java new file mode 100644 index 000000000..a68ed6bc9 --- /dev/null +++ b/module/cleanroom/src/main/java/com/cleanroommc/language/scala/ScalaRemapper.java @@ -0,0 +1,212 @@ +/* + * Copyright (c) 2026 CleanroomMC contributors + * + * This file is licensed under the CleanroomMC License Version 1.0. + * See the applicable LICENSE file in this directory or a parent directory + * for the full licence terms. + * + * This is visible-source software and is not open-source software. + */ + +package com.cleanroommc.language.scala; + +import org.objectweb.asm.ClassReader; +import org.objectweb.asm.ClassVisitor; +import org.objectweb.asm.ClassWriter; +import org.objectweb.asm.commons.ClassRemapper; +import org.objectweb.asm.commons.Remapper; + +import java.io.ByteArrayOutputStream; +import java.io.File; +import java.io.IOException; +import java.io.InputStream; +import java.util.Collections; +import java.util.Map; +import java.util.Set; +import java.util.regex.Pattern; +import java.util.zip.Deflater; +import java.util.zip.ZipEntry; +import java.util.zip.ZipFile; +import java.util.zip.ZipOutputStream; + +import static java.util.Map.entry; + +/** + * Rewrites a mod jar so it links against the relocated Scala 2.11 runtime in {@code scala211}. + * Or against Cleanroom's shims when it only imported Scala or akka by accident. + */ +public final class ScalaRemapper { + + static final String LEGACY_PACKAGE = "scala211/"; + static final String SHIM = "com/cleanroommc/language/scala/shim/"; + static final Map SHIMS = Map.ofEntries( + entry("scala/actors/threadpool/Arrays", new Shim("java/util/Arrays", null, true)), + // Tinkers' Defense declares an unused field of this type + entry("scala/reflect/internal/Trees$Modifiers", new Shim("java/lang/Object", Set.of(), true)), + entry( + "akka/japi/Pair", + new Shim( + SHIM + "Pair", + Set.of( + " (Ljava/lang/Object;Ljava/lang/Object;)V", "first ()Ljava/lang/Object;", + "second ()Ljava/lang/Object;", "apply (Ljava/lang/Object;Ljava/lang/Object;)Lakka/japi/Pair;" + ), + true + ) + ), + entry("akka/japi/Predicate", new Shim(SHIM + "Predicate", Set.of("test (Ljava/lang/Object;)Z"), true)), + entry( + "akka/japi/Function", + new Shim(SHIM + "Function", Set.of("apply (Ljava/lang/Object;)Ljava/lang/Object;"), true) + ), + entry( + "scala/util/Random", + new Shim( + SHIM + "Random", + Set.of( + " ()V", " (J)V", " (I)V", "setSeed (J)V", "nextInt ()I", "nextInt (I)I", + "nextLong ()J", "nextFloat ()F", "nextDouble ()D", "nextGaussian ()D", "nextBoolean ()Z", + "nextBytes ([B)V" + ), + false + ) + ), + entry( + "scala/Int", + new Shim(SHIM + "Statics", Set.of("MaxValue ()I", "MinValue ()I", "unbox (Ljava/lang/Object;)I"), false) + ), + entry( + "scala/Console", + new Shim( + SHIM + "Statics", + Set.of( + "println (Ljava/lang/Object;)V", "print (Ljava/lang/Object;)V", "out ()Ljava/io/PrintStream;", + "RESET ()Ljava/lang/String;" + ), + false + ) + ), + entry( + "scala/collection/concurrent/Debug", + new Shim(SHIM + "Statics", Set.of("log (Ljava/lang/Object;)Z"), false) + ), + entry( + "scala/Array", + new Shim( + SHIM + "Statics", Set.of("copy (Ljava/lang/Object;ILjava/lang/Object;II)V", "emptyIntArray ()[I"), + false + ) + ), + entry( + "scala/NotImplementedError", + new Shim(SHIM + "NotImplementedError", Set.of(" ()V", " (Ljava/lang/String;)V"), false) + ) + ); + + private static final String SCALA = "scala/"; + private static final Pattern SIGNATURE_FILE = Pattern.compile("META-INF/[^/]+\\.(SF|RSA|DSA|EC)"); + + private ScalaRemapper() { } + + /** + * @param legacy moves every other {@code scala} reference into {@code scala211}, otherwise only shims apply + * @return the rewritten jar, without signature files as the classes no longer match them + */ + public static byte[] remap(File jar, boolean legacy) throws IOException { + Remapper remapper = new JarRemapper(legacy); + ByteArrayOutputStream bytes = new ByteArrayOutputStream((int) Math.min(jar.length() * 2, Integer.MAX_VALUE)); + try (ZipFile zip = new ZipFile(jar); ZipOutputStream out = new ZipOutputStream(bytes)) { + out.setLevel(Deflater.BEST_SPEED); + for (ZipEntry entry : Collections.list(zip.entries())) { + String name = entry.getName(); + if (SIGNATURE_FILE.matcher(name).matches()) { + continue; + } + out.putNextEntry(new ZipEntry(name)); + if (!entry.isDirectory()) { + try (InputStream in = zip.getInputStream(entry)) { + byte[] content = in.readAllBytes(); + out.write(name.endsWith(".class") ? remapClass(content, remapper, legacy) : content); + } + } + out.closeEntry(); + } + } + return bytes.toByteArray(); + } + + static boolean allowsMember(String owner, String name, String descriptor) { + Set members = SHIMS.get(owner).members(); + return members == null || members.contains(name + ' ' + descriptor); + } + + private static byte[] remapClass(byte[] bytes, Remapper remapper, boolean legacy) { + if (!ScalaScanner.mentionsScala(bytes, bytes.length)) { + return bytes; + } + ClassReader reader = new ClassReader(bytes); + ClassWriter writer = new ClassWriter(reader, 0); + ClassVisitor remapping = new ClassRemapper(writer, remapper) { + + @Override + public void visitInnerClass(String name, String outerName, String innerName, int access) { + Shim shim = SHIMS.get(name); + if (shim == null || !shim.target().equals(remapper.map(name))) { + super.visitInnerClass(name, outerName, innerName, access); + } + } + + }; + reader.accept(legacy ? new PickleRemapper(remapping, writer) : remapping, 0); + return writer.toByteArray(); + } + + record Shim(String target, Set members, boolean always) { } + + private static final class JarRemapper extends Remapper { + + private final boolean legacy; + + private JarRemapper(boolean legacy) { + this.legacy = legacy; + } + + private static String relocate(String value, String prefix) { + return value.startsWith(prefix) ? "scala211" + value.substring("scala".length()) : null; + } + + @Override + public String map(String internalName) { + Shim shim = SHIMS.get(internalName); + if (shim != null && (shim.always() || !legacy)) { + return shim.target(); + } + if (legacy && internalName.startsWith(SCALA)) { + return LEGACY_PACKAGE + internalName.substring(SCALA.length()); + } + return internalName; + } + + // Class.forName targets + // Coremod descriptors + // Mixin targets + @Override + public Object mapValue(Object value) { + if (legacy && value instanceof String string) { + String relocated = relocate(string, "scala."); + if (relocated == null) { + relocated = relocate(string, SCALA); + } + if (relocated == null && string.contains("Lscala/")) { + relocated = string.replace("Lscala/", "L" + LEGACY_PACKAGE); + } + if (relocated != null) { + return relocated; + } + } + return super.mapValue(value); + } + + } + +} diff --git a/module/cleanroom/src/main/java/com/cleanroommc/language/scala/ScalaScanner.java b/module/cleanroom/src/main/java/com/cleanroommc/language/scala/ScalaScanner.java new file mode 100644 index 000000000..f3a55f34c --- /dev/null +++ b/module/cleanroom/src/main/java/com/cleanroommc/language/scala/ScalaScanner.java @@ -0,0 +1,234 @@ +/* + * Copyright (c) 2026 CleanroomMC contributors + * + * This file is licensed under the CleanroomMC License Version 1.0. + * See the applicable LICENSE file in this directory or a parent directory + * for the full licence terms. + * + * This is visible-source software and is not open-source software. + */ + +package com.cleanroommc.language.scala; + +import com.cleanroommc.language.scala.ScalaUsage.Kind; + +import org.objectweb.asm.AnnotationVisitor; +import org.objectweb.asm.ClassReader; +import org.objectweb.asm.ClassVisitor; +import org.objectweb.asm.FieldVisitor; +import org.objectweb.asm.MethodVisitor; +import org.objectweb.asm.Opcodes; +import org.objectweb.asm.TypePath; +import org.objectweb.asm.commons.ClassRemapper; +import org.objectweb.asm.commons.Remapper; + +import java.nio.charset.StandardCharsets; + +/** + * Works out how one jar uses Scala while mod discovery reads its classes. Not thread-safe, use one per jar. + */ +public final class ScalaScanner { + + private static final byte[] SCALA = "scala/".getBytes(StandardCharsets.US_ASCII); + private static final byte[] AKKA = "akka/japi/".getBytes(StandardCharsets.US_ASCII); + private static final byte[] CONFIG = "com/typesafe/config/".getBytes(StandardCharsets.US_ASCII); + private static final String SCALA_SIGNATURE = "scala/reflect/ScalaSignature"; + // Present in the 2.13 standard library, which Scala 3 builds on, and absent from 2.11 + private static final String ITERABLE_ONCE = "scala/collection/IterableOnce"; + private static final String ARRAY_SEQ = "scala/collection/immutable/ArraySeq"; + + private static final AnnotationVisitor ANNOTATION = new AnnotationVisitor(Opcodes.ASM9) { + + @Override + public AnnotationVisitor visitAnnotation(String name, String descriptor) { + return this; + } + + @Override + public AnnotationVisitor visitArray(String name) { + return this; + } + + }; + private static final FieldVisitor FIELD = new FieldVisitor(Opcodes.ASM9) { + + @Override + public AnnotationVisitor visitAnnotation(String descriptor, boolean visible) { + return ANNOTATION; + } + + }; + private static final MethodVisitor METHOD = new MethodVisitor(Opcodes.ASM9) { + + @Override + public AnnotationVisitor visitAnnotationDefault() { + return ANNOTATION; + } + + @Override + public AnnotationVisitor visitAnnotation(String descriptor, boolean visible) { + return ANNOTATION; + } + + @Override + public AnnotationVisitor visitParameterAnnotation(int parameter, String descriptor, boolean visible) { + return ANNOTATION; + } + + @Override + public AnnotationVisitor visitInsnAnnotation( + int typeRef, TypePath typePath, String descriptor, boolean visible) { + return ANNOTATION; + } + + }; + // ClassRemapper only walks what its delegate visits, so this visits everything and keeps nothing + private static final ClassVisitor EVERYTHING = new ClassVisitor(Opcodes.ASM9) { + + @Override + public AnnotationVisitor visitAnnotation(String descriptor, boolean visible) { + return ANNOTATION; + } + + @Override + public FieldVisitor visitField(int access, String name, String descriptor, String signature, Object value) { + return FIELD; + } + + @Override + public MethodVisitor visitMethod( + int access, String name, String descriptor, String signature, String[] exceptions) { + return METHOD; + } + + }; + + private final ClassVisitor visitor = new ClassRemapper(EVERYTHING, new Collector()); + + private boolean tasty; + private boolean bundled; + private boolean bundlesConfig; + private boolean signature; + private boolean modern; + private boolean linked; + private boolean shim; + private boolean config; + + /** + * @return whether the class names Scala, akka's Java API or Typesafe Config anywhere. + */ + static boolean mentionsScala(byte[] bytes, int length) { + for (int i = 0; i < length; i++) { + byte b = bytes[i]; + if (b == 's' && startsWith(bytes, length, i, SCALA) || + b == 'a' && startsWith(bytes, length, i, AKKA) || + b == 'c' && startsWith(bytes, length, i, CONFIG)) { + return true; + } + } + return false; + } + + private static boolean startsWith(byte[] bytes, int length, int offset, byte[] prefix) { + if (offset + prefix.length > length) { + return false; + } + for (int i = 1; i < prefix.length; i++) { + if (bytes[offset + i] != prefix[i]) { + return false; + } + } + return true; + } + + /** + * Called for every entry, including the shaded libraries discovery skips. + */ + public void entry(String name) { + if (name.endsWith(".tasty")) { + tasty = true; + } else if ("scala/Predef.class".equals(name)) { + bundled = true; + } else if ("com/typesafe/config/Config.class".equals(name)) { + bundlesConfig = true; + } + } + + public void scan(byte[] bytes, int length) { + if (!mentionsScala(bytes, length)) { + return; + } + try { + new ClassReader(bytes, 0, length).accept(visitor, ClassReader.SKIP_FRAMES); + } catch (RuntimeException ignored) { + // Malformed classes are reported when they are loaded, if ever + } + } + + public ScalaUsage result() { + Kind kind; + if (bundled) { + kind = Kind.BUNDLED; + } else if (tasty || modern) { + kind = Kind.MODERN; + } else if (signature) { + kind = Kind.LEGACY; + } else if (linked) { + kind = Kind.LINKED; + } else if (shim) { + kind = Kind.SHIM; + } else { + kind = Kind.NONE; + } + return new ScalaUsage(kind, config && !bundlesConfig, null); + } + + private final class Collector extends Remapper { + + @Override + public String map(String internalName) { + if (internalName.startsWith("scala/") || internalName.startsWith("akka/")) { + if (SCALA_SIGNATURE.equals(internalName)) { + signature = true; + } else if (ITERABLE_ONCE.equals(internalName) || ARRAY_SEQ.equals(internalName)) { + modern = true; + } else if (ScalaRemapper.SHIMS.containsKey(internalName)) { + shim = true; + } else { + linked = true; + } + } else if (internalName.startsWith("com/typesafe/config/")) { + config = true; + } + return internalName; + } + + @Override + public String mapMethodName(String owner, String name, String descriptor) { + checkMember(owner, name, descriptor); + return name; + } + + @Override + public String mapFieldName(String owner, String name, String descriptor) { + checkMember(owner, name, descriptor); + return name; + } + + @Override + public Object mapValue(Object value) { + if (value instanceof String string && string.contains("Lscala/")) { + linked = true; + } + return super.mapValue(value); + } + + private void checkMember(String owner, String name, String descriptor) { + if (ScalaRemapper.SHIMS.containsKey(owner) && !ScalaRemapper.allowsMember(owner, name, descriptor)) { + linked = true; + } + } + + } + +} diff --git a/module/cleanroom/src/main/java/com/cleanroommc/language/scala/ScalaUsage.java b/module/cleanroom/src/main/java/com/cleanroommc/language/scala/ScalaUsage.java new file mode 100644 index 000000000..ece4dcf8d --- /dev/null +++ b/module/cleanroom/src/main/java/com/cleanroommc/language/scala/ScalaUsage.java @@ -0,0 +1,50 @@ +/* + * Copyright (c) 2026 CleanroomMC contributors + * + * This file is licensed under the CleanroomMC License Version 1.0. + * See the applicable LICENSE file in this directory or a parent directory + * for the full licence terms. + * + * This is visible-source software and is not open-source software. + */ + +package com.cleanroommc.language.scala; + +import java.io.File; + +/** + * @param config whether the jar references Typesafe Config without bundling it, as Forge used to ship it alongside + * Scala + * @param original the jar before it was rewritten for Scala, null if it was not rewritten + */ +public record ScalaUsage(Kind kind, boolean config, File original) { + + public static final ScalaUsage NONE = new ScalaUsage(Kind.NONE, false, null); + + public enum Kind { + + NONE, + /** + * Java that imported Scala or akka by accident, fully covered by Cleanroom's shims + */ + SHIM, + /** + * Java that calls into Scala 2 mods + */ + LINKED, + /** + * Written in Scala 2.11 + */ + LEGACY, + /** + * Written in Scala 2.13 or 3. TODO: marker in CG's integration with language providers + */ + MODERN, + /** + * Ships its own Scala runtime + */ + BUNDLED + + } + +} diff --git a/module/cleanroom/src/main/java/com/cleanroommc/language/scala/ScalarContainer.java b/module/cleanroom/src/main/java/com/cleanroommc/language/scala/ScalarContainer.java new file mode 100644 index 000000000..de3e10e4b --- /dev/null +++ b/module/cleanroom/src/main/java/com/cleanroommc/language/scala/ScalarContainer.java @@ -0,0 +1,38 @@ +/* + * Copyright (c) 2026 CleanroomMC contributors + * + * This file is licensed under the CleanroomMC License Version 1.0. + * See the applicable LICENSE file in this directory or a parent directory + * for the full licence terms. + * + * This is visible-source software and is not open-source software. + */ + +package com.cleanroommc.language.scala; + +import com.google.common.eventbus.EventBus; + +import net.minecraftforge.fml.common.DummyModContainer; +import net.minecraftforge.fml.common.LoadController; +import net.minecraftforge.fml.common.ModMetadata; + +/** + * Stands in for the Scalar mod, which mods built for Scala 3 still declare as a dependency. + */ +public class ScalarContainer extends DummyModContainer { + + public ScalarContainer() { + super(new ModMetadata()); + ModMetadata meta = this.getMetadata(); + meta.modId = "scalar"; + meta.name = "Scala Language Provider"; + meta.description = "Scala 2.11 and Scala 3, provided by Cleanroom."; + meta.version = "3.10.0"; + } + + @Override + public boolean registerBus(EventBus bus, LoadController controller) { + return true; + } + +} diff --git a/module/cleanroom/src/main/java/com/cleanroommc/language/scala/shim/Function.java b/module/cleanroom/src/main/java/com/cleanroommc/language/scala/shim/Function.java new file mode 100644 index 000000000..da5879bd9 --- /dev/null +++ b/module/cleanroom/src/main/java/com/cleanroommc/language/scala/shim/Function.java @@ -0,0 +1,21 @@ +/* + * Copyright (c) 2026 CleanroomMC contributors + * + * This file is licensed under the CleanroomMC License Version 1.0. + * See the applicable LICENSE file in this directory or a parent directory + * for the full licence terms. + * + * This is visible-source software and is not open-source software. + */ + +package com.cleanroommc.language.scala.shim; + +/** + * Stands in for {@code akka.japi.Function}. + */ +@FunctionalInterface +public interface Function { + + R apply(T param) throws Exception; + +} diff --git a/module/cleanroom/src/main/java/com/cleanroommc/language/scala/shim/NotImplementedError.java b/module/cleanroom/src/main/java/com/cleanroommc/language/scala/shim/NotImplementedError.java new file mode 100644 index 000000000..736ed243e --- /dev/null +++ b/module/cleanroom/src/main/java/com/cleanroommc/language/scala/shim/NotImplementedError.java @@ -0,0 +1,26 @@ +/* + * Copyright (c) 2026 CleanroomMC contributors + * + * This file is licensed under the CleanroomMC License Version 1.0. + * See the applicable LICENSE file in this directory or a parent directory + * for the full licence terms. + * + * This is visible-source software and is not open-source software. + */ + +package com.cleanroommc.language.scala.shim; + +/** + * Stands in for {@code scala.NotImplementedError}. + */ +public class NotImplementedError extends Error { + + public NotImplementedError() { + this("an implementation is missing"); + } + + public NotImplementedError(String message) { + super(message); + } + +} diff --git a/module/cleanroom/src/main/java/com/cleanroommc/language/scala/shim/Pair.java b/module/cleanroom/src/main/java/com/cleanroommc/language/scala/shim/Pair.java new file mode 100644 index 000000000..462d41493 --- /dev/null +++ b/module/cleanroom/src/main/java/com/cleanroommc/language/scala/shim/Pair.java @@ -0,0 +1,22 @@ +/* + * Copyright (c) 2026 CleanroomMC contributors + * + * This file is licensed under the CleanroomMC License Version 1.0. + * See the applicable LICENSE file in this directory or a parent directory + * for the full licence terms. + * + * This is visible-source software and is not open-source software. + */ + +package com.cleanroommc.language.scala.shim; + +/** + * Stands in for {@code akka.japi.Pair}. + */ +public record Pair(A first, B second) { + + public static Pair apply(A first, B second) { + return new Pair<>(first, second); + } + +} diff --git a/module/cleanroom/src/main/java/com/cleanroommc/language/scala/shim/Predicate.java b/module/cleanroom/src/main/java/com/cleanroommc/language/scala/shim/Predicate.java new file mode 100644 index 000000000..37c17bdac --- /dev/null +++ b/module/cleanroom/src/main/java/com/cleanroommc/language/scala/shim/Predicate.java @@ -0,0 +1,21 @@ +/* + * Copyright (c) 2026 CleanroomMC contributors + * + * This file is licensed under the CleanroomMC License Version 1.0. + * See the applicable LICENSE file in this directory or a parent directory + * for the full licence terms. + * + * This is visible-source software and is not open-source software. + */ + +package com.cleanroommc.language.scala.shim; + +/** + * Stands in for {@code akka.japi.Predicate}. + */ +@FunctionalInterface +public interface Predicate { + + boolean test(T param); + +} diff --git a/module/cleanroom/src/main/java/com/cleanroommc/language/scala/shim/Random.java b/module/cleanroom/src/main/java/com/cleanroommc/language/scala/shim/Random.java new file mode 100644 index 000000000..98e777088 --- /dev/null +++ b/module/cleanroom/src/main/java/com/cleanroommc/language/scala/shim/Random.java @@ -0,0 +1,28 @@ +/* + * Copyright (c) 2026 CleanroomMC contributors + * + * This file is licensed under the CleanroomMC License Version 1.0. + * See the applicable LICENSE file in this directory or a parent directory + * for the full licence terms. + * + * This is visible-source software and is not open-source software. + */ + +package com.cleanroommc.language.scala.shim; + +/** + * Stands in for {@code scala.util.Random}, which wraps the JDK's with the same methods. + */ +public class Random extends java.util.Random { + + public Random() { } + + public Random(long seed) { + super(seed); + } + + public Random(int seed) { + super(seed); + } + +} diff --git a/module/cleanroom/src/main/java/com/cleanroommc/language/scala/shim/Statics.java b/module/cleanroom/src/main/java/com/cleanroommc/language/scala/shim/Statics.java new file mode 100644 index 000000000..e9288b6e0 --- /dev/null +++ b/module/cleanroom/src/main/java/com/cleanroommc/language/scala/shim/Statics.java @@ -0,0 +1,66 @@ +/* + * Copyright (c) 2026 CleanroomMC contributors + * + * This file is licensed under the CleanroomMC License Version 1.0. + * See the applicable LICENSE file in this directory or a parent directory + * for the full licence terms. + * + * This is visible-source software and is not open-source software. + */ + +package com.cleanroommc.language.scala.shim; + +import java.io.PrintStream; + +/** + * Stands in for the static forwarders of {@code scala.Int}, {@code scala.Console}, {@code scala.Array} and + * {@code scala.collection.concurrent.Debug}. The names match the forwarders, so only the owner is remapped. + */ +// CHECKSTYLE:OFF +public final class Statics { + + private Statics() { } + + public static int MaxValue() { + return Integer.MAX_VALUE; + } + + public static int MinValue() { + return Integer.MIN_VALUE; + } + + public static int unbox(Object value) { + return (Integer) value; + } + + public static void println(Object value) { + System.out.println(value); + } + + public static void print(Object value) { + System.out.print(value); + } + + public static PrintStream out() { + return System.out; + } + + public static String RESET() { + return "\u001b[0m"; + } + + public static boolean log(Object value) { + return true; + } + + public static void copy( + Object source, int sourcePosition, Object destination, int destinationPosition, int length) { + System.arraycopy(source, sourcePosition, destination, destinationPosition, length); + } + + public static int[] emptyIntArray() { + return new int[0]; + } + +} +// CHECKSTYLE:ON diff --git a/module/cleanroom/src/main/java/com/cleanroommc/language/scala/shim/package-info.java b/module/cleanroom/src/main/java/com/cleanroommc/language/scala/shim/package-info.java new file mode 100644 index 000000000..cf255d08b --- /dev/null +++ b/module/cleanroom/src/main/java/com/cleanroommc/language/scala/shim/package-info.java @@ -0,0 +1,13 @@ +/* + * Copyright (c) 2026 CleanroomMC contributors + * + * This file is licensed under the CleanroomMC License Version 1.0. + * See the applicable LICENSE file in this directory or a parent directory + * for the full licence terms. + * + * This is visible-source software and is not open-source software. + */ + +@HideFromUserdev package com.cleanroommc.language.scala.shim; + +import com.cleanroommc.hidefromuserdev.HideFromUserdev; diff --git a/module/cleanroom/src/main/java/com/cleanroommc/loader/LanguageAdapterRegistry.java b/module/cleanroom/src/main/java/com/cleanroommc/loader/LanguageAdapterRegistry.java index 771dfd1a0..53e226c08 100644 --- a/module/cleanroom/src/main/java/com/cleanroommc/loader/LanguageAdapterRegistry.java +++ b/module/cleanroom/src/main/java/com/cleanroommc/loader/LanguageAdapterRegistry.java @@ -10,6 +10,8 @@ package com.cleanroommc.loader; +import com.cleanroommc.language.scala.ScalaAdapter; + import com.google.common.collect.Maps; import net.minecraftforge.fml.common.FMLLog; @@ -23,6 +25,7 @@ public final class LanguageAdapterRegistry { static { registerLanguageAdapter("java", new ILanguageAdapter.JavaAdapter()); + registerLanguageAdapter("scala", new ScalaAdapter()); } private LanguageAdapterRegistry() { } diff --git a/module/cleanroom/src/test/java/com/cleanroommc/test/scala/ScalaRemapperTest.java b/module/cleanroom/src/test/java/com/cleanroommc/test/scala/ScalaRemapperTest.java new file mode 100644 index 000000000..efe570754 --- /dev/null +++ b/module/cleanroom/src/test/java/com/cleanroommc/test/scala/ScalaRemapperTest.java @@ -0,0 +1,271 @@ +/* + * Copyright (c) 2026 CleanroomMC contributors + * + * This file is licensed under the CleanroomMC License Version 1.0. + * See the applicable LICENSE file in this directory or a parent directory + * for the full licence terms. + * + * This is visible-source software and is not open-source software. + */ + +package com.cleanroommc.test.scala; + +import com.cleanroommc.language.scala.PickleRemapper; +import com.cleanroommc.language.scala.ScalaRemapper; +import com.cleanroommc.language.scala.ScalaScanner; +import com.cleanroommc.language.scala.ScalaUsage.Kind; + +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; + +import org.objectweb.asm.AnnotationVisitor; +import org.objectweb.asm.ClassReader; +import org.objectweb.asm.ClassVisitor; +import org.objectweb.asm.ClassWriter; +import org.objectweb.asm.MethodVisitor; +import org.objectweb.asm.Opcodes; +import org.objectweb.asm.commons.ClassRemapper; +import org.objectweb.asm.commons.Remapper; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.File; +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.TreeSet; +import java.util.function.Consumer; +import java.util.zip.ZipEntry; +import java.util.zip.ZipInputStream; +import java.util.zip.ZipOutputStream; + +import static org.assertj.core.api.Assertions.assertThat; + +public class ScalaRemapperTest { + + @TempDir Path dir; + + private static byte[] type(Consumer body, String annotation) { + ClassWriter writer = new ClassWriter(ClassWriter.COMPUTE_MAXS); + writer.visit(Opcodes.V1_8, Opcodes.ACC_PUBLIC, "test/Mod", null, "java/lang/Object", null); + if (annotation != null) { + writer.visitAnnotation(annotation, true).visitEnd(); + } + MethodVisitor method = writer.visitMethod(Opcodes.ACC_PUBLIC | Opcodes.ACC_STATIC, "run", "()V", null, null); + method.visitCode(); + body.accept(method); + method.visitInsn(Opcodes.RETURN); + method.visitMaxs(0, 0); + method.visitEnd(); + writer.visitEnd(); + return writer.toByteArray(); + } + + private static void pair(MethodVisitor method) { + method.visitInsn(Opcodes.ACONST_NULL); + method.visitInsn(Opcodes.ACONST_NULL); + method.visitMethodInsn( + Opcodes.INVOKESTATIC, "akka/japi/Pair", "apply", "(Ljava/lang/Object;Ljava/lang/Object;)Lakka/japi/Pair;", + false + ); + method.visitInsn(Opcodes.POP); + } + + private static void random(MethodVisitor method, String name) { + method.visitTypeInsn(Opcodes.NEW, "scala/util/Random"); + method.visitInsn(Opcodes.DUP); + method.visitMethodInsn(Opcodes.INVOKESPECIAL, "scala/util/Random", "", "()V", false); + method.visitMethodInsn(Opcodes.INVOKEVIRTUAL, "scala/util/Random", name, "()I", false); + method.visitInsn(Opcodes.POP); + } + + private static void modifiers(MethodVisitor method) { + method.visitFieldInsn(Opcodes.GETSTATIC, "test/Mod", "mods", "Lscala/reflect/internal/Trees$Modifiers;"); + method.visitInsn(Opcodes.POP); + } + + private static void legacy(MethodVisitor method) { + pair(method); + modifiers(method); + method.visitFieldInsn(Opcodes.GETSTATIC, "scala/Predef$", "MODULE$", "Lscala/Predef$;"); + method.visitInsn(Opcodes.POP); + method.visitLdcInsn("scala.Option"); + method.visitInsn(Opcodes.POP); + method.visitLdcInsn("(Lscala/Option;)V"); + method.visitInsn(Opcodes.POP); + random(method, "nextInt"); + } + + private static Kind kind(byte[] bytes) { + ScalaScanner scanner = new ScalaScanner(); + scanner.entry("test/Mod.class"); + scanner.scan(bytes, bytes.length); + return scanner.result().kind(); + } + + private static byte[] bytes(Object... parts) { + ByteArrayOutputStream out = new ByteArrayOutputStream(); + for (Object part : parts) { + if (part instanceof String string) { + out.writeBytes(string.getBytes(StandardCharsets.US_ASCII)); + } else { + out.write((Integer) part); + } + } + return out.toByteArray(); + } + + @Test + public void classifies() { + assertThat(kind(type(_ -> { }, null))).isEqualTo(Kind.NONE); + assertThat(kind(type( + method -> { + pair(method); + random(method, "nextInt"); + }, + null + ))).isEqualTo(Kind.SHIM); + assertThat(kind(type(ScalaRemapperTest::modifiers, null))).isEqualTo(Kind.SHIM); + assertThat(kind(type(method -> random(method, "nextPrintableChar"), null))).isEqualTo(Kind.LINKED); + assertThat(kind(type(method -> method.visitLdcInsn("(Lscala/Option;)V"), null))).isEqualTo(Kind.LINKED); + assertThat(kind(type(ScalaRemapperTest::legacy, "Lscala/reflect/ScalaSignature;"))).isEqualTo(Kind.LEGACY); + assertThat(kind(type( + method -> method.visitTypeInsn(Opcodes.CHECKCAST, "scala/collection/IterableOnce"), + "Lscala/reflect/ScalaSignature;" + ))).isEqualTo(Kind.MODERN); + } + + @Test + public void remapsLegacy() throws IOException { + ClassWriter writer = new ClassWriter(0); + new ClassReader(type(ScalaRemapperTest::legacy, "Lscala/reflect/ScalaSignature;")).accept( + new ClassVisitor(Opcodes.ASM9, writer) { + + @Override + public void visitEnd() { + visitInnerClass( + "scala/reflect/internal/Trees$Modifiers", "scala/reflect/internal/Trees", "Modifiers", + Opcodes.ACC_PUBLIC + ); + super.visitEnd(); + } + + }, + 0 + ); + Remapped remapped = remap(writer.toByteArray(), true); + assertThat(remapped.names) + .noneMatch(name -> name.startsWith("scala/") || name.startsWith("akka/")) + .doesNotContain("scala211/reflect/internal/Trees") + .contains("scala211/Predef$", "scala211/util/Random", "com/cleanroommc/language/scala/shim/Pair"); + assertThat(remapped.strings).containsExactlyInAnyOrder("scala211.Option", "(Lscala211/Option;)V"); + assertThat(remapped.entries).containsExactly("test/Mod.class"); + } + + @Test + public void remapsShims() throws IOException { + Remapped remapped = remap( + type( + method -> { + pair(method); + random(method, "nextInt"); + }, + null + ), + false + ); + assertThat(remapped.names) + .noneMatch(name -> name.startsWith("scala/") || name.startsWith("akka/")) + .contains("com/cleanroommc/language/scala/shim/Pair", "com/cleanroommc/language/scala/shim/Random"); + } + + @Test + public void relocatesPickles() throws IOException { + byte[] pickle = bytes(5, 0, 4, 1, 5, "scala", 10, 1, 0, 2, 7, "Boolean", 9, 2, 2, 1); + assertThat(PickleRemapper.decode(PickleRemapper.encode(pickle))).isEqualTo(pickle); + + ClassWriter writer = new ClassWriter(0); + writer.visit(Opcodes.V1_8, Opcodes.ACC_PUBLIC, "test/Mod", null, "java/lang/Object", null); + AnnotationVisitor signature = writer.visitAnnotation("Lscala/reflect/ScalaSignature;", true); + signature.visit("bytes", PickleRemapper.encode(pickle)); + signature.visitEnd(); + writer.visitEnd(); + + Map signatures = new HashMap<>(); + new ClassReader(remap(writer.toByteArray(), true).classes.getFirst()).accept( + new ClassVisitor(Opcodes.ASM9) { + + @Override + public AnnotationVisitor visitAnnotation(String descriptor, boolean visible) { + return new AnnotationVisitor(Opcodes.ASM9) { + + @Override + public void visit(String name, Object value) { + signatures.put(descriptor, (String) value); + } + + }; + } + + }, + 0 + ); + assertThat(signatures).containsOnlyKeys("Lscala211/reflect/ScalaSignature;"); + assertThat(PickleRemapper.decode(signatures.get("Lscala211/reflect/ScalaSignature;"))).isEqualTo(bytes( + 5, 0, 5, 1, 5, "scala", 10, 1, 4, 2, 7, "Boolean", 9, 2, 2, 1, 1, 8, "scala211" + )); + } + + private Remapped remap(byte[] bytes, boolean legacy) throws IOException { + File jar = this.dir.resolve("mod.jar").toFile(); + try (ZipOutputStream out = new ZipOutputStream(Files.newOutputStream(jar.toPath()))) { + out.putNextEntry(new ZipEntry("test/Mod.class")); + out.write(bytes); + out.putNextEntry(new ZipEntry("META-INF/MOD.SF")); + out.putNextEntry(new ZipEntry("META-INF/MOD.RSA")); + } + Remapped remapped = new Remapped(new TreeSet<>(), new ArrayList<>(), new ArrayList<>(), new ArrayList<>()); + try (ZipInputStream in = new ZipInputStream(new ByteArrayInputStream(ScalaRemapper.remap(jar, legacy)))) { + for (ZipEntry entry; (entry = in.getNextEntry()) != null;) { + remapped.entries.add(entry.getName()); + if (entry.getName().endsWith(".class")) { + remapped.collect(in.readAllBytes()); + } + } + } + return remapped; + } + + private record Remapped(Set names, List strings, List entries, List classes) { + + private void collect(byte[] bytes) { + classes.add(bytes); + Remapper collector = new Remapper() { + + @Override + public String map(String internalName) { + names.add(internalName); + return internalName; + } + + @Override + public Object mapValue(Object value) { + if (value instanceof String string) { + strings.add(string); + } + return super.mapValue(value); + } + + }; + new ClassReader(bytes).accept(new ClassRemapper(new ClassWriter(0), collector), 0); + } + + } + +} diff --git a/module/forge/src/main/java/net/minecraftforge/common/ForgeEarlyConfig.java b/module/forge/src/main/java/net/minecraftforge/common/ForgeEarlyConfig.java index ddd48cf88..a236c52c4 100644 --- a/module/forge/src/main/java/net/minecraftforge/common/ForgeEarlyConfig.java +++ b/module/forge/src/main/java/net/minecraftforge/common/ForgeEarlyConfig.java @@ -25,10 +25,9 @@ public class ForgeEarlyConfig { public static boolean OPENGL_DEBUG_CONTEXT = false; @Config.Comment({ - "Disable the Fugue/Scalar coremod presence check at startup.", + "Disable the Fugue coremod presence check at startup.", "When enabled, the patch mod check is skipped and always returns true.", - "When disabled, checks whether Fugue (https://www.curseforge.com/minecraft/mc-mods/fugue)", - "and Scalar (https://www.curseforge.com/minecraft/mc-mods/scalar-legacy) are present.", + "When disabled, checks whether Fugue (https://www.curseforge.com/minecraft/mc-mods/fugue) is present.", "Only disable this if you know what you are doing!" }) public static boolean DISABLE_PATCH_MOD_CHECK = false; diff --git a/module/forge/src/main/java/net/minecraftforge/fml/client/config/GuiButtonExt.java b/module/forge/src/main/java/net/minecraftforge/fml/client/config/GuiButtonExt.java index f07b8d648..0680b08b4 100644 --- a/module/forge/src/main/java/net/minecraftforge/fml/client/config/GuiButtonExt.java +++ b/module/forge/src/main/java/net/minecraftforge/fml/client/config/GuiButtonExt.java @@ -20,13 +20,18 @@ package net.minecraftforge.fml.client.config; import net.minecraft.client.Minecraft; +import net.minecraft.client.gui.FontRenderer; import net.minecraft.client.gui.GuiButton; +import net.minecraft.client.gui.ScaledResolution; + +import org.lwjgl.opengl.GL11; /** * This class provides a button that fixes several bugs present in the vanilla GuiButton drawing code. * The gist of it is that it allows buttons of any size without gaps in the graphics and with the * borders drawn properly. It also prevents button text from extending out of the sides of the button by - * trimming the end of the string and adding an ellipsis.

+ * trimming the end of the string and adding an ellipsis. While hovered, overflowing text scrolls + * smoothly so the full label can be read.

* * The code that handles drawing the button is in GuiUtils. * @@ -34,6 +39,16 @@ */ public class GuiButtonExt extends GuiButton { + /** Wait before scrolling starts and at each end of the scroll, in ms. */ + private static final long PAUSE_MS = 1000; + /** Scroll speed in GUI pixels per second. */ + private static final float SCROLL_SPEED = 30F; + /** Horizontal padding between the button edge and the text. */ + private static final int PADDING = 3; + + /** When the current hover started, or -1 if not hovering. */ + private long hoverStart = -1; + public GuiButtonExt(int id, int xPos, int yPos, String displayString) { super(id, xPos, yPos, displayString); @@ -71,14 +86,77 @@ else if (this.hovered) color = 16777120; } - String buttonText = this.displayString; - int strWidth = mc.fontRenderer.getStringWidth(buttonText); - int ellipsisWidth = mc.fontRenderer.getStringWidth("..."); + FontRenderer font = mc.fontRenderer; + String text = this.displayString; + int maxWidth = this.width - PADDING * 2; + int strWidth = font.getStringWidth(text); + int textY = this.y + (this.height - 8) / 2; + + if (k == 2) + { + if (hoverStart < 0) + hoverStart = System.currentTimeMillis(); + } + else + { + hoverStart = -1; + } + + if (strWidth <= maxWidth) + { + this.drawCenteredString(font, text, this.x + this.width / 2, textY, color); + return; + } + + float offset = hoverStart < 0 ? 0F : getScrollOffset(System.currentTimeMillis() - hoverStart, strWidth - maxWidth); - if (strWidth > width - 6 && strWidth > ellipsisWidth) - buttonText = mc.fontRenderer.trimStringToWidth(buttonText, width - 6 - ellipsisWidth).trim() + "..."; + if (offset <= 0F) + { + int ellipsisWidth = font.getStringWidth("..."); + String trimmed = font.trimStringToWidth(text, maxWidth - ellipsisWidth).trim() + "..."; + this.drawCenteredString(font, trimmed, this.x + this.width / 2, textY, color); + } + else + { + int f = new ScaledResolution(mc).getScaleFactor(); - this.drawCenteredString(mc.fontRenderer, buttonText, this.x + this.width / 2, this.y + (this.height - 8) / 2, color); + int x = (this.x + PADDING) * f; + int y = mc.displayHeight - (this.y * f + this.height * f); + int w = Math.max(0, maxWidth * f); + int h = Math.max(0, this.height * f); + + GL11.glEnable(GL11.GL_SCISSOR_TEST); + GL11.glScissor(x, y, w, h); + font.drawStringWithShadow(text, this.x + PADDING - offset, textY, color); + GL11.glDisable(GL11.GL_SCISSOR_TEST); + } } } + + /** + * Ping-pong scroll: wait -> forward -> wait -> backward -> repeat. Stateless, so it is + * frame-rate independent and cannot go out of range if the text changes. + * + * @param elapsed ms since the hover started + * @param distance how many pixels the text overflows by + * @return the offset in pixels, 0..distance + */ + private static float getScrollOffset(long elapsed, int distance) + { + if (elapsed < PAUSE_MS) + return 0F; + + long travel = (long) (distance / SCROLL_SPEED * 1000F); + long t = (elapsed - PAUSE_MS) % (2 * (travel + PAUSE_MS)); + + if (t < travel) + return distance * (t / (float) travel); + t -= travel; + if (t < PAUSE_MS) + return distance; + t -= PAUSE_MS; + if (t < travel) + return distance * (1F - t / (float) travel); + return 0F; + } } diff --git a/module/forge/src/main/java/net/minecraftforge/fml/common/FMLModContainer.java b/module/forge/src/main/java/net/minecraftforge/fml/common/FMLModContainer.java index c36633a65..ac74be06b 100644 --- a/module/forge/src/main/java/net/minecraftforge/fml/common/FMLModContainer.java +++ b/module/forge/src/main/java/net/minecraftforge/fml/common/FMLModContainer.java @@ -37,6 +37,7 @@ import java.util.Properties; import java.util.Set; +import com.cleanroommc.language.scala.ScalaProvider; import com.cleanroommc.loader.LanguageAdapterRegistry; import net.minecraftforge.common.MinecraftForge; import net.minecraftforge.common.config.Config; @@ -560,7 +561,7 @@ public void constructMod(FMLConstructionEvent event) throw new LoaderException(message.getFormattedMessage(), e); } - Certificate[] certificates = clazz.getProtectionDomain().getCodeSource().getCertificates(); + Certificate[] certificates = ScalaProvider.certificates(clazz, source); ImmutableList certList = CertificateHelper.getFingerprints(certificates); sourceFingerprints = ImmutableSet.copyOf(certList); diff --git a/module/forge/src/main/java/net/minecraftforge/fml/relauncher/FMLLaunchHandler.java b/module/forge/src/main/java/net/minecraftforge/fml/relauncher/FMLLaunchHandler.java index 6aaa28341..81a19b4ba 100644 --- a/module/forge/src/main/java/net/minecraftforge/fml/relauncher/FMLLaunchHandler.java +++ b/module/forge/src/main/java/net/minecraftforge/fml/relauncher/FMLLaunchHandler.java @@ -86,6 +86,7 @@ private FMLLaunchHandler(LaunchClassLoader launchLoader, FMLTweaker tweaker) this.classLoader.addTransformerExclusion("net.minecraftforge.fml.repackage."); this.classLoader.addTransformerExclusion("LZMA."); this.classLoader.addTransformerExclusion("scala."); + this.classLoader.addTransformerExclusion("scala211."); this.classLoader.addTransformerExclusion("it.unimi.dsi."); this.classLoader.addTransformerExclusion("oshi."); }