RoughlyEnoughItemsCore.java 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263
  1. /*
  2. * Roughly Enough Items by Danielshe.
  3. * Licensed under the MIT License.
  4. */
  5. package me.shedaniel.rei;
  6. import com.google.common.collect.Lists;
  7. import com.google.common.collect.Maps;
  8. import com.google.gson.JsonElement;
  9. import com.google.gson.JsonObject;
  10. import me.shedaniel.cloth.api.ClientUtils;
  11. import me.shedaniel.cloth.hooks.ClothClientHooks;
  12. import me.shedaniel.rei.api.*;
  13. import me.shedaniel.rei.client.*;
  14. import me.shedaniel.rei.gui.ContainerScreenOverlay;
  15. import me.shedaniel.rei.listeners.RecipeBookGuiHooks;
  16. import net.fabricmc.api.ClientModInitializer;
  17. import net.fabricmc.fabric.api.network.ClientSidePacketRegistry;
  18. import net.fabricmc.loader.api.FabricLoader;
  19. import net.fabricmc.loader.api.ModContainer;
  20. import net.fabricmc.loader.api.metadata.ModMetadata;
  21. import net.minecraft.client.MinecraftClient;
  22. import net.minecraft.client.gui.Element;
  23. import net.minecraft.client.gui.screen.ingame.AbstractContainerScreen;
  24. import net.minecraft.client.gui.screen.ingame.CreativeInventoryScreen;
  25. import net.minecraft.client.gui.screen.ingame.InventoryScreen;
  26. import net.minecraft.client.gui.screen.recipebook.RecipeBookScreen;
  27. import net.minecraft.client.gui.widget.RecipeBookButtonWidget;
  28. import net.minecraft.client.gui.widget.TextFieldWidget;
  29. import net.minecraft.util.ActionResult;
  30. import net.minecraft.util.Identifier;
  31. import net.minecraft.util.Pair;
  32. import org.apache.logging.log4j.LogManager;
  33. import org.apache.logging.log4j.Logger;
  34. import java.util.LinkedList;
  35. import java.util.List;
  36. import java.util.Map;
  37. import java.util.Optional;
  38. import java.util.stream.Collectors;
  39. public class RoughlyEnoughItemsCore implements ClientModInitializer {
  40. public static final Logger LOGGER;
  41. private static final RecipeHelper RECIPE_HELPER = new RecipeHelperImpl();
  42. private static final PluginDisabler PLUGIN_DISABLER = new PluginDisablerImpl();
  43. private static final ItemRegistry ITEM_REGISTRY = new ItemRegistryImpl();
  44. private static final DisplayHelper DISPLAY_HELPER = new DisplayHelperImpl();
  45. private static final Map<Identifier, REIPluginEntry> plugins = Maps.newHashMap();
  46. private static ConfigManagerImpl configManager;
  47. static {
  48. LOGGER = LogManager.getFormatterLogger("REI");
  49. }
  50. public static RecipeHelper getRecipeHelper() {
  51. return RECIPE_HELPER;
  52. }
  53. public static me.shedaniel.rei.api.ConfigManager getConfigManager() {
  54. return configManager;
  55. }
  56. public static ItemRegistry getItemRegisterer() {
  57. return ITEM_REGISTRY;
  58. }
  59. public static PluginDisabler getPluginDisabler() {
  60. return PLUGIN_DISABLER;
  61. }
  62. public static DisplayHelper getDisplayHelper() {
  63. return DISPLAY_HELPER;
  64. }
  65. /**
  66. * Registers a REI plugin
  67. *
  68. * @param identifier the identifier of the plugin
  69. * @param plugin the plugin instance
  70. * @deprecated Check REI wiki
  71. */
  72. @Deprecated
  73. public static REIPluginEntry registerPlugin(Identifier identifier, REIPluginEntry plugin) {
  74. plugins.put(identifier, plugin);
  75. RoughlyEnoughItemsCore.LOGGER.info("[REI] Registered plugin %s from %s", identifier.toString(), plugin.getClass().getSimpleName());
  76. plugin.onFirstLoad(getPluginDisabler());
  77. return plugin;
  78. }
  79. public static List<REIPluginEntry> getPlugins() {
  80. return new LinkedList<>(plugins.values());
  81. }
  82. public static Optional<Identifier> getPluginIdentifier(REIPluginEntry plugin) {
  83. for(Identifier identifier : plugins.keySet())
  84. if (identifier != null && plugins.get(identifier).equals(plugin))
  85. return Optional.of(identifier);
  86. return Optional.empty();
  87. }
  88. public static boolean hasPermissionToUsePackets() {
  89. try {
  90. MinecraftClient.getInstance().getNetworkHandler().getCommandSource().hasPermissionLevel(0);
  91. return hasOperatorPermission() && canUsePackets();
  92. } catch (NullPointerException e) {
  93. return true;
  94. }
  95. }
  96. public static boolean hasOperatorPermission() {
  97. try {
  98. return MinecraftClient.getInstance().getNetworkHandler().getCommandSource().hasPermissionLevel(1);
  99. } catch (NullPointerException e) {
  100. return true;
  101. }
  102. }
  103. public static boolean canUsePackets() {
  104. return ClientSidePacketRegistry.INSTANCE.canServerReceive(RoughlyEnoughItemsNetwork.CREATE_ITEMS_PACKET) && ClientSidePacketRegistry.INSTANCE.canServerReceive(RoughlyEnoughItemsNetwork.DELETE_ITEMS_PACKET);
  105. }
  106. @Override
  107. public void onInitializeClient() {
  108. configManager = new ConfigManagerImpl();
  109. registerClothEvents();
  110. discoverOldPlugins();
  111. discoverPluginEntries();
  112. }
  113. @SuppressWarnings("deprecation")
  114. private void discoverPluginEntries() {
  115. for(REIPluginEntry reiPlugin : FabricLoader.getInstance().getEntrypoints("rei_plugins", REIPluginEntry.class)) {
  116. try {
  117. if (reiPlugin instanceof REIPlugin)
  118. throw new IllegalStateException("REI Plugins on Entry Points should not implement REIPlugin");
  119. registerPlugin(reiPlugin.getPluginIdentifier(), reiPlugin);
  120. } catch (Exception e) {
  121. e.printStackTrace();
  122. RoughlyEnoughItemsCore.LOGGER.error("[REI] Can't load REI plugins from %s: %s", reiPlugin.getClass(), e.getLocalizedMessage());
  123. }
  124. }
  125. }
  126. @SuppressWarnings("deprecation")
  127. private void discoverOldPlugins() {
  128. List<Pair<Identifier, String>> list = Lists.newArrayList();
  129. for(ModMetadata metadata : FabricLoader.getInstance().getAllMods().stream().map(ModContainer::getMetadata).filter(metadata -> metadata.containsCustomElement("roughlyenoughitems:plugins")).collect(Collectors.toList())) {
  130. RoughlyEnoughItemsCore.LOGGER.warn("[REI] %s(%s) is still using the old way to register its plugin! Support will be dropped in the future!", metadata.getName(), metadata.getId());
  131. try {
  132. JsonElement pluginsElement = metadata.getCustomElement("roughlyenoughitems:plugins");
  133. if (pluginsElement.isJsonArray()) {
  134. for(JsonElement element : pluginsElement.getAsJsonArray())
  135. if (element.isJsonObject())
  136. loadPluginFromJsonObject(list, metadata, element.getAsJsonObject());
  137. else
  138. throw new IllegalStateException("Custom Element in an array is not an object.");
  139. } else if (pluginsElement.isJsonObject()) {
  140. loadPluginFromJsonObject(list, metadata, pluginsElement.getAsJsonObject());
  141. } else
  142. throw new IllegalStateException("Custom Element not an array or an object.");
  143. } catch (Exception e) {
  144. e.printStackTrace();
  145. RoughlyEnoughItemsCore.LOGGER.error("[REI] Can't load REI plugins from %s: %s", metadata.getId(), e.getLocalizedMessage());
  146. }
  147. }
  148. for(Pair<Identifier, String> pair : list) {
  149. String s = pair.getRight();
  150. try {
  151. Class<?> aClass = Class.forName(s);
  152. if (!REIPlugin.class.isAssignableFrom(aClass)) {
  153. RoughlyEnoughItemsCore.LOGGER.error("[REI] Plugin class from %s is not implementing REIPlugin!", s);
  154. break;
  155. }
  156. REIPlugin o = REIPlugin.class.cast(aClass.newInstance());
  157. registerPlugin(pair.getLeft(), o);
  158. } catch (ClassNotFoundException | InstantiationException | IllegalAccessException e) {
  159. RoughlyEnoughItemsCore.LOGGER.error("[REI] Can't load REI plugin class from %s!", s);
  160. } catch (ClassCastException e) {
  161. RoughlyEnoughItemsCore.LOGGER.error("[REI] Failed to cast plugin class from %s to REIPlugin!", s);
  162. }
  163. }
  164. }
  165. private void loadPluginFromJsonObject(List<Pair<Identifier, String>> list, ModMetadata modMetadata, JsonObject object) {
  166. String namespace = modMetadata.getId();
  167. if (object.has("namespace"))
  168. namespace = object.get("namespace").getAsString();
  169. String id = object.get("id").getAsString();
  170. String className = object.get("class").getAsString();
  171. list.add(new Pair<>(new Identifier(namespace, id), className));
  172. }
  173. private void registerClothEvents() {
  174. ClothClientHooks.SYNC_RECIPES.register((minecraftClient, recipeManager, synchronizeRecipesS2CPacket) -> {
  175. ((RecipeHelperImpl) RoughlyEnoughItemsCore.getRecipeHelper()).recipesLoaded(recipeManager);
  176. });
  177. ClothClientHooks.SCREEN_ADD_BUTTON.register((minecraftClient, screen, abstractButtonWidget) -> {
  178. if (RoughlyEnoughItemsCore.getConfigManager().getConfig().disableRecipeBook && screen instanceof AbstractContainerScreen && abstractButtonWidget instanceof RecipeBookButtonWidget)
  179. return ActionResult.FAIL;
  180. return ActionResult.PASS;
  181. });
  182. ClothClientHooks.SCREEN_INIT_POST.register((minecraftClient, screen, screenHooks) -> {
  183. if (screen instanceof AbstractContainerScreen) {
  184. if (screen instanceof InventoryScreen && minecraftClient.interactionManager.hasCreativeInventory())
  185. return;
  186. ScreenHelper.setLastContainerScreen((AbstractContainerScreen) screen);
  187. boolean alreadyAdded = false;
  188. for(Element element : Lists.newArrayList(screenHooks.cloth_getInputListeners()))
  189. if (ContainerScreenOverlay.class.isAssignableFrom(element.getClass()))
  190. if (alreadyAdded)
  191. screenHooks.cloth_getInputListeners().remove(element);
  192. else
  193. alreadyAdded = true;
  194. if (!alreadyAdded)
  195. screenHooks.cloth_getInputListeners().add(ScreenHelper.getLastOverlay(true, false));
  196. }
  197. });
  198. ClothClientHooks.SCREEN_RENDER_POST.register((minecraftClient, screen, i, i1, v) -> {
  199. if (screen instanceof AbstractContainerScreen)
  200. ScreenHelper.getLastOverlay().render(i, i1, v);
  201. });
  202. ClothClientHooks.SCREEN_MOUSE_CLICKED.register((minecraftClient, screen, v, v1, i) -> {
  203. if (screen instanceof CreativeInventoryScreen)
  204. if (ScreenHelper.isOverlayVisible() && ScreenHelper.getLastOverlay().mouseClicked(v, v1, i)) {
  205. screen.setFocused(ScreenHelper.getLastOverlay());
  206. if (i == 0)
  207. screen.setDragging(true);
  208. return ActionResult.SUCCESS;
  209. }
  210. return ActionResult.PASS;
  211. });
  212. ClothClientHooks.SCREEN_MOUSE_SCROLLED.register((minecraftClient, screen, v, v1, v2) -> {
  213. if (screen instanceof AbstractContainerScreen)
  214. if (ScreenHelper.isOverlayVisible() && ScreenHelper.getLastOverlay().isInside(ClientUtils.getMouseLocation()) && ScreenHelper.getLastOverlay().mouseScrolled(v, v1, v2))
  215. return ActionResult.SUCCESS;
  216. return ActionResult.PASS;
  217. });
  218. ClothClientHooks.SCREEN_CHAR_TYPED.register((minecraftClient, screen, character, keyCode) -> {
  219. if (screen instanceof AbstractContainerScreen)
  220. if (ScreenHelper.getLastOverlay().charTyped(character, keyCode))
  221. return ActionResult.SUCCESS;
  222. return ActionResult.PASS;
  223. });
  224. ClothClientHooks.SCREEN_LATE_RENDER.register((minecraftClient, screen, i, i1, v) -> {
  225. if (!ScreenHelper.isOverlayVisible())
  226. return;
  227. if (screen instanceof AbstractContainerScreen)
  228. ScreenHelper.getLastOverlay().lateRender(i, i1, v);
  229. });
  230. ClothClientHooks.SCREEN_KEY_PRESSED.register((minecraftClient, screen, i, i1, i2) -> {
  231. if (screen.getFocused() != null && screen.getFocused() instanceof TextFieldWidget || (screen.getFocused() instanceof RecipeBookScreen && ((RecipeBookGuiHooks) screen.getFocused()).rei_getSearchField() != null && ((RecipeBookGuiHooks) screen.getFocused()).rei_getSearchField().isFocused()))
  232. return ActionResult.PASS;
  233. if (screen instanceof AbstractContainerScreen)
  234. if (ScreenHelper.getLastOverlay().keyPressed(i, i1, i2))
  235. return ActionResult.SUCCESS;
  236. return ActionResult.PASS;
  237. });
  238. }
  239. }