-
Notifications
You must be signed in to change notification settings - Fork 54
Expand file tree
/
Copy pathParticleGroupPresetManager.java
More file actions
503 lines (435 loc) · 23.9 KB
/
ParticleGroupPresetManager.java
File metadata and controls
503 lines (435 loc) · 23.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
package dev.esophose.playerparticles.manager;
import dev.esophose.playerparticles.PlayerParticles;
import dev.esophose.playerparticles.config.Settings;
import dev.esophose.playerparticles.gui.GuiInventory.BorderColor;
import dev.esophose.playerparticles.particles.PPlayer;
import dev.esophose.playerparticles.particles.ParticleEffect;
import dev.esophose.playerparticles.particles.ParticleGroup;
import dev.esophose.playerparticles.particles.ParticlePair;
import dev.esophose.playerparticles.particles.data.ColorTransition;
import dev.esophose.playerparticles.particles.data.NoteColor;
import dev.esophose.playerparticles.particles.data.OrdinaryColor;
import dev.esophose.playerparticles.particles.data.TransparentColor;
import dev.esophose.playerparticles.particles.data.Vibration;
import dev.esophose.playerparticles.particles.preset.ParticleGroupPreset;
import dev.esophose.playerparticles.particles.preset.ParticleGroupPresetPage;
import dev.esophose.playerparticles.styles.ParticleStyle;
import dev.esophose.playerparticles.util.inputparser.InputParser;
import dev.rosewood.rosegarden.RosePlugin;
import dev.rosewood.rosegarden.config.CommentedConfigurationSection;
import dev.rosewood.rosegarden.config.CommentedFileConfiguration;
import dev.rosewood.rosegarden.manager.Manager;
import dev.rosewood.rosegarden.utils.HexUtils;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import org.bukkit.Material;
import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.configuration.file.YamlConfiguration;
public class ParticleGroupPresetManager extends Manager {
public static final String FILE_NAME = "preset_groups.yml";
private Map<Integer, ParticleGroupPresetPage> presetGroupPages;
public ParticleGroupPresetManager(RosePlugin playerParticles) {
super(playerParticles);
}
/**
* Loads the preset groups from the preset_groups.yml file
*/
@Override
public void reload() {
this.presetGroupPages = new HashMap<>();
File pluginDataFolder = PlayerParticles.getInstance().getDataFolder();
if (!pluginDataFolder.exists())
pluginDataFolder.mkdir();
File presetsFile = new File(pluginDataFolder, FILE_NAME);
// Create the file if it doesn't exist
if (!presetsFile.exists()) {
try (InputStream inStream = PlayerParticles.getInstance().getResource(FILE_NAME)) {
Files.copy(inStream, Paths.get(presetsFile.getAbsolutePath()));
} catch (IOException e) {
e.printStackTrace();
}
} else {
this.tryMigrateOld(presetsFile);
}
this.rosePlugin.getScheduler().runTaskLater(() -> this.tryParseFile(presetsFile), 3L);
}
private void tryParseFile(File presetsFile) {
// Parse groups.yml file
try {
YamlConfiguration groupsYaml = YamlConfiguration.loadConfiguration(presetsFile);
int pageNumber = 1;
for (String pageKey: groupsYaml.getKeys(false)) {
ConfigurationSection pageSection = groupsYaml.getConfigurationSection(pageKey);
String title = HexUtils.colorify(pageSection.getString("title"));
ConfigurationSection presetsSection = pageSection.getConfigurationSection("presets");
List<ParticleGroupPreset> presets = new ArrayList<>();
if (presetsSection != null) {
for (String groupName : presetsSection.getKeys(false)) {
Map<Integer, ParticlePair> particles = new HashMap<>();
String displayName = "";
Material guiIcon = Material.ENDER_CHEST;
int guiSlot = -1;
List<String> lore = new ArrayList<>();
String permission = "";
boolean allowPermissionOverride = false;
Integer customModelData = null;
ConfigurationSection groupSection = presetsSection.getConfigurationSection(groupName);
Set<String> particleKeys = groupSection.getKeys(false);
for (String stringId : particleKeys) {
if (stringId.equalsIgnoreCase("display-name")) {
displayName = HexUtils.colorify(groupSection.getString(stringId));
continue;
}
if (stringId.equalsIgnoreCase("gui-icon")) {
guiIcon = Material.matchMaterial(groupSection.getString(stringId));
continue;
}
if (stringId.equalsIgnoreCase("gui-slot")) {
guiSlot = groupSection.getInt(stringId);
continue;
}
if (stringId.equalsIgnoreCase("lore")) {
lore = groupSection.getStringList("lore");
lore.replaceAll(HexUtils::colorify);
continue;
}
if (stringId.equalsIgnoreCase("permission")) {
permission = groupSection.getString(stringId);
continue;
}
if (stringId.equalsIgnoreCase("allow-permission-override")) {
allowPermissionOverride = groupSection.getBoolean(stringId);
continue;
}
if (stringId.equalsIgnoreCase("custom-model-data")) {
customModelData = groupSection.getInt(stringId);
continue;
}
ConfigurationSection particleSection = groupSection.getConfigurationSection(stringId);
int id = Integer.parseInt(stringId);
ParticleEffect effect = new InputParser(null, new String[] { particleSection.getString("effect") }).next(ParticleEffect.class);
ParticleStyle style = new InputParser(null, new String[] { particleSection.getString("style") }).next(ParticleStyle.class);
if (effect == null) {
PlayerParticles.getInstance().getLogger().severe("Invalid effect name: '" + particleSection.getString("effect") + "'!");
continue;
}
if (style == null) {
PlayerParticles.getInstance().getLogger().severe("Invalid style name: '" + particleSection.getString("style") + "'!");
continue;
}
Material itemData = null;
Material blockData = null;
OrdinaryColor colorData = null;
NoteColor noteColorData = null;
ColorTransition colorTransitionData = null;
Vibration vibrationData = null;
String dataString = particleSection.getString("data");
if (dataString != null && !dataString.isEmpty()) {
String[] args = dataString.split(" ");
InputParser inputParser = new InputParser(null, args);
switch (effect.getDataType()) {
case COLORABLE:
if (effect == ParticleEffect.NOTE) {
noteColorData = inputParser.next(NoteColor.class);
if (noteColorData == null) {
PlayerParticles.getInstance().getLogger().severe("Invalid note: '" + dataString + "'!");
continue;
}
} else {
colorData = inputParser.next(OrdinaryColor.class);
if (colorData == null) {
PlayerParticles.getInstance().getLogger().severe("Invalid color: '" + dataString + "'!");
continue;
}
}
break;
case COLORABLE_TRANSPARENCY:
colorData = inputParser.next(TransparentColor.class);
if (colorData == null) {
PlayerParticles.getInstance().getLogger().severe("Invalid color with transparency: '" + dataString + "'!");
continue;
}
break;
case BLOCK:
blockData = inputParser.next(Material.class);
if (blockData == null || !blockData.isBlock()) {
PlayerParticles.getInstance().getLogger().severe("Invalid block: '" + dataString + "'!");
continue;
}
break;
case ITEM:
itemData = inputParser.next(Material.class);
if (itemData == null || itemData.isBlock()) {
PlayerParticles.getInstance().getLogger().severe("Invalid item: '" + dataString + "'!");
continue;
}
break;
case COLORABLE_TRANSITION:
colorTransitionData = inputParser.next(ColorTransition.class);
if (colorTransitionData == null) {
PlayerParticles.getInstance().getLogger().severe("Invalid color transition: '" + dataString + "'!");
return;
}
break;
case VIBRATION:
vibrationData = inputParser.next(Vibration.class);
if (vibrationData == null) {
PlayerParticles.getInstance().getLogger().severe("Invalid vibration: '" + dataString + "'!");
return;
}
break;
}
}
particles.put(id, new ParticlePair(null, id, effect, style, itemData, blockData, colorData, noteColorData, colorTransitionData, vibrationData));
}
presets.add(new ParticleGroupPreset(displayName, guiIcon, guiSlot, lore, permission, allowPermissionOverride, new ParticleGroup(groupName, particles), customModelData));
}
}
Map<Integer, BorderColor> extra = new HashMap<>();
ConfigurationSection extraSection = pageSection.getConfigurationSection("extra");
if (extraSection != null) {
for (String slots : extraSection.getKeys(false)) {
BorderColor borderColor = BorderColor.valueOf(extraSection.getString(slots));
try {
if (slots.contains("-")) {
String[] split = slots.split("-");
int start = Integer.parseInt(split[0]);
int end = Integer.parseInt(split[1]);
for (int i = start; i <= end; i++)
extra.put(i, borderColor);
} else {
extra.put(Integer.parseInt(slots), borderColor);
}
} catch (NumberFormatException ignored) { }
}
}
this.presetGroupPages.put(pageNumber++, new ParticleGroupPresetPage(title, presets, extra));
}
} catch (Exception ex) {
ex.printStackTrace();
this.rosePlugin.getLogger().severe("An error occurred while parsing the preset_groups.yml file!");
}
}
@Override
public void disable() {
}
/**
* Gets a map of page numbers to preset pages for a PPlayer
*
* @param pplayer The PPlayer
* @return a Map of page numbers to preset pages for a PPlayer
*/
public Map<Integer, ParticleGroupPresetPage> getPresetGroupPages(PPlayer pplayer) {
List<Integer> configPageNumbers = this.presetGroupPages.keySet().stream().sorted().collect(Collectors.toList());
// Collect all "globally-packed" (gui-slot = -2) presets visible to the player, preserving config page order
List<ParticleGroupPreset> globalPresets = new ArrayList<>();
for (int key : configPageNumbers) {
ParticleGroupPresetPage page = this.presetGroupPages.get(key);
page.getPresets().stream()
.filter(p -> p.getGuiSlot() == -2 && p.canPlayerUse(pplayer))
.forEach(globalPresets::add);
}
Map<Integer, ParticleGroupPresetPage> result = new HashMap<>();
int pageNumber = 1;
// Pack "globally-packed" presets into pages, using each config page's title and border
if (!globalPresets.isEmpty()) {
int presetIndex = 0;
for (int key : configPageNumbers) {
if (presetIndex >= globalPresets.size()) break;
ParticleGroupPresetPage configPage = this.presetGroupPages.get(key);
Map<Integer, BorderColor> extraBorder = configPage.getExtraBorder();
long freeSlotCount = IntStream.range(0, 54)
.filter(i -> !extraBorder.containsKey(i))
.count();
if (freeSlotCount == 0)
continue;
List<ParticleGroupPreset> pagePresets = new ArrayList<>();
for (int i = 0; i < freeSlotCount && presetIndex < globalPresets.size(); i++)
pagePresets.add(globalPresets.get(presetIndex++));
result.put(pageNumber++, new ParticleGroupPresetPage(configPage.getTitle(), pagePresets, extraBorder));
}
}
// Handle regular pages (presets with gui-slot != -2), skipping pages with nothing visible
for (int key : configPageNumbers) {
ParticleGroupPresetPage page = this.presetGroupPages.get(key);
List<ParticleGroupPreset> nonGlobalPresets = page.getPresets().stream()
.filter(p -> p.getGuiSlot() != -2)
.collect(Collectors.toList());
if (nonGlobalPresets.stream().noneMatch(x -> x.canPlayerUse(pplayer)))
continue;
result.put(pageNumber++, new ParticleGroupPresetPage(page.getTitle(), nonGlobalPresets, page.getExtraBorder()));
}
// Use a default page
if (result.isEmpty()) {
LocaleManager localeManager = this.rosePlugin.getManager(LocaleManager.class);
Map<Integer, BorderColor> extraBorder = new HashMap<>();
BorderColor borderColor = BorderColor.getOrDefault(Settings.GUI_GLASS_COLORS_LOAD_PRESET_GROUPS.get(), BorderColor.GREEN);
IntStream.range(0, 9).forEach(x -> extraBorder.put(x, borderColor));
IntStream.range(45, 54).forEach(x -> extraBorder.put(x, borderColor));
Arrays.asList(9, 18, 27, 36, 17, 26, 35, 44).forEach(x -> extraBorder.put(x, borderColor));
result.put(1, new ParticleGroupPresetPage(localeManager.getLocaleMessage("gui-load-a-preset-group"), Collections.emptyList(), extraBorder));
}
return Collections.unmodifiableMap(result);
}
/**
* Gets the max page number for preset groups for a PPlayer
*
* @param pplayer The PPlayer
* @return the max page number for the preset groups for a PPlayer
*/
public int getMaxPageNumber(PPlayer pplayer) {
return this.getPresetGroupPages(pplayer).keySet().stream()
.mapToInt(Integer::intValue)
.max()
.orElse(1);
}
/**
* Gets all the preset ParticleGroups that a player can use
*
* @param player The PPlayer
* @return a List of preset ParticleGroups the player can use
*/
public List<ParticleGroupPreset> getPresetGroupsForPlayer(PPlayer player) {
return this.getAllPresets().stream()
.filter(x -> x.canPlayerUse(player))
.sorted(Comparator.comparing(ParticleGroupPreset::getDisplayName))
.collect(Collectors.toList());
}
/**
* Gets a preset ParticleGroup by its name
*
* @param groupName The ParticleGroup name
* @return The preset ParticleGroup if it exists, otherwise null
*/
public ParticleGroupPreset getPresetGroup(String groupName) {
return this.getAllPresets().stream()
.filter(x -> x.getGroup().getName().equalsIgnoreCase(groupName))
.findFirst()
.orElse(null);
}
/**
* @return a list of all preset groups
*/
private List<ParticleGroupPreset> getAllPresets() {
List<ParticleGroupPreset> allPresets = new ArrayList<>();
for (ParticleGroupPresetPage page : this.presetGroupPages.values())
allPresets.addAll(page.getPresets());
return allPresets;
}
private void tryMigrateOld(File presetsFile) {
CommentedFileConfiguration presetsConfig = CommentedFileConfiguration.loadConfiguration(presetsFile);
// Check all keys to see if we have any that match both "presets" and "extra", that should be good enough
boolean title = false;
boolean extras = false;
boolean presets = false;
for (String key : presetsConfig.getKeys(true)) {
if (!title && key.contains("title"))
title = true;
if (!extras && key.contains("extra"))
extras = true;
if (!presets && key.contains("presets"))
presets = true;
}
if (title && extras && presets)
return;
// Convert existing preset_groups.yml into the new format
List<PresetData> existingPresets = new ArrayList<>();
for (String groupName : presetsConfig.getKeys(false)) {
CommentedConfigurationSection groupSection = presetsConfig.getConfigurationSection(groupName);
String displayName = groupSection.getString("display-name");
String guiIcon = groupSection.getString("gui-icon");
String permission = groupSection.getString("permission");
boolean allowPermissionOverride = groupSection.getBoolean("allow-permission-override");
List<ParticleData> particleData = new ArrayList<>();
for (String key : groupSection.getKeys(false)) {
try {
int id = Integer.parseInt(key);
CommentedConfigurationSection particleGroup = groupSection.getConfigurationSection(key);
String effect = particleGroup.getString("effect");
String style = particleGroup.getString("style");
String data = particleGroup.getString("data");
particleData.add(new ParticleData(id, effect, style, data));
} catch (NumberFormatException ignored) { }
}
existingPresets.add(new PresetData(groupName, displayName, guiIcon, permission, allowPermissionOverride, particleData));
}
// Rename existing file to something else since we're going to remove it
this.rosePlugin.getLogger().warning("Migrating preset_groups.yml from the old format to the new! A backup of the previous file will be created.");
presetsFile.renameTo(new File(presetsFile.getParentFile(), "preset_groups.yml-" + System.currentTimeMillis() + ".old"));
// Copy over the new file
try (InputStream inStream = PlayerParticles.getInstance().getResource(ParticleGroupPresetManager.FILE_NAME)) {
Files.copy(inStream, Paths.get(presetsFile.getAbsolutePath()));
} catch (IOException e) {
e.printStackTrace();
}
// Reload the config
presetsConfig = CommentedFileConfiguration.loadConfiguration(presetsFile);
// Delete everything in the presets section
presetsConfig.set("page1.presets", null);
// Recreate presets section
CommentedConfigurationSection presetsSection = presetsConfig.createSection("page1.presets");
// Fill the data back in
int slot = 10;
int nextWrap = 17;
int maxSlot = 43;
for (PresetData presetData : existingPresets) {
CommentedConfigurationSection presetSection = presetsSection.createSection(presetData.groupName);
presetSection.set("display-name", presetData.displayName);
presetSection.set("gui-icon", presetData.guiIcon);
presetSection.set("gui-slot", slot);
presetSection.set("permission", presetData.permission);
presetSection.set("allow-permission-override", presetData.allowPermissionOverride);
for (ParticleData particleData : presetData.particleData) {
CommentedConfigurationSection particleSection = presetSection.createSection(String.valueOf(particleData.id));
particleSection.set("effect", particleData.effect);
particleSection.set("style", particleData.style);
particleSection.set("data", particleData.data);
}
slot++;
if (slot == nextWrap) { // Loop around border
nextWrap += 9;
slot += 2;
}
// Overflowed the available space
if (slot > maxSlot)
slot = maxSlot;
}
presetsConfig.save(presetsFile);
}
private static class PresetData {
private final String groupName, displayName, guiIcon, permission;
private final boolean allowPermissionOverride;
private final List<ParticleData> particleData;
private PresetData(String groupName, String displayName, String guiIcon, String permission, boolean allowPermissionOverride, List<ParticleData> particleData) {
this.groupName = groupName;
this.displayName = displayName;
this.guiIcon = guiIcon;
this.permission = permission;
this.allowPermissionOverride = allowPermissionOverride;
this.particleData = particleData;
}
}
private static class ParticleData {
private final int id;
private final String effect, style, data;
private ParticleData(int id, String effect, String style, String data) {
this.id = id;
this.effect = effect;
this.style = style;
this.data = data;
}
}
}