Replace translation architecture with libjf-translate-v0

This commit is contained in:
Johannes Frohnmeyer 2022-01-29 13:53:04 +01:00
parent feaa462c0c
commit 8cc66d4081
Signed by: Johannes
GPG Key ID: E76429612C2929F4
22 changed files with 92 additions and 627 deletions

View File

@ -2,15 +2,10 @@ apply from: "https://jfmods.gitlab.io/scripts/jfmod.gradle"
dependencies {
include modImplementation("io.gitlab.jfronny.libjf:libjf-config-v0:${project.jfapi_version}")
include modImplementation("io.gitlab.jfronny.libjf:libjf-translate-v0:${project.jfapi_version}")
include("io.gitlab.jfronny.libjf:libjf-unsafe-v0:${project.jfapi_version}")
include("io.gitlab.jfronny.libjf:libjf-base:${project.jfapi_version}")
modRuntimeOnly("io.gitlab.jfronny.libjf:libjf-devutil-v0:${project.jfapi_version}")
modImplementation "com.terraformersmc:modmenu:3.0.1"
testImplementation('org.junit.jupiter:junit-jupiter:5.8.2')
}
test {
useJUnitPlatform()
}

View File

@ -1,15 +1,13 @@
# Done to increase the memory available to gradle.
org.gradle.jvmargs=-Xmx1G
# Fabric Properties
# check these on https://fabricmc.net/versions.html
# check these on https://fabricmc.net/develop/
minecraft_version=1.18.1
yarn_mappings=build.6
yarn_mappings=build.22
loader_version=0.12.12
# Mod Properties
maven_group=io.gitlab.jfronny
archives_base_name=translater
# Dependencies
jfapi_version=2.2.0
jfapi_version=2.4.0
modrinth_id=YnU8kpyc
modrinth_optional_dependencies=eueI9czw

Binary file not shown.

View File

@ -1,5 +0,0 @@
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-7.2-bin.zip
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists

234
gradlew vendored
View File

@ -1,234 +0,0 @@
#!/bin/sh
#
# Copyright © 2015-2021 the original authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
##############################################################################
#
# Gradle start up script for POSIX generated by Gradle.
#
# Important for running:
#
# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is
# noncompliant, but you have some other compliant shell such as ksh or
# bash, then to run this script, type that shell name before the whole
# command line, like:
#
# ksh Gradle
#
# Busybox and similar reduced shells will NOT work, because this script
# requires all of these POSIX shell features:
# * functions;
# * expansions «$var», «${var}», «${var:-default}», «${var+SET}»,
# «${var#prefix}», «${var%suffix}», and «$( cmd )»;
# * compound commands having a testable exit status, especially «case»;
# * various built-in commands including «command», «set», and «ulimit».
#
# Important for patching:
#
# (2) This script targets any POSIX shell, so it avoids extensions provided
# by Bash, Ksh, etc; in particular arrays are avoided.
#
# The "traditional" practice of packing multiple parameters into a
# space-separated string is a well documented source of bugs and security
# problems, so this is (mostly) avoided, by progressively accumulating
# options in "$@", and eventually passing that to Java.
#
# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS,
# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly;
# see the in-line comments for details.
#
# There are tweaks for specific operating systems such as AIX, CygWin,
# Darwin, MinGW, and NonStop.
#
# (3) This script is generated from the Groovy template
# https://github.com/gradle/gradle/blob/master/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt
# within the Gradle project.
#
# You can find Gradle at https://github.com/gradle/gradle/.
#
##############################################################################
# Attempt to set APP_HOME
# Resolve links: $0 may be a link
app_path=$0
# Need this for daisy-chained symlinks.
while
APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path
[ -h "$app_path" ]
do
ls=$( ls -ld "$app_path" )
link=${ls#*' -> '}
case $link in #(
/*) app_path=$link ;; #(
*) app_path=$APP_HOME$link ;;
esac
done
APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit
APP_NAME="Gradle"
APP_BASE_NAME=${0##*/}
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
# Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD=maximum
warn () {
echo "$*"
} >&2
die () {
echo
echo "$*"
echo
exit 1
} >&2
# OS specific support (must be 'true' or 'false').
cygwin=false
msys=false
darwin=false
nonstop=false
case "$( uname )" in #(
CYGWIN* ) cygwin=true ;; #(
Darwin* ) darwin=true ;; #(
MSYS* | MINGW* ) msys=true ;; #(
NONSTOP* ) nonstop=true ;;
esac
CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
# Determine the Java command to use to start the JVM.
if [ -n "$JAVA_HOME" ] ; then
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
# IBM's JDK on AIX uses strange locations for the executables
JAVACMD=$JAVA_HOME/jre/sh/java
else
JAVACMD=$JAVA_HOME/bin/java
fi
if [ ! -x "$JAVACMD" ] ; then
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
else
JAVACMD=java
which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
# Increase the maximum file descriptors if we can.
if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
case $MAX_FD in #(
max*)
MAX_FD=$( ulimit -H -n ) ||
warn "Could not query maximum file descriptor limit"
esac
case $MAX_FD in #(
'' | soft) :;; #(
*)
ulimit -n "$MAX_FD" ||
warn "Could not set maximum file descriptor limit to $MAX_FD"
esac
fi
# Collect all arguments for the java command, stacking in reverse order:
# * args from the command line
# * the main class name
# * -classpath
# * -D...appname settings
# * --module-path (only if needed)
# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables.
# For Cygwin or MSYS, switch paths to Windows format before running java
if "$cygwin" || "$msys" ; then
APP_HOME=$( cygpath --path --mixed "$APP_HOME" )
CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" )
JAVACMD=$( cygpath --unix "$JAVACMD" )
# Now convert the arguments - kludge to limit ourselves to /bin/sh
for arg do
if
case $arg in #(
-*) false ;; # don't mess with options #(
/?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath
[ -e "$t" ] ;; #(
*) false ;;
esac
then
arg=$( cygpath --path --ignore --mixed "$arg" )
fi
# Roll the args list around exactly as many times as the number of
# args, so each arg winds up back in the position where it started, but
# possibly modified.
#
# NB: a `for` loop captures its iteration list before it begins, so
# changing the positional parameters here affects neither the number of
# iterations, nor the values presented in `arg`.
shift # remove old arg
set -- "$@" "$arg" # push replacement arg
done
fi
# Collect all arguments for the java command;
# * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of
# shell script including quotes and variable substitutions, so put them in
# double quotes to make sure that they get re-expanded; and
# * put everything else in single quotes, so that it's not re-expanded.
set -- \
"-Dorg.gradle.appname=$APP_BASE_NAME" \
-classpath "$CLASSPATH" \
org.gradle.wrapper.GradleWrapperMain \
"$@"
# Use "xargs" to parse quoted args.
#
# With -n1 it outputs one arg per line, with the quotes and backslashes removed.
#
# In Bash we could simply go:
#
# readarray ARGS < <( xargs -n1 <<<"$var" ) &&
# set -- "${ARGS[@]}" "$@"
#
# but POSIX shell has neither arrays nor command substitution, so instead we
# post-process each arg (as a line of input to sed) to backslash-escape any
# character that might be a shell metacharacter, then use eval to reverse
# that process (while maintaining the separation between arguments), and wrap
# the whole thing up as a single "set" statement.
#
# This will of course break if any of these variables contains a newline or
# an unmatched quote.
#
eval "set -- $(
printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" |
xargs -n1 |
sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' |
tr '\n' ' '
)" '"$@"'
exec "$JAVACMD" "$@"

89
gradlew.bat vendored
View File

@ -1,89 +0,0 @@
@rem
@rem Copyright 2015 the original author or authors.
@rem
@rem Licensed under the Apache License, Version 2.0 (the "License");
@rem you may not use this file except in compliance with the License.
@rem You may obtain a copy of the License at
@rem
@rem https://www.apache.org/licenses/LICENSE-2.0
@rem
@rem Unless required by applicable law or agreed to in writing, software
@rem distributed under the License is distributed on an "AS IS" BASIS,
@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@rem See the License for the specific language governing permissions and
@rem limitations under the License.
@rem
@if "%DEBUG%" == "" @echo off
@rem ##########################################################################
@rem
@rem Gradle startup script for Windows
@rem
@rem ##########################################################################
@rem Set local scope for the variables with windows NT shell
if "%OS%"=="Windows_NT" setlocal
set DIRNAME=%~dp0
if "%DIRNAME%" == "" set DIRNAME=.
set APP_BASE_NAME=%~n0
set APP_HOME=%DIRNAME%
@rem Resolve any "." and ".." in APP_HOME to make it shorter.
for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
@rem Find java.exe
if defined JAVA_HOME goto findJavaFromJavaHome
set JAVA_EXE=java.exe
%JAVA_EXE% -version >NUL 2>&1
if "%ERRORLEVEL%" == "0" goto execute
echo.
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:findJavaFromJavaHome
set JAVA_HOME=%JAVA_HOME:"=%
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
if exist "%JAVA_EXE%" goto execute
echo.
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:execute
@rem Setup the command line
set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
@rem Execute Gradle
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %*
:end
@rem End local scope for the variables with windows NT shell
if "%ERRORLEVEL%"=="0" goto mainEnd
:fail
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
rem the _cmd.exe /c_ return code!
if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
exit /b 1
:mainEnd
if "%OS%"=="Windows_NT" endlocal
:omega

View File

@ -2,6 +2,7 @@ package io.gitlab.jfronny.translater;
import io.gitlab.jfronny.libjf.config.api.Entry;
import io.gitlab.jfronny.libjf.config.api.JfConfig;
import io.gitlab.jfronny.libjf.translate.Language;
public class Cfg implements JfConfig {
@Entry
@ -9,7 +10,7 @@ public class Cfg implements JfConfig {
@Entry
public static boolean breakFully = false;
@Entry
public static String targetLanguage = "en";
public static String targetLanguage = Language.ENGLISH.id;
@Entry
public static ProgressMode renderProgress = ProgressMode.None;
@Entry
@ -17,6 +18,7 @@ public class Cfg implements JfConfig {
public enum ProgressMode {
Full,
Gui,
Console,
None
}

View File

@ -3,11 +3,11 @@ package io.gitlab.jfronny.translater;
import io.gitlab.jfronny.translater.transformer.CachingTransformer;
import io.gitlab.jfronny.translater.transformer.TransformingMap;
import io.gitlab.jfronny.translater.transformer.TranslatingTransformer;
import io.gitlab.jfronny.translater.translation.WurstGoogleBackend;
import net.fabricmc.api.EnvType;
import net.fabricmc.api.Environment;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.Map;
@ -16,30 +16,17 @@ import java.util.Map;
public class Translater {
public static final String MOD_ID = "translater";
public static final Logger LOGGER = LogManager.getFormatterLogger(MOD_ID);
private static TransformingMap map;
private static final TransformingMap map = new TransformingMap(new CachingTransformer(new TranslatingTransformer()));
public static boolean progressUIEnabled() {
return Cfg.renderProgress == Cfg.ProgressMode.Full;
return Cfg.renderProgress == Cfg.ProgressMode.Full || Cfg.renderProgress == Cfg.ProgressMode.Gui;
}
public static boolean progressLogsEnabled() {
return Cfg.renderProgress == Cfg.ProgressMode.Full || Cfg.renderProgress == Cfg.ProgressMode.Console;
}
public static @Nullable TransformingMap getMap(@Nullable Map<String, String> base) {
if (map == null) {
if (base == null) {
LOGGER.error("Tried to mutate translations before they were accessed. This should NEVER happen!");
return null;
}
map = new TransformingMap(base,
new CachingTransformer(
new TranslatingTransformer<>(
new WurstGoogleBackend()
)
)
);
map.init();
}
public static @NotNull TransformingMap getMap(@Nullable Map<String, String> base) {
if (base != null) map.updateBacker(base);
return map;
}
}

View File

@ -15,6 +15,7 @@ public class LanguageMixin {
if (language instanceof TranslationStorage t) {
TranslationStorageAccessor ta = (TranslationStorageAccessor) t;
ta.setTranslations(Translater.getMap(ta.getTranslations()));
Translater.LOGGER.info("Set translater backend");
}
}
}

View File

@ -7,5 +7,5 @@ import org.spongepowered.asm.mixin.gen.Invoker;
@Mixin(MinecraftClient.class)
public interface MinecraftClientAccessor {
@Invoker
void render(boolean tick);
void invokeRender(boolean tick);
}

View File

@ -12,7 +12,6 @@ import java.util.Set;
public class Plugin implements IMixinConfigPlugin {
@Override
public void onLoad(String mixinPackage) {
}
@Override
@ -36,7 +35,6 @@ public class Plugin implements IMixinConfigPlugin {
@Override
public void acceptTargets(Set<String> myTargets, Set<String> otherTargets) {
}
@Override
@ -46,11 +44,9 @@ public class Plugin implements IMixinConfigPlugin {
@Override
public void preApply(String targetClassName, ClassNode targetClass, String mixinClassName, IMixinInfo mixinInfo) {
}
@Override
public void postApply(String targetClassName, ClassNode targetClass, String mixinClassName, IMixinInfo mixinInfo) {
}
}

View File

@ -22,49 +22,45 @@ import java.util.Collections;
@Mixin(SplashOverlay.class)
public abstract class SplashScreenMixin extends Overlay {
@Shadow
@Final
private MinecraftClient client;
@Shadow @Final private MinecraftClient client;
private TextRenderer translater$textRenderer;
@Inject(at = @At("RETURN"), method = "renderProgressBar")
private void renderTranslationProgress(MatrixStack matrixStack, int i, int j, int k, int l, float f, CallbackInfo ci) {
TransformingMap map = Translater.getMap(null);
if (map != null && map.initializing) {
renderer.draw(matrixStack, "Transforming " + map.initI + "/" + map.initMax, 10, 10, 0);
if (map.initializing) {
translater$textRenderer.draw(matrixStack, map.getInitProgress(), 10, 10, 0);
}
}
private TextRenderer renderer;
private static final String FONT_JSON = """
{
"type": "bitmap",
"file": "minecraft:font/ascii.png",
"ascent": 7,
"chars": [
"\\u00c0\\u00c1\\u00c2\\u00c8\\u00ca\\u00cb\\u00cd\\u00d3\\u00d4\\u00d5\\u00da\\u00df\\u00e3\\u00f5\\u011f\\u0130",
"\\u0131\\u0152\\u0153\\u015e\\u015f\\u0174\\u0175\\u017e\\u0207\\u0000\\u0000\\u0000\\u0000\\u0000\\u0000\\u0000",
"\\u0020\\u0021\\"\\u0023\\u0024\\u0025\\u0026\\u0027\\u0028\\u0029\\u002a\\u002b\\u002c\\u002d\\u002e\\u002f",
"\\u0030\\u0031\\u0032\\u0033\\u0034\\u0035\\u0036\\u0037\\u0038\\u0039\\u003a\\u003b\\u003c\\u003d\\u003e\\u003f",
"\\u0040\\u0041\\u0042\\u0043\\u0044\\u0045\\u0046\\u0047\\u0048\\u0049\\u004a\\u004b\\u004c\\u004d\\u004e\\u004f",
"\\u0050\\u0051\\u0052\\u0053\\u0054\\u0055\\u0056\\u0057\\u0058\\u0059\\u005a\\u005b\\\\\\u005d\\u005e\\u005f",
"\\u0060\\u0061\\u0062\\u0063\\u0064\\u0065\\u0066\\u0067\\u0068\\u0069\\u006a\\u006b\\u006c\\u006d\\u006e\\u006f",
"\\u0070\\u0071\\u0072\\u0073\\u0074\\u0075\\u0076\\u0077\\u0078\\u0079\\u007a\\u007b\\u007c\\u007d\\u007e\\u0000",
"\\u00c7\\u00fc\\u00e9\\u00e2\\u00e4\\u00e0\\u00e5\\u00e7\\u00ea\\u00eb\\u00e8\\u00ef\\u00ee\\u00ec\\u00c4\\u00c5",
"\\u00c9\\u00e6\\u00c6\\u00f4\\u00f6\\u00f2\\u00fb\\u00f9\\u00ff\\u00d6\\u00dc\\u00f8\\u00a3\\u00d8\\u00d7\\u0192",
"\\u00e1\\u00ed\\u00f3\\u00fa\\u00f1\\u00d1\\u00aa\\u00ba\\u00bf\\u00ae\\u00ac\\u00bd\\u00bc\\u00a1\\u00ab\\u00bb",
"\\u2591\\u2592\\u2593\\u2502\\u2524\\u2561\\u2562\\u2556\\u2555\\u2563\\u2551\\u2557\\u255d\\u255c\\u255b\\u2510",
"\\u2514\\u2534\\u252c\\u251c\\u2500\\u253c\\u255e\\u255f\\u255a\\u2554\\u2569\\u2566\\u2560\\u2550\\u256c\\u2567",
"\\u2568\\u2564\\u2565\\u2559\\u2558\\u2552\\u2553\\u256b\\u256a\\u2518\\u250c\\u2588\\u2584\\u258c\\u2590\\u2580",
"\\u03b1\\u03b2\\u0393\\u03c0\\u03a3\\u03c3\\u03bc\\u03c4\\u03a6\\u0398\\u03a9\\u03b4\\u221e\\u2205\\u2208\\u2229",
"\\u2261\\u00b1\\u2265\\u2264\\u2320\\u2321\\u00f7\\u2248\\u00b0\\u2219\\u00b7\\u221a\\u207f\\u00b2\\u25a0\\u0000"
]
}""";
@Inject(method = "<init>", at = @At("RETURN"))
public void setup(CallbackInfo ci) {
final FontStorage fontStorage_1 = new FontStorage(client.getTextureManager(), new Identifier("loading"));
fontStorage_1.setFonts(Collections.singletonList(FontType.BITMAP.createLoader(new JsonParser().parse(FONT_JSON).getAsJsonObject()).load(client.getResourceManager())));
renderer = new TextRenderer(id -> fontStorage_1);
final FontStorage fontStorage = new FontStorage(client.getTextureManager(), new Identifier("loading"));
fontStorage.setFonts(Collections.singletonList(FontType.BITMAP.createLoader(JsonParser.parseString("""
{
"type": "bitmap",
"file": "minecraft:font/ascii.png",
"ascent": 7,
"chars": [
"\\u00c0\\u00c1\\u00c2\\u00c8\\u00ca\\u00cb\\u00cd\\u00d3\\u00d4\\u00d5\\u00da\\u00df\\u00e3\\u00f5\\u011f\\u0130",
"\\u0131\\u0152\\u0153\\u015e\\u015f\\u0174\\u0175\\u017e\\u0207\\u0000\\u0000\\u0000\\u0000\\u0000\\u0000\\u0000",
"\\u0020\\u0021\\"\\u0023\\u0024\\u0025\\u0026\\u0027\\u0028\\u0029\\u002a\\u002b\\u002c\\u002d\\u002e\\u002f",
"\\u0030\\u0031\\u0032\\u0033\\u0034\\u0035\\u0036\\u0037\\u0038\\u0039\\u003a\\u003b\\u003c\\u003d\\u003e\\u003f",
"\\u0040\\u0041\\u0042\\u0043\\u0044\\u0045\\u0046\\u0047\\u0048\\u0049\\u004a\\u004b\\u004c\\u004d\\u004e\\u004f",
"\\u0050\\u0051\\u0052\\u0053\\u0054\\u0055\\u0056\\u0057\\u0058\\u0059\\u005a\\u005b\\\\\\u005d\\u005e\\u005f",
"\\u0060\\u0061\\u0062\\u0063\\u0064\\u0065\\u0066\\u0067\\u0068\\u0069\\u006a\\u006b\\u006c\\u006d\\u006e\\u006f",
"\\u0070\\u0071\\u0072\\u0073\\u0074\\u0075\\u0076\\u0077\\u0078\\u0079\\u007a\\u007b\\u007c\\u007d\\u007e\\u0000",
"\\u00c7\\u00fc\\u00e9\\u00e2\\u00e4\\u00e0\\u00e5\\u00e7\\u00ea\\u00eb\\u00e8\\u00ef\\u00ee\\u00ec\\u00c4\\u00c5",
"\\u00c9\\u00e6\\u00c6\\u00f4\\u00f6\\u00f2\\u00fb\\u00f9\\u00ff\\u00d6\\u00dc\\u00f8\\u00a3\\u00d8\\u00d7\\u0192",
"\\u00e1\\u00ed\\u00f3\\u00fa\\u00f1\\u00d1\\u00aa\\u00ba\\u00bf\\u00ae\\u00ac\\u00bd\\u00bc\\u00a1\\u00ab\\u00bb",
"\\u2591\\u2592\\u2593\\u2502\\u2524\\u2561\\u2562\\u2556\\u2555\\u2563\\u2551\\u2557\\u255d\\u255c\\u255b\\u2510",
"\\u2514\\u2534\\u252c\\u251c\\u2500\\u253c\\u255e\\u255f\\u255a\\u2554\\u2569\\u2566\\u2560\\u2550\\u256c\\u2567",
"\\u2568\\u2564\\u2565\\u2559\\u2558\\u2552\\u2553\\u256b\\u256a\\u2518\\u250c\\u2588\\u2584\\u258c\\u2590\\u2580",
"\\u03b1\\u03b2\\u0393\\u03c0\\u03a3\\u03c3\\u03bc\\u03c4\\u03a6\\u0398\\u03a9\\u03b4\\u221e\\u2205\\u2208\\u2229",
"\\u2261\\u00b1\\u2265\\u2264\\u2320\\u2321\\u00f7\\u2248\\u00b0\\u2219\\u00b7\\u221a\\u207f\\u00b2\\u25a0\\u0000"
]
}""").getAsJsonObject()).load(client.getResourceManager())));
translater$textRenderer = new TextRenderer(id -> fontStorage);
}
}

View File

@ -9,10 +9,7 @@ import java.util.Map;
@Mixin(TranslationStorage.class)
public interface TranslationStorageAccessor {
@Mutable
@Accessor("translations")
void setTranslations(Map<String, String> translations);
@Mutable @Accessor("translations") void setTranslations(Map<String, String> translations);
@Accessor("translations")
Map<String, String> getTranslations();
@Accessor("translations") Map<String, String> getTranslations();
}

View File

@ -23,8 +23,8 @@ public class CachingTransformer implements Transformer {
if (!cache.containsKey(str)) {
String transformed = transformer.transform(str);
if (transformed == null) {
Translater.LOGGER.warn("Very concerning, got null for non-null key " + str);
return null;
// The transformer failed
return str;
}
cache.put(str, transformed);
save();

View File

@ -9,32 +9,38 @@ import java.util.Map;
import java.util.Set;
public class TransformingMap implements Map<String, String> {
private final Map<String, String> backer;
private final Transformer transformer;
public boolean initializing;
public int initI;
public int initMax;
private Map<String, String> backer = null;
public boolean initializing = false;
private String initProgress = null;
public TransformingMap(Map<String, String> m, Transformer t) {
backer = m;
public TransformingMap(Transformer t) {
transformer = t;
}
public void init() {
Collection<String> strings = backer.values();
initI = 0;
initMax = strings.size();
initializing = true;
for (String value : strings) {
if (Translater.progressLogsEnabled()) {
initI++;
Translater.LOGGER.info("Transforming " + initI + "/" + initMax);
public void updateBacker(Map<String, String> backer) {
if (this.backer != backer) {
this.backer = backer;
Collection<String> strings = backer.values();
initializing = true;
final int max = strings.size();
int i = 0;
for (String value : strings) {
initProgress = "Transforming " + i++ + "/" + max;
if (Translater.progressLogsEnabled())
Translater.LOGGER.info(initProgress);
if (Translater.progressUIEnabled() && i % 10 == 0)
((MinecraftClientAccessor) MinecraftClient.getInstance()).invokeRender(false);
initProgress = null;
transformer.transform(value);
}
if (Translater.progressUIEnabled() && initI % 10 == 0)
((MinecraftClientAccessor) MinecraftClient.getInstance()).render(false);
transformer.transform(value);
initializing = false;
}
initializing = false;
}
public String getInitProgress() {
if (initProgress == null || !initializing) throw new IllegalStateException("Tried to get init progress while not initializing");
return initProgress;
}
@Override

View File

@ -1,20 +1,20 @@
package io.gitlab.jfronny.translater.transformer;
import io.gitlab.jfronny.libjf.translate.Language;
import io.gitlab.jfronny.libjf.translate.TranslateException;
import io.gitlab.jfronny.libjf.translate.TranslateService;
import io.gitlab.jfronny.translater.Cfg;
import io.gitlab.jfronny.translater.Translater;
import io.gitlab.jfronny.translater.translation.ITranslationBackend;
import org.apache.commons.lang3.StringUtils;
import java.util.List;
import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class TranslatingTransformer<T> implements Transformer {
public class TranslatingTransformer implements Transformer {
private static final Pattern SURROUNDING_SPACE_PATTERN = Pattern.compile("^(\\s*)(.*[^\\s]+)(\\s*)$");
private final Random rnd;
private final List<T> languages;
private final ITranslationBackend<T> backend;
private final Language[] languages = Language.values();
@Override
public String transform(String str) {
try {
@ -60,28 +60,28 @@ public class TranslatingTransformer<T> implements Transformer {
catch (Exception e) {
Translater.LOGGER.warn("Failed to transform: \"" + str + "\" (" + str.length() + " characters)");
Translater.LOGGER.warn("Please report this bug with the mod containing the lang file");
throw e;
return null;
}
}
private String translateMultiple(String str) {
private String translateMultiple(String str) throws TranslateException {
Matcher m = SURROUNDING_SPACE_PATTERN.matcher(str);
if (!m.find()) {
Translater.LOGGER.info("Skipping translation of \"" + str + "\"");
return str;
}
try {
T startLang = StringUtils.isAlpha(Cfg.targetLanguage) && Cfg.targetLanguage.length() == 2
? backend.parseLang(Cfg.targetLanguage)
: backend.detect(m.group(2)); // Identify target language
Language startLang = StringUtils.isAlpha(Cfg.targetLanguage) && Cfg.targetLanguage.length() == 2
? Language.byId(Cfg.targetLanguage)
: Language.AUTO_DETECT; // Identify target language
String currentState = m.group(2);
T currentLang = startLang;
Language currentLang = startLang;
for (int i = 0; i < Cfg.rounds; i++) { // Translate around
T newLang = randomLanguage();
currentState = backend.translate(currentState, newLang, Cfg.breakFully ? randomLanguage() : currentLang);
Language newLang = randomLanguage();
currentState = TranslateService.translate(currentState, Cfg.breakFully ? randomLanguage() : currentLang, newLang);
currentLang = newLang;
}
currentState = backend.translate(currentState, startLang, currentLang); // Translate to starting language
currentState = TranslateService.translate(currentState, currentLang, startLang == Language.AUTO_DETECT ? Language.ENGLISH : startLang); // Translate to starting language
currentState = m.group(1) + currentState + m.group(3); // Add back surrounding white space
Translater.LOGGER.info("Transformed: \"" + str + "\" to: \"" + currentState + "\"");
return currentState;
@ -91,13 +91,11 @@ public class TranslatingTransformer<T> implements Transformer {
}
}
private T randomLanguage() {
return languages.get(rnd.nextInt(languages.size()));
private Language randomLanguage() {
return languages[rnd.nextInt(languages.length)];
}
public TranslatingTransformer(ITranslationBackend<T> translationBackend) {
backend = translationBackend;
public TranslatingTransformer() {
rnd = new Random();
languages = backend.getLanguages();
}
}

View File

@ -1,26 +0,0 @@
package io.gitlab.jfronny.translater.translation;
import java.util.List;
//Since Yandex removed the API this will allow the mod to keep running
public class EmptyBackend implements ITranslationBackend<Object> {
@Override
public String translate(String text, Object target, Object current) {
return text;
}
@Override
public Object detect(String text) {
return "null";
}
@Override
public Object parseLang(String lang) {
return "null";
}
@Override
public List<Object> getLanguages() {
return List.of("null");
}
}

View File

@ -1,101 +0,0 @@
package io.gitlab.jfronny.translater.translation;
import io.gitlab.jfronny.translater.Translater;
import org.apache.commons.lang3.StringEscapeUtils;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class GoogleService {
private static final Pattern TRANSLATION_RESULT = Pattern.compile("class=\"result-container\">([^<]*)</div>", Pattern.MULTILINE);
public enum Language {
AUTO_DETECT("AUTO_DETECT", "auto"), ARABIC("ARABIC", "ar"), CHINESE_SIMPLIFIED("CHINESE_SIMPLIFIED", "zh-CN"),
CHINESE_TRADITIONAL("CHINESE_TRADITIONAL", "zh-TW"), ENGLISH("ENGLISH", "en"), FILIPINO("FILIPINO", "tl"),
FRENCH("FRENCH", "fr"), GERMAN("GERMAN", "de"), GREEK("GREEK", "el"), INDONESIAN("INDONESIAN", "id"),
IRISH("IRISH", "ga"), ITALIAN("ITALIAN", "it"), JAPANESE("JAPANESE", "ja"), JAVANESE("JAVANESE", "jw"),
KOREAN("KOREAN", "ko"), LATIN("LATIN", "la"), POLISH("POLISH", "pl"), PORTUGUESE("PORTUGUESE", "pt"),
RUSSIAN("RUSSIAN", "ru"), SPANISH("SPANISH", "es"), SWEDISH("SWEDISH", "sv"), THAI("THAI", "th"),
VIETNAMESE("VIETNAMESE", "vi");
public final String name;
public final String value;
Language(String name, String value) {
this.name = name;
this.value = value;
}
@Override
public String toString() {
return name;
}
}
public static String translate(String textToTranslate, String translateFrom, String translateTo) {
if (textToTranslate == null)
return null;
String pageSource = "";
try {
pageSource = getPageSource(textToTranslate, translateFrom, translateTo);
Matcher matcher = TRANSLATION_RESULT.matcher(pageSource);
if (matcher.find()) {
String match = matcher.group(1);
if (match != null && !match.isEmpty()) {
return StringEscapeUtils.unescapeHtml4(match);
}
}
Translater.LOGGER.error("Could not translate \"" + textToTranslate + "\": result page couldn't be parsed");
return null;
} catch (Exception e) {
try {
Path p = Files.createTempFile("translater-pagedump-", ".html").toAbsolutePath();
Files.writeString(p, pageSource);
Translater.LOGGER.error("Could not translate string, see dumped page at " + p, e);
} catch (IOException ioe) {
Translater.LOGGER.error("Could not translate string and the page could not be dumped", ioe);
}
return null;
}
}
private static String getPageSource(String textToTranslate, String translateFrom, String translateTo)
throws Exception {
if (textToTranslate == null)
return null;
String pageUrl = String.format("https://translate.google.com/m?hl=en&sl=%s&tl=%s&ie=UTF-8&prev=_m&q=%s",
translateFrom, translateTo, URLEncoder.encode(textToTranslate.trim(), StandardCharsets.UTF_8));
URL url = new URL(pageUrl);
HttpURLConnection connection = null;
BufferedReader bufferedReader = null;
StringBuilder pageSource = new StringBuilder();
try {
connection = (HttpURLConnection) url.openConnection();
connection.setConnectTimeout(5000);
connection.setRequestProperty("User-Agent",
"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.95 Safari/537.11");
bufferedReader = new BufferedReader(new InputStreamReader(connection.getInputStream(), StandardCharsets.UTF_8));
String line;
while ((line = bufferedReader.readLine()) != null) {
pageSource.append(line).append('\n');
}
return pageSource.toString();
} catch (Exception e) {
Translater.LOGGER.error("Could not load translation from google", e);
return null;
} finally {
if (connection != null)
connection.disconnect();
if (bufferedReader != null)
bufferedReader.close();
}
}
}

View File

@ -1,10 +0,0 @@
package io.gitlab.jfronny.translater.translation;
import java.util.List;
public interface ITranslationBackend<T> {
String translate(String text, T target, T current);
T detect(String text);
T parseLang(String lang);
List<T> getLanguages();
}

View File

@ -1,33 +0,0 @@
package io.gitlab.jfronny.translater.translation;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class WurstGoogleBackend implements ITranslationBackend<GoogleService.Language> {
@Override
public String translate(String text, GoogleService.Language target, GoogleService.Language current) {
return GoogleService.translate(text, current.value, target.value);
}
@Override
public GoogleService.Language detect(String text) {
return GoogleService.Language.AUTO_DETECT;
}
@Override
public GoogleService.Language parseLang(String lang) {
for (GoogleService.Language value : GoogleService.Language.values()) {
if (value.value.equals(lang))
return value;
}
return null;
}
@Override
public List<GoogleService.Language> getLanguages() {
List<GoogleService.Language> langs = new ArrayList<>(Arrays.asList(GoogleService.Language.values()));
langs.remove(GoogleService.Language.AUTO_DETECT);
return langs;
}
}

View File

@ -11,6 +11,7 @@
"translater.jfconfig.forceRegenerate": "Force Regenerate",
"translater.jfconfig.forceRegenerate.tooltip": "Use this if something is broken. This initiates the regeneration of the cache",
"translater.jfconfig.enum.ProgressMode.Full": "Full",
"translater.jfconfig.enum.ProgressMode.Gui": "Gui",
"translater.jfconfig.enum.ProgressMode.Console": "Console",
"translater.jfconfig.enum.ProgressMode.None": "None"
}

View File

@ -1,14 +0,0 @@
package io.gitlab.jfronny.translater;
import io.gitlab.jfronny.translater.translation.GoogleService;
import io.gitlab.jfronny.translater.translation.WurstGoogleBackend;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
public class GoogleBackendTest {
@Test
void simpleTranslate() {
WurstGoogleBackend gb = new WurstGoogleBackend();
assertEquals("Guten Morgen.", gb.translate("Good morning.", GoogleService.Language.GERMAN, GoogleService.Language.ENGLISH));
}
}