├── .github
└── FUNDING.yml
├── .gitignore
├── .idea
├── .gitignore
├── misc.xml
├── modules
│ └── MenuAPI.main.iml
├── runConfigurations
│ ├── Build_MenuAPI.xml
│ ├── Clean_MenuAPI.xml
│ └── Publish_MenuAPI.xml
└── vcs.xml
├── LICENSE.md
├── README.md
├── build.gradle.kts
├── core
├── build.gradle.kts
└── src
│ └── main
│ └── java
│ └── net
│ └── j4c0b3y
│ └── api
│ └── menu
│ ├── Menu.java
│ ├── MenuHandler.java
│ ├── MenuSize.java
│ ├── annotation
│ ├── Async.java
│ └── AutoUpdate.java
│ ├── button
│ ├── Button.java
│ └── ButtonClick.java
│ ├── layer
│ ├── Layer.java
│ └── impl
│ │ ├── BackgroundLayer.java
│ │ └── ForegroundLayer.java
│ ├── listener
│ └── InventoryListener.java
│ ├── pagination
│ ├── PaginatedMenu.java
│ └── PaginationSlot.java
│ ├── task
│ └── AutoUpdateTask.java
│ ├── template
│ └── Template.java
│ └── utils
│ └── Position.java
├── extras
├── build.gradle.kts
└── src
│ └── main
│ └── java
│ └── net
│ └── j4c0b3y
│ └── api
│ └── menu
│ └── item
│ └── Item.java
├── gradle
└── wrapper
│ ├── gradle-wrapper.jar
│ └── gradle-wrapper.properties
├── gradlew
├── gradlew.bat
└── settings.gradle.kts
/.github/FUNDING.yml:
--------------------------------------------------------------------------------
1 | custom: https://donate.j4c0b3y.net
2 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | .gradle
2 | build/
3 | !gradle/wrapper/gradle-wrapper.jar
4 | !**/src/main/**/build/
5 | !**/src/test/**/build/
6 | gradle.properties
7 | jars/
8 |
9 | *.iws
10 | *.iml
11 | *.ipr
12 | out/
13 | !**/src/main/**/out/
14 | !**/src/test/**/out/
15 |
16 |
--------------------------------------------------------------------------------
/.idea/.gitignore:
--------------------------------------------------------------------------------
1 | *
2 |
3 | !.gitignore
4 |
5 | !vcs.xml
6 | !encodings.xml
7 | !codeStyleSettings.xml
8 | !misc.xml
9 |
10 | !runConfigurations
11 | !runConfigurations/*
12 |
13 | !modules
14 | !modules/*
--------------------------------------------------------------------------------
/.idea/misc.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
--------------------------------------------------------------------------------
/.idea/modules/MenuAPI.main.iml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 | SPIGOT
8 |
9 | 1
10 |
11 |
12 |
13 |
--------------------------------------------------------------------------------
/.idea/runConfigurations/Build_MenuAPI.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 | true
20 | true
21 | false
22 | false
23 |
24 |
25 |
--------------------------------------------------------------------------------
/.idea/runConfigurations/Clean_MenuAPI.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 | true
19 | true
20 | false
21 | false
22 |
23 |
24 |
--------------------------------------------------------------------------------
/.idea/runConfigurations/Publish_MenuAPI.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 | true
19 | true
20 | false
21 | false
22 |
23 |
24 |
--------------------------------------------------------------------------------
/.idea/vcs.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
--------------------------------------------------------------------------------
/LICENSE.md:
--------------------------------------------------------------------------------
1 | MIT License
2 |
3 | Copyright (c) 2024-Present J4C0B3Y
4 |
5 | Permission is hereby granted, free of charge, to any person obtaining a copy
6 | of this software and associated documentation files (the "Software"), to deal
7 | in the Software without restriction, including without limitation the rights
8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 | copies of the Software, and to permit persons to whom the Software is
10 | furnished to do so, subject to the following conditions:
11 |
12 | The above copyright notice and this permission notice shall be included in all
13 | copies or substantial portions of the Software.
14 |
15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21 | SOFTWARE.
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # MenuAPI
2 |
3 | Simple to use, high performance bukkit menu api.
4 |
5 | ## Features
6 |
7 | - Inbuilt paginated menus
8 | - Asynchronous menu option
9 | - Foreground & background layers
10 | - Reusable layer templates
11 | - Auto update annotation
12 | - Small and lightweight (~22kb)
13 | - Inbuilt item builder utility
14 | - Supports spigot 1.8+
15 |
16 | ## Support
17 |
18 | If you need any assistance using or installing my MenuAPI,
19 | feel free to contact me by either adding me on discord (@J4C0B3Y)
20 | or by creating an issue and explaining your problem or question.
21 |
22 | ## Installation
23 |
24 | Prebuilt jars can be found in [releases](https://github.com/J4C0B3Y/MenuAPI/releases).
25 |
26 | > **NOTE:**
27 | > It is recommended to relocate the library to prevent
28 | > version mismatches with other plugins that use the api.
29 |
30 | ### Maven & Gradle
31 |
32 | Replace `VERSION` with the latest release version on GitHub.
33 |
34 | ```kts
35 | repositories {
36 | maven("https://repo.j4c0b3y.net/public/")
37 | }
38 |
39 | dependencies {
40 | implementation("net.j4c0b3y:MenuAPI-core:VERSION")
41 | }
42 | ```
43 |
44 | ```xml
45 |
46 |
47 | j4c0b3y-public
48 | https://repo.j4c0b3y.net/public/
49 |
50 |
51 |
52 |
53 |
54 | net.j4c0b3y
55 | MenuAPI-core
56 | VERSION
57 |
58 |
59 | ```
60 |
61 | ### Building
62 |
63 | 1. Clone this repository and enter its directory.
64 | 2. Run the intellij build configuration by clicking the top right icon.
65 | 3. Alternatively you can run `gradle shadowJar`.
66 |
67 | ## Usage
68 |
69 | A MenuHandler instance is required before opening any menus.
70 |
71 | ```java
72 | public class ExamplePlugin extends JavaPlugin {
73 | private MenuHandler menuHandler;
74 |
75 | @Override
76 | public void onEnable() {
77 | this.menuHandler = new MenuHandler(this);
78 | }
79 | }
80 | ```
81 |
82 | Optionally, you can change default menu behaviour.
83 |
84 | ```java
85 | // Reset the cursor to the center when switching between menus.
86 | menuHandler.setResetCursor(true);
87 |
88 | // Close the menu when Menu#back() is called and there is no previous menu.
89 | menuHandler.setCloseOnBack(true);
90 | ```
91 |
92 | ### Menus
93 |
94 | To make a menu, all you need to do is extend the `Menu` class.
95 |
96 | ```java
97 | public class ExampleMenu extends Menu {
98 |
99 | public ExampleMenu(Player player) {
100 | // You must specify the title, size and
101 | // player when calling the super constructor.
102 | super("Example Menu", MenuSize.THREE, player);
103 | }
104 |
105 | @Override
106 | public void setup(BackgroundLayer background, ForegroundLayer foreground) {
107 | // Here you can add buttons to the foreground and background layers.
108 | // This method is called the first time the menu is opened.
109 | // See layers & templates further down for more information.
110 | }
111 | }
112 | ```
113 |
114 | There are some optional methods you can use to listen to certain menu actions.
115 |
116 | ```java
117 | @Override
118 | public void onOpen() {
119 | // Called when the menu is opened.
120 | }
121 |
122 | @Override
123 | public void onClose() {
124 | // Called when the menu is closed.
125 | }
126 | ```
127 |
128 | To make a menu asynchronous you can annotate the class with `@Async`.
129 |
130 | > **WARNING:**
131 | > Using bukkit api methods in async menus is not recommended, this is
132 | > because the buttons and menu methods are not called on the server thread.
133 |
134 | ```java
135 | @Async // Annotate the class with @Async
136 | public class ExampleMenu extends Menu {
137 | // ...
138 | }
139 | ```
140 |
141 | To use the `Menu#back()` method, you must set the previous menu in the constructor.
142 |
143 | If the previous menu is not set and the back method is called, by default
144 | nothing will happen unless `menuHandler.setCloseOnBack(true)` is set.
145 |
146 | ```java
147 | public ExampleMenu(Menu previous) {
148 | super("Example Menu", MenuSize.THREE, previous.getPlayer());
149 | setPreviousMenu(previous);
150 | }
151 | ```
152 |
153 | Here is how you open the menu for the player.
154 |
155 | ```java
156 | new ExampleMenu(player).open()
157 | ```
158 |
159 | To close the menu you can do one of two things, both achieve the same thing.
160 |
161 | ```java
162 | menu.close();
163 | // or
164 | player.closeInventory();
165 | ```
166 |
167 | There are two ways to update menus, the first way is to call `Menu#update()`.
168 |
169 | Alternatively, you can make a menu auto update by annotating it with `@AutoUpdate`.
170 |
171 | ```java
172 | // You can specify the update interval in ticks.
173 | // Remember 20 ticks is equal to 1 second.
174 | @AutoUpdate(20)
175 | public class ExampleMenu { }
176 | ```
177 |
178 | ### Buttons
179 |
180 | You must create an item / icon for the button to display in the menu.
181 |
182 | ```java
183 | public class ExampleButton extends Button {
184 |
185 | @Override
186 | public ItemStack getIcon() {
187 | // If you have an ItemBuilder util, you should use that.
188 | ItemStack icon = new ItemStack(Material.WOOL);
189 | ItemMeta meta = icon.getItemMeta();
190 |
191 | meta.setDisplayName("Example Button");
192 |
193 | icon.setItemMeta(meta);
194 | return icon;
195 | }
196 |
197 | @Override
198 | public void onClick(ButtonClick click) {
199 | // This method is called when your button is clicked.
200 | if (!click.getType().equals(ClickType.LEFT)) return;
201 |
202 | // Do something here.
203 | }
204 | }
205 | ```
206 |
207 | ### Layers
208 |
209 | A menu has two layers to place buttons on, the background and the foreground.
210 |
211 | - The background layer should obviously be used for the menu background, border design, etc.
212 | - The foreground layer should be used for functional buttons, a back button, etc.
213 |
214 | You can use a variety of methods for adding buttons to a layer,
215 | there are javadocs on each method but here is an example.
216 |
217 | ```java
218 | public class ExampleMenu extends Menu {
219 | // ...
220 |
221 | @Override
222 | public void setup(BackgroundLayer background, ForegroundLayer foreground) {
223 | background.border(new PlaceholderButton());
224 |
225 | foreground.set(1, 1, new TeamButton(Team.RED));
226 | foreground.set(3, 1, new TeamButton(Team.BLUE));
227 | foreground.set(5, 1, new TeamButton(Team.GREEN));
228 | foreground.set(7, 1, new TeamButton(Team.YELLOW));
229 | }
230 | }
231 | ```
232 |
233 | If a button returns a null icon, it will not be placed in the menu.
234 |
235 | This makes layers powerful as the background button will be used
236 | if a foreground button in the same slot returns null.
237 |
238 | An example on why this is useful is making a back button that returns the item only if
239 | there is a previous menu otherwise it will be ignored and use the button on the background.
240 |
241 | ### Templates
242 |
243 | Templates can be utilized to make reusable menu designs easily, here is an example.
244 |
245 | ```java
246 | @RequiredArgsConstructor
247 | public class BorderTemplate implements Template {
248 | private final Menu menu;
249 |
250 | @Override
251 | public void apply(BackgroundLayer background, ForegroundLayer foreground) {
252 | background.border(new PlaceholderButton());
253 | foreground.set(0, new BackButton(menu));
254 | }
255 | }
256 | ```
257 |
258 | You can then apply the template in the menu's setup method.
259 |
260 | ```java
261 | public class ExampleMenu extends Menu {
262 | // ...
263 |
264 | @Override
265 | public void setup(BackgroundLayer background, ForegroundLayer foreground) {
266 | apply(new BorderTemplate(this));
267 |
268 | // You can then add menu specific buttons.
269 | }
270 | }
271 | ```
272 |
273 | ### Paginated Menus
274 |
275 | To make a paginated menu, extend the `PaginatedMenu` class.
276 |
277 | ```java
278 | public class TagsMenu extends PaginatedMenu {
279 | // ...
280 |
281 | // It is recommended to put all this in a PaginationTemplate
282 | // so this doesn't have to be copied each time you make a menu.
283 | @Override
284 | public void setup(BackgroundLayer background, ForegroundLayer foreground) {
285 | background.border(new PlaceholderButton());
286 | foreground.set(0, new BackButton(this));
287 |
288 | // Add the inbuilt pagination slot button where
289 | // you want your paginated buttons / entries to go.
290 | // NOTE: You cannot add pagination slots to the background layer.
291 | foreground.center(new PaginationSlot());
292 |
293 | // You can also add your own previous page and next page buttons.
294 | foreground.set(0, menu.getRows() - 1, new PreviousPageButton(menu));
295 | foreground.set(Menu.COLUMNS - 1, menu.getRows() - 1, new NextPageButton(menu));
296 | }
297 |
298 | // Here you create a list of the buttons that you want
299 | // to be paginated and put in the pagination slots added above.
300 | @Override
301 | public List getEntries() {
302 | List buttons = new ArrayList();
303 |
304 | for (Tag tag : plugin.getTagHandler().getTags()) {
305 | buttons.add(new TagButton(tag));
306 | }
307 |
308 | return buttons;
309 | }
310 | }
311 | ```
312 |
313 | Here are some pagination menu specific methods you can use.
314 |
315 | ```java
316 | // Changes the page and updates the menu.
317 | menu.page(int page);
318 | menu.next();
319 | menu.previous();
320 |
321 | // Get information about the paginated menu.
322 | menu.getPage();
323 | menu.getTotalPages();
324 | menu.hasNextPage();
325 | menu.hasPreviousPage();
326 |
327 | // More can be found in the pagination menu class.
328 | ```
329 |
330 | ### Item Builder Utility
331 |
332 | The menu api contains a utility class for creating item stacks using a builder.
333 |
334 | Since the builder heavily utilizes XSeries, the library will contain many extra classes resulting in increased size,
335 | the utility is contained in a separate package called `MenuAPI-extras`, which should be added in your build configuration.
336 |
337 | Here is an example of its usage, refer to it's javadocs for more information:
338 |
339 | ```java
340 | ItemStack item = new Item(XMaterial.PLAYER_HEAD) // Uses XSeries throughout
341 | .setName("&c&lTest") // Set the item's display name.
342 | .addLore("&7Test lore") // You can also use setLore.
343 | .setAmount(10) // Set the quantity of items in the item stack.
344 | .setUnbreakable() // You can optionally put a boolean here.
345 | .addEnchantment(XEnchantment.AQUA_AFFINITY, 3) // You can use unsafe levels.
346 | .addFlag(XItemFlag.HIDE_ENCHANTS) // Add item flags to the item.
347 | .setTexture("J4C0B3Y") // Can be uuid, username, base64, etc.
348 | .setData((short) 3) // Set the data / durability of the item.
349 | .build(); // Finalize the item, converting it into the item stack.
350 | ```
351 |
352 | You can change how the name and lore is translated by setting the translator.
353 |
354 | ```java
355 | // Specific to item instance:
356 | ItemStack item = new Item()
357 | .setName("Some text.")
358 | .setFormatter(Color::translate)
359 | .build();
360 |
361 | // Set for any future Item instances created.
362 | Item.setDefaultFormatter(Color::translate);
363 | ```
364 |
365 | ### Want more?
366 |
367 | Each and every class in my menu api has detailed javadocs explaining what
368 | methods and variables are used for, and functionality of internal methods.
369 |
370 | > Made with ❤ // J4C0B3Y 2024
371 |
--------------------------------------------------------------------------------
/build.gradle.kts:
--------------------------------------------------------------------------------
1 | import com.github.jengelman.gradle.plugins.shadow.tasks.ShadowJar
2 | import java.nio.charset.StandardCharsets
3 | import kotlin.io.path.Path
4 |
5 | plugins {
6 | java
7 | `maven-publish`
8 | id("io.freefair.lombok") version "8.12.1"
9 | id("com.gradleup.shadow") version "9.0.0-beta8"
10 | }
11 |
12 | object Project {
13 | const val NAME = "MenuAPI"
14 | const val GROUP = "net.j4c0b3y"
15 | const val VERSION = "1.5.2"
16 | }
17 |
18 | allprojects {
19 | repositories {
20 | mavenCentral()
21 | }
22 | }
23 |
24 | subprojects {
25 | apply(plugin = "java")
26 | apply(plugin = "io.freefair.lombok")
27 | apply(plugin = "maven-publish")
28 | apply(plugin = "com.gradleup.shadow")
29 |
30 | java {
31 | sourceCompatibility = JavaVersion.VERSION_1_8
32 | targetCompatibility = JavaVersion.VERSION_1_8
33 | withSourcesJar()
34 | }
35 |
36 | tasks {
37 | compileJava {
38 | options.encoding = StandardCharsets.UTF_8.name()
39 | }
40 |
41 | register("copy") {
42 | from(shadowJar)
43 | rename("(.*)-all.jar", "${Project.NAME}-${this@subprojects.name}-${Project.VERSION}.jar")
44 | into(Path(rootDir.path, "jars"))
45 | }
46 |
47 | build { dependsOn(named("copy")) }
48 | }
49 |
50 | publishing {
51 | repositories {
52 | maven("https://repo.j4c0b3y.net/public/") {
53 | name = "j4c0b3yPublic"
54 |
55 | credentials(PasswordCredentials::class)
56 |
57 | authentication {
58 | create("basic")
59 | }
60 | }
61 | }
62 |
63 | publications {
64 | create(name) {
65 | artifactId = Project.NAME + "-" + name
66 | groupId = Project.GROUP
67 | version = Project.VERSION
68 |
69 | artifact(tasks.named("shadowJar").get().archiveFile)
70 |
71 | artifact(tasks.named("sourcesJar").get().archiveFile) {
72 | classifier = "sources"
73 | }
74 | }
75 | }
76 | }
77 | }
78 |
79 |
80 |
--------------------------------------------------------------------------------
/core/build.gradle.kts:
--------------------------------------------------------------------------------
1 | repositories {
2 | maven("https://repo.codemc.io/repository/nms/")
3 | }
4 |
5 | dependencies {
6 | compileOnly("org.spigotmc:spigot:1.8.8-R0.1-SNAPSHOT")
7 | }
--------------------------------------------------------------------------------
/core/src/main/java/net/j4c0b3y/api/menu/Menu.java:
--------------------------------------------------------------------------------
1 | package net.j4c0b3y.api.menu;
2 |
3 | import lombok.Getter;
4 | import lombok.Setter;
5 | import net.j4c0b3y.api.menu.annotation.Async;
6 | import net.j4c0b3y.api.menu.button.Button;
7 | import net.j4c0b3y.api.menu.button.ButtonClick;
8 | import net.j4c0b3y.api.menu.layer.impl.BackgroundLayer;
9 | import net.j4c0b3y.api.menu.layer.impl.ForegroundLayer;
10 | import net.j4c0b3y.api.menu.template.Template;
11 | import net.j4c0b3y.api.menu.utils.Position;
12 | import org.bukkit.Bukkit;
13 | import org.bukkit.entity.Player;
14 | import org.bukkit.event.inventory.InventoryClickEvent;
15 | import org.bukkit.inventory.Inventory;
16 | import org.bukkit.inventory.ItemStack;
17 |
18 | import java.util.HashMap;
19 | import java.util.Map;
20 |
21 | /**
22 | * A wrapper around a bukkit inventory with
23 | * buttons, layers, and async functionality.
24 | *
25 | * @author J4C0B3Y
26 | * @version MenuAPI
27 | * @since 12/05/2024
28 | */
29 | @Getter
30 | public abstract class Menu {
31 | /**
32 | * The in game chest inventory width.
33 | */
34 | public static final int COLUMNS = 9;
35 |
36 | /**
37 | * The menu handler the menu should use.
38 | */
39 | private final MenuHandler handler;
40 |
41 | /**
42 | * The buttons shown inside the inventory.
43 | */
44 | private final Map buttons = new HashMap<>();
45 |
46 | /**
47 | * The player associated with the menu.
48 | */
49 | private final Player player;
50 |
51 | /**
52 | * The underlying bukkit inventory the player sees.
53 | */
54 | private final Inventory inventory;
55 |
56 | /**
57 | * The title shown at the top of the inventory.
58 | */
59 | private final String title;
60 |
61 | /**
62 | * The menu size in rows.
63 | */
64 | private final int rows;
65 |
66 | /**
67 | * The menu's foreground layer.
68 | */
69 | private final ForegroundLayer foreground = new ForegroundLayer(this);
70 |
71 | /**
72 | * The menu's background layer.
73 | */
74 | private final BackgroundLayer background = new BackgroundLayer(this);
75 |
76 | /**
77 | * The previous menu, if present.
78 | */
79 | @Setter private Menu previousMenu;
80 |
81 | /**
82 | * If the menu should be asynchronous.
83 | */
84 | private final boolean async;
85 |
86 | /**
87 | * The last tick that the menu was updated.
88 | */
89 | private long lastUpdate = 0;
90 |
91 | /**
92 | * If the menu's buttons have been set up.
93 | */
94 | private boolean setup = false;
95 |
96 | /**
97 | * Creates a new menu, initializing the underlying bukkit inventory.
98 | *
99 | * @param title The title, auto translated.
100 | * @param size The menu size, in rows.
101 | * @param player The player to open the menu with.
102 | * @param handler The handler to open the menu with.
103 | */
104 | public Menu(String title, MenuSize size, Player player, MenuHandler handler) {
105 | this.title = title;
106 | this.rows = size.getRows();
107 | this.player = player;
108 | this.handler = handler;
109 |
110 | if (this.handler == null) {
111 | throw new IllegalStateException("No menu handler instance found.");
112 | }
113 |
114 | this.inventory = Bukkit.createInventory(player, getTotalSlots(), this.title);
115 | this.async = getClass().isAnnotationPresent(Async.class);
116 | }
117 |
118 | /**
119 | * Creates a new menu, initializing the underlying bukkit inventory.
120 | *
121 | * @param title The title, auto translated.
122 | * @param size The menu size, in rows.
123 | * @param player The player to open the menu with.
124 | */
125 | public Menu(String title, MenuSize size, Player player) {
126 | this(title, size, player, MenuHandler.getInstance());
127 | }
128 |
129 | /**
130 | * Used for setting up the menu layout,
131 | * called when the inventory is first opened.
132 | *
133 | * @param background The background layer.
134 | * @param foreground The foreground layer.
135 | */
136 | public abstract void setup(BackgroundLayer background, ForegroundLayer foreground);
137 |
138 | /**
139 | * Called when the menu opens.
140 | */
141 | public void onOpen() { }
142 |
143 | /**
144 | * Called when the menu closes.
145 | */
146 | public void onClose() { }
147 |
148 | /**
149 | * Opens the menu, closing any existing menus if they are open.
150 | * The setup method is called on the first invocation of this method.
151 | */
152 | public void open() {
153 | // This will schedule at most 1 task using the bukkit scheduler.
154 | // Usually none, except when the menu is async or the menu is
155 | // sync and opened not on the server thread.
156 | handler.schedule(() -> {
157 | if (!setup) {
158 | setup(background, foreground);
159 | setup = true;
160 | }
161 |
162 | refresh();
163 |
164 | handler.schedule(() -> {
165 | Menu existing = handler.getOpenMenus().get(player);
166 |
167 | if (existing == null) {
168 | player.closeInventory();
169 | } else {
170 | existing.close(handler.isResetCursor());
171 | }
172 |
173 | player.openInventory(inventory);
174 | handler.getOpenMenus().put(player, this);
175 | handler.run(this::onOpen, async);
176 | });
177 | }, async);
178 | }
179 |
180 | /**
181 | * Removes the player from the open menus map.
182 | *
183 | * @param exit If the player's inventory should be closed.
184 | */
185 | public void close(boolean exit) {
186 | if (exit) {
187 | player.closeInventory();
188 | }
189 |
190 | handler.getOpenMenus().remove(player, this);
191 | handler.run(this::onClose, async);
192 | }
193 |
194 | /**
195 | * Closes the menu and removes the player from the open menus map.
196 | */
197 | public void close() {
198 | close(true);
199 | }
200 |
201 | /**
202 | * Merges layers and updates the inventory contents.
203 | */
204 | protected void refresh() {
205 | lastUpdate = handler.getAutoUpdateTask().getTicks();
206 | buttons.clear();
207 |
208 | ItemStack[] icons = new ItemStack[getTotalSlots()];
209 | buttons.putAll(foreground.getButtons(icons));
210 | buttons.putAll(background.getButtons(icons));
211 |
212 | handler.schedule(() -> {
213 | inventory.setContents(icons);
214 | player.updateInventory();
215 | });
216 | }
217 |
218 | /**
219 | * Updates the inventory buttons shown in the menu.
220 | */
221 | public void update() {
222 | handler.schedule(this::refresh, async);
223 | }
224 |
225 | /**
226 | * Returns to the previous menu, if the handler
227 | * has closeOnBack set and there is no previous
228 | * menu, then the menu will close.
229 | */
230 | public void back() {
231 | if (previousMenu != null) {
232 | previousMenu.open();
233 | return;
234 | }
235 |
236 | if (handler.isCloseOnBack()) {
237 | close();
238 | }
239 | }
240 |
241 | /**
242 | * Applies a template to the background and foreground layers.
243 | *
244 | * @param template The template to apply.
245 | */
246 | public void apply(Template template) {
247 | template.apply(background, foreground);
248 | }
249 |
250 | /**
251 | * Handles a menu click, sending the click to the slot's button.
252 | *
253 | * @param event The inventory click event.
254 | */
255 | public void click(InventoryClickEvent event) {
256 | handler.schedule(() -> {
257 | Button button = buttons.get(event.getRawSlot());
258 | if (button == null) return;
259 |
260 | button.onClick(new ButtonClick(event, button, this));
261 | }, async);
262 | }
263 |
264 | /**
265 | * Checks if there is a previous menu set.
266 | *
267 | * @return If there is a previous menu.
268 | */
269 | public boolean hasPreviousMenu() {
270 | return previousMenu != null;
271 | }
272 |
273 | /**
274 | * Gets the maximum slots in the menu.
275 | *
276 | * @return The total slots.
277 | */
278 | public int getTotalSlots() {
279 | return rows * COLUMNS;
280 | }
281 |
282 | /**
283 | * Converts x and y coordinates from the
284 | * top left of the menu into an index.
285 | *
286 | * @param x The x coordinate.
287 | * @param y The y coordinate
288 | * @return The index of the coordinates.
289 | */
290 | public int getIndex(int x, int y) {
291 | return y * COLUMNS + x;
292 | }
293 |
294 | /**
295 | * Converts an index into x and y
296 | * coordinates from the top left of the menu.
297 | *
298 | * @param index The index of the slot.
299 | * @return The x and y coordinates.
300 | */
301 | public Position getPosition(int index) {
302 | return new Position(index % COLUMNS, index / COLUMNS);
303 | }
304 | }
305 |
--------------------------------------------------------------------------------
/core/src/main/java/net/j4c0b3y/api/menu/MenuHandler.java:
--------------------------------------------------------------------------------
1 | package net.j4c0b3y.api.menu;
2 |
3 |
4 | import lombok.Getter;
5 | import lombok.Setter;
6 | import net.j4c0b3y.api.menu.listener.InventoryListener;
7 | import net.j4c0b3y.api.menu.task.AutoUpdateTask;
8 | import org.bukkit.Bukkit;
9 | import org.bukkit.entity.Player;
10 | import org.bukkit.plugin.java.JavaPlugin;
11 |
12 | import java.util.Map;
13 | import java.util.concurrent.CompletableFuture;
14 | import java.util.concurrent.ConcurrentHashMap;
15 | import java.util.function.Consumer;
16 |
17 | /**
18 | * Stores open menus, menu options, starts tasks
19 | * and registers listeners for menus to function.
20 | *
21 | * @author J4C0B3Y
22 | * @version MenuAPI
23 | * @since 12/05/2024
24 | */
25 | @Getter
26 | public class MenuHandler {
27 | /**
28 | * The menu handler instance.
29 | */
30 | @Getter private static MenuHandler instance;
31 |
32 | /**
33 | * The plugin to register listeners and start tasks with.
34 | */
35 | private final JavaPlugin plugin;
36 |
37 | /**
38 | * Stores menus that players have open.
39 | */
40 | private final Map openMenus = new ConcurrentHashMap<>();
41 |
42 | /**
43 | * Handles auto updating menus.
44 | */
45 | private final AutoUpdateTask autoUpdateTask;
46 |
47 | /**
48 | * If the cursor position should
49 | * reset when switching between menus.
50 | */
51 | @Setter private boolean resetCursor = false;
52 |
53 | /**
54 | * If the menu should close when the back
55 | * method is called and there is no previous menu.
56 | */
57 | @Setter private boolean closeOnBack = false;
58 |
59 | /**
60 | * Creates a new menu handler, starting the autoupdating
61 | * task and registering inventory and connection listeners.
62 | *
63 | * @param plugin The plugin to register listeners and start tasks with.
64 | */
65 | public MenuHandler(JavaPlugin plugin) {
66 | instance = this;
67 |
68 | this.plugin = plugin;
69 | this.autoUpdateTask = new AutoUpdateTask(this);
70 |
71 | Bukkit.getScheduler().runTaskTimer(plugin, autoUpdateTask, 0, 1);
72 | Bukkit.getPluginManager().registerEvents(new InventoryListener(this), plugin);
73 | }
74 |
75 | /**
76 | * Executes a callback if the
77 | * specified player has an open menu.
78 | *
79 | * @param player The player to check.
80 | * @param callback The callback to execute.
81 | */
82 | public void ifOpen(Player player, Consumer callback) {
83 | Menu menu = openMenus.get(player);
84 | if (menu != null) callback.accept(menu);
85 | }
86 |
87 | /**
88 | * Displays a warning message that comes
89 | * from the plugin associated with the handler.
90 | *
91 | * @param message The warning message.
92 | */
93 | public void warning(String message) {
94 | plugin.getLogger().warning("[MenuAPI] " + message);
95 | }
96 |
97 | /**
98 | * Runs a task on the server thread.
99 | *
100 | * @param task The task to run.
101 | */
102 | protected void schedule(Runnable task) {
103 | if (Bukkit.isPrimaryThread()) {
104 | task.run();
105 | } else {
106 | Bukkit.getScheduler().runTask(plugin, task);
107 | }
108 | }
109 |
110 | /**
111 | * Runs a task using the bukkit scheduler.
112 | *
113 | * @param task The task to run.
114 | * @param async If the task should be run asynchronously.
115 | */
116 | protected void schedule(Runnable task, boolean async) {
117 | if (async) {
118 | CompletableFuture.runAsync(task);
119 | } else {
120 | schedule(task);
121 | }
122 | }
123 |
124 | /**
125 | * Runs a task asynchronously.
126 | *
127 | * @param task The task to run.
128 | * @param async If the task should be run asynchronously.
129 | */
130 | protected void run(Runnable task, boolean async) {
131 | if (async) {
132 | CompletableFuture.runAsync(task);
133 | } else {
134 | task.run();
135 | }
136 | }
137 | }
138 |
--------------------------------------------------------------------------------
/core/src/main/java/net/j4c0b3y/api/menu/MenuSize.java:
--------------------------------------------------------------------------------
1 | package net.j4c0b3y.api.menu;
2 |
3 | import lombok.Getter;
4 | import lombok.RequiredArgsConstructor;
5 |
6 | /**
7 | * The possible sizes for a bukkit inventory.
8 | *
9 | * @author J4C0B3Y
10 | * @version MenuAPI
11 | * @since 12/05/2024
12 | */
13 | @Getter
14 | @RequiredArgsConstructor
15 | public enum MenuSize {
16 | /**
17 | * A menu with three rows.
18 | */
19 | THREE(3),
20 |
21 | /**
22 | * A menu with four rows.
23 | */
24 | FOUR(4),
25 |
26 | /**
27 | * A menu with five rows.
28 | */
29 | FIVE(5),
30 |
31 | /**
32 | * A menu with six rows.
33 | */
34 | SIX(6);
35 |
36 | /**
37 | * How many rows the menu has.
38 | */
39 | private final int rows;
40 |
41 | /**
42 | * Returns the menu size using the input number,
43 | * which can be either the amount of rows or slots.
44 | *
45 | * @param input The rows or slots.
46 | * @return The associated menu size.
47 | */
48 | public static MenuSize of(int input) {
49 | for (MenuSize size : MenuSize.values()) {
50 | int rows = size.getRows();
51 |
52 | if (rows == input || rows == input * Menu.COLUMNS) {
53 | return size;
54 | }
55 | }
56 |
57 | throw new IllegalArgumentException("There is no menu size with " + input + " rows or slots!");
58 | }
59 | }
60 |
--------------------------------------------------------------------------------
/core/src/main/java/net/j4c0b3y/api/menu/annotation/Async.java:
--------------------------------------------------------------------------------
1 | package net.j4c0b3y.api.menu.annotation;
2 |
3 | import java.lang.annotation.ElementType;
4 | import java.lang.annotation.Retention;
5 | import java.lang.annotation.RetentionPolicy;
6 | import java.lang.annotation.Target;
7 |
8 | /**
9 | * Marks the menu as asynchronous.
10 | *
11 | * @author J4C0B3Y
12 | * @version MenuAPI
13 | * @since 22/05/2024
14 | */
15 | @Target(ElementType.TYPE)
16 | @Retention(RetentionPolicy.RUNTIME)
17 | public @interface Async {
18 | }
19 |
--------------------------------------------------------------------------------
/core/src/main/java/net/j4c0b3y/api/menu/annotation/AutoUpdate.java:
--------------------------------------------------------------------------------
1 | package net.j4c0b3y.api.menu.annotation;
2 |
3 | import java.lang.annotation.ElementType;
4 | import java.lang.annotation.Retention;
5 | import java.lang.annotation.RetentionPolicy;
6 | import java.lang.annotation.Target;
7 |
8 | /**
9 | * Marks the menu for auto updating
10 | * using the specified tick interval.
11 | *
12 | * @author J4C0B3Y
13 | * @version MenuAPI
14 | * @since 12/05/2024
15 | */
16 | @Target(ElementType.TYPE)
17 | @Retention(RetentionPolicy.RUNTIME)
18 | public @interface AutoUpdate {
19 | /**
20 | * The interval in ticks to auto update the menu.
21 | *
22 | * @return The auto update ticks.
23 | */
24 | int value();
25 | }
26 |
--------------------------------------------------------------------------------
/core/src/main/java/net/j4c0b3y/api/menu/button/Button.java:
--------------------------------------------------------------------------------
1 | package net.j4c0b3y.api.menu.button;
2 |
3 | import org.bukkit.inventory.ItemStack;
4 |
5 | /**
6 | * A menu button, used to display an icon
7 | * and a click handler for the inventory item.
8 | *
9 | * @author J4C0B3Y
10 | * @version MenuAPI
11 | * @since 12/05/2024
12 | */
13 | public abstract class Button {
14 | /**
15 | * Gets the button's display item stack, this can
16 | * be null if the button should not be displayed.
17 | *
18 | * @return The buttons icon.
19 | */
20 | public abstract ItemStack getIcon();
21 |
22 | /**
23 | * Called when the button is clicked,
24 | * this can be ignored by the onClick
25 | * handler in the button's menu.
26 | *
27 | * @param click The button click.
28 | */
29 | public void onClick(ButtonClick click) { }
30 | }
31 |
--------------------------------------------------------------------------------
/core/src/main/java/net/j4c0b3y/api/menu/button/ButtonClick.java:
--------------------------------------------------------------------------------
1 | package net.j4c0b3y.api.menu.button;
2 |
3 | import lombok.AccessLevel;
4 | import lombok.Getter;
5 | import net.j4c0b3y.api.menu.Menu;
6 | import org.bukkit.event.inventory.ClickType;
7 | import org.bukkit.event.inventory.InventoryClickEvent;
8 |
9 | /**
10 | * Stores information about a player clicking a menu.
11 | *
12 | * @author J4C0B3Y
13 | * @version MenuAPI
14 | * @since 12/05/2024
15 | */
16 | @Getter
17 | public class ButtonClick {
18 | /**
19 | * The underlying click event.
20 | */
21 | @Getter(AccessLevel.NONE)
22 | private final InventoryClickEvent event;
23 |
24 | /**
25 | * The menu that was clicked.
26 | */
27 | private final Menu menu;
28 |
29 | /**
30 | * The button that was clicked, this can be
31 | * null if the click was outside the inventory.
32 | */
33 | private final Button button;
34 |
35 | /**
36 | * Creates a new button click, extracting
37 | * values from the underlying click event.
38 | *
39 | * @param event The click event.
40 | * @param button The clicked button, can be null.
41 | * @param menu The clicked menu.
42 | */
43 | public ButtonClick(InventoryClickEvent event, Button button, Menu menu) {
44 | this.event = event;
45 | this.menu = menu;
46 | this.button = button;
47 | }
48 |
49 | /**
50 | * @return The type of click.
51 | */
52 | public ClickType getType() {
53 | return event.getClick();
54 | }
55 |
56 | /**
57 | * @return The slot of the click.
58 | */
59 | public int getSlot() {
60 | return event.getSlot();
61 | }
62 | }
63 |
--------------------------------------------------------------------------------
/core/src/main/java/net/j4c0b3y/api/menu/layer/Layer.java:
--------------------------------------------------------------------------------
1 | package net.j4c0b3y.api.menu.layer;
2 |
3 | import lombok.Getter;
4 | import lombok.RequiredArgsConstructor;
5 | import net.j4c0b3y.api.menu.Menu;
6 | import net.j4c0b3y.api.menu.button.Button;
7 | import net.j4c0b3y.api.menu.pagination.PaginationSlot;
8 | import net.j4c0b3y.api.menu.utils.Position;
9 | import org.bukkit.inventory.ItemStack;
10 |
11 | import java.util.*;
12 |
13 | /**
14 | * Represents a layer of buttons in a menu with
15 | * many methods to manipulate the layer's content.
16 | *
17 | * @author J4C0B3Y
18 | * @version MenuAPI
19 | * @since 12/05/2024
20 | */
21 | @Getter
22 | @RequiredArgsConstructor
23 | public abstract class Layer {
24 | /**
25 | * The menu the layer belongs to.
26 | */
27 | private final Menu menu;
28 |
29 | /**
30 | * The buttons in the layer, this is a tree map in the
31 | * foreground so the buttons are sorted for pagination.
32 | */
33 | private final Map buttons;
34 |
35 | /**
36 | * The name of the layer which
37 | * is used in warning messages.
38 | *
39 | * @return The name of the layer.
40 | */
41 | public abstract String getName();
42 |
43 | /**
44 | * Sets a button using an index,
45 | * validates if the placement is legal.
46 | *
47 | * @param index The index.
48 | * @param button The button to set.
49 | */
50 | public void set(int index, Button button) {
51 | if (isInvalid(button, index)) {
52 | return;
53 | }
54 |
55 | buttons.put(index, button);
56 | }
57 |
58 | /**
59 | * Sets a button using x and y coordinates.
60 | *
61 | * @param x The x coordinate.
62 | * @param y The y coordinate.
63 | * @param button The button to set.
64 | */
65 | public void set(int x, int y, Button button) {
66 | set(menu.getIndex(x, y), button);
67 | }
68 |
69 | /**
70 | * Sets a button using a position.
71 | *
72 | * @param position The position.
73 | * @param button The button to set.
74 | */
75 | public void set(Position position, Button button) {
76 | set(position.getX(), position.getY(), button);
77 | }
78 |
79 | /**
80 | * Adds a button to the next available slot,
81 | * checking the other layer if present.
82 | *
83 | * @param button The button to add.
84 | * @param other The other layer to check.
85 | */
86 | protected void add(Button button, Layer other) {
87 | for (int i = 0; i < menu.getTotalSlots(); i++) {
88 | if (buttons.get(i) != null) {
89 | continue;
90 | }
91 |
92 | if (other != null && other.getButtons().get(i) != null) {
93 | continue;
94 | }
95 |
96 | set(i, button);
97 | return;
98 | }
99 | }
100 |
101 | /**
102 | * Adds a button to the next available slot.
103 | *
104 | * @param button The button to add.
105 | * @param other If the other layer should be checked.
106 | */
107 | public void add(Button button, boolean other) {
108 | add(button, null);
109 | }
110 |
111 | /**
112 | * Adds a button to the next available slot,
113 | * checking slots in the other layer as well.
114 | *
115 | * @param button The button to add.
116 | */
117 | public void add(Button button) {
118 | add(button, true);
119 | }
120 |
121 | /**
122 | * Fills the whole layer with a button.
123 | *
124 | * @param button The button to fill.
125 | */
126 | public void fill(Button button) {
127 | for (int i = 0; i < menu.getTotalSlots(); i++) {
128 | set(i, button);
129 | }
130 | }
131 |
132 | /**
133 | * Fills a button between two x and y coordinates.
134 | *
135 | * @param ax The first x coordinate.
136 | * @param ay The first y coordinate.
137 | * @param bx The second x coordinate.
138 | * @param by The second y coordinate.
139 | * @param button The button to fill.
140 | */
141 | public void fill(int ax, int ay, int bx, int by, Button button) {
142 | int maxX = Math.max(ax, bx);
143 | int maxY = Math.max(ay, by);
144 |
145 | for (int x = Math.min(ax, bx); x <= maxX; x++) {
146 | for (int y = Math.min(ay, by); y <= maxY; y++) {
147 | set(x, y, button);
148 | }
149 | }
150 | }
151 |
152 | /**
153 | * Fills a button between two positions.
154 | *
155 | * @param a The first position.
156 | * @param b The second position.
157 | * @param button The button to fill.
158 | */
159 | public void fill(Position a, Position b, Button button) {
160 | fill(a.getX(), a.getY(), b.getX(), b.getY(), button);
161 | }
162 |
163 | /**
164 | * Fills a button between two slot indexes.
165 | *
166 | * @param a The first slot index.
167 | * @param b The second slot index.
168 | * @param button The button to fill.
169 | */
170 | public void fill(int a, int b, Button button) {
171 | fill(menu.getPosition(a), menu.getPosition(b), button);
172 | }
173 |
174 | /**
175 | * Fills a row with a button.
176 | *
177 | * @param row The row index.
178 | * @param button The button to fill.
179 | */
180 | public void row(int row, Button button) {
181 | for (int i = 0; i < Menu.COLUMNS; i++) {
182 | set(i, row, button);
183 | }
184 | }
185 |
186 | /**
187 | * Fills a column with a button.
188 | *
189 | * @param column The column index.
190 | * @param button The button to fill.
191 | */
192 | public void column(int column, Button button) {
193 | for (int i = 0; i < menu.getRows(); i++) {
194 | set(column, i, button);
195 | }
196 | }
197 |
198 | /**
199 | * Fills the border with a button.
200 | *
201 | * @param button The button to fill.
202 | */
203 | public void border(Button button) {
204 | row(0, button);
205 |
206 | if (menu.getRows() < 2) {
207 | return;
208 | }
209 |
210 | row(menu.getRows() - 1, button);
211 |
212 | if (menu.getRows() < 3) {
213 | return;
214 | }
215 |
216 | column(0, button);
217 | column(Menu.COLUMNS - 1, button);
218 | }
219 |
220 | /**
221 | * Fills the center using an inset with a button.
222 | *
223 | * @param button The button to fill.
224 | * @param inset The inset.
225 | */
226 | public void center(Button button, int inset) {
227 | if (menu.getRows() < inset * 2 + 1) {
228 | return;
229 | }
230 |
231 | if (inset < 1) {
232 | fill(button);
233 | return;
234 | }
235 |
236 | for (int x = inset; x < Menu.COLUMNS - inset; x++) {
237 | for (int y = inset; y < menu.getRows() - inset; y++) {
238 | set(x, y, button);
239 | }
240 | }
241 | }
242 |
243 | /**
244 | * Fills the center with a button.
245 | *
246 | * @param button The button to fill.
247 | */
248 | public void center(Button button) {
249 | center(button, 1);
250 | }
251 |
252 | /**
253 | * Removes a button using an index.
254 | *
255 | * @param index The index to remove.
256 | */
257 | public void remove(int index) {
258 | buttons.remove(index);
259 | }
260 |
261 | /**
262 | * Removes a button using x and y coordinates.
263 | *
264 | * @param x The x coordinate.
265 | * @param y The y coordinate.
266 | */
267 | public void remove(int x, int y) {
268 | remove(menu.getIndex(x, y));
269 | }
270 |
271 | /**
272 | * Removes a button using a position
273 | *
274 | * @param position The position.
275 | */
276 | public void remove(Position position) {
277 | remove(position.getX(), position.getY());
278 | }
279 |
280 | /**
281 | * Clears all buttons from the layer.
282 | */
283 | public void clear() {
284 | buttons.clear();
285 | }
286 |
287 | /**
288 | * Finds all buttons of a certain type.
289 | *
290 | * @param type The button class.
291 | * @return The matching buttons.
292 | */
293 | @SuppressWarnings("unchecked")
294 | public List getButtons(Class type) {
295 | List buttons = new ArrayList<>();
296 |
297 | for (Button button : this.buttons.values()) {
298 | if (type.isInstance(button)) {
299 | buttons.add((T) button);
300 | }
301 | }
302 |
303 | return buttons;
304 | }
305 |
306 | /**
307 | * Checks if a button to be set is invalid,
308 | * if so sends a warning message.
309 | *
310 | * @param button The button to check
311 | * @param index The index to check
312 | * @return If the button or index is invalid.
313 | */
314 | protected boolean isInvalid(Button button, int index) {
315 | if (button == null) {
316 | warning("null", null, index);
317 | return true;
318 | }
319 |
320 | if (index < 0 || index >= menu.getTotalSlots()) {
321 | warning("out of bounds", button, index);
322 | return true;
323 | }
324 |
325 | return false;
326 | }
327 |
328 | /**
329 | * Sends a warning for an incorrect button or
330 | * button placement with detailed information.
331 | *
332 | * @param reason The warning reason.
333 | * @param button The warning button.
334 | * @param slot The warning slot.
335 | */
336 | protected void warning(String reason, Button button, int slot) {
337 | menu.getHandler().warning(
338 | "Menu '" + menu.getClass().getSimpleName() +
339 | "' tried to add " + reason + " button '" +
340 | (button != null ? button.getClass().getSimpleName() : "unknown") +
341 | "' to layer '" + getName() + "' at index '" + slot +
342 | "' out of '" + menu.getTotalSlots() + "'."
343 | );
344 | }
345 |
346 | /**
347 | * Gets the buttons in the layer that don't already have a
348 | * position in the icons array and have a non-null icon.
349 | *
350 | * @param icons The existing icons.
351 | * @return The resulting buttons.
352 | */
353 | public Map getButtons(ItemStack[] icons) {
354 | Map buttons = new HashMap<>();
355 |
356 | this.buttons.forEach((slot, button) -> {
357 | // Return if the icons array already has an icon in the slot.
358 | if (icons != null && icons[slot] != null) {
359 | return;
360 | }
361 |
362 | // If the button is a pagination slot, set the icon
363 | // index so the slot can calculate which entry to show.
364 | if (button instanceof PaginationSlot) {
365 | ((PaginationSlot) button).setIconSlot(slot);
366 | }
367 |
368 | ItemStack icon = button.getIcon();
369 |
370 | // If the button has an icon, add it to the icon
371 | // array and to the slot-button map being returned.
372 | if (icon != null) {
373 | if (icons != null) icons[slot] = icon;
374 | buttons.put(slot, button);
375 | }
376 | });
377 |
378 | return buttons;
379 | }
380 | }
381 |
--------------------------------------------------------------------------------
/core/src/main/java/net/j4c0b3y/api/menu/layer/impl/BackgroundLayer.java:
--------------------------------------------------------------------------------
1 | package net.j4c0b3y.api.menu.layer.impl;
2 |
3 | import net.j4c0b3y.api.menu.Menu;
4 | import net.j4c0b3y.api.menu.button.Button;
5 | import net.j4c0b3y.api.menu.layer.Layer;
6 | import net.j4c0b3y.api.menu.pagination.PaginationSlot;
7 |
8 | import java.util.HashMap;
9 |
10 | /**
11 | * Represents a background layer in a menu with
12 | * many methods to manipulate the layer's content.
13 | *
14 | * @author J4C0B3Y
15 | * @version MenuAPI
16 | * @since 12/05/2024
17 | */
18 | public class BackgroundLayer extends Layer {
19 | /**
20 | * Creates a new background layer.
21 | *
22 | * @param menu The menu the layer belongs to.
23 | */
24 | public BackgroundLayer(Menu menu) {
25 | super(menu, new HashMap<>());
26 | }
27 |
28 | /**
29 | * Returns the name of the background layer.
30 | *
31 | * @return The background layer name.
32 | */
33 | @Override
34 | public String getName() {
35 | return "background";
36 | }
37 |
38 | /**
39 | * Adds a button to the next available slot,
40 | * checking slots in the foreground layer as well.
41 | *
42 | * @param button The button to add.
43 | * @param other If the foreground layer should be checked.
44 | */
45 | @Override
46 | public void add(Button button, boolean other) {
47 | add(button, other ? getMenu().getForeground() : null);
48 | }
49 |
50 | /**
51 | * Checks if a button to be set is invalid,
52 | * if so sends a warning message.
53 | * Also prevents pagination slots from
54 | * being added to the background layer.
55 | *
56 | * @param button The button to check
57 | * @param index The index to check
58 | * @return If the button or index is invalid.
59 | */
60 | @Override
61 | protected boolean isInvalid(Button button, int index) {
62 | if (super.isInvalid(button, index)) return true;
63 |
64 | if (button instanceof PaginationSlot) {
65 | warning("pagination slot", button, index);
66 | return true;
67 | }
68 |
69 | return false;
70 | }
71 | }
72 |
--------------------------------------------------------------------------------
/core/src/main/java/net/j4c0b3y/api/menu/layer/impl/ForegroundLayer.java:
--------------------------------------------------------------------------------
1 | package net.j4c0b3y.api.menu.layer.impl;
2 |
3 | import net.j4c0b3y.api.menu.Menu;
4 | import net.j4c0b3y.api.menu.button.Button;
5 | import net.j4c0b3y.api.menu.layer.Layer;
6 |
7 | import java.util.TreeMap;
8 |
9 | /**
10 | * Represents a foreground layer in a menu with
11 | * many methods to manipulate the layer's content.
12 | *
13 | * @author J4C0B3Y
14 | * @version MenuAPI
15 | * @since 12/05/2024
16 | */
17 | public class ForegroundLayer extends Layer {
18 |
19 | /**
20 | * Creates a new foreground layer.
21 | *
22 | * @param menu The menu the layer belongs to.
23 | */
24 | public ForegroundLayer(Menu menu) {
25 | super(menu, new TreeMap<>());
26 | }
27 |
28 | /**
29 | * Returns the name of the foreground layer.
30 | *
31 | * @return The foreground layer name.
32 | */
33 | @Override
34 | public String getName() {
35 | return "foreground";
36 | }
37 |
38 | /**
39 | * Adds a button to the next available slot,
40 | * checking slots in the background layer as well.
41 | *
42 | * @param button The button to add.
43 | * @param other If the background layer should be checked.
44 | */
45 | @Override
46 | public void add(Button button, boolean other) {
47 | add(button, other ? getMenu().getBackground() : null);
48 | }
49 | }
50 |
--------------------------------------------------------------------------------
/core/src/main/java/net/j4c0b3y/api/menu/listener/InventoryListener.java:
--------------------------------------------------------------------------------
1 | package net.j4c0b3y.api.menu.listener;
2 |
3 | import lombok.RequiredArgsConstructor;
4 | import net.j4c0b3y.api.menu.Menu;
5 | import net.j4c0b3y.api.menu.MenuHandler;
6 | import org.bukkit.entity.Player;
7 | import org.bukkit.event.EventHandler;
8 | import org.bukkit.event.Listener;
9 | import org.bukkit.event.inventory.InventoryClickEvent;
10 | import org.bukkit.event.inventory.InventoryCloseEvent;
11 | import org.bukkit.event.player.PlayerQuitEvent;
12 |
13 | /**
14 | * Handles inventories being clicked or closed,
15 | * also closing the inventory when players quit.
16 | *
17 | * @author J4C0B3Y
18 | * @version MenuAPI
19 | * @since 12/05/2024
20 | */
21 | @RequiredArgsConstructor
22 | public class InventoryListener implements Listener {
23 | /**
24 | * The menu handler that registered the listener.
25 | */
26 | private final MenuHandler handler;
27 |
28 | /**
29 | * Sends a click event to a player's menu if they have one
30 | * open, cancelling the click, so they can't pick up the item.
31 | *
32 | * @param event The click event.
33 | */
34 | @EventHandler
35 | public void onClick(InventoryClickEvent event) {
36 | if (!(event.getWhoClicked() instanceof Player)) {
37 | return;
38 | }
39 |
40 | handler.ifOpen((Player) event.getWhoClicked(), menu -> {
41 | event.setCancelled(true);
42 | menu.click(event);
43 | });
44 | }
45 |
46 | /**
47 | * When an inventory is closed, the menu
48 | * gets closed and remove from the open menus map.
49 | *
50 | * @param event The close event.
51 | */
52 | @EventHandler
53 | public void onClose(InventoryCloseEvent event) {
54 | if (!(event.getPlayer() instanceof Player)) {
55 | return;
56 | }
57 |
58 | handler.ifOpen((Player) event.getPlayer(), menu ->
59 | menu.close(false)
60 | );
61 | }
62 |
63 | /**
64 | * Closes a players menu when they leave the game.
65 | *
66 | * @param event The quit event.
67 | */
68 | @EventHandler
69 | public void onQuit(PlayerQuitEvent event) {
70 | handler.ifOpen(event.getPlayer(), Menu::close);
71 | }
72 | }
73 |
--------------------------------------------------------------------------------
/core/src/main/java/net/j4c0b3y/api/menu/pagination/PaginatedMenu.java:
--------------------------------------------------------------------------------
1 | package net.j4c0b3y.api.menu.pagination;
2 |
3 | import lombok.Getter;
4 | import net.j4c0b3y.api.menu.Menu;
5 | import net.j4c0b3y.api.menu.MenuSize;
6 | import net.j4c0b3y.api.menu.button.Button;
7 | import org.bukkit.entity.Player;
8 |
9 | import java.util.ArrayList;
10 | import java.util.HashMap;
11 | import java.util.List;
12 | import java.util.Map;
13 |
14 | /**
15 | * A menu with pagination functionality.
16 | *
17 | * @author J4C0B3Y
18 | * @version MenuAPI
19 | * @since 12/05/2024
20 | */
21 | @Getter
22 | public abstract class PaginatedMenu extends Menu {
23 | /**
24 | * The minimum / first page possible in a paginated menu.
25 | */
26 | public final static int MINIMUM_PAGE = 1;
27 |
28 | /**
29 | * A list of the buttons that should be paginated.
30 | */
31 | private final List paginationEntries = new ArrayList<>();
32 |
33 | /**
34 | * A map of a slot to an index in the pagination entries.
35 | */
36 | private final Map indexCache = new HashMap<>();
37 |
38 | /**
39 | * The current page of the pagination menu.
40 | */
41 | private int page = MINIMUM_PAGE;
42 |
43 | /**
44 | * The total pages in the pagination menu.
45 | */
46 | private int totalPages = MINIMUM_PAGE;
47 |
48 | /**
49 | * Creates a new paginated menu, initializing the underlying bukkit inventory.
50 | *
51 | * @param title The title, auto translated.
52 | * @param size The menu size, in rows.
53 | * @param player The player to open the menu with.
54 | */
55 | public PaginatedMenu(String title, MenuSize size, Player player) {
56 | super(title, size, player);
57 | }
58 |
59 | /**
60 | * A list of the buttons that should be paginated.
61 | *
62 | * @return The buttons to paginate.
63 | */
64 | public abstract List getEntries();
65 |
66 | /**
67 | * Updates the pagination entries, recreates the index cache,
68 | * calculates the total and current page then updates the menu.
69 | */
70 | @Override
71 | protected void refresh() {
72 | // Update the pagination entries.
73 | paginationEntries.clear();
74 | paginationEntries.addAll(getEntries());
75 |
76 | // Clear the index cache.
77 | indexCache.clear();
78 | int index = 0;
79 |
80 | // For each pagination slot in the menu's foreground layer,
81 | // map the slot of the button in the layer to the index
82 | // relative to other pagination slots.
83 | for (Map.Entry entry : getForeground().getButtons().entrySet()) {
84 | if (entry.getValue() instanceof PaginationSlot) {
85 | indexCache.put(entry.getKey(), index++);
86 | }
87 | }
88 |
89 | // Calculate the total pages by dividing the amount of entries
90 | // by the amount of slots then rounding to the next highest whole number.
91 | // If the index cache or the pagination entries is empty, use the MINIMUM_PAGE.
92 | totalPages = indexCache.isEmpty() ? MINIMUM_PAGE : Math.max(
93 | (int) Math.ceil((double) paginationEntries.size() / getPaginationSlots()), MINIMUM_PAGE
94 | );
95 |
96 | // Clamps the page number from MINIMUM_PAGE to the total page count.
97 | page = Math.min(Math.max(page, MINIMUM_PAGE), totalPages);
98 |
99 | // Refreshes the menu to reflect the changes.
100 | super.refresh();
101 | }
102 |
103 | /**
104 | * Increments the page then updates the menu.
105 | */
106 | public void nextPage() {
107 | page++;
108 | update();
109 | }
110 |
111 | /**
112 | * Decrements the page then updates the menu.
113 | */
114 | public void previousPage() {
115 | page--;
116 | update();
117 | }
118 |
119 | /**
120 | * Sets the page then updates the menu.
121 | *
122 | * @param number The page number.
123 | */
124 | public void setPage(int number) {
125 | page = number;
126 | update();
127 | }
128 |
129 | /**
130 | * If there is a next page in the menu,
131 | * which is true if page < total pages.
132 | *
133 | * @return If there is a next page.
134 | */
135 | public boolean hasNextPage() {
136 | return page < totalPages;
137 | }
138 |
139 | /**
140 | * If there is a previous page in the
141 | * menu, which is true if page > 1.
142 | *
143 | * @return If there is previous page.
144 | */
145 | public boolean hasPreviousPage() {
146 | return page > 1;
147 | }
148 |
149 | /**
150 | * The total amount of slots for pagination in the menu,
151 | * this corresponds directly to the size of the index cache.
152 | *
153 | * @return The pagination slot count.
154 | */
155 | public int getPaginationSlots() {
156 | return indexCache.size();
157 | }
158 |
159 | /**
160 | * The index of the current page which
161 | * is the current page number - 1.
162 | *
163 | * @return The page index.
164 | */
165 | public int getPageIndex() {
166 | return page - 1;
167 | }
168 | }
169 |
--------------------------------------------------------------------------------
/core/src/main/java/net/j4c0b3y/api/menu/pagination/PaginationSlot.java:
--------------------------------------------------------------------------------
1 | package net.j4c0b3y.api.menu.pagination;
2 |
3 | import lombok.RequiredArgsConstructor;
4 | import lombok.Setter;
5 | import net.j4c0b3y.api.menu.button.Button;
6 | import net.j4c0b3y.api.menu.button.ButtonClick;
7 | import org.bukkit.inventory.ItemStack;
8 |
9 | /**
10 | * Acts as a placeholder for a pagination entry
11 | * which uses the entry icon and click handler.
12 | *
13 | * @author J4C0B3Y
14 | * @version MenuAPI
15 | * @since 12/05/2024
16 | */
17 | @RequiredArgsConstructor
18 | public class PaginationSlot extends Button {
19 | /**
20 | * The pagination menu the slot belongs to.
21 | */
22 | private final PaginatedMenu menu;
23 |
24 | /**
25 | * The slot index for displaying the icon.
26 | */
27 | @Setter private int iconSlot;
28 |
29 | /**
30 | * Uses the pagination entry's icon.
31 | *
32 | * @return The entry's icon.
33 | */
34 | @Override
35 | public ItemStack getIcon() {
36 | Button button = getButton(iconSlot);
37 | return button != null ? button.getIcon() : null;
38 | }
39 |
40 | /**
41 | * Uses the pagination entry's click handler.
42 | *
43 | * @param click The button click.
44 | */
45 | @Override
46 | public void onClick(ButtonClick click) {
47 | Button button = getButton(click.getSlot());
48 | if (button != null) button.onClick(click);
49 | }
50 |
51 | /**
52 | * Gets the pagination entry that belongs to a slot.
53 | *
54 | * @param slot The slot.
55 | * @return The pagination entry.
56 | */
57 | private Button getButton(int slot) {
58 | // Uses the index cache to map the slot to the index in the entries array,
59 | // pageIndex * paginationSlots is the offset to shift by depending on the page.
60 | int index = menu.getPageIndex() * menu.getPaginationSlots() + menu.getIndexCache().get(slot);
61 |
62 | // If the index lies outside the list of entries there is
63 | // no entry for that slot and no icon should be displayed.
64 | if (index >= menu.getPaginationEntries().size()) {
65 | return null;
66 | }
67 |
68 | return menu.getPaginationEntries().get(index);
69 | }
70 | }
71 |
--------------------------------------------------------------------------------
/core/src/main/java/net/j4c0b3y/api/menu/task/AutoUpdateTask.java:
--------------------------------------------------------------------------------
1 | package net.j4c0b3y.api.menu.task;
2 |
3 | import lombok.Getter;
4 | import lombok.RequiredArgsConstructor;
5 | import net.j4c0b3y.api.menu.Menu;
6 | import net.j4c0b3y.api.menu.MenuHandler;
7 | import net.j4c0b3y.api.menu.annotation.AutoUpdate;
8 |
9 | /**
10 | * Used to automatically update menus annotated with @AutoUpdate
11 | *
12 | * @author J4C0B3Y
13 | * @version MenuAPI
14 | * @since 12/05/2024
15 | */
16 | @RequiredArgsConstructor
17 | public class AutoUpdateTask implements Runnable {
18 | /**
19 | * The menu handler.
20 | */
21 | private final MenuHandler handler;
22 |
23 | /**
24 | * The tick time since the task started.
25 | */
26 | @Getter private long ticks = 0;
27 |
28 | /**
29 | * Loops through all open menus that is annotated with
30 | * AutoUpdate and updates them if the ticks since the
31 | * last update matches the value of the annotation.
32 | */
33 | @Override
34 | public void run() {
35 | for (Menu menu : handler.getOpenMenus().values()) {
36 | AutoUpdate annotation = menu.getClass().getAnnotation(AutoUpdate.class);
37 |
38 | if (annotation != null && ticks - menu.getLastUpdate() >= annotation.value()) {
39 | menu.update();
40 | }
41 | }
42 |
43 | ticks++;
44 | }
45 | }
46 |
--------------------------------------------------------------------------------
/core/src/main/java/net/j4c0b3y/api/menu/template/Template.java:
--------------------------------------------------------------------------------
1 | package net.j4c0b3y.api.menu.template;
2 |
3 | import net.j4c0b3y.api.menu.layer.impl.BackgroundLayer;
4 | import net.j4c0b3y.api.menu.layer.impl.ForegroundLayer;
5 |
6 | /**
7 | * Used to apply a reusable design preset to a menus layers.
8 | *
9 | * @author J4C0B3Y
10 | * @version MenuAPI
11 | * @since 12/05/2024
12 | */
13 | public interface Template {
14 | /**
15 | * Applies a design to a menu.
16 | *
17 | * @param background The menu's background layer.
18 | * @param foreground The menu's foreground layer.
19 | */
20 | void apply(BackgroundLayer background, ForegroundLayer foreground);
21 | }
22 |
--------------------------------------------------------------------------------
/core/src/main/java/net/j4c0b3y/api/menu/utils/Position.java:
--------------------------------------------------------------------------------
1 | package net.j4c0b3y.api.menu.utils;
2 |
3 | import lombok.Getter;
4 | import lombok.RequiredArgsConstructor;
5 |
6 | /**
7 | * Represents a 2d position with an x and y coordinate.
8 | *
9 | * @author J4C0B3Y
10 | * @version MenuAPI
11 | * @since 12/05/2024
12 | */
13 | @Getter
14 | @RequiredArgsConstructor
15 | public class Position {
16 | /**
17 | * The x coordinate.
18 | */
19 | private final int x;
20 |
21 | /**
22 | * The y coordinate.
23 | */
24 | private final int y;
25 | }
26 |
--------------------------------------------------------------------------------
/extras/build.gradle.kts:
--------------------------------------------------------------------------------
1 | repositories {
2 | maven("https://repo.codemc.io/repository/nms/")
3 | }
4 |
5 | dependencies {
6 | compileOnly("org.spigotmc:spigot:1.8.8-R0.1-SNAPSHOT")
7 | implementation("com.github.cryptomorin:XSeries:13.0.0")
8 | }
--------------------------------------------------------------------------------
/extras/src/main/java/net/j4c0b3y/api/menu/item/Item.java:
--------------------------------------------------------------------------------
1 | package net.j4c0b3y.api.menu.item;
2 |
3 | import com.cryptomorin.xseries.XEnchantment;
4 | import com.cryptomorin.xseries.XItemFlag;
5 | import com.cryptomorin.xseries.XMaterial;
6 | import com.cryptomorin.xseries.profiles.builder.XSkull;
7 | import com.cryptomorin.xseries.profiles.objects.Profileable;
8 | import lombok.AccessLevel;
9 | import lombok.Setter;
10 | import lombok.experimental.Accessors;
11 | import org.bukkit.ChatColor;
12 | import org.bukkit.entity.Player;
13 | import org.bukkit.inventory.ItemStack;
14 | import org.bukkit.inventory.meta.ItemMeta;
15 | import org.bukkit.inventory.meta.SkullMeta;
16 |
17 | import java.lang.reflect.Method;
18 | import java.util.*;
19 | import java.util.function.Consumer;
20 | import java.util.function.Function;
21 |
22 | /**
23 | * A builder utility to create items easily.
24 | *
25 | * @author J4C0B3Y
26 | * @version MenuAPI
27 | * @since 1/02/2025
28 | */
29 | @Setter
30 | @Accessors(chain = true)
31 | public class Item implements Cloneable {
32 | /**
33 | * A reference to the modern setUnbreakable method, if applicable.
34 | */
35 | private static Method MODERN_SET_UNBREAKABLE_METHOD = getModernSetUnbreakableMethod();
36 |
37 | /**
38 | * The default formatter to use when an item class instance is created.
39 | */
40 | @Setter private static Function defaultFormatter =
41 | content -> ChatColor.translateAlternateColorCodes('&', content);
42 |
43 | /**
44 | * The underlying item stack associated with the item instance.
45 | */
46 | private @Setter(AccessLevel.NONE) ItemStack item;
47 |
48 | /**
49 | * The underlying item meta associated with the item instance.
50 | */
51 | private @Setter(AccessLevel.NONE) ItemMeta meta;
52 |
53 | /**
54 | * The name of the item.
55 | */
56 | private String name;
57 |
58 | /**
59 | * The item's lore.
60 | */
61 | private List lore = new ArrayList<>();
62 |
63 | /**
64 | * The item's formatter.
65 | */
66 | private Function formatter = defaultFormatter;
67 |
68 | /**
69 | * Creates an item builder using an item stack.
70 | *
71 | * @param item The item stack.
72 | */
73 | public Item(ItemStack item) {
74 | this.item = item != null ? item.clone() : null;
75 | this.meta = item != null ? this.item.getItemMeta() : null;
76 | }
77 |
78 | /**
79 | * Creates an item builder using an XMaterial.
80 | *
81 | * @param material The XMaterial.
82 | */
83 | public Item(XMaterial material) {
84 | this(material != null ? material.parseItem() : null);
85 | }
86 |
87 | /**
88 | * A chain method to perform modifications on the item stack.
89 | * Ensures the item stack is not null, then accepts the consumer.
90 | *
91 | * @param consumer The consumer.
92 | * @return The item instance.
93 | */
94 | public Item modifyItem(Consumer consumer) {
95 | if (this.item != null) {
96 | consumer.accept(this.item);
97 | }
98 |
99 | return this;
100 | }
101 |
102 | /**
103 | * A chain method to perform modifications on the item meta.
104 | * Ensures the item meta is not null, then accepts the consumer.
105 | *
106 | * @param consumer The consumer.
107 | * @return The item instance.
108 | */
109 | public Item modifyMeta(Consumer consumer) {
110 | return modifyItem(item -> {
111 | if (this.meta != null) {
112 | consumer.accept(this.meta);
113 | }
114 | });
115 | }
116 |
117 | /**
118 | * A chain method to perform modifications on the specified item meta.
119 | * Ensures the item meta is not null and is the correct type, then accepts the consumer.
120 | *
121 | * @param type The item meta type.
122 | * @param consumer The consumer.
123 | * @return The item instance.
124 | */
125 | @SuppressWarnings("unchecked")
126 | public Item modifyMeta(Class type, Consumer consumer) {
127 | return modifyMeta(meta -> {
128 | if (type.isAssignableFrom(meta.getClass())) {
129 | consumer.accept((T) meta);
130 | }
131 | });
132 | }
133 |
134 | /**
135 | * Sets the amount of items in the item stack.
136 | *
137 | * @param amount The amount.
138 | * @return The item instance.
139 | */
140 | public Item setAmount(int amount) {
141 | return modifyItem(item -> item.setAmount(amount));
142 | }
143 |
144 | /**
145 | * Sets the data / durability of the item.
146 | *
147 | * @param data The data / durability.
148 | * @return The item instance.
149 | */
150 | public Item setData(short data) {
151 | return modifyItem(item -> item.setDurability(data));
152 | }
153 |
154 | /**
155 | * Sets the item's lore using the provided string list.
156 | *
157 | * @param lore The lore string list.
158 | * @return The item instance.
159 | */
160 | public Item setLore(List lore) {
161 | this.lore = lore;
162 | return this;
163 | }
164 |
165 | /**
166 | * Sets the item's lore using the provided lines.
167 | *
168 | * @param lore The lore lines.
169 | * @return The item instance.
170 | */
171 | public Item setLore(String... lore) {
172 | return setLore(Arrays.asList(lore));
173 | }
174 |
175 | /**
176 | * Adds the provided lines to the item's lore.
177 | *
178 | * @param lines The lore lines to add.
179 | * @return The item instance.
180 | */
181 | public Item addLore(String... lines) {
182 | this.lore.addAll(Arrays.asList(lines));
183 | return this;
184 | }
185 |
186 | /**
187 | * Unsafely adds an enchantment to the item using XEnchantment.
188 | *
189 | * @param enchantment The XEnchantment.
190 | * @param level The enchantment level.
191 | * @return The item instance.
192 | */
193 | public Item addEnchantment(XEnchantment enchantment, int level) {
194 | return modifyItem(item -> item.addUnsafeEnchantment(enchantment.get(), level));
195 | }
196 |
197 | /**
198 | * Adds an item flag to the item using XItemFlag.
199 | *
200 | * @param flag The XItemFlag.
201 | * @return The item instance.
202 | */
203 | public Item addFlag(XItemFlag flag) {
204 | return modifyMeta(meta -> meta.addItemFlags(flag.get()));
205 | }
206 |
207 | /**
208 | * Sets the item as unbreakable, preventing it from losing durability.
209 | *
210 | * @param unbreakable If the item is unbreakable.
211 | * @return The item instance.
212 | */
213 | public Item setUnbreakable(boolean unbreakable) {
214 | return modifyMeta(meta -> {
215 | if (MODERN_SET_UNBREAKABLE_METHOD == null) {
216 | meta.spigot().setUnbreakable(unbreakable);
217 | return;
218 | }
219 |
220 | try {
221 | MODERN_SET_UNBREAKABLE_METHOD.invoke(meta, unbreakable);
222 | } catch (ReflectiveOperationException exception) {
223 | throw new RuntimeException("Failed to set item as unbreakable!", exception);
224 | }
225 | });
226 | }
227 |
228 | /**
229 | * Sets the item as unbreakable, preventing it from losing durability.
230 | *
231 | * @return The item instance.
232 | */
233 | public Item setUnbreakable() {
234 | return setUnbreakable(true);
235 | }
236 |
237 | /**
238 | * Sets the skull texture of the item using XSkull.
239 | * The texture can be a name, uuid, base64, etc.
240 | *
241 | * @param texture The texture string.
242 | * @return The item instance.
243 | */
244 | public Item setTexture(String texture) {
245 | return modifyMeta(meta -> {
246 | if (!(meta instanceof SkullMeta)) return;
247 |
248 | this.meta = XSkull.of(meta)
249 | .profile(Profileable.detect(texture))
250 | .apply();
251 | });
252 | }
253 |
254 | /**
255 | * Sets the skull texture of the item using XSkull.
256 | *
257 | * @param uniqueId The player's uuid.
258 | * @return The item instance.
259 | */
260 | public Item setTexture(UUID uniqueId) {
261 | return setTexture(uniqueId.toString());
262 | }
263 |
264 | /**
265 | * Sets the skull texture of the item using XSkull.
266 | *
267 | * @param player The player.
268 | * @return The item instance.
269 | */
270 | public Item setTexture(Player player) {
271 | return setTexture(player.getUniqueId());
272 | }
273 |
274 | /**
275 | * Formats the content using the item formatter.
276 | *
277 | * @param content The content to format.
278 | * @return The formatted content.
279 | */
280 | private String format(String content) {
281 | return this.formatter.apply(content);
282 | }
283 |
284 | /**
285 | * Formats the content lines using the item formatter.
286 | *
287 | * @param lines The content lines to format.
288 | * @return The formatted content lines.
289 | */
290 | private List format(List lines) {
291 | List formatted = new ArrayList<>(lines);
292 | formatted.replaceAll(this::format);
293 | return formatted;
294 | }
295 |
296 | /**
297 | * Finalizes the builder, converting all saved data into a final item stack.
298 | *
299 | * @return The final item stack.
300 | */
301 | public ItemStack build() {
302 | modifyMeta(meta -> {
303 | if (this.name == null) return;
304 | meta.setDisplayName(format(this.name));
305 | });
306 |
307 | modifyMeta(meta -> {
308 | if (this.lore == null) return;
309 | meta.setLore(format(this.lore));
310 | });
311 |
312 | modifyItem(item -> item.setItemMeta(this.meta));
313 |
314 | return this.item;
315 | }
316 |
317 | /**
318 | * Creates a deep clone of the item builder.
319 | *
320 | * @return The cloned item builder.
321 | */
322 | @Override
323 | public Item clone() {
324 | try {
325 | // Create a structured clone, includes name and formatter.
326 | Item clone = (Item) super.clone();
327 |
328 | if (this.item != null) {
329 | // Clone the ItemStack.
330 | clone.item = this.item.clone();
331 |
332 | if (this.meta != null) {
333 | // Clone the ItemMeta.
334 | clone.meta = clone.item.getItemMeta().clone();
335 | }
336 | }
337 |
338 | if (this.lore != null) {
339 | // Deep copy the lore.
340 | clone.lore = new ArrayList<>(this.lore);
341 | }
342 |
343 | return clone;
344 | } catch (CloneNotSupportedException exception) {
345 | throw new Error(exception);
346 | }
347 | }
348 |
349 | /**
350 | * Tries to get the modern setUnbreakable method from the ItemMeta class.
351 | *
352 | * @return The modern unbreakable method.
353 | */
354 | @SuppressWarnings("JavaReflectionMemberAccess")
355 | private static Method getModernSetUnbreakableMethod() {
356 | try {
357 | return ItemMeta.class.getMethod("setUnbreakable", boolean.class);
358 | } catch (ReflectiveOperationException exception) {
359 | return null;
360 | }
361 | }
362 | }
363 |
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/J4C0B3Y/MenuAPI/55363515953ad2386163cc6f72027eb6eecbc4e0/gradle/wrapper/gradle-wrapper.jar
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.properties:
--------------------------------------------------------------------------------
1 | #Sat May 04 01:11:13 AEST 2024
2 | distributionBase=GRADLE_USER_HOME
3 | distributionPath=wrapper/dists
4 | distributionUrl=https\://services.gradle.org/distributions/gradle-8.5-bin.zip
5 | zipStoreBase=GRADLE_USER_HOME
6 | zipStorePath=wrapper/dists
7 |
--------------------------------------------------------------------------------
/gradlew:
--------------------------------------------------------------------------------
1 | #!/bin/sh
2 |
3 | #
4 | # Copyright © 2015-2021 the original authors.
5 | #
6 | # Licensed under the Apache License, Version 2.0 (the "License");
7 | # you may not use this file except in compliance with the License.
8 | # You may obtain a copy of the License at
9 | #
10 | # https://www.apache.org/licenses/LICENSE-2.0
11 | #
12 | # Unless required by applicable law or agreed to in writing, software
13 | # distributed under the License is distributed on an "AS IS" BASIS,
14 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 | # See the License for the specific language governing permissions and
16 | # limitations under the License.
17 | #
18 |
19 | ##############################################################################
20 | #
21 | # Gradle start up script for POSIX generated by Gradle.
22 | #
23 | # Important for running:
24 | #
25 | # (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is
26 | # noncompliant, but you have some other compliant shell such as ksh or
27 | # bash, then to run this script, type that shell name before the whole
28 | # command line, like:
29 | #
30 | # ksh Gradle
31 | #
32 | # Busybox and similar reduced shells will NOT work, because this script
33 | # requires all of these POSIX shell features:
34 | # * functions;
35 | # * expansions «$var», «${var}», «${var:-default}», «${var+SET}»,
36 | # «${var#prefix}», «${var%suffix}», and «$( cmd )»;
37 | # * compound commands having a testable exit status, especially «case»;
38 | # * various built-in commands including «command», «set», and «ulimit».
39 | #
40 | # Important for patching:
41 | #
42 | # (2) This script targets any POSIX shell, so it avoids extensions provided
43 | # by Bash, Ksh, etc; in particular arrays are avoided.
44 | #
45 | # The "traditional" practice of packing multiple parameters into a
46 | # space-separated string is a well documented source of bugs and security
47 | # problems, so this is (mostly) avoided, by progressively accumulating
48 | # options in "$@", and eventually passing that to Java.
49 | #
50 | # Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS,
51 | # and GRADLE_OPTS) rely on word-splitting, this is performed explicitly;
52 | # see the in-line comments for details.
53 | #
54 | # There are tweaks for specific operating systems such as AIX, CygWin,
55 | # Darwin, MinGW, and NonStop.
56 | #
57 | # (3) This script is generated from the Groovy template
58 | # https://github.com/gradle/gradle/blob/master/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt
59 | # within the Gradle project.
60 | #
61 | # You can find Gradle at https://github.com/gradle/gradle/.
62 | #
63 | ##############################################################################
64 |
65 | # Attempt to set APP_HOME
66 |
67 | # Resolve links: $0 may be a link
68 | app_path=$0
69 |
70 | # Need this for daisy-chained symlinks.
71 | while
72 | APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path
73 | [ -h "$app_path" ]
74 | do
75 | ls=$( ls -ld "$app_path" )
76 | link=${ls#*' -> '}
77 | case $link in #(
78 | /*) app_path=$link ;; #(
79 | *) app_path=$APP_HOME$link ;;
80 | esac
81 | done
82 |
83 | APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit
84 |
85 | APP_NAME="Gradle"
86 | APP_BASE_NAME=${0##*/}
87 |
88 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
89 | DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
90 |
91 | # Use the maximum available, or set MAX_FD != -1 to use that value.
92 | MAX_FD=maximum
93 |
94 | warn () {
95 | echo "$*"
96 | } >&2
97 |
98 | die () {
99 | echo
100 | echo "$*"
101 | echo
102 | exit 1
103 | } >&2
104 |
105 | # OS specific support (must be 'true' or 'false').
106 | cygwin=false
107 | msys=false
108 | darwin=false
109 | nonstop=false
110 | case "$( uname )" in #(
111 | CYGWIN* ) cygwin=true ;; #(
112 | Darwin* ) darwin=true ;; #(
113 | MSYS* | MINGW* ) msys=true ;; #(
114 | NONSTOP* ) nonstop=true ;;
115 | esac
116 |
117 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
118 |
119 |
120 | # Determine the Java command to use to start the JVM.
121 | if [ -n "$JAVA_HOME" ] ; then
122 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
123 | # IBM's JDK on AIX uses strange locations for the executables
124 | JAVACMD=$JAVA_HOME/jre/sh/java
125 | else
126 | JAVACMD=$JAVA_HOME/bin/java
127 | fi
128 | if [ ! -x "$JAVACMD" ] ; then
129 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
130 |
131 | Please set the JAVA_HOME variable in your environment to match the
132 | location of your Java installation."
133 | fi
134 | else
135 | JAVACMD=java
136 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
137 |
138 | Please set the JAVA_HOME variable in your environment to match the
139 | location of your Java installation."
140 | fi
141 |
142 | # Increase the maximum file descriptors if we can.
143 | if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
144 | case $MAX_FD in #(
145 | max*)
146 | MAX_FD=$( ulimit -H -n ) ||
147 | warn "Could not query maximum file descriptor limit"
148 | esac
149 | case $MAX_FD in #(
150 | '' | soft) :;; #(
151 | *)
152 | ulimit -n "$MAX_FD" ||
153 | warn "Could not set maximum file descriptor limit to $MAX_FD"
154 | esac
155 | fi
156 |
157 | # Collect all arguments for the java command, stacking in reverse order:
158 | # * args from the command line
159 | # * the main class name
160 | # * -classpath
161 | # * -D...appname settings
162 | # * --module-path (only if needed)
163 | # * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables.
164 |
165 | # For Cygwin or MSYS, switch paths to Windows format before running java
166 | if "$cygwin" || "$msys" ; then
167 | APP_HOME=$( cygpath --path --mixed "$APP_HOME" )
168 | CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" )
169 |
170 | JAVACMD=$( cygpath --unix "$JAVACMD" )
171 |
172 | # Now convert the arguments - kludge to limit ourselves to /bin/sh
173 | for arg do
174 | if
175 | case $arg in #(
176 | -*) false ;; # don't mess with options #(
177 | /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath
178 | [ -e "$t" ] ;; #(
179 | *) false ;;
180 | esac
181 | then
182 | arg=$( cygpath --path --ignore --mixed "$arg" )
183 | fi
184 | # Roll the args list around exactly as many times as the number of
185 | # args, so each arg winds up back in the position where it started, but
186 | # possibly modified.
187 | #
188 | # NB: a `for` loop captures its iteration list before it begins, so
189 | # changing the positional parameters here affects neither the number of
190 | # iterations, nor the values presented in `arg`.
191 | shift # remove old arg
192 | set -- "$@" "$arg" # push replacement arg
193 | done
194 | fi
195 |
196 | # Collect all arguments for the java command;
197 | # * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of
198 | # shell script including quotes and variable substitutions, so put them in
199 | # double quotes to make sure that they get re-expanded; and
200 | # * put everything else in single quotes, so that it's not re-expanded.
201 |
202 | set -- \
203 | "-Dorg.gradle.appname=$APP_BASE_NAME" \
204 | -classpath "$CLASSPATH" \
205 | org.gradle.wrapper.GradleWrapperMain \
206 | "$@"
207 |
208 | # Use "xargs" to parse quoted args.
209 | #
210 | # With -n1 it outputs one arg per line, with the quotes and backslashes removed.
211 | #
212 | # In Bash we could simply go:
213 | #
214 | # readarray ARGS < <( xargs -n1 <<<"$var" ) &&
215 | # set -- "${ARGS[@]}" "$@"
216 | #
217 | # but POSIX shell has neither arrays nor command substitution, so instead we
218 | # post-process each arg (as a line of input to sed) to backslash-escape any
219 | # character that might be a shell metacharacter, then use eval to reverse
220 | # that process (while maintaining the separation between arguments), and wrap
221 | # the whole thing up as a single "set" statement.
222 | #
223 | # This will of course break if any of these variables contains a newline or
224 | # an unmatched quote.
225 | #
226 |
227 | eval "set -- $(
228 | printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" |
229 | xargs -n1 |
230 | sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' |
231 | tr '\n' ' '
232 | )" '"$@"'
233 |
234 | exec "$JAVACMD" "$@"
235 |
--------------------------------------------------------------------------------
/gradlew.bat:
--------------------------------------------------------------------------------
1 | @rem
2 | @rem Copyright 2015 the original author or authors.
3 | @rem
4 | @rem Licensed under the Apache License, Version 2.0 (the "License");
5 | @rem you may not use this file except in compliance with the License.
6 | @rem You may obtain a copy of the License at
7 | @rem
8 | @rem https://www.apache.org/licenses/LICENSE-2.0
9 | @rem
10 | @rem Unless required by applicable law or agreed to in writing, software
11 | @rem distributed under the License is distributed on an "AS IS" BASIS,
12 | @rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | @rem See the License for the specific language governing permissions and
14 | @rem limitations under the License.
15 | @rem
16 |
17 | @if "%DEBUG%" == "" @echo off
18 | @rem ##########################################################################
19 | @rem
20 | @rem Gradle startup script for Windows
21 | @rem
22 | @rem ##########################################################################
23 |
24 | @rem Set local scope for the variables with windows NT shell
25 | if "%OS%"=="Windows_NT" setlocal
26 |
27 | set DIRNAME=%~dp0
28 | if "%DIRNAME%" == "" set DIRNAME=.
29 | set APP_BASE_NAME=%~n0
30 | set APP_HOME=%DIRNAME%
31 |
32 | @rem Resolve any "." and ".." in APP_HOME to make it shorter.
33 | for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
34 |
35 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
36 | set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
37 |
38 | @rem Find java.exe
39 | if defined JAVA_HOME goto findJavaFromJavaHome
40 |
41 | set JAVA_EXE=java.exe
42 | %JAVA_EXE% -version >NUL 2>&1
43 | if "%ERRORLEVEL%" == "0" goto execute
44 |
45 | echo.
46 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
47 | echo.
48 | echo Please set the JAVA_HOME variable in your environment to match the
49 | echo location of your Java installation.
50 |
51 | goto fail
52 |
53 | :findJavaFromJavaHome
54 | set JAVA_HOME=%JAVA_HOME:"=%
55 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe
56 |
57 | if exist "%JAVA_EXE%" goto execute
58 |
59 | echo.
60 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
61 | echo.
62 | echo Please set the JAVA_HOME variable in your environment to match the
63 | echo location of your Java installation.
64 |
65 | goto fail
66 |
67 | :execute
68 | @rem Setup the command line
69 |
70 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
71 |
72 |
73 | @rem Execute Gradle
74 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %*
75 |
76 | :end
77 | @rem End local scope for the variables with windows NT shell
78 | if "%ERRORLEVEL%"=="0" goto mainEnd
79 |
80 | :fail
81 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
82 | rem the _cmd.exe /c_ return code!
83 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
84 | exit /b 1
85 |
86 | :mainEnd
87 | if "%OS%"=="Windows_NT" endlocal
88 |
89 | :omega
90 |
--------------------------------------------------------------------------------
/settings.gradle.kts:
--------------------------------------------------------------------------------
1 | rootProject.name = "MenuAPI"
2 | include("core", "extras")
3 |
--------------------------------------------------------------------------------