default + personal groups (close #51) + basic help command

This commit is contained in:
Flemmli97 2021-05-02 21:39:06 +02:00
parent f3e7b6c2cc
commit ecd50b8ec1
20 changed files with 594 additions and 31 deletions

View File

@ -1,6 +0,0 @@
package com.flemmli97.flan;
public interface IClaimData<T> {
T getClaimData();
}

View File

@ -58,7 +58,7 @@ public class PermissionRegistry {
public static ClaimPermission BUCKET = register(new ClaimPermission("BUCKET", () -> new ItemStack(Items.BUCKET), "Permission to take liquids with buckets"));
public static ClaimPermission ENDERPEARL = register(new ClaimPermission("ENDERPEARL", () -> new ItemStack(Items.ENDER_PEARL), "Permission to use enderpearls"));
public static ClaimPermission CHORUSFRUIT = register(new ClaimPermission("CHORUSFRUIT", () -> new ItemStack(Items.CHORUS_FRUIT), "Permission to eat chorus fruits"));
public static ClaimPermission ANIMALINTERACT = register(new ClaimPermission("ANIMALINTERACT", () -> new ItemStack(Items.CHICKEN_SPAWN_EGG), "Permission to interact with animals (e.g. shearing sheeps)"));
public static ClaimPermission ANIMALINTERACT = register(new ClaimPermission("ANIMALINTERACT", () -> new ItemStack(Items.CHICKEN_SPAWN_EGG), "Permission to interact with animals", "(e.g. shearing sheeps)"));
public static ClaimPermission HURTANIMAL = register(new ClaimPermission("HURTANIMAL", () -> new ItemStack(Items.BEEF), "Permission to hurt animals"));
public static ClaimPermission XP = register(new ClaimPermission("XP", () -> new ItemStack(Items.EXPERIENCE_BOTTLE), "Permission to pick up xp orbs"));
public static ClaimPermission TRADING = register(new ClaimPermission("TRADING", () -> new ItemStack(Items.EMERALD), "Permission to trade with villagers"));
@ -73,7 +73,7 @@ public class PermissionRegistry {
public static ClaimPermission WATERBORDER = global(new ClaimPermission("WATERBORDER", () -> new ItemStack(Items.WATER_BUCKET), "Toggle water crossing claim borders"));
public static ClaimPermission PISTONBORDER = global(new ClaimPermission("PISTONBORDER", () -> new ItemStack(Items.PISTON), "Toggle piston pull/push across claim borders"));
public static ClaimPermission MOBSPAWN = global(new ClaimPermission("MOBSPAWN", () -> new ItemStack(Items.ZOMBIE_SPAWN_EGG), "Prevent hostile mobspawn in claim"));
public static ClaimPermission ANIMALSPAWN = global(new ClaimPermission("ANIMALSPAWN", () -> new ItemStack(Items.CHICKEN_SPAWN_EGG), "Prevent other spawn in claim"));
public static ClaimPermission ANIMALSPAWN = global(new ClaimPermission("ANIMALSPAWN", () -> new ItemStack(Items.PIG_SPAWN_EGG), "Prevent other spawn in claim"));
private static ClaimPermission register(ClaimPermission perm) {
if (locked) {

View File

@ -59,11 +59,20 @@ public class Claim implements IPermissionContainer {
this.world = world;
}
public Claim(BlockPos pos1, BlockPos pos2, ServerPlayerEntity creator) {
this(pos1.getX(), pos2.getX(), pos1.getZ(), pos2.getZ(), Math.min(pos1.getY(), pos2.getY()), creator.getUuid(), creator.getServerWorld(), PlayerClaimData.get(creator).playerDefaultGroups().isEmpty());
PlayerClaimData.get(creator).playerDefaultGroups().forEach((s, m) -> m.forEach((perm, bool) -> this.editPerms(null, s, perm, bool ? 1 : 0)));
}
public Claim(BlockPos pos1, BlockPos pos2, UUID creator, ServerWorld world) {
this(pos1.getX(), pos2.getX(), pos1.getZ(), pos2.getZ(), Math.min(pos1.getY(), pos2.getY()), creator, world);
}
public Claim(int x1, int x2, int z1, int z2, int minY, UUID creator, ServerWorld world) {
this(x1, x2, z1, z2, minY, creator, world, true);
}
public Claim(int x1, int x2, int z1, int z2, int minY, UUID creator, ServerWorld world, boolean setDefaultGroups) {
this.minX = Math.min(x1, x2);
this.minZ = Math.min(z1, z2);
this.maxX = Math.max(x1, x2);
@ -73,6 +82,8 @@ public class Claim implements IPermissionContainer {
this.world = world;
this.setDirty(true);
PermissionRegistry.getPerms().stream().filter(perm -> perm.defaultVal).forEach(perm -> this.globalPerm.put(perm, true));
if (setDefaultGroups)
ConfigHandler.config.defaultGroups.forEach((s, m) -> m.forEach((perm, bool) -> this.editPerms(null, s, perm, bool ? 1 : 0)));
}
public static Claim fromJson(JsonObject obj, UUID owner, ServerWorld world) {
@ -384,10 +395,10 @@ public class Claim implements IPermissionContainer {
* @param mode -1 = makes it resort to the global perm, 0 = deny perm, 1 = allow perm
* @return If editing was successful or not
*/
public boolean editPerms(ServerPlayerEntity player, String group, ClaimPermission perm, int mode, boolean griefPrevention) {
public boolean editPerms(ServerPlayerEntity player, String group, ClaimPermission perm, int mode, boolean alwaysCan) {
if (PermissionRegistry.globalPerms().contains(perm) || (!this.isAdminClaim() && ConfigHandler.config.globallyDefined(this.world, perm)))
return false;
if (griefPrevention || this.canInteract(player, PermissionRegistry.EDITPERMS, player.getBlockPos())) {
if (alwaysCan || this.canInteract(player, PermissionRegistry.EDITPERMS, player.getBlockPos())) {
if (mode > 1)
mode = -1;
boolean has = this.permissions.containsKey(group);

View File

@ -1,7 +1,6 @@
package com.flemmli97.flan.claim;
import com.flemmli97.flan.Flan;
import com.flemmli97.flan.IClaimData;
import com.flemmli97.flan.api.ClaimPermission;
import com.flemmli97.flan.api.PermissionRegistry;
import com.flemmli97.flan.config.ConfigHandler;
@ -55,7 +54,7 @@ public class ClaimStorage {
private final GlobalClaim globalClaim;
public static ClaimStorage get(ServerWorld world) {
return ((IClaimData<ClaimStorage>) world).getClaimData();
return ((IClaimStorage) world).get();
}
public ClaimStorage(MinecraftServer server, ServerWorld world) {
@ -71,7 +70,7 @@ public class ClaimStorage {
}
public boolean createClaim(BlockPos pos1, BlockPos pos2, ServerPlayerEntity player) {
Claim claim = new Claim(pos1.down(ConfigHandler.config.defaultClaimDepth), pos2.down(ConfigHandler.config.defaultClaimDepth), player.getUuid(), player.getServerWorld());
Claim claim = new Claim(pos1.down(ConfigHandler.config.defaultClaimDepth), pos2.down(ConfigHandler.config.defaultClaimDepth), player);
Set<Claim> conflicts = this.conflicts(claim, null);
if (conflicts.isEmpty()) {
PlayerClaimData data = PlayerClaimData.get(player);

View File

@ -0,0 +1,6 @@
package com.flemmli97.flan.claim;
public interface IClaimStorage {
ClaimStorage get();
}

View File

@ -7,6 +7,7 @@ import com.flemmli97.flan.claim.ClaimStorage;
import com.flemmli97.flan.claim.PermHelper;
import com.flemmli97.flan.config.ConfigHandler;
import com.flemmli97.flan.gui.ClaimMenuScreenHandler;
import com.flemmli97.flan.gui.PersonalGroupScreenHandler;
import com.flemmli97.flan.player.EnumDisplayType;
import com.flemmli97.flan.player.EnumEditMode;
import com.flemmli97.flan.player.OfflinePlayerData;
@ -17,6 +18,7 @@ import com.mojang.brigadier.CommandDispatcher;
import com.mojang.brigadier.arguments.BoolArgumentType;
import com.mojang.brigadier.arguments.IntegerArgumentType;
import com.mojang.brigadier.arguments.StringArgumentType;
import com.mojang.brigadier.builder.LiteralArgumentBuilder;
import com.mojang.brigadier.context.CommandContext;
import com.mojang.brigadier.exceptions.CommandSyntaxException;
import com.mojang.brigadier.suggestion.Suggestions;
@ -46,10 +48,11 @@ import java.util.regex.Pattern;
public class CommandClaim {
public static void register(CommandDispatcher<ServerCommandSource> dispatcher, boolean dedicated) {
dispatcher.register(CommandManager.literal("flan")
LiteralArgumentBuilder<ServerCommandSource> builder = CommandManager.literal("flan")
.then(CommandManager.literal("reload").requires(src -> CommandPermission.perm(src, CommandPermission.cmdReload, true)).executes(CommandClaim::reloadConfig))
.then(CommandManager.literal("addClaim").requires(src -> CommandPermission.perm(src, CommandPermission.claimCreate)).then(CommandManager.argument("from", BlockPosArgumentType.blockPos()).then(CommandManager.argument("to", BlockPosArgumentType.blockPos()).executes(CommandClaim::addClaim))))
.then(CommandManager.literal("menu").requires(src -> CommandPermission.perm(src, CommandPermission.cmdMenu)).executes(CommandClaim::openMenu))
.then(CommandManager.literal("personalGroups").requires(src -> CommandPermission.perm(src, CommandPermission.cmdPGroup)).executes(CommandClaim::openPersonalGroups))
.then(CommandManager.literal("claimInfo").requires(src -> CommandPermission.perm(src, CommandPermission.cmdInfo)).executes(CommandClaim::claimInfo))
.then(CommandManager.literal("transferClaim").requires(src -> CommandPermission.perm(src, CommandPermission.cmdTransfer)).then(CommandManager.argument("player", GameProfileArgumentType.gameProfile()).executes(CommandClaim::transferClaim)))
.then(CommandManager.literal("delete").requires(src -> CommandPermission.perm(src, CommandPermission.cmdTransfer)).executes(CommandClaim::deleteClaim))
@ -89,13 +92,18 @@ public class CommandClaim {
return CommandSource.suggestMatching(list, build);
}).executes(CommandClaim::removePlayer))))))
.then(CommandManager.literal("permission").requires(src -> CommandPermission.perm(src, CommandPermission.cmdPermission))
.then(CommandManager.literal("personal").then(CommandManager.argument("group", StringArgumentType.string()).suggests(CommandClaim::personalGroupSuggestion)
.then(CommandManager.argument("permission", StringArgumentType.word()).suggests((ctx, b) -> permSuggestions(ctx, b, true))
.then(CommandManager.argument("toggle", StringArgumentType.word())
.suggests((ctx, b) -> CommandSource.suggestMatching(new String[]{"default", "true", "false"}, b)).executes(CommandClaim::editPersonalPerm)))))
.then(CommandManager.literal("global").then(CommandManager.argument("permission", StringArgumentType.word()).suggests((ctx, b) -> permSuggestions(ctx, b, false))
.then(CommandManager.argument("toggle", StringArgumentType.word()).suggests((ctx, b) -> CommandSource.suggestMatching(new String[]{"default", "true", "false"}, b)).executes(CommandClaim::editGlobalPerm))))
.then(CommandManager.literal("group").then(CommandManager.argument("group", StringArgumentType.string()).suggests(CommandClaim::groupSuggestion)
.then(CommandManager.argument("permission", StringArgumentType.word()).suggests((ctx, b) -> permSuggestions(ctx, b, true))
.then(CommandManager.argument("toggle", StringArgumentType.word())
.suggests((ctx, b) -> CommandSource.suggestMatching(new String[]{"default", "true", "false"}, b)).executes(CommandClaim::editGroupPerm))))))
);
.suggests((ctx, b) -> CommandSource.suggestMatching(new String[]{"default", "true", "false"}, b)).executes(CommandClaim::editGroupPerm))))));
builder.then(CommandManager.literal("help").executes(ctx -> CommandHelp.helpMessage(ctx, 0, builder.getArguments())).then(CommandManager.argument("page", IntegerArgumentType.integer()).executes(ctx -> CommandHelp.helpMessage(ctx, builder.getArguments()))));
dispatcher.register(builder);
}
private static int reloadConfig(CommandContext<ServerCommandSource> context) {
@ -176,6 +184,12 @@ public class CommandClaim {
return Command.SINGLE_SUCCESS;
}
private static int openPersonalGroups(CommandContext<ServerCommandSource> context) throws CommandSyntaxException {
ServerPlayerEntity player = context.getSource().getPlayer();
PersonalGroupScreenHandler.openGroupMenu(player);
return Command.SINGLE_SUCCESS;
}
private static int claimInfo(CommandContext<ServerCommandSource> context) throws CommandSyntaxException {
ServerPlayerEntity player = context.getSource().getPlayer();
Claim claim = ClaimStorage.get(player.getServerWorld()).getClaimAt(player.getBlockPos());
@ -188,7 +202,7 @@ public class CommandClaim {
Claim sub = claim.getSubClaim(player.getBlockPos());
if (sub != null) {
List<Text> info = sub.infoString(player);
player.sendMessage(PermHelper.simpleColoredText("==SubclaimInfo==", Formatting.AQUA), false);
player.sendMessage(PermHelper.simpleColoredText(ConfigHandler.lang.claimSubHeader, Formatting.AQUA), false);
for (Text text : info)
player.sendMessage(text, false);
return Command.SINGLE_SUCCESS;
@ -433,6 +447,18 @@ public class CommandClaim {
return CommandSource.suggestMatching(list, build);
}
private static CompletableFuture<Suggestions> personalGroupSuggestion(CommandContext<ServerCommandSource> context, SuggestionsBuilder build) throws CommandSyntaxException {
ServerPlayerEntity player = context.getSource().getPlayer();
List<String> list = new ArrayList<>(PlayerClaimData.get(player).playerDefaultGroups().keySet());
list.sort(null);
for (int i = 0; i < list.size(); i++) {
if (allowed.matcher(list.get(i)).matches())
continue;
list.set(i, '\"' + list.get(i) + '\"');
}
return CommandSource.suggestMatching(list, build);
}
private static int addGroup(CommandContext<ServerCommandSource> context) throws CommandSyntaxException {
return modifyGroup(context, false);
@ -594,4 +620,35 @@ public class CommandClaim {
}
return Command.SINGLE_SUCCESS;
}
private static int editPersonalPerm(CommandContext<ServerCommandSource> context) throws CommandSyntaxException {
ServerPlayerEntity player = context.getSource().getPlayer();
String group = StringArgumentType.getString(context, "group");
int mode = 0;
switch (StringArgumentType.getString(context, "toggle")) {
case "true":
mode = 1;
break;
case "false":
mode = 0;
break;
case "default":
mode = -1;
break;
}
ClaimPermission perm;
String p = StringArgumentType.getString(context, "permission");
try {
perm = PermissionRegistry.get(p);
if (PermissionRegistry.globalPerms().contains(perm))
throw new IllegalArgumentException();
} catch (NullPointerException e) {
player.sendMessage(PermHelper.simpleColoredText(String.format(ConfigHandler.lang.noSuchPerm, p), Formatting.DARK_RED), false);
return 0;
}
String setPerm = mode == 1 ? "true" : mode == 0 ? "false" : "default";
if (PlayerClaimData.get(player).editDefaultPerms(group, perm, mode))
player.sendMessage(PermHelper.simpleColoredText(String.format(ConfigHandler.lang.editPersonalGroup, group, perm, setPerm), Formatting.GOLD), false);
return Command.SINGLE_SUCCESS;
}
}

View File

@ -0,0 +1,49 @@
package com.flemmli97.flan.commands;
import com.flemmli97.flan.claim.PermHelper;
import com.flemmli97.flan.config.ConfigHandler;
import com.mojang.brigadier.Command;
import com.mojang.brigadier.arguments.IntegerArgumentType;
import com.mojang.brigadier.context.CommandContext;
import com.mojang.brigadier.tree.CommandNode;
import net.minecraft.server.command.ServerCommandSource;
import net.minecraft.text.ClickEvent;
import net.minecraft.text.MutableText;
import net.minecraft.text.Style;
import net.minecraft.util.Formatting;
import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;
public class CommandHelp {
public static int helpMessage(CommandContext<ServerCommandSource> context, Collection<CommandNode<ServerCommandSource>> nodes) {
int page = IntegerArgumentType.getInteger(context, "page");
return helpMessage(context, page, nodes);
}
public static int helpMessage(CommandContext<ServerCommandSource> context, int page, Collection<CommandNode<ServerCommandSource>> nodes) {
List<String> subCommands = nodes.stream().filter(node -> node.canUse(context.getSource())).map(CommandNode::getName).collect(Collectors.toList());
int max = subCommands.size() / 8;
if (page > max)
page = max;
context.getSource().sendFeedback(PermHelper.simpleColoredText(String.format(ConfigHandler.lang.helpHeader, page), Formatting.GOLD), false);
for (int i = 8 * page; i < 8 * (page + 1); i++)
if (i < subCommands.size())
context.getSource().sendFeedback(PermHelper.simpleColoredText(" -" + subCommands.get(i), Formatting.GRAY), false);
MutableText pageText = PermHelper.simpleColoredText((page > 0 ? " " : "") + " ", Formatting.DARK_GREEN);
if (page > 0) {
MutableText pageTextBack = PermHelper.simpleColoredText("<<", Formatting.DARK_GREEN);
pageTextBack.fillStyle(pageTextBack.getStyle().withClickEvent(new ClickEvent(ClickEvent.Action.RUN_COMMAND, "/flan help " + (page - 1))));
pageText = pageTextBack.append(pageText);
}
if (page < max) {
MutableText pageTextNext = PermHelper.simpleColoredText(">>");
pageTextNext.fillStyle(Style.EMPTY.withClickEvent(new ClickEvent(ClickEvent.Action.RUN_COMMAND, "/flan help " + (page + 1))));
pageText = pageText.append(pageTextNext);
}
context.getSource().sendFeedback(pageText, false);
return Command.SINGLE_SUCCESS;
}
}

View File

@ -14,6 +14,7 @@ public class CommandPermission {
public static final String claimCreate = "flan.claim.create";
public static final String cmdMenu = "flan.command.menu";
public static final String cmdPGroup = "flan.command.personal";
public static final String cmdInfo = "flan.command.info";
public static final String cmdTransfer = "flan.command.transfer";

View File

@ -19,8 +19,10 @@ import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Consumer;
public class Config {
@ -46,6 +48,22 @@ public class Config {
public boolean log;
public Map<String, Map<ClaimPermission, Boolean>> defaultGroups = createHashMap(map -> {
map.put("Co-Owner", createLinkedHashMap(perms -> PermissionRegistry.getPerms().forEach(p -> perms.put(p, true))));
map.put("Visitor", createLinkedHashMap(perms -> {
perms.put(PermissionRegistry.BED, true);
perms.put(PermissionRegistry.DOOR, true);
perms.put(PermissionRegistry.FENCEGATE, true);
perms.put(PermissionRegistry.TRAPDOOR, true);
perms.put(PermissionRegistry.BUTTONLEVER, true);
perms.put(PermissionRegistry.PRESSUREPLATE, true);
perms.put(PermissionRegistry.ENDERCHEST, true);
perms.put(PermissionRegistry.ENCHANTMENTTABLE, true);
perms.put(PermissionRegistry.ITEMFRAMEROTATE, true);
perms.put(PermissionRegistry.PORTAL, true);
perms.put(PermissionRegistry.TRADING, true);
}));
});
private final Map<String, Map<ClaimPermission, Boolean>> globalDefaultPerms = new HashMap<>();
public Config(MinecraftServer server) {
@ -89,6 +107,21 @@ public class Config {
if (obj.has("inspectionItem"))
this.inspectionItem = Registry.ITEM.get(new Identifier((obj.get("inspectionItem").getAsString())));
this.claimDisplayTime = ConfigHandler.fromJson(obj, "claimDisplayTime", this.claimDisplayTime);
this.defaultGroups.clear();
JsonObject defP = ConfigHandler.fromJson(obj, "defaultGroups");
defP.entrySet().forEach(e -> {
Map<ClaimPermission, Boolean> perms = new HashMap<>();
if (e.getValue().isJsonObject()) {
e.getValue().getAsJsonObject().entrySet().forEach(jperm -> {
try {
perms.put(PermissionRegistry.get(jperm.getKey()), jperm.getValue().getAsBoolean());
} catch (NullPointerException ex) {
Flan.log("No permission with name {}", jperm.getKey());
}
});
}
this.defaultGroups.put(e.getKey(), perms);
});
this.globalDefaultPerms.clear();
JsonObject glob = ConfigHandler.fromJson(obj, "globalDefaultPerms");
glob.entrySet().forEach(e -> {
@ -134,6 +167,13 @@ public class Config {
obj.addProperty("inspectionItem", Registry.ITEM.getId(this.inspectionItem).toString());
obj.addProperty("claimDisplayTime", this.claimDisplayTime);
obj.addProperty("permissionLevel", this.permissionLevel);
JsonObject defPerm = new JsonObject();
this.defaultGroups.forEach((key, value) -> {
JsonObject perm = new JsonObject();
value.forEach((key1, value1) -> perm.addProperty(key1.id, value1));
defPerm.add(key, perm);
});
obj.add("defaultGroups", defPerm);
JsonObject global = new JsonObject();
this.globalDefaultPerms.forEach((key, value) -> {
JsonObject perm = new JsonObject();
@ -161,4 +201,16 @@ public class Config {
Map<ClaimPermission, Boolean> permMap = ConfigHandler.config.globalDefaultPerms.get(world.getRegistryKey().getValue().toString());
return permMap == null ? null : permMap.getOrDefault(perm, null);
}
private <V, K> Map<V, K> createHashMap(Consumer<Map<V, K>> cons) {
Map<V, K> map = new HashMap<>();
cons.accept(map);
return map;
}
private <V, K> Map<V, K> createLinkedHashMap(Consumer<Map<V, K>> cons) {
Map<V, K> map = new LinkedHashMap<>();
cons.accept(map);
return map;
}
}

View File

@ -65,6 +65,7 @@ public class LangConfig {
public String noSuchPerm = "No such Permission %s";
public String editPerm = "%1$s now set to %2$s";
public String editPermGroup = "%1$s for %2$s now set to %3$s";
public String editPersonalGroup = "Default permission %1$s for group %2$s now set to %3$s";
public String adminMode = "Adminmode (Ignore Claims) set to: %s";
public String adminDeleteAll = "Deleted all claims for following players: %s";
@ -76,11 +77,13 @@ public class LangConfig {
public String giveClaimBlocks = "Gave following players %2$d claimblocks: %1$s";
public String claimBasicInfo = "Owner: %1$s, from: [x=%2$d,z=%3$d] to [x=%4$d,z=%5$d]; Subclaim-amount: %6$d";
public String claimSubHeader = "==SubclaimInfo==";
public String claimBasicInfoSub = "Owner: %1$s, from: [x=%2$d,z=%3$d] to [x=%4$d,z=%5$d]";
public String claimInfoPerms = "Permissions: %s";
public String claimGroupInfoHeader = "Groups: ";
public String claimGroupPerms = " Permissions: %s";
public String claimGroupPlayers = " Players: %s";
public String helpHeader = "Available subcommands are (page %d):";
public String screenEnableText = "Enabled: %s";
public String screenUneditable = "Non Editable!";

View File

@ -101,7 +101,7 @@ public class GroupPlayerScreenHandler extends ServerOnlyScreenHandler {
}
if (index == 3) {
player.closeHandledScreen();
player.getServer().execute(() -> StringResultScreenHandler.createNewStringResult(player, this.claim, (s) -> {
player.getServer().execute(() -> StringResultScreenHandler.createNewStringResult(player, (s) -> {
GameProfile prof = player.getServer().getUserCache().findByName(s);
boolean fl = prof == null || this.claim.setPlayerGroup(prof.getId(), this.group, false);
player.closeHandledScreen();

View File

@ -94,7 +94,7 @@ public class GroupScreenHandler extends ServerOnlyScreenHandler {
}
if (index == 3) {
player.closeHandledScreen();
player.getServer().execute(() -> StringResultScreenHandler.createNewStringResult(player, this.claim, (s) -> {
player.getServer().execute(() -> StringResultScreenHandler.createNewStringResult(player, (s) -> {
this.claim.editPerms(player, s, PermissionRegistry.EDITPERMS, -1);
player.closeHandledScreen();
player.getServer().execute(() -> GroupScreenHandler.openGroupMenu(player, this.claim));

View File

@ -0,0 +1,130 @@
package com.flemmli97.flan.gui;
import com.flemmli97.flan.api.PermissionRegistry;
import com.flemmli97.flan.claim.PermHelper;
import com.flemmli97.flan.player.PlayerClaimData;
import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.entity.player.PlayerInventory;
import net.minecraft.inventory.Inventory;
import net.minecraft.item.ItemStack;
import net.minecraft.item.Items;
import net.minecraft.screen.NamedScreenHandlerFactory;
import net.minecraft.screen.ScreenHandler;
import net.minecraft.screen.slot.Slot;
import net.minecraft.server.network.ServerPlayerEntity;
import net.minecraft.sound.SoundEvents;
import net.minecraft.text.LiteralText;
import net.minecraft.text.Style;
import net.minecraft.text.Text;
import net.minecraft.util.Formatting;
import java.util.ArrayList;
import java.util.List;
public class PersonalGroupScreenHandler extends ServerOnlyScreenHandler {
private boolean removeMode;
private PersonalGroupScreenHandler(int syncId, PlayerInventory playerInventory) {
super(syncId, playerInventory, 6);
}
public static void openGroupMenu(PlayerEntity player) {
NamedScreenHandlerFactory fac = new NamedScreenHandlerFactory() {
@Override
public ScreenHandler createMenu(int syncId, PlayerInventory inv, PlayerEntity player) {
return new PersonalGroupScreenHandler(syncId, inv);
}
@Override
public Text getDisplayName() {
return PermHelper.simpleColoredText("Personal-Groups");
}
};
player.openHandledScreen(fac);
}
@Override
protected void fillInventoryWith(PlayerEntity player, Inventory inv, Object... additionalData) {
if (!(player instanceof ServerPlayerEntity))
return;
for (int i = 0; i < 54; i++) {
if (i == 0) {
ItemStack close = new ItemStack(Items.TNT);
close.setCustomName(new LiteralText("Back").setStyle(Style.EMPTY.withFormatting(Formatting.DARK_RED)));
inv.setStack(i, close);
} else if (i == 3) {
ItemStack stack = new ItemStack(Items.ANVIL);
stack.setCustomName(new LiteralText("Add").setStyle(Style.EMPTY.withFormatting(Formatting.DARK_GREEN)));
inv.setStack(i, stack);
} else if (i == 4) {
ItemStack stack = new ItemStack(Items.REDSTONE_BLOCK);
stack.setCustomName(new LiteralText("Remove Mode: " + this.removeMode).setStyle(Style.EMPTY.withFormatting(Formatting.DARK_RED)));
inv.setStack(i, stack);
} else if (i < 9 || i > 44 || i % 9 == 0 || i % 9 == 8)
inv.setStack(i, ServerScreenHelper.emptyFiller());
else {
List<String> groups = new ArrayList<>(PlayerClaimData.get(player).playerDefaultGroups().keySet());
groups.sort(null);
int row = i / 9 - 1;
int id = (i % 9) + row * 7 - 1;
if (id < groups.size()) {
ItemStack group = new ItemStack(Items.PAPER);
group.setCustomName(new LiteralText(groups.get(id)).setStyle(Style.EMPTY.withFormatting(Formatting.DARK_BLUE)));
inv.setStack(i, group);
}
}
}
}
@Override
protected boolean isRightSlot(int slot) {
return slot == 0 || slot == 3 || slot == 4 || (slot < 45 && slot > 8 && slot % 9 != 0 && slot % 9 != 8);
}
@Override
protected boolean handleSlotClicked(ServerPlayerEntity player, int index, Slot slot, int clickType) {
if (index == 0) {
player.closeHandledScreen();
ServerScreenHelper.playSongToPlayer(player, SoundEvents.UI_BUTTON_CLICK, 1, 1f);
return true;
}
if (index == 3) {
player.closeHandledScreen();
player.getServer().execute(() -> StringResultScreenHandler.createNewStringResult(player, (s) -> {
PlayerClaimData.get(player).editDefaultPerms(s, PermissionRegistry.EDITPERMS, -1);
player.closeHandledScreen();
player.getServer().execute(() -> PersonalGroupScreenHandler.openGroupMenu(player));
ServerScreenHelper.playSongToPlayer(player, SoundEvents.BLOCK_ANVIL_USE, 1, 1f);
}, () -> {
player.closeHandledScreen();
player.getServer().execute(() -> PersonalGroupScreenHandler.openGroupMenu(player));
ServerScreenHelper.playSongToPlayer(player, SoundEvents.ENTITY_VILLAGER_NO, 1, 1f);
}));
ServerScreenHelper.playSongToPlayer(player, SoundEvents.UI_BUTTON_CLICK, 1, 1f);
return true;
}
if (index == 4) {
this.removeMode = !this.removeMode;
ItemStack stack = new ItemStack(Items.REDSTONE_BLOCK);
stack.setCustomName(new LiteralText("Remove Mode: " + this.removeMode).setStyle(Style.EMPTY.withFormatting(Formatting.DARK_RED)));
slot.setStack(stack);
ServerScreenHelper.playSongToPlayer(player, SoundEvents.UI_BUTTON_CLICK, 1, 1f);
return true;
}
ItemStack stack = slot.getStack();
if (!stack.isEmpty()) {
String name = stack.getName().asString();
if (this.removeMode) {
PlayerClaimData.get(player).playerDefaultGroups().remove(name);
slot.setStack(ItemStack.EMPTY);
ServerScreenHelper.playSongToPlayer(player, SoundEvents.ENTITY_BAT_DEATH, 1, 1f);
} else {
player.closeHandledScreen();
player.getServer().execute(() -> PersonalPermissionScreenHandler.openClaimMenu(player, name));
ServerScreenHelper.playSongToPlayer(player, SoundEvents.UI_BUTTON_CLICK, 1, 1f);
}
}
return false;
}
}

View File

@ -0,0 +1,183 @@
package com.flemmli97.flan.gui;
import com.flemmli97.flan.api.ClaimPermission;
import com.flemmli97.flan.api.PermissionRegistry;
import com.flemmli97.flan.claim.PermHelper;
import com.flemmli97.flan.player.PlayerClaimData;
import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.entity.player.PlayerInventory;
import net.minecraft.inventory.Inventory;
import net.minecraft.item.ItemStack;
import net.minecraft.item.Items;
import net.minecraft.screen.NamedScreenHandlerFactory;
import net.minecraft.screen.ScreenHandler;
import net.minecraft.screen.slot.Slot;
import net.minecraft.server.network.ServerPlayerEntity;
import net.minecraft.sound.SoundEvents;
import net.minecraft.text.LiteralText;
import net.minecraft.text.Style;
import net.minecraft.text.Text;
import net.minecraft.util.Formatting;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class PersonalPermissionScreenHandler extends ServerOnlyScreenHandler {
private final String group;
private int page;
private final PlayerEntity player;
private PersonalPermissionScreenHandler(int syncId, PlayerInventory playerInventory, String group, int page) {
super(syncId, playerInventory, 6, group, page);
this.group = group;
this.page = page;
this.player = playerInventory.player;
}
public static void openClaimMenu(PlayerEntity player, String group) {
NamedScreenHandlerFactory fac = new NamedScreenHandlerFactory() {
@Override
public ScreenHandler createMenu(int syncId, PlayerInventory inv, PlayerEntity player) {
return new PersonalPermissionScreenHandler(syncId, inv, group, 0);
}
@Override
public Text getDisplayName() {
return PermHelper.simpleColoredText(String.format("Personal Permissions for %s", group));
}
};
player.openHandledScreen(fac);
}
private static void openClaimMenu(PlayerEntity player, String group, int page) {
NamedScreenHandlerFactory fac = new NamedScreenHandlerFactory() {
@Override
public ScreenHandler createMenu(int syncId, PlayerInventory inv, PlayerEntity player) {
return new PersonalPermissionScreenHandler(syncId, inv, group, page);
}
@Override
public Text getDisplayName() {
return PermHelper.simpleColoredText(String.format("Personal Permissions for %s", group));
}
};
player.openHandledScreen(fac);
}
@Override
protected void fillInventoryWith(PlayerEntity player, Inventory inv, Object... additionalData) {
if (!(player instanceof ServerPlayerEntity))
return;
List<ClaimPermission> perms = new ArrayList<>(PermissionRegistry.getPerms());
if (this.group != null)
perms.removeAll(PermissionRegistry.globalPerms());
for (int i = 0; i < 54; i++) {
int page = (int) additionalData[1];
if (i == 0) {
ItemStack close = new ItemStack(Items.TNT);
close.setCustomName(new LiteralText("Back").setStyle(Style.EMPTY.withFormatting(Formatting.DARK_RED)));
inv.setStack(i, close);
} else if (page == 1 && i == 47) {
ItemStack close = new ItemStack(Items.ARROW);
close.setCustomName(new LiteralText("Prev").setStyle(Style.EMPTY.withFormatting(Formatting.WHITE)));
inv.setStack(i, close);
} else if (page == 0 && i == 51) {
ItemStack close = new ItemStack(Items.ARROW);
close.setCustomName(new LiteralText("Next").setStyle(Style.EMPTY.withFormatting(Formatting.WHITE)));
inv.setStack(i, close);
} else if (i < 9 || i > 44 || i % 9 == 0 || i % 9 == 8)
inv.setStack(i, ServerScreenHelper.emptyFiller());
else {
int row = i / 9 - 1;
int id = (i % 9) + row * 7 - 1 + page * 28;
if (id < perms.size())
inv.setStack(i, ServerScreenHelper.getFromPersonal((ServerPlayerEntity) player, perms.get(id), additionalData[0] == null ? null : additionalData[0].toString()));
}
}
}
private void flipPage() {
if (!(this.player instanceof ServerPlayerEntity))
return;
List<ClaimPermission> perms = new ArrayList<>(PermissionRegistry.getPerms());
if (this.group != null)
perms.removeAll(PermissionRegistry.globalPerms());
int maxPages = perms.size() / 28;
for (int i = 0; i < 54; i++) {
if (i == 0) {
ItemStack close = new ItemStack(Items.TNT);
close.setCustomName(new LiteralText("Back").setStyle(Style.EMPTY.withFormatting(Formatting.DARK_RED)));
this.slots.get(i).setStack(close);
} else if (i == 47) {
ItemStack stack = ServerScreenHelper.emptyFiller();
if (this.page >= 1) {
stack = new ItemStack(Items.ARROW);
stack.setCustomName(new LiteralText("Prev").setStyle(Style.EMPTY.withFormatting(Formatting.WHITE)));
}
this.slots.get(i).setStack(stack);
} else if (i == 51) {
ItemStack stack = ServerScreenHelper.emptyFiller();
if (this.page < maxPages) {
stack = new ItemStack(Items.ARROW);
stack.setCustomName(new LiteralText("Next").setStyle(Style.EMPTY.withFormatting(Formatting.WHITE)));
}
this.slots.get(i).setStack(stack);
} else if (i < 9 || i > 44 || i % 9 == 0 || i % 9 == 8)
this.slots.get(i).setStack(ServerScreenHelper.emptyFiller());
else {
int row = i / 9 - 1;
int id = (i % 9) + row * 7 - 1 + this.page * 28;
if (id < perms.size()) {
this.slots.get(i).setStack(ServerScreenHelper.getFromPersonal((ServerPlayerEntity) this.player, perms.get(id), this.group));
} else
this.slots.get(i).setStack(ItemStack.EMPTY);
}
}
this.sendContentUpdates();
}
@Override
protected boolean handleSlotClicked(ServerPlayerEntity player, int index, Slot slot, int clickType) {
if (index == 0) {
player.closeHandledScreen();
player.getServer().execute(() -> PersonalGroupScreenHandler.openGroupMenu(player));
ServerScreenHelper.playSongToPlayer(player, SoundEvents.UI_BUTTON_CLICK, 1, 1f);
return true;
}
if (index == 47) {
this.page = 0;
this.flipPage();
ServerScreenHelper.playSongToPlayer(player, SoundEvents.UI_BUTTON_CLICK, 1, 1f);
}
if (index == 51) {
this.page = 1;
this.flipPage();
ServerScreenHelper.playSongToPlayer(player, SoundEvents.UI_BUTTON_CLICK, 1, 1f);
}
ItemStack stack = slot.getStack();
String name = stack.getName().asString();
ClaimPermission perm;
try {
perm = PermissionRegistry.get(name);
} catch (NullPointerException e) {
return false;
}
PlayerClaimData data = PlayerClaimData.get(player);
Map<ClaimPermission, Boolean> perms = data.playerDefaultGroups().getOrDefault(group, new HashMap<>());
boolean success = data.editDefaultPerms(this.group, perm, (perms.containsKey(perm) ? perms.get(perm) ? 1 : 0 : -1) + 1);
slot.setStack(ServerScreenHelper.getFromPersonal(player, perm, this.group));
if (success)
ServerScreenHelper.playSongToPlayer(player, SoundEvents.BLOCK_NOTE_BLOCK_PLING, 1, 1.2f);
else
ServerScreenHelper.playSongToPlayer(player, SoundEvents.ENTITY_VILLAGER_NO, 1, 1f);
return true;
}
@Override
protected boolean isRightSlot(int slot) {
return slot == 0 || (this.page == 1 && slot == 47) || (this.page == 0 && slot == 51) || (slot < 45 && slot > 8 && slot % 9 != 0 && slot % 9 != 8);
}
}

View File

@ -4,6 +4,7 @@ import com.flemmli97.flan.api.ClaimPermission;
import com.flemmli97.flan.claim.Claim;
import com.flemmli97.flan.claim.PermHelper;
import com.flemmli97.flan.config.ConfigHandler;
import com.flemmli97.flan.player.PlayerClaimData;
import net.minecraft.item.ItemStack;
import net.minecraft.item.Items;
import net.minecraft.nbt.ListTag;
@ -17,6 +18,9 @@ import net.minecraft.text.Style;
import net.minecraft.text.Text;
import net.minecraft.util.Formatting;
import java.util.HashMap;
import java.util.Map;
public class ServerScreenHelper {
public static ItemStack emptyFiller() {
@ -78,6 +82,35 @@ public class ServerScreenHelper {
return stack;
}
public static ItemStack getFromPersonal(ServerPlayerEntity player, ClaimPermission perm, String group) {
ItemStack stack = perm.getItem();
stack.setCustomName(new LiteralText(perm.id).setStyle(Style.EMPTY.withFormatting(Formatting.GOLD)));
ListTag lore = new ListTag();
for (String pdesc : perm.desc) {
Text trans = new LiteralText(pdesc).setStyle(Style.EMPTY.withFormatting(Formatting.YELLOW));
lore.add(StringTag.of(Text.Serializer.toJson(trans)));
}
Boolean global = ConfigHandler.config.getGlobal(player.getServerWorld(), perm);
if (global != null) {
Text text = new LiteralText(ConfigHandler.lang.screenUneditable).setStyle(Style.EMPTY.withFormatting(Formatting.DARK_RED));
lore.add(StringTag.of(Text.Serializer.toJson(text)));
String permFlag = global.toString();
Text text2 = new LiteralText(String.format(ConfigHandler.lang.screenEnableText, permFlag)).setStyle(Style.EMPTY.withFormatting(permFlag.equals("true") ? Formatting.GREEN : Formatting.RED));
lore.add(StringTag.of(Text.Serializer.toJson(text2)));
} else {
String permFlag;
Map<ClaimPermission, Boolean> map = PlayerClaimData.get(player).playerDefaultGroups().getOrDefault(group, new HashMap<>());
if (map.containsKey(perm))
permFlag = map.get(perm) ? "true" : "false";
else
permFlag = "default";
Text text = new LiteralText(String.format(ConfigHandler.lang.screenEnableText, permFlag)).setStyle(Style.EMPTY.withFormatting(permFlag.equals("true") ? Formatting.GREEN : Formatting.RED));
lore.add(StringTag.of(Text.Serializer.toJson(text)));
}
stack.getOrCreateSubTag("display").put("Lore", lore);
return stack;
}
public static void playSongToPlayer(ServerPlayerEntity player, SoundEvent event, float vol, float pitch) {
player.networkHandler.sendPacket(
new PlaySoundS2CPacket(event, SoundCategory.PLAYERS, player.getPos().x, player.getPos().y, player.getPos().z, vol, pitch));

View File

@ -1,6 +1,5 @@
package com.flemmli97.flan.gui;
import com.flemmli97.flan.claim.Claim;
import com.flemmli97.flan.claim.PermHelper;
import com.flemmli97.flan.config.ConfigHandler;
import net.minecraft.entity.player.PlayerEntity;
@ -13,6 +12,7 @@ import net.minecraft.screen.ScreenHandler;
import net.minecraft.screen.ScreenHandlerListener;
import net.minecraft.screen.slot.Slot;
import net.minecraft.screen.slot.SlotActionType;
import net.minecraft.server.network.ServerPlayerEntity;
import net.minecraft.text.LiteralText;
import net.minecraft.text.Text;
import org.apache.commons.lang3.StringUtils;
@ -44,7 +44,7 @@ public class StringResultScreenHandler extends AnvilScreenHandler {
}
public static void createNewStringResult(PlayerEntity player, Claim claim, Consumer<String> cons, Runnable ret) {
public static void createNewStringResult(PlayerEntity player, Consumer<String> cons, Runnable ret) {
NamedScreenHandlerFactory fac = new NamedScreenHandlerFactory() {
@Override
public ScreenHandler createMenu(int syncId, PlayerInventory inv, PlayerEntity player) {
@ -73,16 +73,17 @@ public class StringResultScreenHandler extends AnvilScreenHandler {
public ItemStack onSlotClick(int i, int j, SlotActionType actionType, PlayerEntity playerEntity) {
if (i < 0)
return ItemStack.EMPTY;
Slot slot = this.slots.get(i);
if (i == 0)
this.ret.run();
else if (i == 2) {
Slot slot = this.slots.get(i);
String s = slot.getStack().hasCustomName() ? slot.getStack().getName().asString() : "";
if (!s.isEmpty() && !s.equals(ConfigHandler.lang.stringScreenReturn))
this.cons.accept(s);
}
this.sendContentUpdates();
return ItemStack.EMPTY;
((ServerPlayerEntity) playerEntity).updateCursorStack();
return slot.getStack();
}
@Override

View File

@ -1,6 +1,6 @@
package com.flemmli97.flan.mixin;
import com.flemmli97.flan.IClaimData;
import com.flemmli97.flan.player.IPlayerClaimImpl;
import com.flemmli97.flan.player.PlayerClaimData;
import net.minecraft.nbt.CompoundTag;
import net.minecraft.server.MinecraftServer;
@ -13,7 +13,7 @@ import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
@Mixin(ServerPlayerEntity.class)
public abstract class PlayerClaimMixin implements IClaimData<PlayerClaimData> {
public abstract class PlayerClaimMixin implements IPlayerClaimImpl {
@Unique
private PlayerClaimData claimData;
@ -47,7 +47,7 @@ public abstract class PlayerClaimMixin implements IClaimData<PlayerClaimData> {
}
@Override
public PlayerClaimData getClaimData() {
public PlayerClaimData get() {
return this.claimData;
}
}

View File

@ -1,7 +1,7 @@
package com.flemmli97.flan.mixin;
import com.flemmli97.flan.IClaimData;
import com.flemmli97.flan.claim.ClaimStorage;
import com.flemmli97.flan.claim.IClaimStorage;
import com.flemmli97.flan.event.WorldEvents;
import net.minecraft.entity.Entity;
import net.minecraft.entity.damage.DamageSource;
@ -17,7 +17,7 @@ import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable;
import org.spongepowered.asm.mixin.injection.callback.LocalCapture;
@Mixin(ServerWorld.class)
public abstract class ServerWorldMixin implements IClaimData<ClaimStorage> {
public abstract class ServerWorldMixin implements IClaimStorage {
@Unique
private ClaimStorage claimData;
@ -39,7 +39,7 @@ public abstract class ServerWorldMixin implements IClaimData<ClaimStorage> {
}
@Override
public ClaimStorage getClaimData() {
public ClaimStorage get() {
return this.claimData;
}
}

View File

@ -0,0 +1,6 @@
package com.flemmli97.flan.player;
public interface IPlayerClaimImpl {
PlayerClaimData get();
}

View File

@ -1,7 +1,8 @@
package com.flemmli97.flan.player;
import com.flemmli97.flan.Flan;
import com.flemmli97.flan.IClaimData;
import com.flemmli97.flan.api.ClaimPermission;
import com.flemmli97.flan.api.PermissionRegistry;
import com.flemmli97.flan.claim.Claim;
import com.flemmli97.flan.claim.ClaimStorage;
import com.flemmli97.flan.claim.IPermissionContainer;
@ -26,7 +27,9 @@ import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
@ -50,13 +53,15 @@ public class PlayerClaimData {
private boolean confirmDeleteAll, adminIgnoreClaim, claimBlockMessage;
private boolean dirty;
private Map<String, Map<ClaimPermission, Boolean>> defaultGroups = new HashMap<>();
public PlayerClaimData(ServerPlayerEntity player) {
this.player = player;
this.claimBlocks = ConfigHandler.config.startingBlocks;
}
public static PlayerClaimData get(PlayerEntity player) {
return ((IClaimData<PlayerClaimData>) player).getClaimData();
return ((IPlayerClaimImpl) player).get();
}
public int getClaimBlocks() {
@ -175,6 +180,27 @@ public class PlayerClaimData {
return this.adminIgnoreClaim;
}
public Map<String, Map<ClaimPermission, Boolean>> playerDefaultGroups() {
return this.defaultGroups;
}
public boolean editDefaultPerms(String group, ClaimPermission perm, int mode) {
if (PermissionRegistry.globalPerms().contains(perm) || ConfigHandler.config.globallyDefined(this.player.getServerWorld(), perm))
return false;
if (mode > 1)
mode = -1;
boolean has = this.defaultGroups.containsKey(group);
Map<ClaimPermission, Boolean> perms = has ? this.defaultGroups.get(group) : new HashMap<>();
if (mode == -1)
perms.remove(perm);
else
perms.put(perm, mode == 1);
if (!has)
this.defaultGroups.put(group, perms);
this.dirty = true;
return true;
}
public void tick() {
boolean tool = this.player.getMainHandStack().getItem() == ConfigHandler.config.claimingItem
|| this.player.getOffHandStack().getItem() == ConfigHandler.config.claimingItem;
@ -232,6 +258,13 @@ public class PlayerClaimData {
JsonObject obj = new JsonObject();
obj.addProperty("ClaimBlocks", this.claimBlocks);
obj.addProperty("AdditionalBlocks", this.additionalClaimBlocks);
JsonObject defPerm = new JsonObject();
this.defaultGroups.forEach((key, value) -> {
JsonObject perm = new JsonObject();
value.forEach((key1, value1) -> perm.addProperty(key1.id, value1));
defPerm.add(key, perm);
});
obj.add("DefaultGroups", defPerm);
FileWriter writer = new FileWriter(file);
ConfigHandler.GSON.toJson(obj, writer);
writer.close();
@ -256,6 +289,11 @@ public class PlayerClaimData {
Flan.debug("Read following json data {} from file {}", obj, file.getName());
this.claimBlocks = obj.get("ClaimBlocks").getAsInt();
this.additionalClaimBlocks = obj.get("AdditionalBlocks").getAsInt();
JsonObject defP = ConfigHandler.fromJson(obj, "defaultGroups");
defP.entrySet().forEach(e -> {
Map<ClaimPermission, Boolean> perms = new HashMap<>();
perms.forEach((p, b) -> this.editDefaultPerms(e.getKey(), p, b ? 1 : 0));
});
reader.close();
} catch (IOException e) {
e.printStackTrace();