DraggableWidget.java 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. /*
  2. * Roughly Enough Items by Danielshe.
  3. * Licensed under the MIT License.
  4. */
  5. package me.shedaniel.rei.gui.widget;
  6. import me.shedaniel.math.api.Point;
  7. import me.shedaniel.math.api.Rectangle;
  8. import me.shedaniel.math.impl.PointHelper;
  9. import net.minecraft.client.MinecraftClient;
  10. import net.minecraft.client.gui.Element;
  11. import net.minecraft.client.util.Window;
  12. public abstract class DraggableWidget extends WidgetWithBounds {
  13. public boolean dragged = false;
  14. private Point midPoint, startPoint;
  15. private int relateX, relateY;
  16. public DraggableWidget(Point startingPoint) {
  17. initWidgets(midPoint = startingPoint);
  18. }
  19. public DraggableWidget() {
  20. this(new Point(MinecraftClient.getInstance().getWindow().getScaledWidth() / 2, MinecraftClient.getInstance().getWindow().getScaledHeight() / 2));
  21. }
  22. protected abstract void initWidgets(Point midPoint);
  23. public abstract void updateWidgets(Point midPoint);
  24. public abstract Rectangle getGrabBounds();
  25. public abstract Rectangle getDragBounds();
  26. public final Point getMidPoint() {
  27. return midPoint;
  28. }
  29. @Override
  30. public boolean mouseDragged(double double_1, double double_2, int int_1, double double_3, double double_4) {
  31. Point mouse = PointHelper.fromMouse();
  32. if (int_1 == 0) {
  33. if (!dragged) {
  34. if (getGrabBounds().contains(mouse)) {
  35. startPoint = new Point(midPoint.x, midPoint.y);
  36. relateX = mouse.x - midPoint.x;
  37. relateY = mouse.y - midPoint.y;
  38. dragged = true;
  39. }
  40. } else {
  41. Window window = minecraft.getWindow();
  42. midPoint = processMidPoint(midPoint, mouse, startPoint, window, relateX, relateY);
  43. updateWidgets(midPoint);
  44. }
  45. return true;
  46. }
  47. for (Element listener : children())
  48. if (listener.mouseDragged(double_1, double_2, int_1, double_3, double_4))
  49. return true;
  50. return false;
  51. }
  52. public abstract Point processMidPoint(Point midPoint, Point mouse, Point startPoint, Window window, int relateX, int relateY);
  53. @Override
  54. public boolean mouseReleased(double double_1, double double_2, int int_1) {
  55. if (int_1 == 0)
  56. if (dragged) {
  57. dragged = false;
  58. onMouseReleaseMidPoint(getMidPoint());
  59. return true;
  60. }
  61. for (Element listener : children())
  62. if (listener.mouseReleased(double_1, double_2, int_1))
  63. return true;
  64. return false;
  65. }
  66. public void onMouseReleaseMidPoint(Point midPoint) {
  67. }
  68. }