ConfigScreenBuilder.java 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. package me.lortseam.completeconfig.gui;
  2. import me.lortseam.completeconfig.data.Config;
  3. import me.lortseam.completeconfig.gui.cloth.ClothConfigScreenBuilder;
  4. import net.fabricmc.api.EnvType;
  5. import net.fabricmc.api.Environment;
  6. import net.fabricmc.loader.api.FabricLoader;
  7. import net.minecraft.client.gui.screen.Screen;
  8. import java.util.HashMap;
  9. import java.util.Map;
  10. import java.util.Optional;
  11. public abstract class ConfigScreenBuilder {
  12. private static final ConfigScreenBuilder fallback = FabricLoader.getInstance().isModLoaded("cloth-config2") ? new ClothConfigScreenBuilder() : null;
  13. private static final Map<String, ConfigScreenBuilder> mainBuilders = new HashMap<>();
  14. /**
  15. * Sets the main screen builder for a mod. The main screen builder will be used to build the config screen if no
  16. * custom builder was specified.
  17. *
  18. * @param modID the mod's ID
  19. * @param screenBuilder the screen builder
  20. */
  21. public static void setMain(String modID, ConfigScreenBuilder screenBuilder) {
  22. mainBuilders.put(modID, screenBuilder);
  23. }
  24. public static Optional<ConfigScreenBuilder> getMain(String modID) {
  25. if (mainBuilders.containsKey(modID)) {
  26. return Optional.of(mainBuilders.get(modID));
  27. }
  28. if (fallback != null) {
  29. return Optional.of(fallback);
  30. }
  31. return Optional.empty();
  32. }
  33. /**
  34. * Tries to build a screen based on a config. Fails if no main screen builder was specified for the mod and no
  35. * fallback builder exists.
  36. *
  37. * @param parentScreen the parent screen
  38. * @param config the config to build the screen of
  39. * @return the built screen, if successful
  40. */
  41. public static Screen tryBuild(Screen parentScreen, Config config) {
  42. return getMain(config.getMod().getId()).orElseThrow(() -> {
  43. return new UnsupportedOperationException("No screen builder found for mod " + config.getMod().getId());
  44. }).build(parentScreen, config);
  45. }
  46. /**
  47. * Builds a screen based on a config.
  48. *
  49. * @param parentScreen the parent screen
  50. * @param config the config to build the screen of
  51. * @return the built screen
  52. */
  53. @Environment(EnvType.CLIENT)
  54. public abstract Screen build(Screen parentScreen, Config config);
  55. }