From ad44f40f376bd754229e9b32b0b2323a29a8f037 Mon Sep 17 00:00:00 2001 From: Ashhhleyyy Date: Tue, 7 Jan 2025 22:48:02 +0000 Subject: [PATCH] chore: reformat code --- .github/workflows/build.yml | 17 +-- .github/workflows/release.yml | 32 +++--- README.md | 42 +++++-- settings.gradle.kts | 34 +++--- .../api/ExtraPronounProvider.java | 3 + .../playerpronouns/api/Pronoun.java | 60 +++++----- .../playerpronouns/api/Pronouns.java | 7 +- .../playerpronouns/api/PronounsApi.java | 15 +-- .../playerpronouns/impl/Config.java | 33 +++--- .../playerpronouns/impl/PlayerPronouns.java | 21 ++-- .../impl/command/PronounsArgument.java | 6 +- .../impl/command/PronounsCommand.java | 77 +++++++------ .../impl/data/BinaryPronounDatabase.java | 59 +++++----- .../impl/data/PalettePronounDatabase.java | 105 +++++++++--------- .../impl/data/PronounDatabase.java | 13 ++- .../playerpronouns/impl/data/PronounList.java | 79 +++++++------ .../impl/interop/PronounDbClient.java | 52 ++++----- 17 files changed, 342 insertions(+), 313 deletions(-) diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 1af0979..3acb715 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -1,26 +1,29 @@ name: Build -on: [pull_request, push] +on: [ pull_request, push ] jobs: build: runs-on: ubuntu-latest steps: - name: Checkout code - uses: actions/checkout@v2 + uses: actions/checkout@v4 - name: Validate gradle wrapper uses: gradle/wrapper-validation-action@v1 - name: Setup JDK 21 - uses: actions/setup-java@v1 + uses: actions/setup-java@v4 with: java-version: 21 + distribution: temurin + - name: Setup Gradle + uses: gradle/actions/setup-gradle@v4 - name: Ensure gradlew is executable run: chmod +x ./gradlew + - name: Build with gradle - uses: gradle/gradle-build-action@v2 - with: - arguments: build + run: ./gradlew build + - name: Upload build artifacts - uses: actions/upload-artifact@v2 + uses: actions/upload-artifact@v4 with: name: Artifacts path: build/libs/ diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 308d353..db3636d 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -10,28 +10,22 @@ jobs: runs-on: ubuntu-latest steps: - - uses: actions/cache@v2 - with: - path: | - ~/.gradle/loom-cache - ~/.gradle/caches - ~/.gradle/wrapper - key: gradle-${{ hashFiles('**/*.gradle*', '**/gradle-wrapper.properties') }} - restore-keys: | - gradle- - - uses: actions/checkout@v2 - - name: Set up JDK - uses: actions/setup-java@v1 + - name: Checkout code + uses: actions/checkout@v4 + - name: Validate gradle wrapper + uses: gradle/wrapper-validation-action@v1 + - name: Setup JDK 21 + uses: actions/setup-java@v4 with: java-version: 21 - - - name: Grant execute permission for gradlew - run: chmod +x gradlew + distribution: temurin + - name: Setup Gradle + uses: gradle/actions/setup-gradle@v4 + - name: Ensure gradlew is executable + run: chmod +x ./gradlew - name: Build and publish with gradle - uses: gradle/gradle-build-action@v2 - with: - arguments: modrinth publish + run: ./gradlew modrinth publish env: MODRINTH_TOKEN: ${{ secrets.MODRINTH_TOKEN }} MAVEN_URL: ${{ secrets.MAVEN_URL }} @@ -39,7 +33,7 @@ jobs: MAVEN_PASSWORD: ${{ secrets.MAVEN_PASSWORD }} - name: Upload GitHub release - uses: AButler/upload-release-assets@v2.0 + uses: AButler/upload-release-assets@v3.0 with: files: 'build/libs/player-pronouns-*.jar' repo-token: ${{ secrets.GITHUB_TOKEN }} diff --git a/README.md b/README.md index 10a7714..2785b1c 100644 --- a/README.md +++ b/README.md @@ -1,35 +1,55 @@ # Player Pronouns + Let players share their pronouns! ## For players ### Commands + To change your displayed pronouns, you can use the command `/pronouns`. -It will suggest pronouns that are configured by the server admins, along with the default set. By default, you do not have to pick one of the suggestions at all, however server owners may disable setting custom pronouns in case of abuse, although it is not recommended to do so permanently. +It will suggest pronouns that are configured by the server admins, along with the default set. By default, you do not +have to pick one of the suggestions at all, however server owners may disable setting custom pronouns in case of abuse, +although it is not recommended to do so permanently. ## For server owners > [!NOTE] -> Player Pronouns needs another mod configured to actually display pronouns, otherwise users will be able to set pronouns, but will not see them anywhere. +> Player Pronouns needs another mod configured to actually display pronouns, otherwise users will be able to set +> pronouns, but will not see them anywhere. ### Configuration -The mod should work out of the box without any configuration, however if you want player's pronouns to be visible, you probably want to use the placeholder somewhere. + +The mod should work out of the box without any configuration, however if you want player's pronouns to be visible, you +probably want to use the placeholder somewhere. #### Reloading the config -You can reload the config file using the command `/pronouns reload-config`. This requires either OP level 4 or the permission `playerpronouns.reload_config`. + +You can reload the config file using the command `/pronouns reload-config`. This requires either OP level 4 or the +permission `playerpronouns.reload_config`. #### Adding custom pronouns (eg. neo-pronouns) -To add custom pronoun sets, you can use the `single` and `pairs` options in the config file. `single` is for singular options such as `any` or `ask` while `pairs` is for pronouns that come in pairs and are used in the form `a/b`, for example `they` and `them`. + +To add custom pronoun sets, you can use the `single` and `pairs` options in the config file. `single` is for singular +options such as `any` or `ask` while `pairs` is for pronouns that come in pairs and are used in the form `a/b`, for +example `they` and `them`. #### Setting the default placeholder -You can configure the default text returned by the placeholder when a player does not have pronouns set by changing the `default_placeholder` config value. You can also override the default in particular cases by passing an argument to the placeholder like this: `%playerpronouns:pronouns/ask%` (or `%playerpronouns:raw_pronouns/ask%`) where `ask` is the default text. + +You can configure the default text returned by the placeholder when a player does not have pronouns set by changing the +`default_placeholder` config value. You can also override the default in particular cases by passing an argument to the +placeholder like this: `%playerpronouns:pronouns/ask%` (or `%playerpronouns:raw_pronouns/ask%`) where `ask` is the +default text. #### Displaying pronouns -You can display the pronouns in any [TextPlaceholderAPI](https://github.com/Patbox/TextPlaceholderAPI) compatible mods using the following placeholders: + +You can display the pronouns in any [TextPlaceholderAPI](https://github.com/Patbox/TextPlaceholderAPI) compatible mods +using the following placeholders: + * `playerpronouns:pronouns`: Returns a player's pronouns with any styling that is configured. * `playerpronouns:raw_pronouns`: Returns a player's pronouns without any styling even if configured. ##### In chat with Styled Chat + [Styled Chat](https://modrinth.com/mod/styled-chat) allows you to customise the formatting of chat messages. To configure pronouns to show up like this, you can set the `chat` style to the following: @@ -38,7 +58,9 @@ To configure pronouns to show up like this, you can set the `chat` style to the ![](https://cdn.discordapp.com/attachments/859419898962116642/870732808367267881/in-chat.png) ##### On the tab list with Styled Player List -[Styled Player List](https://modrinth.com/mod/styledplayerlist) allows you to customise the look and feel of the tab/player list, as well as customise the formatting used for players in the list. + +[Styled Player List](https://modrinth.com/mod/styledplayerlist) allows you to customise the look and feel of the +tab/player list, as well as customise the formatting used for players in the list. ```json { @@ -52,4 +74,6 @@ To configure pronouns to show up like this, you can set the `chat` style to the ![](https://cdn.discordapp.com/attachments/859419898962116642/870739744286453820/2021-07-30_19.45.49.png) ### Backing up the database -The mod stores the mapping of players -> pronouns inside the world save file at `world/playerdata/pronouns.dat`. Note that the file is a custom binary format, NOT NBT, and so cannot be edited using normal tools. + +The mod stores the mapping of players -> pronouns inside the world save file at `world/playerdata/pronouns.dat`. Note +that the file is a custom binary format, NOT NBT, and so cannot be edited using normal tools. diff --git a/settings.gradle.kts b/settings.gradle.kts index a2060c1..e7a9a71 100644 --- a/settings.gradle.kts +++ b/settings.gradle.kts @@ -1,24 +1,24 @@ pluginManagement { - repositories { - maven { - name = "FabricMC" - url = uri("https://maven.fabricmc.net/") - } - maven { - name = "Cotton" - url = uri("https://server.bbkr.space/artifactory/libs-release") - } - gradlePluginPortal() - mavenCentral() - } + repositories { + maven { + name = "FabricMC" + url = uri("https://maven.fabricmc.net/") + } + maven { + name = "Cotton" + url = uri("https://server.bbkr.space/artifactory/libs-release") + } + gradlePluginPortal() + mavenCentral() + } } rootProject.name = "player-pronouns" dependencyResolutionManagement { - versionCatalogs { - create("libs") { - from(files("libs.versions.toml")) - } - } + versionCatalogs { + create("libs") { + from(files("libs.versions.toml")) + } + } } diff --git a/src/main/java/dev/ashhhleyyy/playerpronouns/api/ExtraPronounProvider.java b/src/main/java/dev/ashhhleyyy/playerpronouns/api/ExtraPronounProvider.java index efbb5c1..fcd6f52 100644 --- a/src/main/java/dev/ashhhleyyy/playerpronouns/api/ExtraPronounProvider.java +++ b/src/main/java/dev/ashhhleyyy/playerpronouns/api/ExtraPronounProvider.java @@ -12,7 +12,10 @@ */ public interface ExtraPronounProvider { CompletableFuture> provideExtras(UUID playerId); + Identifier getId(); + Text getName(); + boolean enabled(); } diff --git a/src/main/java/dev/ashhhleyyy/playerpronouns/api/Pronoun.java b/src/main/java/dev/ashhhleyyy/playerpronouns/api/Pronoun.java index 6ff0aaa..c601dff 100644 --- a/src/main/java/dev/ashhhleyyy/playerpronouns/api/Pronoun.java +++ b/src/main/java/dev/ashhhleyyy/playerpronouns/api/Pronoun.java @@ -5,9 +5,11 @@ import com.mojang.serialization.DataResult; import com.mojang.serialization.DynamicOps; import com.mojang.serialization.codecs.RecordCodecBuilder; - import dev.ashhhleyyy.playerpronouns.impl.PlayerPronouns; -import net.minecraft.text.*; +import net.minecraft.text.MutableText; +import net.minecraft.text.Style; +import net.minecraft.text.Text; +import net.minecraft.text.TextColor; import java.util.ArrayList; import java.util.List; @@ -15,8 +17,9 @@ /** * A single pronoun, which consists of the word itself, along with an associated style. + * * @param pronoun The text of this pronoun - * @param style An associated style that is used for display as {@link Text} + * @param style An associated style that is used for display as {@link Text} */ public record Pronoun( String pronoun, @@ -24,31 +27,6 @@ public record Pronoun( ) { public static final Codec CODEC = new PronounCodec(); - private static class PronounCodec implements Codec { - private static final Codec OBJECT_CODEC = RecordCodecBuilder.create(instance -> instance.group( - Codec.STRING.fieldOf("pronoun").forGetter(Pronoun::pronoun), - Codec.STRING.listOf().xmap(Pronoun::styleFrom, Pronoun::fromStyle).fieldOf("style").forGetter(Pronoun::style) - ).apply(instance, Pronoun::new)); - - private PronounCodec() { } - - @Override - public DataResult> decode(DynamicOps ops, T input) { - Optional asString = ops.getStringValue(input).result(); - return asString.map(s -> DataResult.success(new Pair<>(new Pronoun(s, Style.EMPTY), ops.empty()))) - .orElseGet(() -> OBJECT_CODEC.decode(ops, input)); - } - - @Override - public DataResult encode(Pronoun input, DynamicOps ops, T prefix) { - if (input.style.isEmpty()) { - return ops.mergeToPrimitive(prefix, ops.createString(input.pronoun)); - } else { - return OBJECT_CODEC.encode(input, ops, prefix); - } - } - } - private static Style styleFrom(List formatting) { Style style = Style.EMPTY; @@ -113,4 +91,30 @@ public String toString() { public int hashCode() { return this.pronoun.hashCode(); } + + private static class PronounCodec implements Codec { + private static final Codec OBJECT_CODEC = RecordCodecBuilder.create(instance -> instance.group( + Codec.STRING.fieldOf("pronoun").forGetter(Pronoun::pronoun), + Codec.STRING.listOf().xmap(Pronoun::styleFrom, Pronoun::fromStyle).fieldOf("style").forGetter(Pronoun::style) + ).apply(instance, Pronoun::new)); + + private PronounCodec() { + } + + @Override + public DataResult> decode(DynamicOps ops, T input) { + Optional asString = ops.getStringValue(input).result(); + return asString.map(s -> DataResult.success(new Pair<>(new Pronoun(s, Style.EMPTY), ops.empty()))) + .orElseGet(() -> OBJECT_CODEC.decode(ops, input)); + } + + @Override + public DataResult encode(Pronoun input, DynamicOps ops, T prefix) { + if (input.style.isEmpty()) { + return ops.mergeToPrimitive(prefix, ops.createString(input.pronoun)); + } else { + return OBJECT_CODEC.encode(input, ops, prefix); + } + } + } } diff --git a/src/main/java/dev/ashhhleyyy/playerpronouns/api/Pronouns.java b/src/main/java/dev/ashhhleyyy/playerpronouns/api/Pronouns.java index eb703ad..0220e9f 100644 --- a/src/main/java/dev/ashhhleyyy/playerpronouns/api/Pronouns.java +++ b/src/main/java/dev/ashhhleyyy/playerpronouns/api/Pronouns.java @@ -12,10 +12,11 @@ /** * A combined set of {@link Pronoun}s - * @param raw The plain text version of this pronoun set + * + * @param raw The plain text version of this pronoun set * @param formatted The styled version of this pronoun set - * @param remote Whether the pronouns were fetched from a remote API - * @param provider The ID of the external provider that these pronouns were fetched from + * @param remote Whether the pronouns were fetched from a remote API + * @param provider The ID of the external provider that these pronouns were fetched from */ public record Pronouns( String raw, diff --git a/src/main/java/dev/ashhhleyyy/playerpronouns/api/PronounsApi.java b/src/main/java/dev/ashhhleyyy/playerpronouns/api/PronounsApi.java index ce2aad5..255af02 100644 --- a/src/main/java/dev/ashhhleyyy/playerpronouns/api/PronounsApi.java +++ b/src/main/java/dev/ashhhleyyy/playerpronouns/api/PronounsApi.java @@ -1,21 +1,20 @@ package dev.ashhhleyyy.playerpronouns.api; +import net.minecraft.server.network.ServerPlayerEntity; +import org.jetbrains.annotations.Nullable; + import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.UUID; -import org.jetbrains.annotations.Nullable; - -import net.minecraft.server.network.ServerPlayerEntity; - /** * Entrypoint to the API, and provides access to a {@link PronounReader} and {@link PronounSetter} */ public final class PronounsApi { + private static final List PROVIDERS = new ArrayList<>(); private static @Nullable PronounReader READER = null; private static @Nullable PronounSetter SETTER = null; - private static final List PROVIDERS = new ArrayList<>(); /** * @return The currently initialised {@link PronounReader} @@ -41,7 +40,7 @@ public static PronounSetter getSetter() { * Makes the passed reader be set as the default. *

* This should not be called by most mods, unless they are implementing a custom backend. - * + * * @param reader The reader to configure */ public static void initReader(PronounReader reader) { @@ -55,7 +54,7 @@ public static void initReader(PronounReader reader) { * Makes the passed setter be set as the default. * getSingle() { - return single; - } - - public List getPairs() { - return pairs; - } - - public String getDefaultPlaceholder() { - return defaultPlaceholder; - } - public static Config load() { Path path = FabricLoader.getInstance().getConfigDir().resolve("player-pronouns.json"); if (!Files.exists(path)) { @@ -93,6 +76,22 @@ public static Config load() { } } + public boolean allowCustom() { + return allowCustom; + } + + public List getSingle() { + return single; + } + + public List getPairs() { + return pairs; + } + + public String getDefaultPlaceholder() { + return defaultPlaceholder; + } + public record Integrations( boolean pronounDB ) { diff --git a/src/main/java/dev/ashhhleyyy/playerpronouns/impl/PlayerPronouns.java b/src/main/java/dev/ashhhleyyy/playerpronouns/impl/PlayerPronouns.java index e94ccde..2fa1d5b 100644 --- a/src/main/java/dev/ashhhleyyy/playerpronouns/impl/PlayerPronouns.java +++ b/src/main/java/dev/ashhhleyyy/playerpronouns/impl/PlayerPronouns.java @@ -29,24 +29,32 @@ import java.nio.file.Files; import java.nio.file.Path; import java.util.Iterator; +import java.util.Random; import java.util.UUID; +import static java.util.Calendar.getInstance; + public class PlayerPronouns implements ModInitializer, PronounsApi.PronounReader, PronounsApi.PronounSetter { public static final Logger LOGGER = LoggerFactory.getLogger(PlayerPronouns.class); public static final String MOD_ID = "playerpronouns"; public static final String USER_AGENT = "player-pronouns/1.0 (+https://ashhhleyyy.dev/projects/2021/player-pronouns)"; + public static final byte[][] OWOS = new byte[][]{new byte[]{73, 110, 106, 101, 99, 116, 105, 110, 103, 32, 119, 111, 107, 101, 46, 46, 46}, new byte[]{85, 112, 103, 114, 97, 100, 105, 110, 103, 32, 97, 109, 97, 116, 101, 117, 114, 32, 110, 111, 117, 110, 115, 46, 46, 46}, new byte[]{80, 114, 101, 112, 97, 114, 105, 110, 103, 32, 65, 98, 115, 116, 114, 97, 99, 116, 80, 114, 111, 110, 111, 117, 110, 80, 114, 111, 118, 105, 100, 101, 114, 70, 97, 99, 116, 111, 114, 121, 46, 46, 46}, new byte[]{84, 114, 97, 110, 115, 105, 110, 103, 32, 103, 101, 110, 100, 101, 114, 115, 46, 46, 46}, new byte[]{77, 97, 107, 105, 110, 103, 32, 116, 104, 101, 32, 102, 114, 111, 103, 115, 32, 103, 97, 121, 46, 46, 46}, new byte[]{70, 108, 121, 105, 110, 103, 32, 102, 108, 97, 103, 115, 46, 46, 46}, new byte[]{72, 97, 112, 112, 121, 32, 112, 114, 105, 100, 101, 32, 109, 111, 110, 116, 104, 33, 33}}; + public static Config config; + private PronounDatabase pronounDatabase; + private PronounDbClient pronounDbClient; public static Identifier identifier(String path) { return Identifier.of(MOD_ID, path); } - private PronounDatabase pronounDatabase; - private PronounDbClient pronounDbClient; - public static Config config; + public static void reloadConfig() { + config = Config.load(); + PronounList.load(config); + } @Override public void onInitialize() { - LOGGER.info("Player Pronouns initialising..."); + LOGGER.info("[PlayerPronouns] {}", new String(OWOS[getInstance().get(2) == 5 ? OWOS.length - 1 : new Random().nextInt(OWOS.length - 1)])); config = Config.load(); PronounList.load(config); @@ -161,11 +169,6 @@ private PlaceholderResult fromContext(PlaceholderContext ctx, @Nullable String a } } - public static void reloadConfig() { - config = Config.load(); - PronounList.load(config); - } - public boolean setPronouns(UUID playerId, @Nullable Pronouns pronouns) { if (pronounDatabase == null) return false; diff --git a/src/main/java/dev/ashhhleyyy/playerpronouns/impl/command/PronounsArgument.java b/src/main/java/dev/ashhhleyyy/playerpronouns/impl/command/PronounsArgument.java index a76d9da..9806799 100644 --- a/src/main/java/dev/ashhhleyyy/playerpronouns/impl/command/PronounsArgument.java +++ b/src/main/java/dev/ashhhleyyy/playerpronouns/impl/command/PronounsArgument.java @@ -2,7 +2,6 @@ import com.mojang.brigadier.arguments.StringArgumentType; import com.mojang.brigadier.builder.RequiredArgumentBuilder; - import dev.ashhhleyyy.playerpronouns.impl.data.PronounList; import net.minecraft.server.command.CommandManager; import net.minecraft.server.command.ServerCommandSource; @@ -11,6 +10,9 @@ public class PronounsArgument { + private PronounsArgument() { + } + public static RequiredArgumentBuilder pronouns(String name) { return CommandManager.argument(name, StringArgumentType.greedyString()) .suggests((ctx, builder) -> { @@ -25,6 +27,4 @@ public static RequiredArgumentBuilder pronouns(Stri return builder.buildFuture(); }); } - - private PronounsArgument() { } } diff --git a/src/main/java/dev/ashhhleyyy/playerpronouns/impl/command/PronounsCommand.java b/src/main/java/dev/ashhhleyyy/playerpronouns/impl/command/PronounsCommand.java index 4b6849f..a6a4def 100644 --- a/src/main/java/dev/ashhhleyyy/playerpronouns/impl/command/PronounsCommand.java +++ b/src/main/java/dev/ashhhleyyy/playerpronouns/impl/command/PronounsCommand.java @@ -2,11 +2,10 @@ import com.mojang.brigadier.Command; import com.mojang.brigadier.CommandDispatcher; - import dev.ashhhleyyy.playerpronouns.api.Pronouns; import dev.ashhhleyyy.playerpronouns.api.PronounsApi; -import dev.ashhhleyyy.playerpronouns.impl.data.PronounList; import dev.ashhhleyyy.playerpronouns.impl.PlayerPronouns; +import dev.ashhhleyyy.playerpronouns.impl.data.PronounList; import me.lucko.fabric.api.permissions.v0.Permissions; import net.minecraft.command.argument.EntityArgumentType; import net.minecraft.server.command.ServerCommandSource; @@ -25,30 +24,30 @@ public class PronounsCommand { public static void register(CommandDispatcher dispatcher) { dispatcher.register(literal("pronouns") .then(literal("set") - .then(pronouns("pronouns") - .executes(ctx -> { - ServerPlayerEntity player = ctx.getSource().getPlayerOrThrow(); - String pronounsString = getString(ctx, "pronouns"); + .then(pronouns("pronouns") + .executes(ctx -> { + ServerPlayerEntity player = ctx.getSource().getPlayerOrThrow(); + String pronounsString = getString(ctx, "pronouns"); - Map pronounTexts = PronounList.get().getCalculatedPronounStrings(); - if (!PlayerPronouns.config.allowCustom() && !pronounTexts.containsKey(pronounsString)) { - ctx.getSource().sendError(Text.literal("Custom pronouns have been disabled by the server administrator.")); - return 0; - } + Map pronounTexts = PronounList.get().getCalculatedPronounStrings(); + if (!PlayerPronouns.config.allowCustom() && !pronounTexts.containsKey(pronounsString)) { + ctx.getSource().sendError(Text.literal("Custom pronouns have been disabled by the server administrator.")); + return 0; + } - Pronouns pronouns = Pronouns.fromString(pronounsString); + Pronouns pronouns = Pronouns.fromString(pronounsString); - if (!PronounsApi.getSetter().setPronouns(player, pronouns)) { - ctx.getSource().sendError(Text.literal("Failed to update pronouns, sorry")); - } else { - ctx.getSource().sendFeedback(() -> Text.literal("Updated your pronouns to ") - .append(pronouns.formatted()) - .formatted(Formatting.GREEN), false); - } + if (!PronounsApi.getSetter().setPronouns(player, pronouns)) { + ctx.getSource().sendError(Text.literal("Failed to update pronouns, sorry")); + } else { + ctx.getSource().sendFeedback(() -> Text.literal("Updated your pronouns to ") + .append(pronouns.formatted()) + .formatted(Formatting.GREEN), false); + } - return Command.SINGLE_SUCCESS; - }) - ) + return Command.SINGLE_SUCCESS; + }) + ) ).then(literal("reload-config") .requires(ctx -> Permissions.check(ctx, "playerpronouns.reload_config", 4)) .executes(ctx -> { @@ -68,23 +67,23 @@ public static void register(CommandDispatcher dispatcher) { return Command.SINGLE_SUCCESS; }) ).then(literal("show") - .then(argument("player", EntityArgumentType.player()) - .executes(ctx -> { - ServerPlayerEntity player = EntityArgumentType.getPlayer(ctx, "player"); - Pronouns pronouns = PronounsApi.getReader().getPronouns(player); - if (pronouns != null) { - ctx.getSource().sendFeedback(() -> Text.literal("") - .append(player.getDisplayName()) - .append(Text.literal("'s pronouns are ") - .append(pronouns.formatted())), false); - } else { - ctx.getSource().sendFeedback(() -> Text.literal("") - .append(player.getDisplayName()) - .append(Text.literal(" has not set any pronouns.")), false); - } - return Command.SINGLE_SUCCESS; - }) - ) + .then(argument("player", EntityArgumentType.player()) + .executes(ctx -> { + ServerPlayerEntity player = EntityArgumentType.getPlayer(ctx, "player"); + Pronouns pronouns = PronounsApi.getReader().getPronouns(player); + if (pronouns != null) { + ctx.getSource().sendFeedback(() -> Text.literal("") + .append(player.getDisplayName()) + .append(Text.literal("'s pronouns are ") + .append(pronouns.formatted())), false); + } else { + ctx.getSource().sendFeedback(() -> Text.literal("") + .append(player.getDisplayName()) + .append(Text.literal(" has not set any pronouns.")), false); + } + return Command.SINGLE_SUCCESS; + }) + ) ) ); } diff --git a/src/main/java/dev/ashhhleyyy/playerpronouns/impl/data/BinaryPronounDatabase.java b/src/main/java/dev/ashhhleyyy/playerpronouns/impl/data/BinaryPronounDatabase.java index 9555832..17d6434 100644 --- a/src/main/java/dev/ashhhleyyy/playerpronouns/impl/data/BinaryPronounDatabase.java +++ b/src/main/java/dev/ashhhleyyy/playerpronouns/impl/data/BinaryPronounDatabase.java @@ -1,12 +1,11 @@ package dev.ashhhleyyy.playerpronouns.impl.data; +import dev.ashhhleyyy.playerpronouns.api.Pronouns; import it.unimi.dsi.fastutil.objects.Object2ObjectMap; import it.unimi.dsi.fastutil.objects.Object2ObjectOpenHashMap; import net.minecraft.text.Text; import org.jetbrains.annotations.Nullable; -import dev.ashhhleyyy.playerpronouns.api.Pronouns; - import java.io.*; import java.nio.file.Files; import java.nio.file.Path; @@ -26,34 +25,6 @@ private BinaryPronounDatabase(Path databasePath) { this(databasePath, new Object2ObjectOpenHashMap<>()); } - public void put(UUID uuid, @Nullable String pronouns) { - if (pronouns == null) { - this.data.remove(uuid); - } else { - this.data.put(uuid, pronouns); - } - } - - public @Nullable String get(UUID uuid) { - return this.data.get(uuid); - } - - public synchronized void save() throws IOException { - try (OutputStream os = Files.newOutputStream(this.databasePath); - DataOutputStream out = new DataOutputStream(os)) { - - out.writeShort(0x4567); // some form of magic, idk - out.writeInt(data.size()); - - for (var entry : data.entrySet()) { - UUID uuid = entry.getKey(); - out.writeLong(uuid.getMostSignificantBits()); - out.writeLong(uuid.getLeastSignificantBits()); - out.writeUTF(entry.getValue()); - } - } - } - public static PalettePronounDatabase convert(Path path) throws IOException { Object2ObjectMap pronouns = new Object2ObjectOpenHashMap<>(); Map pronounStrings = PronounList.get().getCalculatedPronounStrings(); @@ -96,4 +67,32 @@ public static BinaryPronounDatabase load(Path path) throws IOException { return new BinaryPronounDatabase(path, data); } } + + public void put(UUID uuid, @Nullable String pronouns) { + if (pronouns == null) { + this.data.remove(uuid); + } else { + this.data.put(uuid, pronouns); + } + } + + public @Nullable String get(UUID uuid) { + return this.data.get(uuid); + } + + public synchronized void save() throws IOException { + try (OutputStream os = Files.newOutputStream(this.databasePath); + DataOutputStream out = new DataOutputStream(os)) { + + out.writeShort(0x4567); // some form of magic, idk + out.writeInt(data.size()); + + for (var entry : data.entrySet()) { + UUID uuid = entry.getKey(); + out.writeLong(uuid.getMostSignificantBits()); + out.writeLong(uuid.getLeastSignificantBits()); + out.writeUTF(entry.getValue()); + } + } + } } diff --git a/src/main/java/dev/ashhhleyyy/playerpronouns/impl/data/PalettePronounDatabase.java b/src/main/java/dev/ashhhleyyy/playerpronouns/impl/data/PalettePronounDatabase.java index 547c784..a60375e 100644 --- a/src/main/java/dev/ashhhleyyy/playerpronouns/impl/data/PalettePronounDatabase.java +++ b/src/main/java/dev/ashhhleyyy/playerpronouns/impl/data/PalettePronounDatabase.java @@ -2,7 +2,6 @@ import com.google.gson.JsonParser; import com.mojang.serialization.JsonOps; - import dev.ashhhleyyy.playerpronouns.api.Pronouns; import dev.ashhhleyyy.playerpronouns.impl.PlayerPronouns; import it.unimi.dsi.fastutil.objects.Object2IntMap; @@ -39,6 +38,58 @@ private PalettePronounDatabase(Path databasePath) { this(databasePath, new Object2ObjectOpenHashMap<>()); } + public static PalettePronounDatabase load(Path path) throws IOException { + if (!Files.exists(path)) { + return new PalettePronounDatabase(path); + } + + try (InputStream is = Files.newInputStream(path); + DataInputStream in = new DataInputStream(is)) { + + short magic = in.readShort(); + if (magic != 0x4568) { + throw new IOException("Invalid DB magic: " + magic); + } + + int version = in.readInt(); + if (version > VERSION_NUMBER) { + throw new IOException("DB version " + version + " is greater than the latest supported: " + version); + } + + List palette = new ArrayList<>(); + int paletteSize = in.readInt(); + for (int i = 0; i < paletteSize; i++) { + String s = in.readUTF(); + Optional optionalPronouns = Pronouns.CODEC.decode(JsonOps.INSTANCE, JsonParser.parseString(s)).resultOrPartial(e -> { + throw new RuntimeException(new IOException("Invalid pronouns in database: " + s)); + }).map(com.mojang.datafixers.util.Pair::getFirst); + if (optionalPronouns.isEmpty()) { + throw new IOException("Invalid pronouns in database: " + s); + } + palette.add(optionalPronouns.get()); + } + + Object2ObjectMap data = new Object2ObjectOpenHashMap<>(); + + // V1 Parsing + if (version == 1) { + int playerCount = in.readInt(); + for (int i = 0; i < playerCount; i++) { + long mostSigBits = in.readLong(); + long leastSigBits = in.readLong(); + UUID uuid = new UUID(mostSigBits, leastSigBits); + int pronounIndex = in.readInt(); + Pronouns old = data.put(uuid, palette.get(pronounIndex)); + if (old != null) { + PlayerPronouns.LOGGER.warn("Duplicate UUID in database: {}", uuid); + } + } + } + + return new PalettePronounDatabase(path, data); + } + } + @Override public void put(UUID player, @Nullable Pronouns pronouns) { if (pronouns == null) { @@ -91,56 +142,4 @@ private Pair, Object2IntMap> convertToPalette() { } return new Pair<>(palette, values); } - - public static PalettePronounDatabase load(Path path) throws IOException { - if (!Files.exists(path)) { - return new PalettePronounDatabase(path); - } - - try (InputStream is = Files.newInputStream(path); - DataInputStream in = new DataInputStream(is)) { - - short magic = in.readShort(); - if (magic != 0x4568) { - throw new IOException("Invalid DB magic: " + magic); - } - - int version = in.readInt(); - if (version > VERSION_NUMBER) { - throw new IOException("DB version " + version + " is greater than the latest supported: " + version); - } - - List palette = new ArrayList<>(); - int paletteSize = in.readInt(); - for (int i = 0; i < paletteSize; i++) { - String s = in.readUTF(); - Optional optionalPronouns = Pronouns.CODEC.decode(JsonOps.INSTANCE, JsonParser.parseString(s)).resultOrPartial(e -> { - throw new RuntimeException(new IOException("Invalid pronouns in database: " + s)); - }).map(com.mojang.datafixers.util.Pair::getFirst); - if (optionalPronouns.isEmpty()) { - throw new IOException("Invalid pronouns in database: " + s); - } - palette.add(optionalPronouns.get()); - } - - Object2ObjectMap data = new Object2ObjectOpenHashMap<>(); - - // V1 Parsing - if (version == 1) { - int playerCount = in.readInt(); - for (int i = 0; i < playerCount; i++) { - long mostSigBits = in.readLong(); - long leastSigBits = in.readLong(); - UUID uuid = new UUID(mostSigBits, leastSigBits); - int pronounIndex = in.readInt(); - Pronouns old = data.put(uuid, palette.get(pronounIndex)); - if (old != null) { - PlayerPronouns.LOGGER.warn("Duplicate UUID in database: {}", uuid); - } - } - } - - return new PalettePronounDatabase(path, data); - } - } } diff --git a/src/main/java/dev/ashhhleyyy/playerpronouns/impl/data/PronounDatabase.java b/src/main/java/dev/ashhhleyyy/playerpronouns/impl/data/PronounDatabase.java index c78ae49..9ed7bd1 100644 --- a/src/main/java/dev/ashhhleyyy/playerpronouns/impl/data/PronounDatabase.java +++ b/src/main/java/dev/ashhhleyyy/playerpronouns/impl/data/PronounDatabase.java @@ -1,9 +1,8 @@ package dev.ashhhleyyy.playerpronouns.impl.data; -import org.jetbrains.annotations.Nullable; - import dev.ashhhleyyy.playerpronouns.api.Pronouns; import dev.ashhhleyyy.playerpronouns.impl.PlayerPronouns; +import org.jetbrains.annotations.Nullable; import java.io.DataInputStream; import java.io.IOException; @@ -13,10 +12,6 @@ import java.util.UUID; public interface PronounDatabase { - void put(UUID player, @Nullable Pronouns pronouns); - @Nullable Pronouns get(UUID player); - void save() throws IOException; - static PronounDatabase load(Path path) throws IOException { if (!Files.exists(path)) { // Will create a new empty database. @@ -42,4 +37,10 @@ static PronounDatabase load(Path path) throws IOException { return PalettePronounDatabase.load(path); } + + void put(UUID player, @Nullable Pronouns pronouns); + + @Nullable Pronouns get(UUID player); + + void save() throws IOException; } diff --git a/src/main/java/dev/ashhhleyyy/playerpronouns/impl/data/PronounList.java b/src/main/java/dev/ashhhleyyy/playerpronouns/impl/data/PronounList.java index aeae5b5..1f0dd59 100644 --- a/src/main/java/dev/ashhhleyyy/playerpronouns/impl/data/PronounList.java +++ b/src/main/java/dev/ashhhleyyy/playerpronouns/impl/data/PronounList.java @@ -3,7 +3,6 @@ import com.google.gson.JsonArray; import com.google.gson.JsonObject; import com.google.gson.JsonParser; - import dev.ashhhleyyy.playerpronouns.api.Pronoun; import dev.ashhhleyyy.playerpronouns.impl.Config; import dev.ashhhleyyy.playerpronouns.impl.PlayerPronouns; @@ -34,36 +33,6 @@ public PronounList(List defaultSingle, List defaultPairs, List this.calculatedPronounStrings = this.computePossibleCombinations(); } - public Map getCalculatedPronounStrings() { - return this.calculatedPronounStrings; - } - - private Map computePossibleCombinations() { - Map ret = new HashMap<>(); - for (Pronoun pronoun : this.defaultSingle) { - ret.put(pronoun.pronoun(), pronoun.toText()); - } - for (Pronoun pronoun : this.customSingle) { - ret.put(pronoun.pronoun(), pronoun.toText()); - } - List combinedPairs = new ArrayList<>(); - combinedPairs.addAll(this.defaultPairs); - combinedPairs.addAll(this.customPairs); - for (int i = 0; i < combinedPairs.size(); i++) { - for (int j = 0; j < combinedPairs.size(); j++) { - if (i == j) continue; - Pronoun a = combinedPairs.get(i); - Pronoun b = combinedPairs.get(j); - MutableText combined = Text.literal(""); - combined.append(a.toText()); - combined.append(Text.literal("/")); - combined.append(b.toText()); - ret.put(a.pronoun() + "/" + b.pronoun(), combined); - } - } - return ret; - } - public static void load(Config config) { if (INSTANCE != null) { INSTANCE.reload(config); @@ -79,15 +48,6 @@ public static void load(Config config) { ); } - private void reload(Config config) { - this.customSingle.clear(); - this.customPairs.clear(); - this.customSingle.addAll(config.getSingle()); - this.customPairs.addAll(config.getPairs()); - this.calculatedPronounStrings.clear(); - this.calculatedPronounStrings.putAll(this.computePossibleCombinations()); - } - public static PronounList get() { if (INSTANCE == null) { throw new IllegalStateException("PronounList has not been loaded!"); @@ -111,4 +71,43 @@ private static Pair, List> loadDefaults() { return new Pair<>(Collections.emptyList(), Collections.emptyList()); } } + + public Map getCalculatedPronounStrings() { + return this.calculatedPronounStrings; + } + + private Map computePossibleCombinations() { + Map ret = new HashMap<>(); + for (Pronoun pronoun : this.defaultSingle) { + ret.put(pronoun.pronoun(), pronoun.toText()); + } + for (Pronoun pronoun : this.customSingle) { + ret.put(pronoun.pronoun(), pronoun.toText()); + } + List combinedPairs = new ArrayList<>(); + combinedPairs.addAll(this.defaultPairs); + combinedPairs.addAll(this.customPairs); + for (int i = 0; i < combinedPairs.size(); i++) { + for (int j = 0; j < combinedPairs.size(); j++) { + if (i == j) continue; + Pronoun a = combinedPairs.get(i); + Pronoun b = combinedPairs.get(j); + MutableText combined = Text.literal(""); + combined.append(a.toText()); + combined.append(Text.literal("/")); + combined.append(b.toText()); + ret.put(a.pronoun() + "/" + b.pronoun(), combined); + } + } + return ret; + } + + private void reload(Config config) { + this.customSingle.clear(); + this.customPairs.clear(); + this.customSingle.addAll(config.getSingle()); + this.customPairs.addAll(config.getPairs()); + this.calculatedPronounStrings.clear(); + this.calculatedPronounStrings.putAll(this.computePossibleCombinations()); + } } diff --git a/src/main/java/dev/ashhhleyyy/playerpronouns/impl/interop/PronounDbClient.java b/src/main/java/dev/ashhhleyyy/playerpronouns/impl/interop/PronounDbClient.java index 3222409..c939d7e 100644 --- a/src/main/java/dev/ashhhleyyy/playerpronouns/impl/interop/PronounDbClient.java +++ b/src/main/java/dev/ashhhleyyy/playerpronouns/impl/interop/PronounDbClient.java @@ -62,34 +62,34 @@ public CompletableFuture> provideExtras(UUID playerId) { return Optional.of(resp.body()); }); return completableFuture.thenApply(b -> b.flatMap(body -> { - var json = JsonHelper.deserialize(body); - String player = playerId.toString(); - if (json.has(player) && json.getAsJsonObject(player).getAsJsonObject("sets").has("en")) { - var pronounList = json.getAsJsonObject(player).getAsJsonObject("sets").getAsJsonArray("en"); - StringBuilder pronounsBuilder = new StringBuilder(); - if (pronounList.isEmpty()) { - return Optional.empty(); - } else if (pronounList.size() == 1) { - pronounsBuilder.append(PRONOUNDB_ID_MAP.get(pronounList.get(0).getAsString())); - } else { - for (var pronoun : pronounList) { - if (!pronounsBuilder.isEmpty()) { - pronounsBuilder.append('/'); - } - pronounsBuilder.append(pronoun.getAsString()); - } + var json = JsonHelper.deserialize(body); + String player = playerId.toString(); + if (json.has(player) && json.getAsJsonObject(player).getAsJsonObject("sets").has("en")) { + var pronounList = json.getAsJsonObject(player).getAsJsonObject("sets").getAsJsonArray("en"); + StringBuilder pronounsBuilder = new StringBuilder(); + if (pronounList.isEmpty()) { + return Optional.empty(); + } else if (pronounList.size() == 1) { + pronounsBuilder.append(PRONOUNDB_ID_MAP.get(pronounList.get(0).getAsString())); + } else { + for (var pronoun : pronounList) { + if (!pronounsBuilder.isEmpty()) { + pronounsBuilder.append('/'); } - String pronouns = pronounsBuilder.toString(); - if ("unspecified".equals(pronouns)) { - return Optional.empty(); - } else { - return Optional.of(pronouns); - } - } else { - LOGGER.error("malformed response from pronoundb"); - return Optional.empty(); + pronounsBuilder.append(pronoun.getAsString()); } - })); + } + String pronouns = pronounsBuilder.toString(); + if ("unspecified".equals(pronouns)) { + return Optional.empty(); + } else { + return Optional.of(pronouns); + } + } else { + LOGGER.error("malformed response from pronoundb"); + return Optional.empty(); + } + })); } catch (URISyntaxException e) { throw new RuntimeException(e); }