-
-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathControlPanelManager.java
More file actions
543 lines (440 loc) · 18.9 KB
/
Copy pathControlPanelManager.java
File metadata and controls
543 lines (440 loc) · 18.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
//
// Created by BONNe
// Copyright - 2019
//
package world.bentobox.controlpanel.managers;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import org.bukkit.Material;
import org.bukkit.World;
import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.configuration.InvalidConfigurationException;
import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.inventory.ItemStack;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import world.bentobox.bentobox.api.addons.GameModeAddon;
import world.bentobox.bentobox.api.user.User;
import world.bentobox.bentobox.database.Database;
import world.bentobox.bentobox.util.ItemParser;
import world.bentobox.controlpanel.ControlPanelAddon;
import world.bentobox.controlpanel.database.objects.ControlPanelObject;
import world.bentobox.controlpanel.database.objects.ControlPanelObject.ControlPanelButton;
import world.bentobox.controlpanel.panels.GuiUtils;
import world.bentobox.controlpanel.utils.Constants;
import world.bentobox.controlpanel.utils.ItemsAdderParse;
import world.bentobox.controlpanel.utils.Utils;
/**
* This class manages control panel addon data.
*/
public class ControlPanelManager
{
// ---------------------------------------------------------------------
// Section: Constructor
// ---------------------------------------------------------------------
/**
* Default constructor.
* @param addon Likes Addon instance
*/
public ControlPanelManager(ControlPanelAddon addon)
{
this.addon = addon;
// Save the default template file into the directory. The configured template file
// may point elsewhere, but the packaged default is always named controlPanelTemplate.yml.
if (!new File(this.addon.getDataFolder(), "controlPanelTemplate.yml").exists())
{
this.addon.saveResource("controlPanelTemplate.yml", false);
}
this.controlPanelCache = new HashMap<>();
this.controlPanelDatabase = new Database<>(addon, ControlPanelObject.class);
this.load();
}
// ---------------------------------------------------------------------
// Section: Load Methods
// ---------------------------------------------------------------------
/**
* This method loads all control panel objects.
*/
public void load()
{
this.controlPanelCache.clear();
this.addon.getLogger().info("Loading control panels...");
this.controlPanelDatabase.loadObjects().forEach(this::load);
}
/**
* This method loads given controlPanelObject inside cache.
* @param controlPanelObject Object that must be added to cache.
*/
@SuppressWarnings("deprecation")
private void load(ControlPanelObject controlPanelObject)
{
// Migrate older data
controlPanelObject.getPanelButtons().forEach(button -> {
if (button.getName() == null)
{
button.setName(button.getCommand());
}
if (button.getDescriptionLines() == null &&
button.getDescription() != null &&
!button.getDescription().isEmpty())
{
button.setDescriptionLines(new ArrayList<>());
button.getDescriptionLines().addAll(GuiUtils.stringSplit(button.getDescription(), 999, false));
button.setDescription(null);
}
});
// Add object into cache
this.controlPanelCache.put(controlPanelObject.getUniqueId(), controlPanelObject);
}
/**
* This method reloads all control panels from database to cache.
*/
public void reload()
{
this.controlPanelCache.clear();
this.addon.getLogger().info("Reloading control panels...");
this.controlPanelDatabase.loadObjects().forEach(this::load);
}
/**
* This method re-imports the control panels for the given game mode from the
* template file configured via {@code template-file} in config.yml (defaults to
* {@code controlPanelTemplate.yml}), replacing whatever is currently stored in the
* database and cache.
* <p>
* This is what makes edits to the template file take effect on {@code bbox reload}:
* without it, {@link #reload()} only re-reads the database and template changes are
* silently ignored.
*
* @param gameModeAddon Game mode whose panels must be re-imported from the template.
*/
public void reimportControlPanels(@NotNull GameModeAddon gameModeAddon)
{
// Clear existing data so removed/renamed panels do not linger, then re-read the template.
this.wipeData(gameModeAddon, null);
this.importControlPanels(null, gameModeAddon);
}
// ---------------------------------------------------------------------
// Section: Save methods
// ---------------------------------------------------------------------
/**
* This method saves all cached values into database.
*/
public void save()
{
this.controlPanelCache.values().forEach(this.controlPanelDatabase::saveObjectAsync);
}
// ---------------------------------------------------------------------
// Section: Wipe methods
// ---------------------------------------------------------------------
/**
* This method removes all data from database that referee to given world.
*/
public void wipeData(@Nullable World world, @Nullable User user)
{
this.wipeData(Utils.getGameMode(world), user);
}
/**
* This method removes all data from database that referee to given game mode addon.
*/
public void wipeData(@NotNull GameModeAddon addon, @Nullable User user)
{
this.wipeData(Utils.getGameMode(addon), user);
}
/**
* This method removes all data from database that referee to given game mode addon.
*/
private void wipeData(@NotNull String addon, @Nullable User user)
{
if (addon.isEmpty())
{
// Missing gamemode name.
return;
}
if (this.hasAnyControlPanel(addon))
{
// Empty sorted cache
List<String> keySet = new ArrayList<>(this.controlPanelCache.keySet());
// Remove everything that starts with gamemode name.
keySet.forEach(uniqueId -> {
if (uniqueId.startsWith(addon))
{
this.controlPanelCache.remove(uniqueId);
this.controlPanelDatabase.deleteID(uniqueId);
}
});
if (user != null)
{
user.sendMessage(Constants.MESSAGE + "control-panels-wiped", Constants.VARIABLE_GAMEMODE, addon);
}
else
{
this.addon.log("Control Panels in " + addon + " are removed!");
}
}
}
// ---------------------------------------------------------------------
// Section: Import methods
// ---------------------------------------------------------------------
/**
* This method imports control panels into world gamemode.
* @param user User who called import method.
* @param world World that is targeted.
* @param fileName Specifies from which file control panel will be loaded
*/
public void importControlPanels(@Nullable User user, @NotNull World world, @NotNull String fileName)
{
this.importControlPanels(user, Utils.getGameMode(world), fileName);
}
/**
* This method imports control panels into gamemode.
* @param user User who called import method.
* @param addon Addon that is targeted.
*/
public void importControlPanels(@Nullable User user, @NotNull GameModeAddon addon)
{
this.importControlPanels(user, addon, this.addon.getSettings().getTemplateFile());
}
/**
* This method imports control panels into gamemode.
* @param user User who called import method.
* @param addon Addon that is targeted.
* @param fileName Specifies from which file control panel will be loaded
*/
public void importControlPanels(@Nullable User user, @NotNull GameModeAddon addon, @NotNull String fileName)
{
this.importControlPanels(user, Utils.getGameMode(addon), fileName);
}
/**
* This method imports control panels
*
* @param user - user
* @param gameModeName - gamemode name where ControlPanels must be imported.
* @param fileName Specifies from which file control panel will be loaded
*/
private void importControlPanels(@Nullable User user, String gameModeName, @NotNull String fileName)
{
if (gameModeName.isEmpty())
{
if (user != null)
{
user.sendMessage(Constants.ERRORS + "not-a-gamemode-world");
}
else
{
this.addon.logError("Not a GameMode world.");
}
return;
}
// Add yml at the end.
if (!fileName.endsWith(".yml"))
{
fileName = fileName + ".yml";
}
File controlFile = new File(this.addon.getDataFolder(), fileName);
if (!controlFile.exists())
{
if (user != null)
{
user.sendMessage(Constants.ERRORS + "no-file",
Constants.VARIABLE_FILENAME, fileName);
}
else
{
this.addon.logError("Missing [file] file.");
}
return;
}
YamlConfiguration config = new YamlConfiguration();
try
{
config.load(controlFile);
}
catch (IOException | InvalidConfigurationException e)
{
if (user != null)
{
user.sendMessage(Constants.ERRORS + "no-load",
Constants.VARIABLE_MESSAGE, e.getMessage(),
Constants.VARIABLE_FILENAME, fileName);
}
else
{
this.addon.logError(e.getMessage());
e.printStackTrace();
}
return;
}
this.readControlPanel(config, user, gameModeName);
// Update biome order.
this.addon.getAddonManager().save();
}
/**
* This method creates control panel object from config file.
* @param config YamlConfiguration that contains all control panels.
* @param user User who calls reading.
* @param gameMode GameMode where current panel works.
*/
private void readControlPanel(YamlConfiguration config, @Nullable User user, final String gameMode)
{
int newControlPanelCount = 0;
ConfigurationSection reader = config.getConfigurationSection("panel-list");
for (String keyReference : Objects.requireNonNull(reader).getKeys(false))
{
final String uniqueId = gameMode + "_" + keyReference;
if (!this.controlPanelCache.containsKey(uniqueId))
{
ControlPanelObject controlPanel = new ControlPanelObject();
controlPanel.setUniqueId(uniqueId);
controlPanel.setGameMode(gameMode);
ConfigurationSection panelSection = reader.getConfigurationSection(keyReference);
if (panelSection != null)
{
controlPanel.setPanelName(panelSection.getString("panelName", "&1Commands"));
controlPanel.setPermissionSuffix(panelSection.getString("permission", "default"));
controlPanel.setDefaultPanel(panelSection.getBoolean("defaultPanel", false));
List<ControlPanelButton> buttonList = new ArrayList<>();
controlPanel.setPanelButtons(buttonList);
ConfigurationSection buttonListSection = panelSection.getConfigurationSection("buttons");
if (buttonListSection != null)
{
buttonListSection.getKeys(false).forEach(slotReference -> {
for (int slotNum : Utils.readIntArray(List.of(slotReference))) {
ControlPanelButton button = new ControlPanelButton();
button.setSlot(slotNum);
ConfigurationSection buttonSection =
buttonListSection.getConfigurationSection(slotReference);
if (buttonSection != null)
{
button.setName(buttonSection.getString("name"));
button.setCommand(buttonSection.getString("command", "[user_command]"));
button.setRightClickCommand(buttonSection.getString("right_click_command"));
button.setShiftClickCommand(buttonSection.getString("shift_click_command"));
// Create empty list
button.setDescriptionLines(new ArrayList<>());
if (buttonSection.isList("description"))
{
// Read description by each line
buttonSection.getStringList("description").forEach(line ->
button.getDescriptionLines().add(
line.replace("[gamemode]", gameMode.toLowerCase())));
}
else if (buttonSection.isString("description"))
{
// Check if description is not defined as simple string
String input = buttonSection.getString("description", "");
if (!input.isEmpty())
{
button.getDescriptionLines().add(
input.replace("[gamemode]", gameMode.toLowerCase()));
}
}
else
{
this.addon.logWarning("Description for button "
+ button.getSlot() + " could not be read.");
}
button.setMaterial(Material.matchMaterial(buttonSection.getString("material", "GRASS")));
if(buttonSection.getString("icon") != null)
button.setIcon(ItemParser.parse(buttonSection.getString("icon"), new ItemStack(Material.PAPER)));
if(buttonSection.getString("itemsadder") != null)
button.setIcon(ItemsAdderParse.parse(buttonSection.getString("itemsadder")));
buttonList.add(button);
}
}
});
}
// Save and load in cache.
this.controlPanelDatabase.saveObjectAsync(controlPanel);
this.load(controlPanel);
newControlPanelCount++;
}
}
}
if (user != null)
{
user.sendMessage(Constants.MESSAGE + "import-count",
"[number]",
String.valueOf(newControlPanelCount));
}
else
{
this.addon.log("Imported " + newControlPanelCount + " control panels in " + gameMode);
}
}
// ---------------------------------------------------------------------
// Section: Processing methods
// ---------------------------------------------------------------------
/**
* This method returns if controlPanel in given gamemode exists in cache.
* @param world World that must be checked.
* @return {@code true} if game mode has a control panel in database, {@code false} otherwise.
*/
public boolean hasAnyControlPanel(World world)
{
return this.hasAnyControlPanel(Utils.getGameMode(world));
}
/**
* This method returns if controlPanel in given gamemode exists in cache.
* @param addon GameMode addon.
* @return {@code true} if game mode has a control panel in database, {@code false} otherwise.
*/
public boolean hasAnyControlPanel(GameModeAddon addon)
{
return this.hasAnyControlPanel(Utils.getGameMode(addon));
}
/**
* This method returns if controlPanel in given gamemode exists in cache.
* @param gameModeName GameMode addon name.
* @return {@code true} if game mode has a control panel in database, {@code false} otherwise.
*/
private boolean hasAnyControlPanel(String gameModeName)
{
return !gameModeName.isEmpty() && this.controlPanelCache.keySet().stream().
anyMatch(value -> value.startsWith(gameModeName));
}
/**
* This method finds corresponding ControlPanel Object for user in given world.
* @param user User who wants to open panel
* @param world World where panel should be opened
* @param permissionPrefix Permission prefix.
* @return ControlPanelObject or null.
*/
public ControlPanelObject getUserControlPanel(User user, World world, String permissionPrefix)
{
String gameMode = Utils.getGameMode(world);
String permission = Utils.getPermissionValue(user,
permissionPrefix + "controlpanel.panel",
null);
if (permission == null || !this.controlPanelCache.containsKey(gameMode + "_" + permission))
{
// Find first default for current game mode.
return this.controlPanelCache.values().stream().
filter(panel -> panel.isDefaultPanel() && panel.getGameMode().equals(gameMode)).
findFirst().orElse(null);
}
else
{
return this.controlPanelCache.get(gameMode + "_" + permission);
}
}
// ---------------------------------------------------------------------
// Section: Instance Variables
// ---------------------------------------------------------------------
/**
* Control Panel Addon instance.
*/
private final ControlPanelAddon addon;
/**
* This database allows to access to all stored control panels.
*/
private final Database<ControlPanelObject> controlPanelDatabase;
/**
* This map contains all control panel object linked to their reference game mode.
*/
private final Map<String, ControlPanelObject> controlPanelCache;
}