file_name
stringlengths
6
86
file_path
stringlengths
45
249
content
stringlengths
47
6.26M
file_size
int64
47
6.26M
language
stringclasses
1 value
extension
stringclasses
1 value
repo_name
stringclasses
767 values
repo_stars
int64
8
14.4k
repo_forks
int64
0
1.17k
repo_open_issues
int64
0
788
repo_created_at
stringclasses
767 values
repo_pushed_at
stringclasses
767 values
TouchCommand.java
/FileExtraction/Java_unseen/DSH105_HoloAPI/src/main/java/com/dsh105/holoapi/command/sub/TouchCommand.java
/* * This file is part of HoloAPI. * * HoloAPI is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * HoloAPI is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with HoloAPI. If not, see <http://www.gnu.org/licenses/>. */ package com.dsh105.holoapi.command.sub; import com.dsh105.command.Command; import com.dsh105.command.CommandEvent; import com.dsh105.command.CommandListener; import com.dsh105.commodus.StringUtil; import com.dsh105.holoapi.HoloAPI; import com.dsh105.holoapi.api.Hologram; import com.dsh105.holoapi.api.touch.CommandTouchAction; import com.dsh105.holoapi.api.touch.TouchAction; import com.dsh105.holoapi.config.Lang; import com.dsh105.holoapi.conversation.InputFactory; import com.dsh105.holoapi.conversation.basic.SimpleInputPrompt; import com.dsh105.holoapi.conversation.basic.YesNoFunction; import org.apache.commons.lang.BooleanUtils; import org.bukkit.conversations.Conversable; import org.bukkit.conversations.ConversationContext; public class TouchCommand implements CommandListener { @Command( command = "touch add <id> <command...>", description = "Add an action to perform when a certain hologram is touched", permission = "holoapi.holo.touch.add" ) public boolean add(final CommandEvent event) { if (!(event.sender() instanceof Conversable)) { event.respond(Lang.NOT_CONVERSABLE.getValue()); } final Hologram hologram = HoloAPI.getManager().getHologram(event.variable("id")); if (hologram == null) { event.respond(Lang.HOLOGRAM_NOT_FOUND.getValue("id", event.variable("id"))); return true; } InputFactory.buildBasicConversation().withFirstPrompt(new SimpleInputPrompt(new YesNoFunction() { @Override public void onFunction(ConversationContext context, String input) { hologram.addTouchAction(new CommandTouchAction(event.variable("command"), BooleanUtils.toBoolean(input))); } @Override public String getSuccessMessage(ConversationContext context, String input) { return Lang.COMMAND_TOUCH_ACTION_ADDED.getValue().replace("%command%", "/" + event.variable("command")).replace("%id%", hologram.getSaveId()); } @Override public String getPromptText(ConversationContext context) { return Lang.YES_NO_COMMAND_TOUCH_ACTION_AS_CONSOLE.getValue(); } @Override public String getFailedText(ConversationContext context, String invalidInput) { return Lang.YES_NO_INPUT_INVALID.getValue(); } })).buildConversation((Conversable) event.sender()).begin(); return true; } @Command( command = "touch add <id> <r:(?i)\"true|false|yes|no\",n:as_console> <command...>", description = "Add an action to perform when a certain hologram is touched", permission = "holoapi.holo.touch.add" ) public boolean addWithBoolean(CommandEvent event) { Hologram hologram = HoloAPI.getManager().getHologram(event.variable("id")); if (hologram == null) { event.respond(Lang.HOLOGRAM_NOT_FOUND.getValue("id", event.variable("id"))); return true; } hologram.addTouchAction(new CommandTouchAction(event.variable("command"), BooleanUtils.toBoolean(event.variable("as_console")))); event.respond(Lang.COMMAND_TOUCH_ACTION_ADDED.getValue("command", "/" + event.variable("command"), "id", hologram.getSaveId())); return true; } @Command( command = "touch remove <id> <touch_id...>", description = "Add an action to perform when a certain hologram is touched", permission = "holoapi.holo.touch.remove" ) public boolean remove(CommandEvent event) { Hologram hologram = HoloAPI.getManager().getHologram(event.variable("id")); if (hologram == null) { event.respond(Lang.HOLOGRAM_NOT_FOUND.getValue("id", event.variable("id"))); return true; } TouchAction toRemove = null; for (TouchAction touchAction : hologram.getAllTouchActions()) { if (touchAction != null && touchAction.getSaveKey().equalsIgnoreCase(event.variable("touch_id")) || (touchAction instanceof CommandTouchAction && ((CommandTouchAction) touchAction).getCommand().equalsIgnoreCase(event.variable("touch_id")))) { toRemove = touchAction; break; } } if (toRemove == null) { event.respond(Lang.TOUCH_ACTION_NOT_FOUND.getValue("touchid", event.variable("touch_id"))); return true; } hologram.removeTouchAction(toRemove); if (toRemove instanceof CommandTouchAction) { Lang.COMMAND_TOUCH_ACTION_REMOVED.getValue("command", "/" + event.variable("touch_id"), "id", hologram.getSaveId()); } else { Lang.TOUCH_ACTION_REMOVED.getValue("touchid", event.variable("touch_id"), "id", hologram.getSaveId()); } return true; } @Command( command = "touch clear <id>", description = "Add an action to perform when a certain hologram is touched", permission = "holoapi.holo.touch.clear" ) public boolean clear(CommandEvent event) { Hologram hologram = HoloAPI.getManager().getHologram(event.variable("id")); if (hologram == null) { event.respond(Lang.HOLOGRAM_NOT_FOUND.getValue("id", event.variable("id"))); return true; } if (hologram.getAllTouchActions().isEmpty()) { event.respond(Lang.NO_TOUCH_ACTIONS.getValue("id", hologram.getSaveId())); return true; } hologram.clearAllTouchActions(); event.respond(Lang.TOUCH_ACTIONS_CLEARED.getValue("id", hologram.getSaveId())); return true; } @Command( command = "touch info <id>", description = "Add an action to perform when a certain hologram is touched", permission = "holoapi.holo.touch.info" ) public boolean info(CommandEvent event) { Hologram hologram = HoloAPI.getManager().getHologram(event.variable("id")); if (hologram == null) { event.respond(Lang.HOLOGRAM_NOT_FOUND.getValue("id", event.variable("id"))); return true; } if (hologram.getAllTouchActions().isEmpty()) { event.respond(Lang.NO_TOUCH_ACTIONS.getValue("id", hologram.getSaveId())); return true; } event.respond(Lang.TOUCH_ACTIONS.getValue("id", hologram.getSaveId())); for (TouchAction action : hologram.getAllTouchActions()) { if (action instanceof CommandTouchAction) { event.respond("•• " + "{c1}Command {c2}/" + ((CommandTouchAction) action).getCommand() + " {c1}" + (((CommandTouchAction) action).shouldPerformAsConsole() ? "as console" : "as player")); continue; } if (action.getSaveKey() == null) { event.respond("•• {c1}Unidentified TouchAction"); } else { event.respond("•• {c2}" + StringUtil.capitalise(action.getSaveKey().replace("_", " "))); } } return true; } }
7,837
Java
.java
DSH105/HoloAPI
31
16
21
2014-02-21T21:30:11Z
2014-12-24T12:52:54Z
BuildCommand.java
/FileExtraction/Java_unseen/DSH105_HoloAPI/src/main/java/com/dsh105/holoapi/command/sub/BuildCommand.java
/* * This file is part of HoloAPI. * * HoloAPI is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * HoloAPI is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with HoloAPI. If not, see <http://www.gnu.org/licenses/>. */ package com.dsh105.holoapi.command.sub; import com.dsh105.command.Command; import com.dsh105.command.CommandEvent; import com.dsh105.command.CommandListener; import com.dsh105.holoapi.config.Lang; import com.dsh105.holoapi.conversation.InputFactory; import com.dsh105.holoapi.conversation.builder.BuilderInputPrompt; import org.bukkit.conversations.Conversable; public class BuildCommand implements CommandListener { @Command( command = "build", description = "Dynamically build a combined hologram of both text and images", permission = "holoapi.holo.build" ) public boolean command(CommandEvent event) { if (!(event.sender() instanceof Conversable)) { event.respond(Lang.NOT_CONVERSABLE.getValue()); return true; } InputFactory.buildBasicConversation().withFirstPrompt(new BuilderInputPrompt()).buildConversation((Conversable) event.sender()).begin(); return true; } }
1,656
Java
.java
DSH105/HoloAPI
31
16
21
2014-02-21T21:30:11Z
2014-12-24T12:52:54Z
RefreshCommand.java
/FileExtraction/Java_unseen/DSH105_HoloAPI/src/main/java/com/dsh105/holoapi/command/sub/RefreshCommand.java
/* * This file is part of HoloAPI. * * HoloAPI is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * HoloAPI is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with HoloAPI. If not, see <http://www.gnu.org/licenses/>. */ package com.dsh105.holoapi.command.sub; import com.dsh105.command.Command; import com.dsh105.command.CommandEvent; import com.dsh105.command.CommandListener; import com.dsh105.holoapi.HoloAPI; import com.dsh105.holoapi.api.Hologram; import com.dsh105.holoapi.config.Lang; import java.util.Set; public class RefreshCommand implements CommandListener { @Command( command = "refresh", description = "Refresh all holograms", permission = "holoapi.holo.refresh" ) public boolean command(CommandEvent event) { Set<Hologram> holograms = HoloAPI.getManager().getAllComplexHolograms().keySet(); if (holograms.isEmpty()) { event.respond(Lang.NO_ACTIVE_HOLOGRAMS.getValue()); return true; } for (Hologram hologram : holograms) { hologram.refreshDisplay(true); } event.respond(Lang.HOLOGRAMS_REFRESHED.getValue()); return true; } @Command( command = "refresh <id>", description = "Refresh a hologram", permission = "holoapi.holo.refresh" ) public boolean withId(CommandEvent event) { Hologram hologram = HoloAPI.getManager().getHologram(event.variable("id")); if (hologram == null) { event.respond(Lang.HOLOGRAM_NOT_FOUND.getValue("id", event.variable("id"))); return true; } hologram.refreshDisplay(true); event.respond(Lang.HOLOGRAM_REFRESH.getValue("id", hologram.getSaveId())); return true; } }
2,236
Java
.java
DSH105/HoloAPI
31
16
21
2014-02-21T21:30:11Z
2014-12-24T12:52:54Z
ReloadCommand.java
/FileExtraction/Java_unseen/DSH105_HoloAPI/src/main/java/com/dsh105/holoapi/command/sub/ReloadCommand.java
/* * This file is part of HoloAPI. * * HoloAPI is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * HoloAPI is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with HoloAPI. If not, see <http://www.gnu.org/licenses/>. */ package com.dsh105.holoapi.command.sub; import com.dsh105.command.Command; import com.dsh105.command.CommandEvent; import com.dsh105.command.CommandListener; import com.dsh105.holoapi.HoloAPI; import com.dsh105.holoapi.config.ConfigType; import com.dsh105.holoapi.config.Lang; public class ReloadCommand implements CommandListener { @Command( command = "reload", description = "Reload all HoloAPI configuration files and holograms", permission = "holoapi.holo.reload" ) public boolean command(CommandEvent event) { // Reload config files HoloAPI.getConfig(ConfigType.MAIN).reloadConfig(); HoloAPI.getConfig(ConfigType.DATA).reloadConfig(); HoloAPI.getConfig(ConfigType.LANG).reloadConfig(); event.respond(Lang.CONFIGS_RELOADED.getValue()); event.respond(Lang.HOLOGRAM_RELOAD.getValue()); // Load all holograms HoloAPI.getCore().loadHolograms(); return true; } }
1,665
Java
.java
DSH105/HoloAPI
31
16
21
2014-02-21T21:30:11Z
2014-12-24T12:52:54Z
HelpCommand.java
/FileExtraction/Java_unseen/DSH105_HoloAPI/src/main/java/com/dsh105/holoapi/command/sub/HelpCommand.java
/* * This file is part of HoloAPI. * * HoloAPI is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * HoloAPI is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with HoloAPI. If not, see <http://www.gnu.org/licenses/>. */ package com.dsh105.holoapi.command.sub; import com.captainbern.minecraft.reflection.MinecraftReflection; import com.dsh105.command.Command; import com.dsh105.command.CommandEvent; import com.dsh105.command.CommandListener; import com.dsh105.commodus.GeneralUtil; import com.dsh105.holoapi.HoloAPI; import com.dsh105.holoapi.config.Lang; import org.bukkit.entity.Player; public class HelpCommand implements CommandListener { @Command( command = "help", description = "Retrieve help for all HoloAPI commands" ) public boolean help(CommandEvent event) { HoloAPI.getCommandManager().getHelpService().sendPage(event.sender(), 1); if (MinecraftReflection.isUsingNetty() && event.sender() instanceof Player) { event.respond(Lang.TIP_HOVER_COMMANDS.getValue()); } return true; } @Command( command = "help <index>", description = "Retrieve a certain help page of all HoloAPI commands" ) public boolean helpPage(CommandEvent event) { try { HoloAPI.getCommandManager().getHelpService().sendPage(event.sender(), GeneralUtil.toInteger(event.variable("index"))); if (MinecraftReflection.isUsingNetty() && event.sender() instanceof Player) { event.respond(Lang.TIP_HOVER_COMMANDS.getValue()); } } catch (NumberFormatException e) { event.respond(Lang.HELP_INDEX_TOO_BIG.getValue("index", event.variable("index"))); } return true; } }
2,216
Java
.java
DSH105/HoloAPI
31
16
21
2014-02-21T21:30:11Z
2014-12-24T12:52:54Z
IdCommand.java
/FileExtraction/Java_unseen/DSH105_HoloAPI/src/main/java/com/dsh105/holoapi/command/sub/IdCommand.java
/* * This file is part of HoloAPI. * * HoloAPI is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * HoloAPI is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with HoloAPI. If not, see <http://www.gnu.org/licenses/>. */ package com.dsh105.holoapi.command.sub; import com.dsh105.command.Command; import com.dsh105.command.CommandEvent; import com.dsh105.command.CommandListener; import com.dsh105.holoapi.HoloAPI; import com.dsh105.holoapi.api.Hologram; import com.dsh105.holoapi.config.ConfigType; import com.dsh105.holoapi.config.Lang; public class IdCommand implements CommandListener { @Command( command = "id set <old_id> <new_id>", description = "Set the save ID of an existing hologram", permission = "holoapi.holo.saveid", help = "Save IDs are used to identify holograms and are used in the HoloAPI save files" ) public boolean command(CommandEvent event) { Hologram hologram = HoloAPI.getManager().getHologram(event.variable("old_id")); if (hologram == null) { event.respond(Lang.HOLOGRAM_NOT_FOUND.getValue("id", event.variable("old_id"))); return true; } if (HoloAPI.getConfig(ConfigType.DATA).getConfigurationSection("holograms." + event.variable("new_id")) != null) { event.respond(Lang.HOLOGRAM_DUPLICATE_ID.getValue("id", event.variable("new_id"))); return true; } hologram.setSaveId(event.variable("new_id")); event.respond(Lang.HOLOGRAM_SET_ID.getValue("oldid", event.variable("old_id"), "newid", event.variable("new_id"))); return true; } }
2,092
Java
.java
DSH105/HoloAPI
31
16
21
2014-02-21T21:30:11Z
2014-12-24T12:52:54Z
EditCommand.java
/FileExtraction/Java_unseen/DSH105_HoloAPI/src/main/java/com/dsh105/holoapi/command/sub/EditCommand.java
/* * This file is part of HoloAPI. * * HoloAPI is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * HoloAPI is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with HoloAPI. If not, see <http://www.gnu.org/licenses/>. */ package com.dsh105.holoapi.command.sub; import com.dsh105.command.Command; import com.dsh105.command.CommandEvent; import com.dsh105.command.CommandListener; import com.dsh105.commodus.GeneralUtil; import com.dsh105.holoapi.HoloAPI; import com.dsh105.holoapi.api.Hologram; import com.dsh105.holoapi.config.Lang; import com.dsh105.holoapi.conversation.InputFactory; import com.dsh105.holoapi.conversation.basic.SimpleInputFunction; import com.dsh105.holoapi.conversation.basic.SimpleInputPrompt; import org.bukkit.ChatColor; import org.bukkit.conversations.Conversable; import org.bukkit.conversations.ConversationContext; public class EditCommand implements CommandListener { @Command( command = "edit <id> <line_number>", description = "Edit a line of an existing hologram", permission = "holoapi.holo.edit", help = "You will be prompted for the content after the command is entered" ) public boolean edit(CommandEvent event) { if (!(event.sender() instanceof Conversable)) { event.respond(Lang.NOT_CONVERSABLE.getValue()); } final Hologram hologram = HoloAPI.getManager().getHologram(event.variable("id")); if (hologram == null) { event.respond(Lang.HOLOGRAM_NOT_FOUND.getValue("id", event.variable("id"))); return true; } int lineNumber; try { lineNumber = GeneralUtil.toInteger(event.variable("line_number")); } catch (NumberFormatException e) { event.respond(Lang.INT_ONLY.getValue("string", event.variable("line_number"))); return true; } if (lineNumber > hologram.getLines().length) { event.respond(Lang.LINE_INDEX_TOO_BIG.getValue("index", event.variable("line_number"))); return true; } final int index = lineNumber; InputFactory.buildBasicConversation().withFirstPrompt(new SimpleInputPrompt(new SimpleInputFunction() { @Override public void onFunction(ConversationContext context, String input) { hologram.updateLine(index - 1, input); } @Override public String getSuccessMessage(ConversationContext context, String input) { return Lang.HOLOGRAM_UPDATE_LINE.getValue("index", index, "input", ChatColor.translateAlternateColorCodes('&', input)); } @Override public String getPromptText(ConversationContext context) { return Lang.PROMPT_UPDATE_LINE.getValue(); } @Override public String getFailedText(ConversationContext context, String invalidInput) { return ""; } })).buildConversation((Conversable) event.sender()).begin(); return true; } @Command( command = "edit <id> <line> <content...>", description = "Edit a line of an existing hologram", permission = "holoapi.holo.edit", help = "The content can be more than one word" ) public boolean editWithContent(CommandEvent event) { final Hologram hologram = HoloAPI.getManager().getHologram(event.variable("id")); if (hologram == null) { event.respond(Lang.HOLOGRAM_NOT_FOUND.getValue("id", event.variable("id"))); return true; } int lineNumber; try { lineNumber = GeneralUtil.toInteger(event.variable("line_number")); } catch (NumberFormatException e) { event.respond(Lang.INT_ONLY.getValue("string", event.variable("line_number"))); return true; } if (lineNumber > hologram.getLines().length) { event.respond(Lang.LINE_INDEX_TOO_BIG.getValue("index", event.variable("line_number"))); return true; } hologram.updateLine(lineNumber - 1, event.variable("content")); event.respond(Lang.HOLOGRAM_UPDATE_LINE.getValue("index", lineNumber, "input", ChatColor.translateAlternateColorCodes('&', event.variable("content")))); return true; } }
4,817
Java
.java
DSH105/HoloAPI
31
16
21
2014-02-21T21:30:11Z
2014-12-24T12:52:54Z
ReadTxtCommand.java
/FileExtraction/Java_unseen/DSH105_HoloAPI/src/main/java/com/dsh105/holoapi/command/sub/ReadTxtCommand.java
/* * This file is part of HoloAPI. * * HoloAPI is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * HoloAPI is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with HoloAPI. If not, see <http://www.gnu.org/licenses/>. */ package com.dsh105.holoapi.command.sub; import com.dsh105.command.Command; import com.dsh105.command.CommandEvent; import com.dsh105.command.CommandListener; import com.dsh105.holoapi.HoloAPI; import com.dsh105.holoapi.api.Hologram; import com.dsh105.holoapi.api.HologramFactory; import com.dsh105.holoapi.config.Lang; import com.dsh105.holoapi.conversation.InputFactory; import com.dsh105.holoapi.conversation.basic.LocationFunction; import com.dsh105.holoapi.conversation.basic.SimpleInputPrompt; import com.dsh105.holoapi.util.MiscUtil; import org.bukkit.Location; import org.bukkit.conversations.Conversable; import org.bukkit.conversations.ConversationContext; import org.bukkit.entity.Player; import org.bukkit.scheduler.BukkitRunnable; public class ReadTxtCommand implements CommandListener { @Command( command = "readtxt <url>", description = "Creates a hologram from a given URL", permission = "holoapi.holo.readtxt" ) public boolean command(final CommandEvent event) { if (!(event.sender() instanceof Conversable)) { event.respond(Lang.NOT_CONVERSABLE.getValue()); } if (event.sender() instanceof Player) { event.respond(Lang.READING_TXT.getValue("url", event.variable("url"))); this.connect(event, event.variable("url"), ((Player) event.sender()).getLocation()); } else { InputFactory.buildBasicConversation().withFirstPrompt(new SimpleInputPrompt(new LocationFunction() { @Override public void onFunction(ConversationContext context, String input) { connect(event, event.variable("url"), this.getLocation()); } @Override public String getSuccessMessage(ConversationContext context, String input) { return Lang.READING_TXT.getValue("url", event.variable("url")); } })).buildConversation((Conversable) event.sender()).begin(); } return true; } @Command( command = "readtxt <url> <world> <x> <y> <z>", description = "Creates a hologram from a given URL", permission = "holoapi.holo.readtxt" ) public boolean withLocation(CommandEvent event) { Location location = MiscUtil.getLocation(event); if (location == null) { return true; } event.respond(Lang.READING_TXT.getValue("url", event.variable("url"))); this.connect(event, event.variable("url"), location); return true; } private void connect(final CommandEvent event, final String url, final Location location) { new BukkitRunnable() { @Override public void run() { final String[] lines = MiscUtil.readWebsiteContentsSoWeCanUseTheText(url); if (lines != null) { new BukkitRunnable() { @Override public void run() { Hologram hologram = new HologramFactory(HoloAPI.getCore()).withLocation(location).withText(lines).build(); event.respond(Lang.HOLOGRAM_CREATED.getValue("id", hologram.getSaveId())); } }.runTask(HoloAPI.getCore()); } } }.runTaskAsynchronously(HoloAPI.getCore()); } }
4,106
Java
.java
DSH105/HoloAPI
31
16
21
2014-02-21T21:30:11Z
2014-12-24T12:52:54Z
CreateCommand.java
/FileExtraction/Java_unseen/DSH105_HoloAPI/src/main/java/com/dsh105/holoapi/command/sub/CreateCommand.java
/* * This file is part of HoloAPI. * * HoloAPI is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * HoloAPI is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with HoloAPI. If not, see <http://www.gnu.org/licenses/>. */ package com.dsh105.holoapi.command.sub; import com.dsh105.command.Command; import com.dsh105.command.CommandEvent; import com.dsh105.command.CommandListener; import com.dsh105.holoapi.HoloAPI; import com.dsh105.holoapi.api.AnimatedHologram; import com.dsh105.holoapi.api.AnimatedHologramFactory; import com.dsh105.holoapi.api.Hologram; import com.dsh105.holoapi.api.HologramFactory; import com.dsh105.holoapi.config.Lang; import com.dsh105.holoapi.conversation.InputFactory; import com.dsh105.holoapi.conversation.InputPrompt; import com.dsh105.holoapi.conversation.basic.LocationFunction; import com.dsh105.holoapi.conversation.basic.SimpleInputPrompt; import com.dsh105.holoapi.conversation.builder.animation.AnimationBuilderInputPrompt; import com.dsh105.holoapi.image.AnimatedImageGenerator; import com.dsh105.holoapi.image.ImageGenerator; import com.dsh105.holoapi.util.MiscUtil; import org.bukkit.Location; import org.bukkit.conversations.Conversable; import org.bukkit.conversations.ConversationContext; import org.bukkit.entity.Player; public class CreateCommand implements CommandListener { @Command( command = "create", description = "Create a hologram from text", permission = "holoapi.holo.create", help = {"Lines can be entered one after another", "Once the command is entered, you will be prompted to enter the line content"} ) public boolean create(CommandEvent event) { if (!(event.sender() instanceof Conversable)) { event.respond(Lang.NOT_CONVERSABLE.getValue()); return true; } InputFactory.buildBasicConversation().withFirstPrompt(new InputPrompt()).buildConversation((Conversable) event.sender()).begin(); return true; } @Command( command = "create <world> <x> <y> <z> <content...>", description = "Create a hologram from text", permission = "holoapi.holo.create", help = {"<content> defines the first line of the new hologram.", "Extra lines can be added using the /holo addline <id> <content> command"} ) public boolean createWithLocation(CommandEvent event) { Location location = MiscUtil.getLocation(event); if (location == null) { return true; } Hologram hologram = new HologramFactory(HoloAPI.getCore()).withText(event.variable("content")).withLocation(location).build(); event.respond(Lang.HOLOGRAM_CREATED.getValue("id", hologram.getSaveId())); return true; } @Command( command = "create image <image_id>", description = "Create a hologram using images", permission = "holoapi.holo.create", help = "Images can be defined in the HoloAPI config file" ) public boolean createImage(CommandEvent event) { if (!(event.sender() instanceof Conversable)) { event.respond(Lang.NOT_CONVERSABLE.getValue()); return true; } if (!HoloAPI.getImageLoader().isLoaded()) { event.respond(Lang.IMAGES_NOT_LOADED.getValue()); return true; } final ImageGenerator generator = HoloAPI.getImageLoader().getGenerator(event.sender(), event.variable("image_id")); if (generator == null) { return true; } if (event.sender() instanceof Player) { Hologram hologram = new HologramFactory(HoloAPI.getCore()).withImage(generator).withLocation(((Player) event.sender()).getLocation()).build(); event.respond(Lang.HOLOGRAM_CREATED.getValue("id", hologram.getSaveId())); return true; } InputFactory.buildBasicConversation().withFirstPrompt(new SimpleInputPrompt(new LocationFunction() { Hologram hologram; @Override public void onFunction(ConversationContext context, String input) { hologram = new HologramFactory(HoloAPI.getCore()).withImage(generator).withLocation(this.getLocation()).build(); } @Override public String getSuccessMessage(ConversationContext context, String input) { return Lang.HOLOGRAM_CREATED.getValue("id", hologram.getSaveId()); } })).buildConversation((Conversable) event.sender()).begin(); return true; } @Command( command = "create image <image_id> <world> <x> <y> <z>", description = "Create a hologram using images", permission = "holoapi.holo.create", help = "Images can be defined in the HoloAPI config file" ) public boolean createImageWithLocation(CommandEvent event) { if (!HoloAPI.getImageLoader().isLoaded()) { event.respond(Lang.IMAGES_NOT_LOADED.getValue()); return true; } Location location = MiscUtil.getLocation(event); if (location == null) { return true; } final ImageGenerator generator = HoloAPI.getImageLoader().getGenerator(event.sender(), event.variable("image_id")); if (generator == null) { return true; } Hologram hologram = new HologramFactory(HoloAPI.getCore()).withImage(generator).withLocation(location).build(); event.respond(Lang.HOLOGRAM_CREATED.getValue("id", hologram.getSaveId())); return true; } @Command( command = "create animation", description = "Create a hologram using animations", permission = "holoapi.holo.create", help = "Animation can be defined in the HoloAPI config file" ) public boolean createAnimation(CommandEvent event) { if (!(event.sender() instanceof Conversable)) { event.respond(Lang.NOT_CONVERSABLE.getValue()); return true; } InputFactory.buildBasicConversation().withFirstPrompt(new AnimationBuilderInputPrompt()).buildConversation((Conversable) event.sender()).begin(); return true; } @Command( command = "create animation <animation_id>", description = "Create a hologram using animations", permission = "holoapi.holo.create", help = "Animations can be defined in the HoloAPI config file" ) public boolean createAnimationWithId(CommandEvent event) { if (!(event.sender() instanceof Conversable)) { event.respond(Lang.NOT_CONVERSABLE.getValue()); return true; } if (!HoloAPI.getAnimationLoader().isLoaded()) { event.respond(Lang.IMAGES_NOT_LOADED.getValue()); return true; } final AnimatedImageGenerator generator = HoloAPI.getAnimationLoader().getGenerator(event.sender(), event.variable("animation_id")); if (generator == null) { return true; } if (event.sender() instanceof Player) { AnimatedHologram hologram = new AnimatedHologramFactory(HoloAPI.getCore()).withImage(generator).withLocation(((Player) event.sender()).getLocation()).build(); event.respond(Lang.HOLOGRAM_CREATED.getValue("id", hologram.getSaveId())); return true; } InputFactory.buildBasicConversation().withFirstPrompt(new SimpleInputPrompt(new LocationFunction() { AnimatedHologram hologram; @Override public void onFunction(ConversationContext context, String input) { hologram = new AnimatedHologramFactory(HoloAPI.getCore()).withImage(generator).withLocation(this.getLocation()).build(); } @Override public String getSuccessMessage(ConversationContext context, String input) { return Lang.HOLOGRAM_CREATED.getValue("id", hologram.getSaveId()); } })).buildConversation((Conversable) event.sender()).begin(); return true; } @Command( command = "create animation <animation_id> <world> <x> <y> <z>", description = "Create a hologram using animations", permission = "holoapi.holo.create", help = "Animations can be defined in the HoloAPI config file" ) public boolean createAnimationWithLocation(CommandEvent event) { if (!HoloAPI.getAnimationLoader().isLoaded()) { event.respond(Lang.IMAGES_NOT_LOADED.getValue()); return true; } Location location = MiscUtil.getLocation(event); if (location == null) { return true; } final AnimatedImageGenerator generator = HoloAPI.getAnimationLoader().getGenerator(event.sender(), event.variable("image_id")); if (generator == null) { return true; } AnimatedHologram hologram = new AnimatedHologramFactory(HoloAPI.getCore()).withImage(generator).withLocation(location).build(); event.respond(Lang.HOLOGRAM_CREATED.getValue("id", hologram.getSaveId())); return true; } }
9,667
Java
.java
DSH105/HoloAPI
31
16
21
2014-02-21T21:30:11Z
2014-12-24T12:52:54Z
UpdateCommand.java
/FileExtraction/Java_unseen/DSH105_HoloAPI/src/main/java/com/dsh105/holoapi/command/sub/UpdateCommand.java
/* * This file is part of HoloAPI. * * HoloAPI is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * HoloAPI is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with HoloAPI. If not, see <http://www.gnu.org/licenses/>. */ package com.dsh105.holoapi.command.sub; import com.dsh105.command.Command; import com.dsh105.command.CommandEvent; import com.dsh105.command.CommandListener; import com.dsh105.commodus.data.Updater; import com.dsh105.holoapi.HoloAPI; import com.dsh105.holoapi.config.Lang; public class UpdateCommand implements CommandListener { @Command( command = "update", description = "Update the plugin if a new release is available", permission = "holoapi.update" ) public boolean command(CommandEvent event) { if (HoloAPI.getCore().updateChecked) { new Updater(HoloAPI.getCore(), 74914, HoloAPI.getCore().file, Updater.UpdateType.NO_VERSION_CHECK, true); } else { event.respond(Lang.UPDATE_NOT_AVAILABLE.getValue()); } return true; } }
1,512
Java
.java
DSH105/HoloAPI
31
16
21
2014-02-21T21:30:11Z
2014-12-24T12:52:54Z
ScriptCommand.java
/FileExtraction/Java_unseen/DSH105_HoloAPI/src/main/java/com/dsh105/holoapi/command/sub/ScriptCommand.java
package com.dsh105.holoapi.command.sub; import com.dsh105.command.Command; import com.dsh105.command.CommandEvent; import com.dsh105.command.CommandListener; import com.dsh105.commodus.GeneralUtil; import com.dsh105.commodus.IdentUtil; import com.dsh105.commodus.StringUtil; import com.dsh105.holoapi.HoloAPI; import com.dsh105.holoapi.api.Hologram; import com.dsh105.holoapi.config.Lang; import com.dsh105.holoapi.conversation.InputFactory; import com.dsh105.holoapi.conversation.script.ScriptBuilderPrompt; import org.bukkit.command.ConsoleCommandSender; import org.bukkit.conversations.*; import org.bukkit.entity.Player; import java.util.concurrent.ConcurrentHashMap; public class ScriptCommand implements CommandListener { private final static ConcurrentHashMap<String, ScriptBuilderPrompt> SCRIPT_EDITORS = new ConcurrentHashMap<>(); @Command( command = "script add <id> <script_name>", description = "Adds the given script to the hologram with the given id", permission = "holoapi.holo.script.add" ) public boolean addScript(CommandEvent event) { final Hologram hologram = HoloAPI.getManager().getHologram(event.variable("id")); if (hologram == null) { event.respond(Lang.HOLOGRAM_NOT_FOUND.getValue("id", event.variable("id"))); return true; } return false; } @Command( command = "script remove <id> <script_name>", description = "Removes a script from the given hologram", permission = "holoapi.holo.script.remove" ) public boolean removeScript(CommandEvent event) { return false; } @Command( command = "script create <name>", description = "Created a new Script with the given name", permission = "holoapi.holo.script.create" ) public boolean createScript(final CommandEvent event) { if (!(event.sender() instanceof Player) && !(event.sender() instanceof ConsoleCommandSender)) { event.respond(Lang.NOT_CONVERSABLE.getValue()); return true; } String ident = event.sender() instanceof Player ? IdentUtil.getIdentificationForAsString((Player) event.sender()) : "CONSOLE"; final String scriptName = event.variable("script_name"); InputFactory.buildBasicConversation().withFirstPrompt(new StringPrompt() { boolean failed; @Override public String getPromptText(ConversationContext context) { return failed ? Lang.PROMPT_SCRIPT_VALID_TYPE.getValue() : Lang.PROMPT_SCRIPT_TYPE.getValue(); } @Override public Prompt acceptInput(ConversationContext context, String input) { if (input.equalsIgnoreCase("FORMAT") || input.equalsIgnoreCase("TOUCH")) { Lang.PROMPT_SCRIPT_ENTER.send(context.getForWhom()); ScriptBuilderPrompt scriptBuilder = new ScriptBuilderPrompt(input.toLowerCase(), scriptName); SCRIPT_EDITORS.put(event.sender() instanceof Player ? IdentUtil.getIdentificationForAsString((Player) event.sender()) : "CONSOLE", scriptBuilder); return END_OF_CONVERSATION; } failed = true; return this; } }).buildConversation((Conversable) event.sender()); // Now that we have our type... ScriptBuilderPrompt prompt = SCRIPT_EDITORS.get(ident); // And now we build it! InputFactory.buildBasicConversation().withFirstPrompt(prompt).addConversationAbandonedListener(new ScriptAbandonedListener()).buildConversation((Conversable) event.sender()); return true; } /* * NOT INTENDED TO BE USED OUTSIDE OF HOVER TOOLTIPS * ONLY FOR CLICKED SCRIPT LINES */ @Command( command = "script editcurrent <line>", description = "Edits a script currently being built. Not intended for general use outside of context.", includeInHelp = false // No permission, as this cannot be called without another command executing it ) public boolean editCurrentScript(CommandEvent event) { if (!(event.sender() instanceof Conversable)) { event.respond(Lang.NOT_CONVERSABLE.getValue()); return true; } ScriptBuilderPrompt scriptBuilder = SCRIPT_EDITORS.get(getIdent((Conversable) event.sender())); if (scriptBuilder == null) { event.respond(Lang.PROMPT_SCRIPT_NOT_EDITING.getValue()); return true; } int line = 0; try { line = GeneralUtil.toInteger(event.variable("line")); } catch (NumberFormatException e) { event.respond(Lang.INT_ONLY.getValue("string", event.variable("line"))); } event.respond(Lang.PROMPT_SCRIPT_LINE_CHANGE.getValue("line", event.variable("line"))); scriptBuilder.setCurrentlyEditing(line); return true; } @Command( command = "script edit <name>", description = "Edits the script with the given name", permission = "holoapi.holo.script.edit" ) public boolean editScript(CommandEvent event) { return false; } @Command( command = "script list", description = "Displays a list of all loaded Scripts", permission = "holoapi.holo.script.list" ) public boolean showScript(CommandEvent event) { return true; } private String getIdent(Conversable conversable) { return conversable instanceof Player ? IdentUtil.getIdentificationForAsString((Player) conversable) : "CONSOLE"; } class ScriptAbandonedListener implements ConversationAbandonedListener { @Override public void conversationAbandoned(ConversationAbandonedEvent event) { // Make sure to cleanup! SCRIPT_EDITORS.remove(getIdent(event.getContext().getForWhom())); } } }
6,206
Java
.java
DSH105/HoloAPI
31
16
21
2014-02-21T21:30:11Z
2014-12-24T12:52:54Z
CopyCommand.java
/FileExtraction/Java_unseen/DSH105_HoloAPI/src/main/java/com/dsh105/holoapi/command/sub/CopyCommand.java
/* * This file is part of HoloAPI. * * HoloAPI is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * HoloAPI is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with HoloAPI. If not, see <http://www.gnu.org/licenses/>. */ package com.dsh105.holoapi.command.sub; import com.dsh105.command.Command; import com.dsh105.command.CommandEvent; import com.dsh105.command.CommandListener; import com.dsh105.holoapi.HoloAPI; import com.dsh105.holoapi.api.AnimatedHologram; import com.dsh105.holoapi.api.Hologram; import com.dsh105.holoapi.config.Lang; import com.dsh105.holoapi.conversation.InputFactory; import com.dsh105.holoapi.conversation.basic.LocationFunction; import com.dsh105.holoapi.conversation.basic.SimpleInputPrompt; import com.dsh105.holoapi.util.MiscUtil; import org.bukkit.Location; import org.bukkit.conversations.Conversable; import org.bukkit.conversations.ConversationContext; import org.bukkit.entity.Player; public class CopyCommand implements CommandListener { @Command( command = "copy <id>", description = "Copy a hologram to your current position", permission = "holoapi.holo.copy" ) public boolean command(CommandEvent event) { if (!(event.sender() instanceof Conversable)) { event.respond(Lang.NOT_CONVERSABLE.getValue()); } final Hologram hologram = HoloAPI.getManager().getHologram(event.variable("id")); if (hologram == null) { event.respond(Lang.HOLOGRAM_NOT_FOUND.getValue("id", event.variable("id"))); return true; } if (event.sender() instanceof Player) { Hologram copy = HoloAPI.getManager().copy(hologram, ((Player) event.sender()).getLocation()); if (copy instanceof AnimatedHologram) { event.respond(Lang.HOLOGRAM_ANIMATED_COPIED.getValue("id", hologram.getSaveId())); } else { event.respond(Lang.HOLOGRAM_COPIED.getValue("id", hologram.getSaveId())); } return true; } InputFactory.buildBasicConversation().withFirstPrompt(new SimpleInputPrompt(new LocationFunction() { Hologram copy; @Override public void onFunction(ConversationContext context, String input) { copy = HoloAPI.getManager().copy(hologram, getLocation()); } @Override public String getSuccessMessage(ConversationContext context, String input) { if (copy instanceof AnimatedHologram) { return Lang.HOLOGRAM_ANIMATED_COPIED.getValue("id", hologram.getSaveId()); } return Lang.HOLOGRAM_COPIED.getValue("id", hologram.getSaveId()); } })).buildConversation((Conversable) event.sender()).begin(); return true; } @Command( command = "copy <id> <world> <x> <y> <z>", description = "Copy a hologram to a new position", permission = "holoapi.holo.copy" ) public boolean withLocation(CommandEvent event) { Hologram hologram = HoloAPI.getManager().getHologram(event.variable("id")); if (hologram == null) { event.respond(Lang.HOLOGRAM_NOT_FOUND.getValue("id", event.variable("id"))); return true; } Location location = MiscUtil.getLocation(event); if (location == null) { return true; } Hologram copy = HoloAPI.getManager().copy(hologram, location); if (copy instanceof AnimatedHologram) { event.respond(Lang.HOLOGRAM_ANIMATED_COPIED.getValue("id", hologram.getSaveId())); } else { event.respond(Lang.HOLOGRAM_COPIED.getValue("id", hologram.getSaveId())); } return true; } }
4,248
Java
.java
DSH105/HoloAPI
31
16
21
2014-02-21T21:30:11Z
2014-12-24T12:52:54Z
RemoveCommand.java
/FileExtraction/Java_unseen/DSH105_HoloAPI/src/main/java/com/dsh105/holoapi/command/sub/RemoveCommand.java
/* * This file is part of HoloAPI. * * HoloAPI is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * HoloAPI is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with HoloAPI. If not, see <http://www.gnu.org/licenses/>. */ package com.dsh105.holoapi.command.sub; import com.dsh105.command.Command; import com.dsh105.command.CommandEvent; import com.dsh105.command.CommandListener; import com.dsh105.holoapi.HoloAPI; import com.dsh105.holoapi.api.Hologram; import com.dsh105.holoapi.config.Lang; import com.dsh105.holoapi.conversation.InputFactory; import com.dsh105.holoapi.conversation.basic.SimpleInputPrompt; import com.dsh105.holoapi.conversation.basic.YesNoFunction; import org.apache.commons.lang.BooleanUtils; import org.bukkit.conversations.Conversable; import org.bukkit.conversations.ConversationContext; public class RemoveCommand implements CommandListener { @Command( command = "remove <id>", description = "Remove an existing hologram using its ID", permission = "holoapi.holo.remove" ) public boolean command(CommandEvent event) { final Hologram hologram = HoloAPI.getManager().getHologram(event.variable("id")); if (hologram == null) { event.respond(Lang.HOLOGRAM_NOT_FOUND.getValue("id", event.variable("id"))); return true; } if (event.sender() instanceof Conversable) { InputFactory.buildBasicConversation().withFirstPrompt(new SimpleInputPrompt(new YesNoFunction() { private boolean success; @Override public void onFunction(ConversationContext context, String input) { if (BooleanUtils.toBoolean(input)) { HoloAPI.getManager().clearFromFile(hologram.getSaveId()); success = true; } } @Override public String getSuccessMessage(ConversationContext context, String input) { return success ? Lang.HOLOGRAM_CLEARED_FILE.getValue("id", hologram.getSaveId()) : Lang.HOLOGRAM_REMOVED_MEMORY.getValue("id", hologram.getSaveId()); } @Override public String getPromptText(ConversationContext context) { return Lang.YES_NO_CLEAR_FROM_FILE.getValue(); } @Override public String getFailedText(ConversationContext context, String invalidInput) { return Lang.YES_NO_INPUT_INVALID.getValue(); } })).buildConversation((Conversable) event.sender()).begin(); } else { HoloAPI.getManager().clearFromFile(hologram.getSaveId()); event.respond(Lang.HOLOGRAM_CLEARED_FILE.getValue("id", hologram.getSaveId())); } HoloAPI.getManager().stopTracking(hologram); return true; } @Command( command = "remove <id> <keep>", description = "Remove an existing hologram using its ID", permission = "holoapi.holo.remove", help = {"<keep> defines whether the hologram is removed from the save files", "If set to false, the hologram will only be removed from memory"} ) public boolean withKeep(CommandEvent event) { Hologram hologram = HoloAPI.getManager().getHologram(event.variable("id")); if (hologram == null) { event.respond(Lang.HOLOGRAM_NOT_FOUND.getValue("id", event.variable("id"))); return true; } if (BooleanUtils.toBoolean(event.variable("keep"))) { HoloAPI.getManager().clearFromFile(hologram.getSaveId()); } else { Lang.HOLOGRAM_REMOVED_MEMORY.getValue("id", hologram.getSaveId()); } HoloAPI.getManager().stopTracking(hologram); return true; } }
4,325
Java
.java
DSH105/HoloAPI
31
16
21
2014-02-21T21:30:11Z
2014-12-24T12:52:54Z
AddLineCommand.java
/FileExtraction/Java_unseen/DSH105_HoloAPI/src/main/java/com/dsh105/holoapi/command/sub/AddLineCommand.java
/* * This file is part of HoloAPI. * * HoloAPI is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * HoloAPI is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with HoloAPI. If not, see <http://www.gnu.org/licenses/>. */ package com.dsh105.holoapi.command.sub; import com.dsh105.command.Command; import com.dsh105.command.CommandEvent; import com.dsh105.command.CommandListener; import com.dsh105.holoapi.HoloAPI; import com.dsh105.holoapi.api.AnimatedHologram; import com.dsh105.holoapi.api.Hologram; import com.dsh105.holoapi.config.Lang; import com.dsh105.holoapi.conversation.InputFactory; import com.dsh105.holoapi.conversation.basic.SimpleInputFunction; import com.dsh105.holoapi.conversation.basic.SimpleInputPrompt; import org.bukkit.conversations.Conversable; import org.bukkit.conversations.ConversationContext; public class AddLineCommand implements CommandListener { @Command( command = "addline <id> <line...>", description = "Add a new line to an existing hologram", permission = "holoapi.holo.addline", help = "New line content can be more than one word." ) public boolean withLine(CommandEvent event) { Hologram hologram = getHologram(event); if (hologram == null) { return true; } HoloAPI.getManager().copyAndAddLineTo(hologram, event.variable("line")); event.respond(Lang.HOLOGRAM_ADDED_LINE.getValue("id", hologram.getSaveId())); return true; } @Command( command = "addline <id>", description = "Add a new line to an existing hologram", permission = "holoapi.holo.addline", help = {"New line content can be more than one word.", "After entering this command, you will be prompted to enter the new line."} ) public boolean withoutLine(final CommandEvent event) { final Hologram hologram = getHologram(event); if (hologram == null) { return true; } if (!(event.sender() instanceof Conversable)) { event.respond(Lang.NOT_CONVERSABLE.getValue()); return true; } InputFactory.buildBasicConversation().withFirstPrompt(new SimpleInputPrompt(new SimpleInputFunction() { @Override public void onFunction(ConversationContext context, String input) { HoloAPI.getManager().copyAndAddLineTo(hologram, input); event.respond(Lang.HOLOGRAM_ADDED_LINE.getValue("id", hologram.getSaveId())); } @Override public String getSuccessMessage(ConversationContext context, String input) { return Lang.HOLOGRAM_ADDED_LINE.getValue("id", input); } @Override public String getPromptText(ConversationContext context) { return Lang.PROMPT_ENTER_NEW_LINE.getValue(); } @Override public String getFailedText(ConversationContext context, String invalidInput) { return null; } })).buildConversation((Conversable) event.sender()).begin(); return true; } private Hologram getHologram(CommandEvent event) { final Hologram hologram = HoloAPI.getManager().getHologram(event.variable("id")); if (hologram == null) { event.respond(Lang.HOLOGRAM_NOT_FOUND.getValue("id", event.variable("id"))); return null; } if (hologram instanceof AnimatedHologram) { event.respond(Lang.HOLOGRAM_ADD_LINE_ANIMATED.getValue()); return null; } return hologram; } }
4,104
Java
.java
DSH105/HoloAPI
31
16
21
2014-02-21T21:30:11Z
2014-12-24T12:52:54Z
VisibilityCommand.java
/FileExtraction/Java_unseen/DSH105_HoloAPI/src/main/java/com/dsh105/holoapi/command/sub/VisibilityCommand.java
/* * This file is part of HoloAPI. * * HoloAPI is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * HoloAPI is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with HoloAPI. If not, see <http://www.gnu.org/licenses/>. */ package com.dsh105.holoapi.command.sub; import com.dsh105.command.Command; import com.dsh105.command.CommandEvent; import com.dsh105.command.CommandListener; import com.dsh105.commodus.StringUtil; import com.dsh105.holoapi.HoloAPI; import com.dsh105.holoapi.api.Hologram; import com.dsh105.holoapi.api.visibility.Visibility; import com.dsh105.holoapi.config.Lang; public class VisibilityCommand implements CommandListener { @Command( command = "visibility <id>", description = "Fetch the current visibility of a particular hologram", permission = "holoapi.holo.visibility" ) public boolean command(CommandEvent event) { Hologram hologram = HoloAPI.getManager().getHologram(event.variable("id")); if (hologram == null) { event.respond(Lang.HOLOGRAM_NOT_FOUND.getValue("id", event.variable("id"))); return true; } String visibilityKey = HoloAPI.getVisibilityMatcher().getKeyOf(hologram.getVisibility()); if (visibilityKey == null) { event.respond(Lang.HOLOGRAM_VISIBILITY_UNREGISTERED.getValue("id", hologram.getSaveId())); } event.respond(Lang.HOLOGRAM_VISIBILITY.getValue("id", hologram.getSaveId(), "visibility", visibilityKey)); return true; } @Command( command = "visibility <id> <type>", description = "Set the visibility of a particular hologram", permission = "holoapi.holo.visibility.set", help = {"Valid types for HoloAPI are: all, permission.", "Visibility types dynamically registered using the API may be defined using this command.", "See the Wiki for more information"} ) public boolean set(CommandEvent event) { Hologram hologram = HoloAPI.getManager().getHologram(event.variable("id")); if (hologram == null) { event.respond(Lang.HOLOGRAM_NOT_FOUND.getValue("id", event.variable("id"))); return true; } Visibility visibility = HoloAPI.getVisibilityMatcher().get(event.variable("type")); if (visibility == null) { event.respond(Lang.INVALID_VISIBILITY.getValue("visibility", event.variable("type"))); event.respond(Lang.VALID_VISIBILITIES.getValue("vis", StringUtil.combine(", ", HoloAPI.getVisibilityMatcher().getValidVisibilities().keySet()))); return true; } hologram.setVisibility(visibility); event.respond(Lang.HOLOGRAM_VISIBILITY_SET.getValue("id", event.variable("id"), "visibility", event.variable("type"))); return true; } }
3,279
Java
.java
DSH105/HoloAPI
31
16
21
2014-02-21T21:30:11Z
2014-12-24T12:52:54Z
ShowCommand.java
/FileExtraction/Java_unseen/DSH105_HoloAPI/src/main/java/com/dsh105/holoapi/command/sub/ShowCommand.java
/* * This file is part of HoloAPI. * * HoloAPI is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * HoloAPI is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with HoloAPI. If not, see <http://www.gnu.org/licenses/>. */ package com.dsh105.holoapi.command.sub; import com.dsh105.command.Command; import com.dsh105.command.CommandEvent; import com.dsh105.command.CommandListener; import com.dsh105.holoapi.HoloAPI; import com.dsh105.holoapi.api.Hologram; import com.dsh105.holoapi.config.Lang; import org.bukkit.Bukkit; import org.bukkit.entity.Player; public class ShowCommand implements CommandListener { @Command( command = "show <id> <player>", description = "Show a hologram to a player", permission = "holoapi.holo.show" ) public boolean command(CommandEvent event) { Hologram hologram = HoloAPI.getManager().getHologram(event.variable("id")); if (hologram == null) { event.respond(Lang.HOLOGRAM_NOT_FOUND.getValue("id", event.variable("id"))); return true; } Player target = Bukkit.getPlayer(event.variable("player")); if (target == null) { event.respond(Lang.NULL_PLAYER.getValue("player", event.variable("player"))); return true; } if (hologram.canBeSeenBy(target)) { event.respond(Lang.HOLOGRAM_ALREADY_SEE.getValue("id", event.variable("id"), "player", event.variable("player"))); return true; } hologram.show(target); event.respond(Lang.HOLOGRAM_SHOW.getValue("id", event.variable("id"), "player", event.variable("player"))); return true; } }
2,125
Java
.java
DSH105/HoloAPI
31
16
21
2014-02-21T21:30:11Z
2014-12-24T12:52:54Z
MoveCommand.java
/FileExtraction/Java_unseen/DSH105_HoloAPI/src/main/java/com/dsh105/holoapi/command/sub/MoveCommand.java
/* * This file is part of HoloAPI. * * HoloAPI is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * HoloAPI is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with HoloAPI. If not, see <http://www.gnu.org/licenses/>. */ package com.dsh105.holoapi.command.sub; import com.dsh105.command.Command; import com.dsh105.command.CommandEvent; import com.dsh105.command.CommandListener; import com.dsh105.holoapi.HoloAPI; import com.dsh105.holoapi.api.Hologram; import com.dsh105.holoapi.config.Lang; import com.dsh105.holoapi.util.MiscUtil; import org.bukkit.Location; import org.bukkit.entity.Player; public class MoveCommand implements CommandListener { @Command( command = "move <id>", description = "Move a hologram to your current position", permission = "holoapi.holo.move" ) public boolean command(CommandEvent<Player> event) { final Hologram hologram = HoloAPI.getManager().getHologram(event.variable("id")); if (hologram == null) { event.respond(Lang.HOLOGRAM_NOT_FOUND.getValue("id", event.variable("id"))); return true; } hologram.move(event.sender().getLocation()); event.respond(Lang.HOLOGRAM_MOVED.getValue()); return true; } @Command( command = "move <id> <world> <x> <y> <z>", description = "Move a hologram to your current position", permission = "holoapi.holo.move" ) public boolean moveLocation(CommandEvent<Player> event) { Hologram hologram = HoloAPI.getManager().getHologram(event.variable("id")); if (hologram == null) { event.respond(Lang.HOLOGRAM_NOT_FOUND.getValue("id", event.variable("id"))); return true; } Location location = MiscUtil.getLocation(event); if (location == null) { return true; } hologram.move(location); event.respond(Lang.HOLOGRAM_MOVED.getValue()); return true; } }
2,450
Java
.java
DSH105/HoloAPI
31
16
21
2014-02-21T21:30:11Z
2014-12-24T12:52:54Z
ClearCommand.java
/FileExtraction/Java_unseen/DSH105_HoloAPI/src/main/java/com/dsh105/holoapi/command/sub/ClearCommand.java
/* * This file is part of HoloAPI. * * HoloAPI is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * HoloAPI is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with HoloAPI. If not, see <http://www.gnu.org/licenses/>. */ package com.dsh105.holoapi.command.sub; import com.dsh105.command.Command; import com.dsh105.command.CommandEvent; import com.dsh105.command.CommandListener; import com.dsh105.commodus.StringUtil; import com.dsh105.holoapi.HoloAPI; import com.dsh105.holoapi.api.Hologram; import com.dsh105.holoapi.config.Lang; import com.dsh105.holoapi.util.MiscUtil; import org.bukkit.Location; import org.bukkit.entity.LightningStrike; import org.bukkit.entity.Player; import java.util.ArrayList; import java.util.Arrays; import java.util.Iterator; import java.util.List; public class ClearCommand implements CommandListener { private static final List<String> VALID_TYPES = Arrays.asList("all", "complex", "simple"); @Command( command = "clear", description = "Clear all holograms (simple holograms not included)", permission = "holoapi.holo.clear" ) public boolean command(CommandEvent event) { clear("ALL"); event.respond(Lang.COMPLEX_HOLOGRAMS_CLEARED.getValue()); return true; } @Command( command = "clear <type>", description = "Clear all holograms of a certain type", permission = "holoapi.holo.clear", help = "Valid types are: COMPLEX, SIMPLE, ALL" ) public boolean clearType(CommandEvent event) { if (!VALID_TYPES.contains(event.variable("type").toLowerCase())) { event.respond(Lang.INVALID_CLEAR_TYPE.getValue("type", event.variable("type"), "valid", StringUtil.combine(", ", VALID_TYPES))); return true; } clear(event.variable("type")); if (event.variable("type").equalsIgnoreCase("COMPLEX")) { event.respond(Lang.COMPLEX_HOLOGRAMS_CLEARED.getValue()); } else if (event.variable("type").equalsIgnoreCase("SIMPLE")) { event.respond(Lang.SIMPLE_HOLOGRAMS_CLEARED.getValue()); } else { event.respond(Lang.ALL_HOLOGRAMS_CLEARED.getValue()); } return true; } private void clear(String type) { ArrayList<Hologram> toClear = new ArrayList<>(); for (Hologram h : HoloAPI.getManager().getAllComplexHolograms().keySet()) { if (type.equalsIgnoreCase("COMPLEX") && h.isSimple()) { continue; } if (type.equalsIgnoreCase("SIMPLE") && !h.isSimple()) { continue; } if (!h.isSimple()) { HoloAPI.getManager().saveToFile(h); } h.clearAllPlayerViews(); toClear.add(h); } for (Hologram hologram : toClear) { HoloAPI.getManager().remove(hologram); HoloAPI.getManager().clearFromFile(hologram); } } }
3,442
Java
.java
DSH105/HoloAPI
31
16
21
2014-02-21T21:30:11Z
2014-12-24T12:52:54Z
UnloadedImageStorage.java
/FileExtraction/Java_unseen/DSH105_HoloAPI/src/main/java/com/dsh105/holoapi/image/UnloadedImageStorage.java
/* * This file is part of HoloAPI. * * HoloAPI is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * HoloAPI is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with HoloAPI. If not, see <http://www.gnu.org/licenses/>. */ package com.dsh105.holoapi.image; public class UnloadedImageStorage { private String imagePath; private int imageHeight; private int frameRate; private ImageChar charType; private boolean requiresBorder; public UnloadedImageStorage(String imagePath, int imageHeight, ImageChar charType, boolean requiresBorder) { this.imagePath = imagePath; this.imageHeight = imageHeight; this.charType = charType; this.requiresBorder = requiresBorder; } public UnloadedImageStorage(String imagePath, int imageHeight, int frameRate, ImageChar charType, boolean requiresBorder) { this.imagePath = imagePath; this.imageHeight = imageHeight; this.frameRate = frameRate; this.charType = charType; this.requiresBorder = requiresBorder; } public String getImagePath() { return imagePath; } public void setImagePath(String imagePath) { this.imagePath = imagePath; } public int getImageHeight() { return imageHeight; } public void setImageHeight(int imageHeight) { this.imageHeight = imageHeight; } public ImageChar getCharType() { return charType; } public void setCharType(ImageChar charType) { this.charType = charType; } public int getFrameRate() { return frameRate; } public void setFrameRate(int frameRate) { this.frameRate = frameRate; } public boolean requiresBorder() { return requiresBorder; } public void setRequiresBorder(boolean requiresBorder) { this.requiresBorder = requiresBorder; } }
2,334
Java
.java
DSH105/HoloAPI
31
16
21
2014-02-21T21:30:11Z
2014-12-24T12:52:54Z
Generator.java
/FileExtraction/Java_unseen/DSH105_HoloAPI/src/main/java/com/dsh105/holoapi/image/Generator.java
/* * This file is part of HoloAPI. * * HoloAPI is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * HoloAPI is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with HoloAPI. If not, see <http://www.gnu.org/licenses/>. */ package com.dsh105.holoapi.image; public interface Generator { /** * Gets the key of the generator. The key is defined in the HoloAPI Configuration file by the server operator and * is * registered on startup * * @return key of the generator */ public String getKey(); }
985
Java
.java
DSH105/HoloAPI
31
16
21
2014-02-21T21:30:11Z
2014-12-24T12:52:54Z
GIFFrame.java
/FileExtraction/Java_unseen/DSH105_HoloAPI/src/main/java/com/dsh105/holoapi/image/GIFFrame.java
/* * This file is part of HoloAPI. * * HoloAPI is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * HoloAPI is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with HoloAPI. If not, see <http://www.gnu.org/licenses/>. */ package com.dsh105.holoapi.image; import java.awt.image.BufferedImage; /** * Represents an animated frame generated by a GIF image */ public class GIFFrame extends Frame { protected BufferedImage image; protected String disposal; protected ImageGenerator imageGenerator; protected GIFFrame(BufferedImage image, int delay, String disposal) { super(delay); this.image = image; this.disposal = disposal; } protected GIFFrame(ImageGenerator generator, int delay) { super(delay); this.imageGenerator = generator; } /** * Gets the image generator used to generate the frame lines * * @return image generator used */ public ImageGenerator getImageGenerator() { return imageGenerator; } @Override public String[] getLines() { return this.imageGenerator.getLines(); } }
1,574
Java
.java
DSH105/HoloAPI
31
16
21
2014-02-21T21:30:11Z
2014-12-24T12:52:54Z
ImageLoader.java
/FileExtraction/Java_unseen/DSH105_HoloAPI/src/main/java/com/dsh105/holoapi/image/ImageLoader.java
/* * This file is part of HoloAPI. * * HoloAPI is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * HoloAPI is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with HoloAPI. If not, see <http://www.gnu.org/licenses/>. */ package com.dsh105.holoapi.image; import org.bukkit.command.CommandSender; /** * Represents an image loader used to store pre-loaded images and animations from the HoloAPI Configuration file * * @param <T> type of generator */ public interface ImageLoader<T extends Generator> { /** * Gets a loaded generator. If the generator found has a URL type and has not yet been loaded, the loading process * will be started and the method will return null * <p> * Also sends a message to the {@link org.bukkit.command.CommandSender} if the URL image is being loaded * * @param sender sender to send the URL loading message to * @param key key to search for a generator with * @return Image or Animation loader loaded with HoloAPI. Returns null if the image generator is not found or a URL * generator is being loaded */ public T getGenerator(CommandSender sender, String key); /** * Gets a loaded generator. If the generator found has a URL type and has not yet been loaded, the loading process * will be started and the method will return null * * @param key key to search for a generator with * @return Image or Animation loader loaded with HoloAPI. Returns null if the image generator is not found or a URL * generator is being loaded */ public T getGenerator(String key); /** * Checks and returns whether a generator of a key exists. This does NOT check for unloaded URL generators * * @param key key to search for a generator with * @return true if the generator exists */ public boolean exists(String key); /** * Checks and returns whether an unloaded URL generator of a key exists. This ONLY checks for UNLOADED URL * generators * * @param key key to search for a generator with * @return true if the unloaded URL generator exists */ public boolean existsAsUnloadedUrl(String key); /** * Gets whether this loader has finished loading all generators * * @return true if finished loading */ public boolean isLoaded(); /** * Represents the type of image being loaded */ public enum ImageLoadType { /** * Represents a URL image that is retrieved from a HTTP address */ URL, /** * Represents an image that can be located within the HoloAPI plugin data folder */ FILE } }
3,145
Java
.java
DSH105/HoloAPI
31
16
21
2014-02-21T21:30:11Z
2014-12-24T12:52:54Z
ColourMap.java
/FileExtraction/Java_unseen/DSH105_HoloAPI/src/main/java/com/dsh105/holoapi/image/ColourMap.java
/* * This file is part of HoloAPI. * * HoloAPI is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * HoloAPI is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with HoloAPI. If not, see <http://www.gnu.org/licenses/>. */ package com.dsh105.holoapi.image; import org.bukkit.ChatColor; import java.awt.*; public class ColourMap { protected static final Color[] colors = { new Color(0, 0, 0), new Color(0, 0, 170), new Color(0, 170, 0), new Color(0, 170, 170), new Color(170, 0, 0), new Color(170, 0, 170), new Color(255, 170, 0), new Color(170, 170, 170), new Color(85, 85, 85), new Color(85, 85, 255), new Color(85, 255, 85), new Color(85, 255, 255), new Color(255, 85, 85), new Color(255, 85, 255), new Color(255, 255, 85), new Color(255, 255, 255), }; protected static ChatColor getClosest(Color color) { if (color.getAlpha() < 128) return null; int index = 0; double best = -1; for (int i = 0; i < ColourMap.colors.length; i++) { if (areIdentical(ColourMap.colors[i], color)) { return ChatColor.values()[i]; } } for (int i = 0; i < ColourMap.colors.length; i++) { double distance = getDistance(color, ColourMap.colors[i]); if (distance < best || best == -1) { best = distance; index = i; } } // Minecraft has 15 colors return ChatColor.values()[index]; } private static boolean areIdentical(Color c1, Color c2) { return Math.abs(c1.getRed() - c2.getRed()) <= 5 && Math.abs(c1.getGreen() - c2.getGreen()) <= 5 && Math.abs(c1.getBlue() - c2.getBlue()) <= 5; } private static double getDistance(Color c1, Color c2) { double rmean = (c1.getRed() + c2.getRed()) / 2.0; double r = c1.getRed() - c2.getRed(); double g = c1.getGreen() - c2.getGreen(); int b = c1.getBlue() - c2.getBlue(); double weightR = 2 + rmean / 256.0; double weightG = 4.0; double weightB = 2 + (255 - rmean) / 256.0; return weightR * r * r + weightG * g * g + weightB * b * b; } }
2,821
Java
.java
DSH105/HoloAPI
31
16
21
2014-02-21T21:30:11Z
2014-12-24T12:52:54Z
ImageChar.java
/FileExtraction/Java_unseen/DSH105_HoloAPI/src/main/java/com/dsh105/holoapi/image/ImageChar.java
/* * This file is part of HoloAPI. * * HoloAPI is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * HoloAPI is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with HoloAPI. If not, see <http://www.gnu.org/licenses/>. */ package com.dsh105.holoapi.image; public enum ImageChar { /** * Represents a filled block character */ BLOCK('\u2588', "block"), /** * Represents a dark shaded character */ DARK_SHADE('\u2593', "dark"), /** * Represents a half shaded character */ MEDIUM_SHADE('\u2592', "medium"), /** * Represents a lightly shaded character */ LIGHT_SHADE('\u2591', "light"); private char imageChar; private String humanName; ImageChar(char imageChar, String humanName) { this.imageChar = imageChar; this.humanName = humanName; } /** * Gets the character of the ImageChar * * @return character of the ImageChar */ public char getImageChar() { return imageChar; } /** * Gets the friendly name * * @return friendly name */ public String getHumanName() { return humanName; } /** * Gets the appropriate ImageChar from its friendly name * * @param humanName friendly name used to search for * @return ImageChar if found, null if it doesn't exist */ public static ImageChar fromHumanName(String humanName) { for (ImageChar c : ImageChar.values()) { if (c.getHumanName().equalsIgnoreCase(humanName)) { return c; } } return null; } }
2,079
Java
.java
DSH105/HoloAPI
31
16
21
2014-02-21T21:30:11Z
2014-12-24T12:52:54Z
ImageGenerator.java
/FileExtraction/Java_unseen/DSH105_HoloAPI/src/main/java/com/dsh105/holoapi/image/ImageGenerator.java
/* * This file is part of HoloAPI. * * HoloAPI is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * HoloAPI is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with HoloAPI. If not, see <http://www.gnu.org/licenses/>. */ package com.dsh105.holoapi.image; import com.dsh105.holoapi.HoloAPI; import com.dsh105.holoapi.config.Settings; import org.bukkit.ChatColor; import javax.imageio.ImageIO; import java.awt.*; import java.awt.geom.AffineTransform; import java.awt.image.AffineTransformOp; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import java.net.URI; /** * Represents a generator used to produce images * <p> * Original code by @bobacadodl * https://forums.bukkit.org/threads/204902/ */ public class ImageGenerator implements Generator { private String lines[]; private String imageKey; private String imageUrl; private int imageHeight; private ImageChar imageChar = ImageChar.BLOCK; private boolean requiresBorder; private boolean hasLoaded; protected ImageGenerator(BufferedImage image, int height, ImageChar imgChar) { this.imageHeight = height; this.imageChar = imgChar; this.lines = this.generate(generateColours(image, height), imgChar.getImageChar(), false); } /** * Constructs an ImageGenerator for use in a Hologram * * @param image {@link java.awt.image.BufferedImage} used to generate the image * @param height height of the display * @param imgChar {@link com.dsh105.holoapi.image.ImageChar} of the display * @param requiresBorder whether the display requires a border */ public ImageGenerator(BufferedImage image, int height, ImageChar imgChar, boolean requiresBorder) { this.imageHeight = height; this.imageChar = imgChar; this.requiresBorder = requiresBorder; this.lines = this.generate(generateColours(image, height), imgChar.getImageChar(), requiresBorder); } /** * Constructs an ImageGenerator for use in a Hologram * * @param imageUrl URL to search the image for * @param height height of the display * @param imgChar {@link com.dsh105.holoapi.image.ImageChar} of the display * @param requiresBorder whether the display requires a border */ public ImageGenerator(String imageUrl, int height, ImageChar imgChar, boolean requiresBorder) { this(imageUrl, height, imgChar, true, requiresBorder); } /** * Constructs an ImageGenerator for use in a Hologram * * @param imageUrl URL to search the image for * @param height height of the display * @param imgChar {@link com.dsh105.holoapi.image.ImageChar} of the display * @param loadUrl whether to automatically load the image from the specified URL * @param requiresBorder whether the display requires a border */ public ImageGenerator(String imageUrl, int height, ImageChar imgChar, boolean loadUrl, boolean requiresBorder) { this.imageUrl = imageUrl; this.imageHeight = height; this.imageChar = imgChar; this.requiresBorder = requiresBorder; if (loadUrl) { this.loadUrlImage(); } } /** * Constructs an ImageGenerator for use in a Hologram * * @param imageFile file used to generate the image * @param height height of the display * @param imgChar {@link com.dsh105.holoapi.image.ImageChar} of the display * @param requiresBorder whether the display requires a border * @throws java.lang.RuntimeException if the image cannot be read */ public ImageGenerator(File imageFile, int height, ImageChar imgChar, boolean requiresBorder) { this.imageHeight = height; this.imageChar = imgChar; this.requiresBorder = requiresBorder; BufferedImage image; try { image = ImageIO.read(imageFile); } catch (IOException e) { throw new RuntimeException("Cannot read image " + imageFile.getPath(), e); } this.lines = this.generate(generateColours(image, height), imgChar.getImageChar(), requiresBorder); } /** * Constructs an ImageGenerator for use in a Hologram * * @param imageKey key to store the generator under. Only used for recognition of stored image generators * @param image {@link java.awt.image.BufferedImage} used to generate the image * @param height height of the display * @param imgChar {@link com.dsh105.holoapi.image.ImageChar} of the display * @param requiresBorder whether the display requires a border */ public ImageGenerator(String imageKey, BufferedImage image, int height, ImageChar imgChar, boolean requiresBorder) { this(image, height, imgChar, requiresBorder); this.imageKey = imageKey; } /** * Constructs an ImageGenerator for use in a Hologram * * @param imageKey key to store the generator under. Only used for recognition of stored image generators * @param imageUrl URL to search the image for * @param height height of the display * @param imgChar {@link com.dsh105.holoapi.image.ImageChar} of the display * @param requiresBorder whether the display requires a border */ public ImageGenerator(String imageKey, String imageUrl, int height, ImageChar imgChar, boolean requiresBorder) { this(imageKey, imageUrl, height, imgChar, true, requiresBorder); } /** * Constructs an ImageGenerator for use in a Hologram * * @param imageKey key to store the generator under. Only used for recognition of stored image generators * @param imageUrl URL to search the image for * @param height height of the display * @param imgChar {@link com.dsh105.holoapi.image.ImageChar} of the display * @param loadUrl whether to automatically load the image from the specified URL * @param requiresBorder whether the display requires a border */ public ImageGenerator(String imageKey, String imageUrl, int height, ImageChar imgChar, boolean loadUrl, boolean requiresBorder) { this(imageUrl, height, imgChar, loadUrl, requiresBorder); this.imageKey = imageKey; } /** * Constructs an ImageGenerator for use in a Hologram * * @param imageKey key to store the generator under. Only used for recognition of stored image generators * @param imageFile file used to generate the image * @param height height of the display * @param imgChar {@link com.dsh105.holoapi.image.ImageChar} of the display * @param requiresBorder whether the display requires a border * @throws java.lang.RuntimeException if the image cannot be read */ public ImageGenerator(String imageKey, File imageFile, int height, ImageChar imgChar, boolean requiresBorder) { this(imageFile, height, imgChar, requiresBorder); this.imageKey = imageKey; } @Override public String getKey() { return imageKey; } /** * Loads the stored URL data to form a generated image * * @throws java.lang.IllegalArgumentException if the URL is not initiated * @throws java.lang.RuntimeException if the image cannot be read */ public void loadUrlImage() { if (this.hasLoaded) { return; } if (this.imageUrl == null) { throw new IllegalArgumentException("URL not initiated for ImageGenerator."); } URI uri = URI.create(this.imageUrl); BufferedImage image; try { image = ImageIO.read(uri.toURL()); } catch (IOException e) { throw new RuntimeException("Cannot read image " + uri, e); } this.lines = this.generate(generateColours(image, this.imageHeight), this.imageChar.getImageChar(), requiresBorder); this.hasLoaded = true; } /** * Gets the generated lines * * @return generated lines */ public String[] getLines() { return lines; } private String[] generate(ChatColor[][] colors, char imgchar, boolean border) { String[] lines = new String[colors[0].length]; for (int y = 0; y < colors[0].length; y++) { String line = ""; for (ChatColor[] color : colors) { ChatColor colour = color[y]; if (colour == null) { line += border ? Settings.TRANSPARENCY_WITH_BORDER.getValue() : Settings.TRANSPARENCY_WITHOUT_BORDER.getValue(); } else { line += colour.toString() + imgchar + ChatColor.RESET; } } if (!border) { line = line.trim(); } lines[y] = line + ChatColor.RESET; } return lines; } private ChatColor[][] generateColours(BufferedImage image, int height) { double ratio = (double) image.getHeight() / image.getWidth(); BufferedImage resized = resize(image, (int) (height / ratio), height); ChatColor[][] chatImg = new ChatColor[resized.getWidth()][resized.getHeight()]; for (int x = 0; x < resized.getWidth(); x++) { for (int y = 0; y < resized.getHeight(); y++) { int rgb = resized.getRGB(x, y); ChatColor closest = ColourMap.getClosest(new Color(rgb, true)); chatImg[x][y] = closest; } } return chatImg; } private BufferedImage resize(BufferedImage originalImage, int width, int height) { AffineTransform af = new AffineTransform(); af.scale(width / (double) originalImage.getWidth(), height / (double) originalImage.getHeight()); AffineTransformOp operation = new AffineTransformOp(af, AffineTransformOp.TYPE_NEAREST_NEIGHBOR); return operation.filter(originalImage, null); } }
10,566
Java
.java
DSH105/HoloAPI
31
16
21
2014-02-21T21:30:11Z
2014-12-24T12:52:54Z
AnimatedTextGenerator.java
/FileExtraction/Java_unseen/DSH105_HoloAPI/src/main/java/com/dsh105/holoapi/image/AnimatedTextGenerator.java
/* * This file is part of HoloAPI. * * HoloAPI is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * HoloAPI is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with HoloAPI. If not, see <http://www.gnu.org/licenses/>. */ package com.dsh105.holoapi.image; import java.util.ArrayList; import java.util.Collections; /** * Represents a generator used to produce animated text frames */ public class AnimatedTextGenerator { private int maxHeight; private ArrayList<Frame> frames = new ArrayList<>(); private Frame largestFrame; /** * Constructs an AnimatedTextGenerator for use in an AnimatedHologram * * @param frames frames used to construct the generator with */ public AnimatedTextGenerator(Frame... frames) { this.largestFrame = frames[0]; Collections.addAll(this.frames, frames); this.calculateMaxHeight(); for (Frame f : this.frames) { int diff = this.maxHeight - f.getLines().length; if (diff > 0) { ArrayList<String> lines = new ArrayList<>(); Collections.addAll(lines, f.getLines()); for (int i = 0; i <= diff; i++) { lines.add(" "); } f.setLines(lines.toArray(new String[lines.size()])); } } } protected void calculateMaxHeight() { int maxHeight = 0; Frame largestFrame = this.frames.get(0); for (Frame frame : frames) { if (frame.getLines().length > maxHeight) { maxHeight = frame.getLines().length; largestFrame = frame; } } this.maxHeight = maxHeight; this.largestFrame = largestFrame; } /** * Gets the largest frame of the generator * * @return largest frame of the generator */ public Frame getLargestFrame() { return largestFrame; } /** * Gets the frames of the generator * * @return frames of the generator */ public ArrayList<Frame> getFrames() { return frames; } /** * Gets the maximum frame height * * @return maximum frame height */ public int getMaxHeight() { return maxHeight; } }
2,717
Java
.java
DSH105/HoloAPI
31
16
21
2014-02-21T21:30:11Z
2014-12-24T12:52:54Z
SimpleImageLoader.java
/FileExtraction/Java_unseen/DSH105_HoloAPI/src/main/java/com/dsh105/holoapi/image/SimpleImageLoader.java
/* * This file is part of HoloAPI. * * HoloAPI is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * HoloAPI is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with HoloAPI. If not, see <http://www.gnu.org/licenses/>. */ package com.dsh105.holoapi.image; import com.dsh105.commodus.GeneralUtil; import com.dsh105.commodus.config.YAMLConfig; import com.dsh105.holoapi.HoloAPI; import com.dsh105.holoapi.HoloAPICore; import com.dsh105.holoapi.config.Lang; import org.bukkit.command.CommandSender; import org.bukkit.configuration.ConfigurationSection; import org.bukkit.scheduler.BukkitRunnable; import java.io.File; import java.util.HashMap; import java.util.logging.Level; public class SimpleImageLoader implements ImageLoader<ImageGenerator> { private final HashMap<String, ImageGenerator> KEY_TO_IMAGE_MAP = new HashMap<>(); private final HashMap<String, UnloadedImageStorage> URL_UNLOADED = new HashMap<>(); private boolean loaded; public void loadImageConfiguration(YAMLConfig config) { KEY_TO_IMAGE_MAP.clear(); URL_UNLOADED.clear(); File imageFolder = new File(HoloAPI.getCore().getDataFolder() + File.separator + "images"); if (!imageFolder.exists()) { imageFolder.mkdirs(); } ConfigurationSection cs = config.getConfigurationSection("images"); if (cs != null) { for (String key : cs.getKeys(false)) { String path = "images." + key + "."; String imagePath = config.getString(path + "path"); int imageHeight = config.getInt(path + "height", 10); String imageChar = config.getString(path + "characterType", ImageChar.BLOCK.getHumanName()); String imageType = config.getString(path + "type", "FILE"); boolean requiresBorder = config.getBoolean(path + "requiresBorder", true); if (!GeneralUtil.isEnumType(ImageLoader.ImageLoadType.class, imageType.toUpperCase())) { HoloAPI.LOG.info("Failed to load image: " + key + ". Invalid image type."); continue; } ImageLoader.ImageLoadType type = ImageLoader.ImageLoadType.valueOf(imageType.toUpperCase()); ImageGenerator generator = findGenerator(type, key, imagePath, imageHeight, imageChar, requiresBorder); if (generator != null) { this.KEY_TO_IMAGE_MAP.put(key, generator); } } } loaded = true; if (!KEY_TO_IMAGE_MAP.isEmpty() || !URL_UNLOADED.isEmpty()) { HoloAPI.LOG.info("Images loaded."); } } private ImageGenerator findGenerator(ImageLoader.ImageLoadType type, String key, String imagePath, int imageHeight, String imageCharType, boolean requiresBorder) { try { ImageChar c = ImageChar.fromHumanName(imageCharType); if (c == null) { HoloAPI.LOG.info("Invalid image char type for " + key + ". Using default."); c = ImageChar.BLOCK; } switch (type) { case URL: this.URL_UNLOADED.put(key, new UnloadedImageStorage(imagePath, imageHeight, c, requiresBorder)); return null; case FILE: File f = new File(HoloAPI.getCore().getDataFolder() + File.separator + "images" + File.separator + imagePath); return new ImageGenerator(key, f, imageHeight, c, requiresBorder); } } catch (Exception e) { e.printStackTrace(); return null; } return null; } @Override public ImageGenerator getGenerator(CommandSender sender, String key) { ImageGenerator g = this.KEY_TO_IMAGE_MAP.get(key); if (g == null) { if (this.URL_UNLOADED.get(key) != null) { if (sender != null) { Lang.LOADING_URL_IMAGE.send(sender, "key", key); } this.prepareUrlGenerator(sender, key); return null; } else { Lang.FAILED_IMAGE_LOAD.send(sender); } } return g; } @Override public ImageGenerator getGenerator(String key) { ImageGenerator g = this.KEY_TO_IMAGE_MAP.get(key); if (g == null) { if (this.URL_UNLOADED.get(key) != null) { this.prepareUrlGenerator(null, key); return null; } } return g; } private ImageGenerator prepareUrlGenerator(final CommandSender sender, final String key) { UnloadedImageStorage data = this.URL_UNLOADED.get(key); HoloAPI.LOG.info("Loading custom URL image of key " + key); this.URL_UNLOADED.remove(key); final ImageGenerator g = new ImageGenerator(key, data.getImagePath(), data.getImageHeight(), data.getCharType(), false, data.requiresBorder()); new BukkitRunnable() { @Override public void run() { g.loadUrlImage(); if (sender != null) { Lang.IMAGE_LOADED.send(sender, "key", key); } HoloAPI.LOG.info("Custom URL image '" + key + "' loaded."); KEY_TO_IMAGE_MAP.put(key, g); } }.runTaskAsynchronously(HoloAPI.getCore()); return g; } @Override public boolean exists(String key) { return this.KEY_TO_IMAGE_MAP.containsKey(key); } @Override public boolean existsAsUnloadedUrl(String key) { return this.URL_UNLOADED.containsKey(key); } @Override public boolean isLoaded() { return loaded; } }
6,207
Java
.java
DSH105/HoloAPI
31
16
21
2014-02-21T21:30:11Z
2014-12-24T12:52:54Z
SimpleAnimationLoader.java
/FileExtraction/Java_unseen/DSH105_HoloAPI/src/main/java/com/dsh105/holoapi/image/SimpleAnimationLoader.java
/* * This file is part of HoloAPI. * * HoloAPI is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * HoloAPI is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with HoloAPI. If not, see <http://www.gnu.org/licenses/>. */ package com.dsh105.holoapi.image; import com.dsh105.commodus.GeneralUtil; import com.dsh105.commodus.config.YAMLConfig; import com.dsh105.holoapi.HoloAPI; import com.dsh105.holoapi.HoloAPICore; import com.dsh105.holoapi.config.Lang; import org.bukkit.command.CommandSender; import org.bukkit.configuration.ConfigurationSection; import org.bukkit.scheduler.BukkitRunnable; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.net.URLConnection; import java.util.HashMap; import java.util.logging.Level; public class SimpleAnimationLoader implements ImageLoader<AnimatedImageGenerator> { private final HashMap<String, AnimatedImageGenerator> KEY_TO_IMAGE_MAP = new HashMap<>(); private final HashMap<String, UnloadedImageStorage> URL_UNLOADED = new HashMap<>(); private boolean loaded; public void loadAnimationConfiguration(YAMLConfig config) { KEY_TO_IMAGE_MAP.clear(); URL_UNLOADED.clear(); File imageFolder = new File(HoloAPI.getCore().getDataFolder() + File.separator + "animations"); if (!imageFolder.exists()) { imageFolder.mkdirs(); } ConfigurationSection cs = config.getConfigurationSection("animations"); if (cs != null) { for (String key : cs.getKeys(false)) { String path = "animations." + key + "."; String imagePath = config.getString(path + "path"); if (imagePath == null) { HoloAPI.LOG.info("Failed to load animation: " + key + ". Invalid path"); continue; } int imageHeight = config.getInt(path + "height", 10); int frameRate = config.getInt(path + "frameRate", 10); boolean requiresBorder = config.getBoolean(path + "requiresBorder", true); String imageChar = config.getString(path + "characterType", ImageChar.BLOCK.getHumanName()); String imageType = config.getString(path + "type", "FILE"); if (!GeneralUtil.isEnumType(ImageLoader.ImageLoadType.class, imageType.toUpperCase())) { HoloAPI.LOG.info("Failed to load animation: " + key + ". Invalid image type."); continue; } AnimationLoadType type = AnimationLoadType.valueOf(imageType.toUpperCase()); AnimatedImageGenerator generator = findGenerator(type, key, imagePath, frameRate, imageHeight, imageChar, requiresBorder); if (generator != null) { this.KEY_TO_IMAGE_MAP.put(key, generator); } } } loaded = true; if (!KEY_TO_IMAGE_MAP.isEmpty() || !URL_UNLOADED.isEmpty()) { HoloAPI.LOG.info("Animations loaded."); } } private AnimatedImageGenerator findGenerator(AnimationLoadType type, String key, String imagePath, int frameRate, int imageHeight, String imageCharType, boolean requiresBorder) { try { ImageChar c = ImageChar.fromHumanName(imageCharType); if (c == null) { HoloAPI.LOG.info("Invalid image char type for " + key + ". Using default."); c = ImageChar.BLOCK; } switch (type) { case FILE: File f = new File(HoloAPI.getCore().getDataFolder() + File.separator + "animations" + File.separator + imagePath); if (frameRate == 0) { return new AnimatedImageGenerator(key, f, imageHeight, c, requiresBorder); } else { return new AnimatedImageGenerator(key, f, frameRate, imageHeight, c, requiresBorder); } case URL: this.URL_UNLOADED.put(key, new UnloadedImageStorage(imagePath, imageHeight, frameRate, c, requiresBorder)); return null; } } catch (Exception e) { e.printStackTrace(); return null; } return null; } @Override public AnimatedImageGenerator getGenerator(CommandSender sender, String key) { AnimatedImageGenerator g = this.KEY_TO_IMAGE_MAP.get(key); if (g == null) { if (this.URL_UNLOADED.get(key) != null) { HoloAPI.LOG.info("Loading custom URL animation of key " + key); Lang.LOADING_URL_ANIMATION.send(sender, "key", key); if (sender != null) { this.prepareUrlGenerator(sender, key); } return null; } else { Lang.FAILED_ANIMATION_LOAD.send(sender); } } return g; } @Override public AnimatedImageGenerator getGenerator(String key) { AnimatedImageGenerator g = this.KEY_TO_IMAGE_MAP.get(key); if (g == null) { if (this.URL_UNLOADED.get(key) != null) { HoloAPI.LOG.info("Loading custom URL animation of key " + key); this.prepareUrlGenerator(null, key); return null; } } return g; } private AnimatedImageGenerator prepareUrlGenerator(final CommandSender sender, final String key) { final UnloadedImageStorage data = URL_UNLOADED.get(key); final AnimatedImageGenerator generator = new AnimatedImageGenerator(key); new BukkitRunnable() { @Override public void run() { URI uri = URI.create(data.getImagePath()); URLConnection connection; InputStream input; try { connection = uri.toURL().openConnection(); connection.setRequestProperty("Content-Type", "image/gif"); connection.setUseCaches(false); connection.setDoOutput(true); connection.setConnectTimeout(8000); input = connection.getInputStream(); generator.frames = generator.readGif(input); generator.prepare(data.getImageHeight(), data.getCharType(), data.requiresBorder()); if (data.getFrameRate() != 0) { generator.prepareFrameRate(data.getFrameRate()); } if (sender != null) { Lang.ANIMATION_LOADED.send(sender, "key", key); } HoloAPI.LOG.info("Custom URL animation '" + key + "' loaded."); KEY_TO_IMAGE_MAP.put(key, generator); URL_UNLOADED.remove(key); } catch (IOException e) { e.printStackTrace(); } } }.runTaskAsynchronously(HoloAPI.getCore()); return generator; } @Override public boolean exists(String key) { return this.KEY_TO_IMAGE_MAP.containsKey(key); } @Override public boolean existsAsUnloadedUrl(String key) { return this.URL_UNLOADED.containsKey(key); } @Override public boolean isLoaded() { return loaded; } public enum AnimationLoadType { FILE, URL } }
7,943
Java
.java
DSH105/HoloAPI
31
16
21
2014-02-21T21:30:11Z
2014-12-24T12:52:54Z
Frame.java
/FileExtraction/Java_unseen/DSH105_HoloAPI/src/main/java/com/dsh105/holoapi/image/Frame.java
/* * This file is part of HoloAPI. * * HoloAPI is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * HoloAPI is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with HoloAPI. If not, see <http://www.gnu.org/licenses/>. */ package com.dsh105.holoapi.image; /** * Represents a text or image frame used in AnimatedImageGenerators */ public class Frame { private String[] lines; protected int delay; /** * Constructs a new Frame * * @param delay delay before the next frame is displayed * @param lines lines of the frame */ public Frame(int delay, String... lines) { this.delay = delay; this.setLines(lines); } /** * Gets the delay of the frame before the next is displayed * * @return delay of the frame */ public int getDelay() { return delay; } /** * Gets the lines of the frame * * @return lines of the frame */ public String[] getLines() { return this.lines; } protected void setLines(String[] lines) { if (lines != null) { System.arraycopy(lines, 0, lines, 0, lines.length); this.lines = lines; } } }
1,654
Java
.java
DSH105/HoloAPI
31
16
21
2014-02-21T21:30:11Z
2014-12-24T12:52:54Z
AnimatedImageGenerator.java
/FileExtraction/Java_unseen/DSH105_HoloAPI/src/main/java/com/dsh105/holoapi/image/AnimatedImageGenerator.java
/* * This file is part of HoloAPI. * * HoloAPI is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * HoloAPI is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with HoloAPI. If not, see <http://www.gnu.org/licenses/>. */ package com.dsh105.holoapi.image; import com.google.common.collect.ImmutableList; import org.w3c.dom.NamedNodeMap; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import javax.imageio.ImageIO; import javax.imageio.ImageReader; import javax.imageio.metadata.IIOMetadata; import javax.imageio.metadata.IIOMetadataNode; import java.awt.*; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.Collections; /** * Represents a generator used to produce animated image frames from either a GIF or set of images */ public class AnimatedImageGenerator implements Generator { // https://github.com/aadnk/DisplayFloatingImages/blob/master/DisplayFloatingImage/src/main/java/com/comphenix/example/nametags/GifImageMessage.java protected ImmutableList<GIFFrame> frames; private String key; private int maxHeight; private GIFFrame largestFrame; /** * Constructs an AnimatedImageGenerator for use in an AnimatedHologram * * @param frameRate frame rate of the hologram display * @param imageFrames frames to use in the animated hologram */ public AnimatedImageGenerator(int frameRate, ImageGenerator... imageFrames) { for (ImageGenerator generator : imageFrames) { frames.add(new GIFFrame(generator, frameRate)); } } /** * Constructs an AnimatedImageGenerator for use in an AnimatedHologram * * @param gifFile GIF file used to generate the display * @param frameRate frame rate of the hologram display * @param height height of the display * @param imgChar {@link com.dsh105.holoapi.image.ImageChar} of the display * @throws java.lang.RuntimeException If an input exception occurred or the image could not be found */ public AnimatedImageGenerator(File gifFile, int frameRate, int height, ImageChar imgChar) { this(gifFile, frameRate, height, imgChar, false); } /** * Constructs an AnimatedImageGenerator for use in an AnimatedHologram * * @param gifFile GIF file used to generate the display * @param frameRate frame rate of the hologram display * @param height height of the display * @param imgChar {@link com.dsh105.holoapi.image.ImageChar} of the display * @param requiresBorder whether the display requires a border * @throws java.lang.RuntimeException If an input exception occurred or the image could not be found */ public AnimatedImageGenerator(File gifFile, int frameRate, int height, ImageChar imgChar, boolean requiresBorder) { try { this.frames = this.readGif(gifFile); } catch (IOException e) { throw new RuntimeException("Cannot read file " + gifFile.getPath(), e); } this.prepare(height, imgChar, requiresBorder); this.prepareFrameRate(frameRate); } /** * Constructs an AnimatedImageGenerator for use in an AnimatedHologram * * @param gifFile GIF file used to generate the display * @param height height of the display * @param imgChar {@link com.dsh105.holoapi.image.ImageChar} of the display * @throws java.lang.RuntimeException If an input exception occurred or the image could not be found */ public AnimatedImageGenerator(File gifFile, int height, ImageChar imgChar) { this(gifFile, height, imgChar, false); } /** * Constructs an AnimatedImageGenerator for use in an AnimatedHologram * * @param gifFile GIF file used to generate the display * @param height height of the display * @param imgChar {@link com.dsh105.holoapi.image.ImageChar} of the display * @param requiresBorder whether the display requires a border * @throws java.lang.RuntimeException If an input exception occurred or the image could not be found */ public AnimatedImageGenerator(File gifFile, int height, ImageChar imgChar, boolean requiresBorder) { try { this.frames = this.readGif(gifFile); } catch (IOException e) { throw new RuntimeException("Cannot read file " + gifFile.getPath(), e); } this.prepare(height, imgChar, requiresBorder); } /** * Constructs an AnimatedImageGenerator for use in an AnimatedHologram * * @param input {@link java.io.InputStream} used to generate the display * @param frameRate frame rate of the hologram display * @param height height of the display * @param imgChar {@link com.dsh105.holoapi.image.ImageChar} of the display * @throws java.lang.RuntimeException If an input exception occurred or the image could not be found */ public AnimatedImageGenerator(InputStream input, int frameRate, int height, ImageChar imgChar) { this(input, frameRate, height, imgChar, false); } /** * Constructs an AnimatedImageGenerator for use in an AnimatedHologram * * @param input {@link java.io.InputStream} used to generate the display * @param frameRate frame rate of the hologram display * @param height height of the display * @param imgChar {@link com.dsh105.holoapi.image.ImageChar} of the display * @param requiresBorder whether the display requires a border * @throws java.lang.RuntimeException If an input exception occurred or the image could not be found */ public AnimatedImageGenerator(InputStream input, int frameRate, int height, ImageChar imgChar, boolean requiresBorder) { try { this.frames = this.readGif(input); } catch (IOException e) { throw new RuntimeException("Cannot read input", e); } this.prepare(height, imgChar, requiresBorder); this.prepareFrameRate(frameRate); } /** * Constructs an AnimatedImageGenerator for use in an AnimatedHologram * * @param input {@link java.io.InputStream} used to generate the display * @param height height of the display * @param imgChar {@link com.dsh105.holoapi.image.ImageChar} of the display * @throws java.lang.RuntimeException If an input exception occurred or the image could not be found */ public AnimatedImageGenerator(InputStream input, int height, ImageChar imgChar) { this(input, height, imgChar, false); } /** * Constructs an AnimatedImageGenerator for use in an AnimatedHologram * * @param input {@link java.io.InputStream} used to generate the display * @param height height of the display * @param imgChar {@link com.dsh105.holoapi.image.ImageChar} of the display * @param requiresBorder whether the display requires a border * @throws java.lang.RuntimeException If an input exception occurred or the image could not be found */ public AnimatedImageGenerator(InputStream input, int height, ImageChar imgChar, boolean requiresBorder) { try { this.frames = this.readGif(input); } catch (IOException e) { throw new RuntimeException("Cannot read input", e); } this.prepare(height, imgChar, requiresBorder); } /** * Constructs an AnimatedImageGenerator for use in an AnimatedHologram * * @param key key to store the generator under. Only used for recognition of stored animation generators * @param frameRate frame rate of the hologram display * @param imageFrames frames to use in the animated hologram */ public AnimatedImageGenerator(String key, int frameRate, ImageGenerator... imageFrames) { this(frameRate, imageFrames); this.key = key; } /** * Constructs an AnimatedImageGenerator for use in an AnimatedHologram * * @param key key to store the generator under. Only used for recognition of stored animation generators * @param gifFile GIF file used to generate the display * @param frameRate frame rate of the hologram display * @param height height of the display * @param imgChar {@link com.dsh105.holoapi.image.ImageChar} of the display * @throws java.lang.RuntimeException If an input exception occurred or the image could not be found */ public AnimatedImageGenerator(String key, File gifFile, int frameRate, int height, ImageChar imgChar) { this(key, gifFile, frameRate, height, imgChar, false); } /** * Constructs an AnimatedImageGenerator for use in an AnimatedHologram * * @param key key to store the generator under. Only used for recognition of stored animation generators * @param gifFile GIF file used to generate the display * @param frameRate frame rate of the hologram display * @param height height of the display * @param imgChar {@link com.dsh105.holoapi.image.ImageChar} of the display * @param requiresBorder whether the display requires a border * @throws java.lang.RuntimeException If an input exception occurred or the image could not be found */ public AnimatedImageGenerator(String key, File gifFile, int frameRate, int height, ImageChar imgChar, boolean requiresBorder) { this(gifFile, frameRate, height, imgChar, requiresBorder); this.key = key; } /** * Constructs an AnimatedImageGenerator for use in an AnimatedHologram * * @param key key to store the generator under. Only used for recognition of stored animation generators * @param gifFile GIF file used to generate the display * @param height height of the display * @param imgChar {@link com.dsh105.holoapi.image.ImageChar} of the display * @throws java.io.IOException If an input exception occurred or the image could not be found */ public AnimatedImageGenerator(String key, File gifFile, int height, ImageChar imgChar) throws IOException { this(key, gifFile, height, imgChar, false); } /** * Constructs an AnimatedImageGenerator for use in an AnimatedHologram * * @param key key to store the generator under. Only used for recognition of stored animation generators * @param gifFile GIF file used to generate the display * @param height height of the display * @param imgChar {@link com.dsh105.holoapi.image.ImageChar} of the display * @param requiresBorder whether the display requires a border * @throws java.lang.RuntimeException If an input exception occurred or the image could not be found */ public AnimatedImageGenerator(String key, File gifFile, int height, ImageChar imgChar, boolean requiresBorder) { this(gifFile, height, imgChar, requiresBorder); this.key = key; } /** * Constructs an AnimatedImageGenerator for use in an AnimatedHologram * * @param key key to store the generator under. Only used for recognition of stored animation generators * @param input {@link java.io.InputStream} used to generate the display * @param frameRate frame rate of the hologram display * @param height height of the display * @param imgChar {@link com.dsh105.holoapi.image.ImageChar} of the display * @throws java.lang.RuntimeException If an input exception occurred or the image could not be found */ public AnimatedImageGenerator(String key, InputStream input, int frameRate, int height, ImageChar imgChar) { this(key, input, frameRate, height, imgChar, false); } /** * Constructs an AnimatedImageGenerator for use in an AnimatedHologram * * @param key key to store the generator under. Only used for recognition of stored animation generators * @param input {@link java.io.InputStream} used to generate the display * @param frameRate frame rate of the hologram display * @param height height of the display * @param imgChar {@link com.dsh105.holoapi.image.ImageChar} of the display * @param requiresBorder whether the display requires a border * @throws java.lang.RuntimeException If an input exception occurred or the image could not be found */ public AnimatedImageGenerator(String key, InputStream input, int frameRate, int height, ImageChar imgChar, boolean requiresBorder) { this(input, frameRate, height, imgChar, requiresBorder); this.key = key; } /** * Constructs an AnimatedImageGenerator for use in an AnimatedHologram * * @param key key to store the generator under. Only used for recognition of stored animation generators * @param input {@link java.io.InputStream} used to generate the display * @param height height of the display * @param imgChar {@link com.dsh105.holoapi.image.ImageChar} of the display * @throws java.lang.RuntimeException If an input exception occurred or the image could not be found */ public AnimatedImageGenerator(String key, InputStream input, int height, ImageChar imgChar) { this(key, input, height, imgChar, false); } /** * Constructs an AnimatedImageGenerator for use in an AnimatedHologram * * @param key key to store the generator under. Only used for recognition of stored animation generators * @param input {@link java.io.InputStream} used to generate the display * @param height height of the display * @param imgChar {@link com.dsh105.holoapi.image.ImageChar} of the display * @param requiresBorder whether the display requires a border * @throws java.lang.RuntimeException If an input exception occurred or the image could not be found */ public AnimatedImageGenerator(String key, InputStream input, int height, ImageChar imgChar, boolean requiresBorder) { this(input, height, imgChar, requiresBorder); this.key = key; } protected AnimatedImageGenerator(String key) { this.key = key; } protected void prepare(int height, ImageChar imgChar) { this.prepare(height, imgChar, false); } protected void prepare(int height, ImageChar imgChar, boolean requiresBorder) { this.calculateMaxHeight(); for (GIFFrame frame : frames) { int imageHeight = (int) ((frame.image.getHeight() / (double) this.maxHeight) * height); frame.imageGenerator = new ImageGenerator(frame.image, imageHeight, imgChar, requiresBorder); } } protected void prepareFrameRate(int frameRate) { for (GIFFrame frame : this.frames) { frame.delay = frameRate; } } protected void calculateMaxHeight() { int maxHeight = 0; GIFFrame largestFrame = this.frames.get(0); for (GIFFrame frame : frames) { if (frame.image.getHeight() > maxHeight) { maxHeight = frame.image.getHeight(); largestFrame = frame; } } this.maxHeight = maxHeight; this.largestFrame = largestFrame; } protected ImmutableList<GIFFrame> readGif(InputStream input) throws IOException { GIFFrame[] frames; ImageReader reader = ImageIO.getImageReadersBySuffix("GIF").next(); reader.setInput(ImageIO.createImageInputStream(input)); frames = readGIF(reader); return ImmutableList.copyOf(frames); } private ImmutableList<GIFFrame> readGif(File inputFile) throws IOException { GIFFrame[] frames; ImageReader reader = ImageIO.getImageReadersBySuffix("GIF").next(); reader.setInput(ImageIO.createImageInputStream(inputFile)); frames = readGIF(reader); return ImmutableList.copyOf(frames); } // Source: https://stackoverflow.com/questions/8933893/convert-animated-gif-frames-to-separate-bufferedimages-java private GIFFrame[] readGIF(ImageReader reader) throws IOException { ArrayList<GIFFrame> frames = new ArrayList<>(2); int width = -1; int height = -1; IIOMetadata metadata = reader.getStreamMetadata(); if (metadata != null) { IIOMetadataNode globalRoot = (IIOMetadataNode) metadata.getAsTree(metadata.getNativeMetadataFormatName()); NodeList globalScreenDescriptor = globalRoot.getElementsByTagName("LogicalScreenDescriptor"); if (globalScreenDescriptor != null && globalScreenDescriptor.getLength() > 0) { IIOMetadataNode screenDescriptor = (IIOMetadataNode) globalScreenDescriptor.item(0); if (screenDescriptor != null) { width = Integer.parseInt(screenDescriptor.getAttribute("logicalScreenWidth")); height = Integer.parseInt(screenDescriptor.getAttribute("logicalScreenHeight")); } } } BufferedImage master = null; Graphics2D masterGraphics = null; for (int frameIndex = 0; ; frameIndex++) { BufferedImage image; try { image = reader.read(frameIndex); } catch (IndexOutOfBoundsException io) { break; } if (width == -1 || height == -1) { width = image.getWidth(); height = image.getHeight(); } IIOMetadataNode root = (IIOMetadataNode) reader.getImageMetadata(frameIndex).getAsTree("javax_imageio_gif_image_1.0"); IIOMetadataNode gce = (IIOMetadataNode) root.getElementsByTagName("GraphicControlExtension").item(0); int delay = Integer.valueOf(gce.getAttribute("delayTime")); String disposal = gce.getAttribute("disposalMethod"); int x = 0; int y = 0; if (master == null) { master = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB); masterGraphics = master.createGraphics(); masterGraphics.setBackground(new Color(0, 0, 0, 0)); } else { NodeList children = root.getChildNodes(); for (int nodeIndex = 0; nodeIndex < children.getLength(); nodeIndex++) { Node nodeItem = children.item(nodeIndex); if (nodeItem.getNodeName().equals("ImageDescriptor")) { NamedNodeMap map = nodeItem.getAttributes(); x = Integer.valueOf(map.getNamedItem("imageLeftPosition").getNodeValue()); y = Integer.valueOf(map.getNamedItem("imageTopPosition").getNodeValue()); } } } masterGraphics.drawImage(image, x, y, null); BufferedImage copy = new BufferedImage(master.getColorModel(), master.copyData(null), master.isAlphaPremultiplied(), null); frames.add(new GIFFrame(copy, (int) Math.ceil(delay / 2.5D), disposal)); if (disposal.equals("restoreToPrevious")) { BufferedImage from = null; for (int i = frameIndex - 1; i >= 0; i--) { if (!frames.get(i).disposal.equals("restoreToPrevious") || frameIndex == 0) { from = frames.get(i).image; break; } } master = new BufferedImage(from.getColorModel(), from.copyData(null), from.isAlphaPremultiplied(), null); masterGraphics = master.createGraphics(); masterGraphics.setBackground(new Color(0, 0, 0, 0)); } else if (disposal.equals("restoreToBackgroundColor")) { masterGraphics.clearRect(x, y, image.getWidth(), image.getHeight()); } } reader.dispose(); return frames.toArray(new GIFFrame[frames.size()]); } @Override public String getKey() { return key; } /** * Gets the frames of the generator * * @return frames of the generator */ public ImmutableList<GIFFrame> getFrames() { return this.frames; } /** * Gets the maximum frame height * * @return maximum frame height */ public int getMaxHeight() { return maxHeight; } /** * Gets the largest frame of the generator * * @return largest frame of the generator */ public GIFFrame getLargestFrame() { return largestFrame; } }
21,248
Java
.java
DSH105/HoloAPI
31
16
21
2014-02-21T21:30:11Z
2014-12-24T12:52:54Z
SimpleHoloManager.java
/FileExtraction/Java_unseen/DSH105_HoloAPI/src/main/java/com/dsh105/holoapi/api/SimpleHoloManager.java
/* * This file is part of HoloAPI. * * HoloAPI is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * HoloAPI is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with HoloAPI. If not, see <http://www.gnu.org/licenses/>. */ package com.dsh105.holoapi.api; import com.dsh105.commodus.GeneralUtil; import com.dsh105.commodus.config.YAMLConfig; import com.dsh105.holoapi.HoloAPI; import com.dsh105.holoapi.api.events.*; import com.dsh105.holoapi.api.touch.TouchAction; import com.dsh105.holoapi.api.visibility.Visibility; import com.dsh105.holoapi.config.ConfigType; import com.dsh105.holoapi.config.Settings; import com.dsh105.holoapi.image.AnimatedImageGenerator; import com.dsh105.holoapi.image.AnimatedTextGenerator; import com.dsh105.holoapi.image.Frame; import com.dsh105.holoapi.image.ImageGenerator; import com.dsh105.holoapi.util.TagIdGenerator; import org.bukkit.ChatColor; import org.bukkit.Location; import org.bukkit.configuration.ConfigurationSection; import org.bukkit.entity.Entity; import org.bukkit.entity.Player; import org.bukkit.plugin.Plugin; import org.bukkit.scheduler.BukkitRunnable; import org.bukkit.scheduler.BukkitTask; import org.bukkit.util.Vector; import java.util.*; public class SimpleHoloManager implements HoloManager { private YAMLConfig config; private HashMap<Hologram, Plugin> holograms = new HashMap<>(); public SimpleHoloManager() { this.config = HoloAPI.getConfig(ConfigType.DATA); new BukkitRunnable() { @Override public void run() { if (!getAllHolograms().isEmpty()) { for (Hologram hologram : getAllHolograms().keySet()) { hologram.updateDisplay(); } } } }.runTaskTimer(HoloAPI.getCore(), 0L, 20 * 60); } @Override public Map<Hologram, Plugin> getAllHolograms() { return Collections.unmodifiableMap(this.holograms); } @Override public Map<Hologram, Plugin> getAllComplexHolograms() { HashMap<Hologram, Plugin> map = new HashMap<>(); for (Map.Entry<Hologram, Plugin> entry : this.holograms.entrySet()) { if (!entry.getKey().isSimple()) { map.put(entry.getKey(), entry.getValue()); } } return Collections.unmodifiableMap(map); } @Override public Map<Hologram, Plugin> getAllSimpleHolograms() { HashMap<Hologram, Plugin> map = new HashMap<>(); for (Map.Entry<Hologram, Plugin> entry : this.holograms.entrySet()) { if (entry.getKey().isSimple()) { map.put(entry.getKey(), entry.getValue()); } } return Collections.unmodifiableMap(map); } public void clearAll() { Iterator<Hologram> i = holograms.keySet().iterator(); while (i.hasNext()) { Hologram h = i.next(); if (!h.isSimple()) { this.saveToFile(h); } h.clearAllPlayerViews(); i.remove(); } } @Override public List<Hologram> getHologramsFor(Plugin owningPlugin) { ArrayList<Hologram> list = new ArrayList<>(); for (Map.Entry<Hologram, Plugin> entry : this.holograms.entrySet()) { if (entry.getValue().equals(owningPlugin)) { list.add(entry.getKey()); } } return Collections.unmodifiableList(list); } @Override public Hologram getHologram(String hologramId) { for (Hologram hologram : this.holograms.keySet()) { if (hologram.getSaveId().equals(hologramId)) { return hologram; } } return null; } @Override public void track(Hologram hologram, Plugin owningPlugin) { this.holograms.put(hologram, owningPlugin); if (!hologram.isSimple() && this.config.getConfigurationSection("holograms." + hologram.getSaveId()) == null) { this.saveToFile(hologram); } if (hologram instanceof AnimatedHologram && !((AnimatedHologram) hologram).isAnimating()) { ((AnimatedHologram) hologram).animate(); } HoloAPI.getCore().getServer().getPluginManager().callEvent(new HoloCreateEvent(hologram)); HoloAPI.getHoloUpdater().track(hologram); } @Override public void remove(Hologram hologram) { stopTracking(hologram); } @Override public void remove(String hologramId) { stopTracking(hologramId); } @Override public void stopTracking(Hologram hologram) { boolean removed = this.holograms.remove(hologram) != null; if(!removed) return; // No need to go on if we weren't already tracking it... hologram.clearAllPlayerViews(); if (hologram instanceof AnimatedHologram && ((AnimatedHologram) hologram).isAnimating()) { ((AnimatedHologram) hologram).cancelAnimation(); } HoloAPI.getCore().getServer().getPluginManager().callEvent(new HoloDeleteEvent(hologram)); //this.clearFromFile(hologram); HoloAPI.getHoloUpdater().remove(hologram); } @Override public void stopTracking(String hologramId) { Hologram hologram = this.getHologram(hologramId); if (hologram != null) { this.stopTracking(hologram); } } @Override public void saveToFile(String hologramId) { Hologram hologram = this.getHologram(hologramId); if (hologram != null) { this.saveToFile(hologram); } } @Override public void saveToFile(Hologram hologram) { if (!hologram.isSimple()) { String path = "holograms." + hologram.getSaveId() + "."; this.config.set(path + "worldName", hologram.getWorldName()); this.config.set(path + "x", hologram.getDefaultX()); this.config.set(path + "y", hologram.getDefaultY()); this.config.set(path + "z", hologram.getDefaultZ()); if (hologram instanceof AnimatedHologram) { AnimatedHologram animatedHologram = (AnimatedHologram) hologram; if (animatedHologram.isImageGenerated() && (HoloAPI.getAnimationLoader().exists(animatedHologram.getAnimationKey())) || HoloAPI.getAnimationLoader().existsAsUnloadedUrl(animatedHologram.getAnimationKey())) { this.config.set(path + "animatedImage.image", true); this.config.set(path + "animatedImage.key", animatedHologram.getAnimationKey()); } else { this.config.set(path + "animatedImage.image", false); int index = 0; for (Frame f : animatedHologram.getFrames()) { this.config.set(path + "animatedImage.frames." + index + ".delay", f.getDelay()); int tagIndex = 0; for (String tag : f.getLines()) { this.config.set(path + "animatedImage.frames." + index + "." + tagIndex, tag.replace(ChatColor.COLOR_CHAR, '&')); tagIndex++; } index++; } } } else { int index = 0; for (StoredTag tag : hologram.serialise()) { this.config.set(path + "lines." + index + ".type", tag.isImage() ? "image" : "text"); this.config.set(path + "lines." + index + ".value", tag.getContent().replace(ChatColor.COLOR_CHAR, '&')); index++; } } for (TouchAction touch : hologram.getAllTouchActions()) { if (touch.getSaveKey() != null) { Map<String, Object> map = touch.getDataToSave(); if (map != null && !map.isEmpty()) { for (Map.Entry<String, Object> entry : map.entrySet()) { // Let the developer implementing the API handle how data is saved and loaded to and from holograms this.config.set(path + "touchactions." + touch.getSaveKey() + "." + entry.getKey(), entry.getValue()); } } } } Visibility visibility = hologram.getVisibility(); if (visibility != null && visibility.getSaveKey() != null) { Map<String, Object> map = visibility.getDataToSave(); if (map != null && !map.isEmpty()) { this.config.set(path + "visibility", null); for (Map.Entry<String, Object> entry : map.entrySet()) { // Let the developer implementing the API handle how data is saved and loaded to and from holograms this.config.set(path + "visibility." + visibility.getSaveKey() + "." + entry.getKey(), entry.getValue()); } } } this.config.saveConfig(); } } @Override public void clearFromFile(String hologramId) { this.config.set("holograms." + hologramId + "", null); this.config.saveConfig(); } @Override public void clearFromFile(Hologram hologram) { this.clearFromFile(hologram.getSaveId()); } public ArrayList<String> loadFileData() { ArrayList<String> unprepared = new ArrayList<>(); ConfigurationSection cs = config.getConfigurationSection("holograms"); if (cs != null) { for (String key : cs.getKeys(false)) { String path = "holograms." + key + "."; String worldName = config.getString(path + "worldName"); double x = config.getDouble(path + "x"); double y = config.getDouble(path + "y"); double z = config.getDouble(path + "z"); if (config.get(path + "animatedImage.image") != null) { if (config.getBoolean(path + "animatedImage.image")) { unprepared.add(key); } else { ArrayList<Frame> frameList = new ArrayList<>(); ConfigurationSection frames = config.getConfigurationSection("holograms." + key + ".animatedImage.frames"); if (frames != null) { for (String frameKey : frames.getKeys(false)) { ConfigurationSection lines = config.getConfigurationSection("holograms." + key + ".animatedImage.frames." + frameKey); if (lines != null) { ArrayList<String> tagList = new ArrayList<>(); int delay = config.getInt("holograms." + key + ".animatedImage.frames." + frameKey + ".delay", 5); for (String tagKey : lines.getKeys(false)) { if (!tagKey.equalsIgnoreCase("delay")) { tagList.add(config.getString("holograms." + key + ".animatedImage.frames." + frameKey + "." + tagKey)); } } if (!tagList.isEmpty()) { frameList.add(new Frame(delay, tagList.toArray(new String[tagList.size()]))); } } } } if (!frameList.isEmpty()) { this.loadExtraData(new AnimatedHologramFactory(HoloAPI.getCore()) .withSaveId(key) .withText(new AnimatedTextGenerator(frameList.toArray(new Frame[frameList.size()]))) .withLocation(new Vector(x, y, z), worldName) .build(), key); } } } else { ConfigurationSection cs1 = config.getConfigurationSection("holograms." + key + ".lines"); boolean containsImage = false; if (cs1 != null) { //ArrayList<String> lines = new ArrayList<String>(); HologramFactory hf = new HologramFactory(HoloAPI.getCore()); for (String key1 : cs1.getKeys(false)) { if (GeneralUtil.isInt(key1)) { String type = config.getString(path + "lines." + key1 + ".type"); String value = config.getString(path + "lines." + key1 + ".value"); if (type.equalsIgnoreCase("image")) { containsImage = true; break; } else { hf.withText(value); } } else { HoloAPI.LOG.warning("Failed to load line section of " + key1 + " for Hologram of ID " + key + "."); } } if (containsImage) { unprepared.add(key); continue; } this.loadExtraData(hf.withSaveId(key).withLocation(new Vector(x, y, z), worldName).build(), key); } } } } return unprepared; } public Hologram loadFromFile(String hologramId) { String path = "holograms." + hologramId + "."; String worldName = config.getString(path + "worldName"); double x = config.getDouble(path + "x"); double y = config.getDouble(path + "y"); double z = config.getDouble(path + "z"); Hologram finalHologram = null; if (config.get(path + "animatedImage.image") != null) { if (config.getBoolean(path + "animatedImage.image")) { AnimatedImageGenerator generator = HoloAPI.getAnimationLoader().getGenerator(config.getString(path + "animatedImage.key")); if (generator != null) { finalHologram = new AnimatedHologramFactory(HoloAPI.getCore()).withSaveId(hologramId).withImage(generator).withLocation(new Vector(x, y, z), worldName).build(); } } } else { ConfigurationSection cs1 = config.getConfigurationSection("holograms." + hologramId + ".lines"); HologramFactory hf = new HologramFactory(HoloAPI.getCore()); //ArrayList<String> lines = new ArrayList<String>(); for (String key1 : cs1.getKeys(false)) { if (GeneralUtil.isInt(key1)) { String type = config.getString(path + "lines." + key1 + ".type"); String value = config.getString(path + "lines." + key1 + ".value"); if (type.equalsIgnoreCase("image")) { ImageGenerator generator = HoloAPI.getImageLoader().getGenerator(value); if (generator != null) { hf.withImage(generator); } } else { hf.withText(value); } } else { HoloAPI.LOG.warning("Failed to load line section of " + key1 + " for Hologram of ID " + hologramId + "."); } } if (!hf.isEmpty()) { finalHologram = hf.withSaveId(hologramId).withLocation(new Vector(x, y, z), worldName).build(); } } if (finalHologram != null) { this.loadExtraData(finalHologram, hologramId); } return finalHologram; } private void loadExtraData(Hologram hologram, String hologramKey) { String[] sections = new String[]{"touchactions", "visibility"}; for (String sectionKey : sections) { ConfigurationSection section = this.config.getConfigurationSection("holograms." + hologramKey + "." + sectionKey); if (section != null) { for (String objKey : section.getKeys(true)) { LinkedHashMap<String, Object> configMap = new LinkedHashMap<>(); ConfigurationSection objKeySection = this.config.getConfigurationSection("holograms." + hologramKey + "." + sectionKey + "." + objKey); if (objKeySection != null) { for (String fullKey : objKeySection.getKeys(true)) { configMap.put(fullKey, objKeySection.get(fullKey)); } } this.callDataLoadEvent(sectionKey, hologram, objKey, configMap); } } } } private void callDataLoadEvent(String sectionkey, Hologram hologram, String objKey, LinkedHashMap<String, Object> configMap) { HoloDataLoadEvent event = new HoloDataLoadEvent(hologram, objKey, configMap); if (sectionkey.equalsIgnoreCase("touchactions")) { event = new HoloTouchActionLoadEvent(hologram, objKey, configMap); } else if (sectionkey.equalsIgnoreCase("visibility")) { event = new HoloVisibilityLoadEvent(hologram, objKey, configMap); } HoloAPI.getCore().getServer().getPluginManager().callEvent(event); } @Override public Hologram copy(Hologram hologram, Location copyLocation) { return hologram instanceof AnimatedHologram ? this.buildAnimatedCopy((AnimatedHologram) hologram, copyLocation).build() : this.buildCopy(hologram, copyLocation).build(); } @Override public Hologram setLineContent(Hologram original, String... newContent) { if (original.getLines().length >= newContent.length) { original.updateLines(newContent); return original; } if (original instanceof AnimatedHologram) { throw new IllegalArgumentException("Lines cannot be added to AnimatedHolograms."); } // Make preparations // Don't need this one anymore, we can delete it now HoloAPI.getManager().stopTracking(original); HoloAPI.getManager().clearFromFile(original); // Oh look, a new hologram! HologramFactory factory = this.buildCopy(original, original.getDefaultLocation()).withSaveId(original.getSaveId()).clearContent().withText(newContent); Hologram copy = factory.build(); HoloAPI.getManager().saveToFile(copy); return copy; } @Override public Hologram copyAndAddLineTo(Hologram original, String... linesToAdd) { if (original instanceof AnimatedHologram) { throw new IllegalArgumentException("Lines cannot be added to AnimatedHolograms."); } HoloAPI.getManager().stopTracking(original); HoloAPI.getManager().clearFromFile(original); HologramFactory factory = this.buildCopy(original, original.getDefaultLocation()).withSaveId(original.getSaveId()); for (String line : linesToAdd) { factory.withText(line); } return factory.build(); } private AnimatedHologramFactory buildAnimatedCopy(AnimatedHologram original, Location copyLocation) { AnimatedHologramFactory animatedCopyFactory = new AnimatedHologramFactory(HoloAPI.getCore()).withLocation(copyLocation).withSimplicity(original.isSimple()); if (original.isImageGenerated() && (HoloAPI.getAnimationLoader().exists(original.getAnimationKey())) || HoloAPI.getAnimationLoader().existsAsUnloadedUrl(original.getAnimationKey())) { animatedCopyFactory.withImage(HoloAPI.getAnimationLoader().getGenerator(original.getAnimationKey())); } else { ArrayList<Frame> frames = original.getFrames(); animatedCopyFactory.withText(new AnimatedTextGenerator(frames.toArray(new Frame[frames.size()]))); } return animatedCopyFactory; } private HologramFactory buildCopy(Hologram original, Location copyLocation) { HologramFactory copyFactory = new HologramFactory(HoloAPI.getCore()).withLocation(copyLocation).withSimplicity(original.isSimple()); for (StoredTag tag : original.serialise()) { if (tag.isImage()) { ImageGenerator generator = HoloAPI.getImageLoader().getGenerator(tag.getContent()); if (generator != null) { copyFactory.withImage(generator); } } else { copyFactory.withText(tag.getContent()); } } return copyFactory; } @Override public Hologram createSimpleHologram(Location location, int secondsUntilRemoved, List<String> lines) { return this.createSimpleHologram(location, secondsUntilRemoved, false, lines.toArray(new String[lines.size()])); } @Override public Hologram createSimpleHologram(Location location, int secondsUntilRemoved, boolean rise, List<String> lines) { return this.createSimpleHologram(location, secondsUntilRemoved, rise, lines.toArray(new String[lines.size()])); } @Override public Hologram createSimpleHologram(Location location, int secondsUntilRemoved, String... lines) { return this.createSimpleHologram(location, secondsUntilRemoved, false, lines); } @Override public Hologram createSimpleHologram(Location location, int secondsUntilRemoved, boolean rise, String... lines) { int simpleId = TagIdGenerator.next(lines.length); final Hologram hologram = new HologramFactory(HoloAPI.getCore()).withFirstTagId(simpleId).withSaveId(simpleId + "").withText(lines).withLocation(location).withSimplicity(true).build(); for (Entity e : hologram.getDefaultLocation().getWorld().getEntities()) { if (e instanceof Player) { hologram.show((Player) e, true); } } BukkitTask t = null; if (rise) { t = HoloAPI.getCore().getServer().getScheduler().runTaskTimer(HoloAPI.getCore(), new Runnable() { @Override public void run() { Location l = hologram.getDefaultLocation(); l.add(0.0D, 0.02D, 0.0D); hologram.move(l.toVector()); } }, 1L, 1L); } new HologramRemoveTask(hologram, t).runTaskLater(HoloAPI.getCore(), secondsUntilRemoved * 20); return hologram; } @Override public Hologram createSimpleHologram(Location location, int secondsUntilRemoved, Vector velocity, List<String> lines) { return this.createSimpleHologram(location, secondsUntilRemoved, velocity, lines.toArray(new String[lines.size()])); } @Override public Hologram createSimpleHologram(Location location, int secondsUntilRemoved, final Vector velocity, String... lines) { int simpleId = TagIdGenerator.next(lines.length); final Hologram hologram = new HologramFactory(HoloAPI.getCore()).withFirstTagId(simpleId).withSaveId(simpleId + "").withText(lines).withLocation(location).withSimplicity(true).build(); for (Entity e : hologram.getDefaultLocation().getWorld().getEntities()) { if (e instanceof Player) { hologram.show((Player) e, true); } } BukkitTask t = HoloAPI.getCore().getServer().getScheduler().runTaskTimer(HoloAPI.getCore(), new Runnable() { @Override public void run() { Location l = hologram.getDefaultLocation(); l.add(velocity); hologram.move(l.toVector()); } }, 1L, 1L); new HologramRemoveTask(hologram, t).runTaskLater(HoloAPI.getCore(), secondsUntilRemoved * 20); return hologram; } class HologramRemoveTask extends BukkitRunnable { BukkitTask task = null; private Hologram hologram; HologramRemoveTask(Hologram hologram, BukkitTask task) { this.hologram = hologram; this.task = task; } @Override public void run() { if (this.task != null) { task.cancel(); } stopTracking(hologram); } } }
25,089
Java
.java
DSH105/HoloAPI
31
16
21
2014-02-21T21:30:11Z
2014-12-24T12:52:54Z
HoloFactory.java
/FileExtraction/Java_unseen/DSH105_HoloAPI/src/main/java/com/dsh105/holoapi/api/HoloFactory.java
/* * This file is part of HoloAPI. * * HoloAPI is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * HoloAPI is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with HoloAPI. If not, see <http://www.gnu.org/licenses/>. */ package com.dsh105.holoapi.api; import com.dsh105.holoapi.HoloAPI; import com.dsh105.holoapi.api.visibility.Visibility; import com.dsh105.holoapi.api.visibility.VisibilityDefault; import com.dsh105.holoapi.exceptions.HologramNotPreparedException; import com.dsh105.holoapi.listeners.WorldListener; import com.dsh105.holoapi.util.SaveIdGenerator; import org.bukkit.Bukkit; import org.bukkit.Location; import org.bukkit.plugin.Plugin; import org.bukkit.util.Vector; /** * Represents a factory for building new Holograms */ public abstract class HoloFactory { private Plugin owningPlugin; protected String worldName; protected double locX; protected double locY; protected double locZ; protected String saveId; protected Visibility visibility = new VisibilityDefault(); protected boolean simple = false; protected int tagId; protected boolean withTagId; private boolean prepared = false; private boolean preparedId = false; /** * Constructs a factory for building a hologram * * @param owningPlugin plugin to register constructed hologram under * @throws java.lang.IllegalArgumentException if the owning plugin is null */ public HoloFactory(Plugin owningPlugin) { if (owningPlugin == null) { throw new IllegalArgumentException("Plugin cannot be null"); } this.owningPlugin = owningPlugin; } /** * Sets the location for constructed Holograms * * @param location location for constructed Holograms * @return This object */ public HoloFactory withLocation(Location location) { this.withCoords(location.getX(), location.getY(), location.getZ()); this.withWorld(location.getWorld().getName()); return this; } /** * Sets the location for constructed Holograms * * @param vectorLocation a {@link org.bukkit.util.Vector} representing the coordinates of constructed * Holograms * @param worldName the world name to place constructed Holograms in * @return This object */ public HoloFactory withLocation(Vector vectorLocation, String worldName) { this.withCoords(vectorLocation.getX(), vectorLocation.getY(), vectorLocation.getZ()); this.withWorld(worldName); return this; } /** * Sets the visibility of constructed Holograms * * @param visibility visibility of constructed Hologram * @return This object */ public HoloFactory withVisibility(Visibility visibility) { this.visibility = visibility; return this; } /** * Sets the save id of constructed Holograms * * @param saveId save id to be assigned to constructed Holograms * @throws com.dsh105.holoapi.exceptions.DuplicateSaveIdException if the save ID is already registered * @return return save id */ public HoloFactory withSaveId(String saveId) { this.saveId = saveId; this.preparedId = true; return this; } /** * Sets the simplicity of constructed Holograms * * @param simple simplicity of constructed Holograms * @return This object */ public HoloFactory withSimplicity(boolean simple) { this.simple = simple; return this; } public abstract boolean canBuild(); public abstract Hologram prepareHologram(); /** * Constructs a {@link com.dsh105.holoapi.api.Hologram} based on the settings stored in the factory * * @return The constructed Holograms * @throws com.dsh105.holoapi.exceptions.HologramNotPreparedException if the animation is empty or the location is * not initialised */ public Hologram build() { if (!this.canBuild() || !this.prepared) { throw new HologramNotPreparedException("Hologram is not prepared correctly!"); } if (!this.preparedId || this.saveId == null) { this.saveId = SaveIdGenerator.nextId() + ""; } if (Bukkit.getWorld(this.worldName) == null) { HoloAPI.LOG.warning("Could not find valid world (" + this.worldName + ") for Hologram of ID " + this.saveId + ". Maybe the world isn't loaded yet?"); WorldListener.store(this.saveId, this.worldName); return null; } Hologram hologram = prepareHologram(); hologram.setSimplicity(this.simple); hologram.setVisibility(this.visibility); hologram.showNearby(); HoloAPI.getManager().track(hologram, this.owningPlugin); return hologram; } protected HoloFactory withFirstTagId(int tagId) { this.tagId = tagId; this.withTagId = true; return this; } private HoloFactory withCoords(double x, double y, double z) { this.locX = x; this.locY = y; this.locZ = z; this.prepared = true; return this; } private HoloFactory withWorld(String worldName) { this.worldName = worldName; return this; } }
5,821
Java
.java
DSH105/HoloAPI
31
16
21
2014-02-21T21:30:11Z
2014-12-24T12:52:54Z
AnimatedHologramImpl.java
/FileExtraction/Java_unseen/DSH105_HoloAPI/src/main/java/com/dsh105/holoapi/api/AnimatedHologramImpl.java
package com.dsh105.holoapi.api; import com.dsh105.commodus.IdentUtil; import com.dsh105.holoapi.HoloAPI; import com.dsh105.holoapi.config.Settings; import com.dsh105.holoapi.image.AnimatedImageGenerator; import com.dsh105.holoapi.image.AnimatedTextGenerator; import com.dsh105.holoapi.image.Frame; import com.dsh105.holoapi.util.TagIdGenerator; import org.bukkit.Location; import org.bukkit.entity.Player; import org.bukkit.scheduler.BukkitRunnable; import org.bukkit.scheduler.BukkitTask; import org.bukkit.util.Vector; import java.util.ArrayList; import java.util.Map; import static com.google.common.base.Preconditions.*; public class AnimatedHologramImpl extends HologramImpl implements AnimatedHologram { private BukkitTask displayTask; private boolean imageGenerated; private String animationKey; private ArrayList<Frame> frames = new ArrayList<>(); private int index = 0; private Frame currentFrame; protected AnimatedHologramImpl(String saveId, String worldName, double x, double y, double z, AnimatedImageGenerator animatedImage) { super(TagIdGenerator.next(animatedImage.getLargestFrame().getImageGenerator().getLines().length * animatedImage.getFrames().size()), saveId, worldName, x, y, z, animatedImage.getLargestFrame().getImageGenerator().getLines()); this.frames.addAll(animatedImage.getFrames()); this.currentFrame = this.getCurrent(); this.animate(); this.imageGenerated = true; this.animationKey = animatedImage.getKey(); } protected AnimatedHologramImpl(String saveId, String worldName, double x, double y, double z, AnimatedTextGenerator textGenerator) { super(TagIdGenerator.next(textGenerator.getLargestFrame().getLines().length * textGenerator.getFrames().size()), saveId, worldName, x, y, z, textGenerator.getLargestFrame().getLines()); this.frames.addAll(textGenerator.getFrames()); this.currentFrame = this.getCurrent(); this.animate(); } @Override public boolean isImageGenerated() { return this.imageGenerated; } @Override public String getAnimationKey() { return this.animationKey; } @Override public Frame getCurrent() { return this.getFrame(this.index); } @Override public Frame getNext() { return this.getFrame((this.index + 1) >= this.frames.size() ? 0 : this.index + 1); } private Frame next() { if (++this.index >= this.frames.size()) { this.index = 0; } return this.getFrame(this.index); } @Override public Frame getFrame(int index) { if (index >= this.frames.size()) { throw new IndexOutOfBoundsException("Frame " + index + "doesn't exist."); } else if(index < 0) { throw new IndexOutOfBoundsException("Index cannot be less than 0"); } return this.frames.get(index); } @Override public ArrayList<Frame> getFrames() { ArrayList<Frame> list = new ArrayList<>(); list.addAll(this.frames); return list; } @Override public void updateLine(int index, String content) { // Nothing can happen here. Lines are always changing } @Override public void animate() { if (this.isAnimating()) { this.cancelAnimation(); } this.displayTask = new BukkitRunnable() { @Override public void run() { runAnimation(); } }.runTaskTimer(HoloAPI.getCore(), 0L, currentFrame.getDelay()); } private void runAnimation() { for (Map.Entry<String, Vector> entry : getPlayerViews().entrySet()) { final Player p = IdentUtil.getPlayerOf(entry.getKey()); if (p != null) { currentFrame = next(); updateAnimation(p, currentFrame.getLines()); } } } @Override public boolean isAnimating() { return this.displayTask != null; } @Override public void cancelAnimation() { if (this.displayTask != null) { this.displayTask.cancel(); this.displayTask = null; } } @Override public void refreshDisplay() { this.cancelAnimation(); this.animate(); } @Override public void updateAnimation(Player observer, String... lines) { checkNotNull(observer, "The Player object is null in AnimatedHologramImpl#updateAnimation(...)"); for (int index = 0; index < lines.length; index++) { this.updateNametag(observer, lines[index], index); } } @Override public void show(Player observer) { checkNotNull(observer, "The Player object is null in AnimatedHologramImpl#show(Player)"); this.showAnimation(observer, currentFrame.getLines()); } @Override public void show(Player observer, Location location) { checkNotNull(observer, "The Player object is null in AnimatedHologramImpl#show(Player, Observer)"); checkNotNull(location, "The Location object is null in AnimatedHologramImpl#show(Player, Observer)"); this.showAnimation(observer, location.toVector(), currentFrame.getLines()); } @Override public void show(Player observer, double x, double y, double z) { checkNotNull(observer, "The Player object is null in AnimatedHologramImpl#show(Player, double, double, double)"); this.showAnimation(observer, x, y, z, currentFrame.getLines()); } @Override public void showAnimation(Player observer, String... lines) { checkNotNull(observer, "The Player object is null in AnimatedHologramImpl#showAnimation(Player, String...)"); this.showAnimation(observer, this.getDefaultX(), this.getDefaultY(), this.getDefaultZ(), lines); } @Override public void showAnimation(Player observer, Vector v, String... lines) { checkNotNull(observer, "The Player object is null in AnimatedHologramImpl#showAnimation(Player, Vector, String...)"); checkNotNull(v, "The Vector object is null in AnimatedHologramImpl#showAnimation(Player, Vector, String...)"); this.showAnimation(observer, v.getBlockX(), v.getBlockY(), v.getBlockZ(), lines); } private void showAnimation(Player observer, double x, double y, double z, String[] lines) { checkNotNull(observer, "The Player object is null in AnimatedHologramImpl#showAnimation(Player, double, double, double, String[])"); checkNotNull(lines, "The String[] object is null in AnimatedHologramImpl#showAnimation(Player, double, double, double, String[])"); for (int index = 0; index < lines.length; index++) { this.generate(observer, lines[index], index, -index * Settings.VERTICAL_LINE_SPACING.getValue(), x, y, z); } this.playerToLocationMap.put(IdentUtil.getIdentificationForAsString(observer), new Vector(x, y, z)); } @Override public void move(Player observer, Vector to) { checkNotNull(observer, "The Player object is null in AnimatedHologramImpl#move(Player, Vector)"); checkNotNull(to, "The Vector object is null in AnimatedHologramImpl#move(Player, Vector)"); this.cancelAnimation(); super.move(observer, to); this.animate(); } }
7,370
Java
.java
DSH105/HoloAPI
31
16
21
2014-02-21T21:30:11Z
2014-12-24T12:52:54Z
HologramImpl.java
/FileExtraction/Java_unseen/DSH105_HoloAPI/src/main/java/com/dsh105/holoapi/api/HologramImpl.java
package com.dsh105.holoapi.api; import com.captainbern.minecraft.protocol.PacketType; import com.captainbern.minecraft.reflection.MinecraftReflection; import com.captainbern.minecraft.wrapper.WrappedDataWatcher; import com.captainbern.minecraft.wrapper.WrappedPacket; import com.captainbern.reflection.Reflection; import com.captainbern.reflection.accessor.MethodAccessor; import com.dsh105.commodus.GeometryUtil; import com.dsh105.commodus.IdentUtil; import com.dsh105.holoapi.HoloAPI; import com.dsh105.holoapi.api.events.HoloLineUpdateEvent; import com.dsh105.holoapi.api.touch.TouchAction; import com.dsh105.holoapi.api.visibility.Visibility; import com.dsh105.holoapi.api.visibility.VisibilityDefault; import com.dsh105.holoapi.config.ConfigType; import com.dsh105.holoapi.config.Settings; import com.dsh105.holoapi.exceptions.DuplicateSaveIdException; import com.dsh105.holoapi.protocol.Injector; import com.dsh105.holoapi.util.TagIdGenerator; import org.bukkit.Bukkit; import org.bukkit.Location; import org.bukkit.entity.Entity; import org.bukkit.entity.EntityType; import org.bukkit.entity.Player; import org.bukkit.inventory.ItemStack; import org.bukkit.scheduler.BukkitRunnable; import org.bukkit.util.Vector; import java.util.*; import static com.google.common.base.Preconditions.*; public class HologramImpl implements Hologram { private static MethodAccessor AS_NMS_ITEM_COPY = new Reflection().reflect(MinecraftReflection.getCraftItemStackClass()).getSafeMethod("asNMSCopy").getAccessor(); public static int TAG_ENTITY_MULTIPLIER = 4; protected int firstTagId; protected HashMap<String, Vector> playerToLocationMap = new HashMap<>(); protected HashMap<TagSize, String> imageIdMap = new HashMap<>(); protected ArrayList<TouchAction> touchActions = new ArrayList<>(); private String saveId; private String worldName; private double defX; private double defY; private double defZ; private String[] tags; private boolean simple = false; private boolean touchEnabled; private Visibility visibility = new VisibilityDefault(); protected HologramImpl(int firstTagId, String saveId, String worldName, double x, double y, double z, String... lines) { this(worldName, x, y, z); this.saveId = saveId; if (lines.length > 30) { this.tags = new String[30]; System.arraycopy(lines, 0, this.tags, 0, 30); } else { this.tags = lines; } this.firstTagId = firstTagId; } protected HologramImpl(String saveId, String worldName, double x, double y, double z, String... lines) { this(TagIdGenerator.next(lines.length > 30 ? 30 : lines.length), saveId, worldName, x, y, z, lines); } private HologramImpl(String worldName, double x, double y, double z) { this.worldName = worldName; this.defX = x; this.defY = y; this.defZ = z; } @Override public boolean isSimple() { return this.simple; } @Override public void setSimplicity(boolean flag) { this.simple = flag; if (!simple) { HoloAPI.getManager().clearFromFile(this); } HoloAPI.getManager().saveToFile(this); } @Override public int getTagCount() { return this.tags.length; } @Override public double getDefaultX() { return this.defX; } @Override public double getDefaultY() { return this.defY; } @Override public double getDefaultZ() { return this.defZ; } @Override public String getWorldName() { return this.worldName; } @Override public Location getDefaultLocation() { return new Location(Bukkit.getWorld(this.getWorldName()), this.getDefaultX(), this.getDefaultY(), this.getDefaultZ()); } @Override public HashMap<String, Vector> getPlayerViews() { HashMap<String, Vector> map = new HashMap<>(); map.putAll(this.playerToLocationMap); return map; } @Override public boolean canBeSeenBy(Player player) { checkNotNull(player, "The Player object is null in HologramImpl#canBeSeenBy(Player)"); return getPlayerViews().containsKey(IdentUtil.getIdentificationForAsString(player)); } @Override public Vector getPlayerView(Player player) { checkNotNull(player, "The Player object is null in HologramImpl#getPlayerView(Player)"); return getPlayerViews().get(IdentUtil.getIdentificationForAsString(player)); } @Override public void refreshDisplay(boolean obeyVisibility) { for (Map.Entry<String, Vector> entry : this.getPlayerViews().entrySet()) { final Player p = IdentUtil.getPlayerOf(entry.getKey()); if (p != null) { this.refreshDisplay(obeyVisibility, p); } } } @Override public void refreshDisplay(final boolean obeyVisibility, final Player observer) { checkNotNull(observer, "The Player object is null in HologramImpl#refreshDispaly(boolean, Player)"); this.clear(observer); new BukkitRunnable() { @Override public void run() { show(observer, obeyVisibility); } }.runTaskLater(HoloAPI.getCore(), 1L); } @Override public void refreshDisplay(Player observer) { checkNotNull(observer, "The Player object is null in HologramImpl#refreshDisplay(Player)"); this.refreshDisplay(false, observer); } @Override public void refreshDisplay() { this.refreshDisplay(false); } @Override public String[] getLines() { return this.tags; } @Override public Visibility getVisibility() { return this.visibility; } @Override public void setVisibility(Visibility visibility) { checkNotNull(visibility, "The Visibilty object is null in HologramImpl#setVisibility(Visibility)"); this.visibility = visibility; if (!this.isSimple()) { HoloAPI.getManager().saveToFile(this); } } @Override public String getSaveId() { return this.saveId; } @Override public void setSaveId(String saveId) { checkArgument(!saveId.isEmpty(), "The saveId String in HologramImpl#setSaveId(String) cannot be empty"); if (HoloAPI.getConfig(ConfigType.DATA).getConfigurationSection("holograms." + saveId) != null) { throw new DuplicateSaveIdException("Hologram Save IDs must be unique. A Hologram of ID " + saveId + " already exists in the HoloAPI data files!"); } if (!this.isSimple()) { // Make sure all our changes are reflected by the file HoloAPI.getManager().saveToFile(this); // Clear any existing file data HoloAPI.getManager().clearFromFile(this); } // Set the new save id this.saveId = saveId; if (!this.isSimple()) { // And save the data back to the file again under the new id HoloAPI.getManager().saveToFile(this); } } @Override public boolean isTouchEnabled() { return this.touchEnabled; } @Override public void setTouchEnabled(boolean touchEnabled) { this.touchEnabled = touchEnabled; } @Override public ArrayList<StoredTag> serialise() { ArrayList<StoredTag> tagList = new ArrayList<>(); ArrayList<String> tags = new ArrayList<>(); tags.addAll(Arrays.asList(this.tags)); for (int index = 0; index < tags.size(); index++) { String tag = tags.get(index); Map.Entry<TagSize, String> entry = getImageIdOfIndex(index); if (entry != null) { index += entry.getKey().getLast() - entry.getKey().getFirst(); tagList.add(new StoredTag(entry.getValue(), true)); } else { tagList.add(new StoredTag(tag, false)); } } return tagList; } @Override public void changeWorld(String worldName, boolean obeyVisibility) { checkNotNull(Bukkit.getWorld(worldName), "The world used in HologramImpl#changeWorld(Stirng, boolean), does not exist."); this.clearAllPlayerViews(); this.worldName = worldName; if (!this.isSimple()) { HoloAPI.getManager().saveToFile(this); } for (Entity e : this.getDefaultLocation().getWorld().getEntities()) { if (e instanceof Player) { this.show((Player) e, obeyVisibility); } } } @Override public void changeWorld(String worldName) { this.changeWorld(worldName, false); } @Override public void clearAllPlayerViews() { Iterator<String> i = this.playerToLocationMap.keySet().iterator(); while (i.hasNext()) { Player p = IdentUtil.getPlayerOf(i.next()); if (p != null) { this.clearTags(p, this.getAllEntityIds()); } i.remove(); } } @Override public Vector getLocationFor(Player player) { checkNotNull(player, "The Player object in HologramImpl#getLocationFor(Player) is null"); return this.playerToLocationMap.get(IdentUtil.getIdentificationForAsString(player)); } @Override public void updateLine(int index, String content) { if (index >= this.tags.length) { throw new IllegalArgumentException("Tag index doesn't exist!"); } else if(index < 0) { throw new IllegalArgumentException("Tag indicies cannot be less than 0!"); } HoloLineUpdateEvent lineUpdateEvent = new HoloLineUpdateEvent(this, this.tags[index], content, index); Bukkit.getServer().getPluginManager().callEvent(lineUpdateEvent); if (lineUpdateEvent.isCancelled()) { return; } this.tags[index] = lineUpdateEvent.getNewLineContent(); this.updateDisplay(); if (!this.isSimple()) { HoloAPI.getManager().saveToFile(this); } } @Override public void updateLine(int index, String content, Player observer) { if (index >= this.tags.length) { throw new IllegalArgumentException("Tag index doesn't exist!"); } else if(index < 0) { throw new IllegalArgumentException("Tag indicies cannot be less than 0!"); } checkNotNull(observer, "The Player object in HologramImpl#updateLine(int, String, Player) is null"); this.updateNametag(observer, content, index); } @Override public void updateDisplay(Player observer) { checkNotNull(observer, "The Player object in HologramImpl#updateDisplay(Player) is null"); for (int index = 0; index < this.tags.length; index++) { this.updateNametag(observer, this.tags[index], index); } } @Override public void updateDisplay() { for (String ident : this.getPlayerViews().keySet()) { Player player = IdentUtil.getPlayerOf(ident); if (player != null) { this.updateDisplay(player); } } } @Override public void updateLines(String... content) { if (content.length <= 0) { throw new IllegalArgumentException("New hologram content cannot be empty!"); } // Make sure it's not too long String[] cont = content; if (cont.length > this.tags.length) { cont = new String[this.tags.length]; System.arraycopy(content, 0, cont, 0, this.tags.length); } for (String ident : this.playerToLocationMap.keySet()) { Player p = IdentUtil.getPlayerOf(ident); if (p != null) { for (int index = 0; index < cont.length; index++) { HoloLineUpdateEvent lineUpdateEvent = new HoloLineUpdateEvent(this, this.tags[index], cont[index], index); Bukkit.getServer().getPluginManager().callEvent(lineUpdateEvent); if (lineUpdateEvent.isCancelled()) { continue; } this.tags[index] = lineUpdateEvent.getNewLineContent(); this.updateNametag(p, this.tags[index], index); } } } if (!this.isSimple()) { HoloAPI.getManager().saveToFile(this); } } @Override public void updateLines(Player observer, String... content) { checkNotNull(observer, "The Player object in HologramImpl#updateLines(Player, String...) is null"); if (content.length <= 0) { throw new IllegalArgumentException("New hologram content cannot be empty!"); } String[] cont = content; if (cont.length > this.tags.length) { cont = new String[this.tags.length]; System.arraycopy(content, 0, cont, 0, 30); } if (observer != null) { for (int index = 0; index < cont.length; index++) { this.updateNametag(observer, cont[index], index); } } } @Override public void addTouchAction(TouchAction action) { checkNotNull(action, "The TouchAction object in HologramImpl#addTouchAction(TouchAction) is null"); this.touchActions.add(action); if (!this.isSimple()) { HoloAPI.getManager().saveToFile(this); } if (!this.isTouchEnabled()) { // So that the entities aren't cleared before they're created for (Map.Entry<String, Vector> entry : this.getPlayerViews().entrySet()) { final Player p = IdentUtil.getPlayerOf(entry.getKey()); if (p != null) { clearTags(p, this.getAllEntityIds()); } } this.setTouchEnabled(true); this.refreshDisplay(true); } } @Override public void removeTouchAction(TouchAction action) { checkNotNull(action, "The TouchAction object in HologramImpl#removeTouchAction(TouchAction) is null"); this.touchActions.remove(action); if (!this.isSimple()) { HoloAPI.getManager().saveToFile(this); } } @Override public void clearAllTouchActions() { this.touchActions.clear(); if (!this.isSimple()) { HoloAPI.getManager().saveToFile(this); } } @Override public ArrayList<TouchAction> getAllTouchActions() { return new ArrayList<>(this.touchActions); } @Override public int[] getAllEntityIds() { ArrayList<Integer> entityIdList = new ArrayList<>(); for (int index = 0; index < this.getTagCount(); index++) { for (int i = 0; i < TAG_ENTITY_MULTIPLIER; i++) { entityIdList.add(this.getHorseIndex(index) + i); } } int[] ids = new int[entityIdList.size()]; for (int i = 0; i < ids.length; i++) { ids[i] = entityIdList.get(i); } return ids; } @Override public void show(Player observer, boolean obeyVisibility) { checkNotNull(observer, "The Player object in HologramImpl#show(Player, boolean) is null"); this.show(observer, this.getDefaultX(), this.getDefaultY(), this.getDefaultZ(), obeyVisibility); } @Override public void show(Player observer) { checkNotNull(observer, "The Player object in HologramImpl#show(Player) is null"); this.show(observer, false); } @Override public void show(Player observer, Location location, boolean obeyVisibility) { checkNotNull(observer, "The Player object in HologramImpl#show(Player, Location, boolean) is null"); checkNotNull(location, "The Location object in HologramImpl#show(Player, Location, boolean) is null"); this.show(observer, location.getBlockX(), location.getBlockY(), location.getBlockZ(), obeyVisibility); } @Override public void show(Player observer, Location location) { checkNotNull(observer, "The Player object in HologramImpl#show(Player, Location) is null"); checkNotNull(location, "The Location object in HologramImpl#show(Player, Location) is null"); this.show(observer, location, false); } @Override public void show(Player observer, double x, double y, double z, boolean obeyVisibility) { checkNotNull(observer, "The Player object in HologramImpl#show(Player, double, double, double, boolean) is null"); if (obeyVisibility && !this.getVisibility().isVisibleTo(observer, this.getSaveId())) { return; } for (int index = 0; index < this.getTagCount(); index++) { this.generate(observer, this.tags[index], index, -index * Settings.VERTICAL_LINE_SPACING.getValue(), x, y, z); } this.playerToLocationMap.put(IdentUtil.getIdentificationForAsString(observer), new Vector(x, y, z)); } @Override public void show(Player observer, double x, double y, double z) { checkNotNull(observer, "The Player object in HologramImpl#show(Player, double, double, double) is null"); this.show(observer, x, y, z, false); } @Override public void showNearby(Location origin, boolean obeyVisibility, int radius) { checkNotNull(origin, "The Location object in HologramImpl#showNearby(Location, boolean, int) is null"); for (Player player : GeometryUtil.getNearbyPlayers(origin, radius)) { this.show(player, obeyVisibility); } } @Override public void showNearby(Location origin, int radius) { checkNotNull(origin, "The Location object in HologramImpl#showNearby(Location, int) is null"); this.showNearby(origin, false, radius); } @Override public void showNearby(boolean obeyVisibility, int radius) { this.showNearby(getDefaultLocation(), obeyVisibility, radius); } @Override public void showNearby(int radius) { this.showNearby(false, radius); } @Override public void showNearby(boolean obeyVisibility) { this.showNearby(getDefaultLocation(), obeyVisibility, -1); } @Override public void showNearby() { this.showNearby(false); } @Override public void showNearby(double x, double y, double z, boolean obeyVisibility, int radius) { this.showNearby(new Location(Bukkit.getWorld(this.getWorldName()), x, y, z), obeyVisibility, radius); } @Override public void showNearby(double x, double y, double z, int radius) { this.showNearby(x, y, z, false, radius); } @Override public void move(Location to) { checkNotNull(to, "The Location object in HologramImpl#move(Location) is null"); if (!this.worldName.equals(to.getWorld().getName())) { this.changeWorld(to.getWorld().getName()); } this.move(to.toVector()); } @Override public void move(Vector to) { checkNotNull(to, "The Vector object in HologramImpl#move(Vector) is null"); this.defX = to.getX(); this.defY = to.getY(); this.defZ = to.getZ(); if (!this.isSimple()) { HoloAPI.getManager().saveToFile(this); } for (String ident : this.getPlayerViews().keySet()) { Player p = IdentUtil.getPlayerOf(ident); if (p != null) { this.move(p, to); } } } @Override public void move(Player observer, Vector to) { checkNotNull(observer, "The Player object in HologramImpl#move(Player, Vector) is null"); checkNotNull(to, "The Vector object in HologramImpl#move(Player, Vector) is null"); Vector loc = to.clone(); for (int index = 0; index < this.getTagCount(); index++) { this.moveTag(observer, index, loc); loc.setY(loc.getY() - Settings.VERTICAL_LINE_SPACING.getValue()); } this.playerToLocationMap.put(IdentUtil.getIdentificationForAsString(observer), to); } @Override public void clear(Player observer) { checkNotNull(observer, "The Player object in HologramImpl#clear(Player) is null"); clearTags(observer, this.getAllEntityIds()); this.playerToLocationMap.remove(IdentUtil.getIdentificationForAsString(observer)); } protected void setImageTagMap(HashMap<TagSize, String> map) { checkNotNull(map, "The HashMap object in HologramImpl#setImageTagMap(HashMap) is null"); this.imageIdMap = map; } protected Map.Entry<TagSize, String> getImageIdOfIndex(int index) { for (Map.Entry<TagSize, String> entry : this.imageIdMap.entrySet()) { if (entry.getKey().getFirst() == index) { return entry; } } return null; } protected Map.Entry<TagSize, String> getForPartOfImage(int index) { for (Map.Entry<TagSize, String> entry : this.imageIdMap.entrySet()) { if (index >= entry.getKey().getFirst() && index <= entry.getKey().getLast()) { return entry; } } return null; } protected void clearTags(Player observer, int... entityIds) { checkNotNull(observer, "The Player object in HologramImpl#clearTags(Player, int...) is null"); if (entityIds.length > 0) { WrappedPacket packet = new WrappedPacket(PacketType.Play.Server.ENTITY_DESTROY); packet.getIntegerArrays().write(0, entityIds); HoloAPI.getCore().getInjectionManager().getInjectorFor(observer).sendPacket(packet.getHandle()); } } protected void moveTag(Player observer, Vector to, int... entityIds) { checkNotNull(observer, "The Player object in HologramImpl#moveTag(Player, Vector, int...) is null"); checkNotNull(to, "The Vector object in HologramImpl#moveTag(Player, Vector, int...) is null"); WrappedPacket teleportHorse = new WrappedPacket(PacketType.Play.Server.ENTITY_TELEPORT); teleportHorse.getIntegers().write(0, entityIds[0]); teleportHorse.getIntegers().write(1, (int) Math.floor( to.getBlockX()* 32.0D)); teleportHorse.getIntegers().write(2, (int) Math.floor((to.getBlockY() + 55)* 32.0D)); teleportHorse.getIntegers().write(3,(int) Math.floor( to.getBlockZ() * 32.0D)); WrappedPacket teleportSkull = new WrappedPacket(PacketType.Play.Server.ENTITY_TELEPORT); teleportSkull.getIntegers().write(0, entityIds[1]); teleportSkull.getIntegers().write(1, (int) Math.floor( to.getBlockX()* 32.0D)); teleportSkull.getIntegers().write(2, (int) Math.floor((to.getBlockY() + 55)* 32.0D)); teleportSkull.getIntegers().write(3,(int) Math.floor( to.getBlockZ() * 32.0D)); Injector injector = HoloAPI.getCore().getInjectionManager().getInjectorFor(observer); injector.sendPacket(teleportHorse.getHandle()); injector.sendPacket(teleportSkull.getHandle()); } protected void moveTag(Player observer, int index, Vector to) { checkNotNull(observer, "The Player object in HologramImpl#moveTag(Player, int, Vector) is null"); checkNotNull(to, "The Vector object in HologramImpl#moveTag(Player, int, Vector) is null"); this.moveTag(observer, to, getHorseIndex(index), getSkullIndex(index)); if (this.isTouchEnabled()) { this.teleportTouchSlime(observer, index, to); } } protected void teleportTouchSlime(Player observer, int index, Vector to) { checkNotNull(observer, "The Player object in HologramImpl#teleportTouchSlime(Player, int, Vector) is null"); checkNotNull(to, "The Vector object in HologramImpl#teleportTouchSlime(Player, int, Vector) is null"); this.moveTag(observer, to, getTouchSlimeIndex(index), getTouchSkullIndex(index)); } protected void generate(Player observer, String message, int index, double diffY, double x, double y, double z) { checkNotNull(observer, "The Player object in HologramImpl#generate(Player, String, int, double, double, double, double) is null"); String content = HoloAPI.getTagFormatter().format(this, observer, message); ItemStack itemMatch = HoloAPI.getTagFormatter().matchItem(content); if (itemMatch != null) { this.generateFloatingItem(observer, itemMatch, index, diffY, x, y, z); } else { WrappedPacket horse = new WrappedPacket(PacketType.Play.Server.SPAWN_ENTITY_LIVING); horse.getIntegers().write(0, this.getHorseIndex(index)); horse.getIntegers().write(1, (int) EntityType.HORSE.getTypeId()); horse.getIntegers().write(2, (int) Math.floor(x * 32.0D)); horse.getIntegers().write(3, (int) Math.floor((y + diffY + 55) * 32.0D)); horse.getIntegers().write(4, (int) Math.floor(z * 32.0D)); WrappedDataWatcher dw = new WrappedDataWatcher(); dw.setObject(10, content); dw.setObject(11, Byte.valueOf((byte) 1)); dw.setObject(12, Integer.valueOf(-1700000)); horse.getDataWatchers().write(0, dw); WrappedPacket skull = new WrappedPacket(PacketType.Play.Server.SPAWN_ENTITY); skull.getIntegers().write(0, this.getSkullIndex(index)); skull.getIntegers().write(1, (int) Math.floor(x * 32.0D)); skull.getIntegers().write(2, (int) Math.floor((y + diffY + 55) * 32.0D)); skull.getIntegers().write(3, (int) Math.floor(z * 32.0D)); skull.getIntegers().write(9, 66); WrappedPacket attach = new WrappedPacket(PacketType.Play.Server.ATTACH_ENTITY); attach.getIntegers().write(0, 0); attach.getIntegers().write(1, horse.getIntegers().read(0)); attach.getIntegers().write(2, skull.getIntegers().read(0)); Injector injector = HoloAPI.getCore().getInjectionManager().getInjectorFor(observer); injector.sendPacket(horse.getHandle()); injector.sendPacket(skull.getHandle()); injector.sendPacket(attach.getHandle()); } if (this.isTouchEnabled()) { this.prepareTouchScreen(observer, index, diffY, x, y, z); } } protected void prepareTouchScreen(Player observer, int index, double diffY, double x, double y, double z) { checkNotNull(observer, "The Player object in HologramImpl#prepareTouchScreen(Player, int, double, double, double, double) is null"); int size = (this.calculateMaxLineLength() / 2); Map.Entry<TagSize, String> imagePart = this.getForPartOfImage(index); if (imagePart != null) { if (index == imagePart.getKey().getLast() || index == ((imagePart.getKey().getLast() - size / 4) + 1)) { this.generateTouchScreen(size / 10, observer, index, diffY, x, y, z); } } else if (index % (size < 1 ? 1 : size) == 0 || index >= (this.tags.length - 1)) { if (tags.length > 1 && index == 0) { return; } this.generateTouchScreen(size / 3, observer, index, diffY, x, y, z); } } protected void generateTouchScreen(int slimeSize, Player observer, int index, double diffY, double x, double y, double z) { checkNotNull(observer, "The Player object in HologramImpl#generateTouchScreen(int, Player, int, double, double, double, double) is null"); WrappedPacket touchSlime = new WrappedPacket(PacketType.Play.Server.SPAWN_ENTITY_LIVING); touchSlime.getIntegers().write(0, this.getTouchSlimeIndex(index)); touchSlime.getIntegers().write(1, (int) EntityType.SLIME.getTypeId()); touchSlime.getIntegers().write(2, (int) Math.floor(x * 32.0D)); touchSlime.getIntegers().write(3, (int) Math.floor((y + diffY) * 32.0D)); touchSlime.getIntegers().write(4, (int) Math.floor(z * 32.0D)); WrappedDataWatcher dw = new WrappedDataWatcher(); dw.setObject(0, Byte.valueOf((byte) 32)); dw.setObject(16, new Byte((byte) (slimeSize < 1 ? 1 : (slimeSize > 100 ? 100 : slimeSize)))); touchSlime.getDataWatchers().write(0, dw); WrappedPacket touchSkull = new WrappedPacket(PacketType.Play.Server.SPAWN_ENTITY); touchSkull.getIntegers().write(0, this.getTouchSkullIndex(index)); touchSkull.getIntegers().write(1, (int) Math.floor(x * 32.0D)); touchSkull.getIntegers().write(2, (int) Math.floor((y + diffY) * 32.0D)); touchSkull.getIntegers().write(3, (int) Math.floor(z * 32.0D)); touchSkull.getIntegers().write(9, 66); WrappedPacket attachTouch = new WrappedPacket(PacketType.Play.Server.ATTACH_ENTITY); attachTouch.getIntegers().write(0, 0); attachTouch.getIntegers().write(1, touchSlime.getIntegers().read(0)); attachTouch.getIntegers().write(2, touchSkull.getIntegers().read(0)); Injector injector = HoloAPI.getCore().getInjectionManager().getInjectorFor(observer); injector.sendPacket(touchSlime.getHandle()); injector.sendPacket(touchSkull.getHandle()); injector.sendPacket(attachTouch.getHandle()); } protected void generateFloatingItem(Player observer, ItemStack stack, int index, double diffY, double x, double y, double z) { checkNotNull(observer, "The Player object in HologramImpl#generateFloatingItem(Player, ItemStack, int, double, double, double, double) is null"); checkNotNull(stack, "The ItemStack object in HologramImpl#generateFloatingItem(Player, ItemStack, int, double, double, double, double) is null"); WrappedPacket item = new WrappedPacket(PacketType.Play.Server.SPAWN_ENTITY); item.getIntegers().write(0, this.getHorseIndex(index)); item.getIntegers().write(1, (int) Math.floor(x * 32.0D)); item.getIntegers().write(2, (int) Math.floor((y + diffY + 55) * 32.0D)); item.getIntegers().write(3, (int) Math.floor(z * 32.0D)); item.getIntegers().write(9, 2); item.getIntegers().write(10, 1); WrappedDataWatcher dw = new WrappedDataWatcher(); // Set what item we want to see dw.setObject(10, AS_NMS_ITEM_COPY.invokeStatic(stack)); WrappedPacket meta = new WrappedPacket(PacketType.Play.Server.ENTITY_METADATA); meta.getIntegers().write(0, item.getIntegers().read(0)); meta.getDataWatchers().write(0, dw); WrappedPacket itemSkull = new WrappedPacket(PacketType.Play.Server.SPAWN_ENTITY); itemSkull.getIntegers().write(0, this.getHorseIndex(index)); itemSkull.getIntegers().write(1, (int) Math.floor(x * 32.0D)); itemSkull.getIntegers().write(2, (int) Math.floor((y + diffY + 55) * 32.0D)); itemSkull.getIntegers().write(3, (int) Math.floor(z * 32.0D)); WrappedPacket attachItem = new WrappedPacket(PacketType.Play.Server.ATTACH_ENTITY); attachItem.getIntegers().write(0, item.getIntegers().read(0)); attachItem.getIntegers().write(0, itemSkull.getIntegers().read(0)); Injector injector = HoloAPI.getCore().getInjectionManager().getInjectorFor(observer); injector.sendPacket(item.getHandle()); injector.sendPacket(meta.getHandle()); injector.sendPacket(itemSkull.getHandle()); injector.sendPacket(attachItem.getHandle()); } protected void updateNametag(Player observer, String message, int index) { checkNotNull(observer, "The Player object in HologramImpl#updateNametag(Player, String, int) is null"); WrappedDataWatcher dw = new WrappedDataWatcher(); String content = HoloAPI.getTagFormatter().format(this, observer, message); ItemStack itemMatch = HoloAPI.getTagFormatter().matchItem(content); if (itemMatch != null) { dw.setObject(10, AS_NMS_ITEM_COPY.invokeStatic(itemMatch)); } else { dw.setObject(10, content); dw.setObject(11, Byte.valueOf((byte) 1)); dw.setObject(12, Integer.valueOf(-1700000)); } WrappedPacket metadata = new WrappedPacket(PacketType.Play.Server.ENTITY_METADATA); metadata.getIntegers().write(0, this.getHorseIndex(index)); metadata.getWatchableObjectLists().write(0, dw.getWatchableObjects()); HoloAPI.getCore().getInjectionManager().getInjectorFor(observer).sendPacket(metadata.getHandle()); } protected int getHorseIndex(int index) { return firstTagId + (index * TAG_ENTITY_MULTIPLIER); } protected int getSkullIndex(int index) { return this.getHorseIndex(index) + 1; } protected int getTouchSlimeIndex(int index) { return this.getHorseIndex(index) + 2; } protected int getTouchSkullIndex(int index) { return this.getSkullIndex(index) + 2; } protected int calculateMaxLineLength() { int max = 0; for (String tag : this.tags) { max = Math.max(tag.length(), max); } return max; } }
33,984
Java
.java
DSH105/HoloAPI
31
16
21
2014-02-21T21:30:11Z
2014-12-24T12:52:54Z
TagFormatter.java
/FileExtraction/Java_unseen/DSH105_HoloAPI/src/main/java/com/dsh105/holoapi/api/TagFormatter.java
/* * This file is part of HoloAPI. * * HoloAPI is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * HoloAPI is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with HoloAPI. If not, see <http://www.gnu.org/licenses/>. */ package com.dsh105.holoapi.api; import com.captainbern.minecraft.reflection.MinecraftReflection; import com.dsh105.commodus.ServerUtil; import com.dsh105.commodus.TimeUtil; import com.dsh105.holoapi.HoloAPI; import com.dsh105.holoapi.config.Settings; import com.dsh105.holoapi.util.UnicodeFormatter; import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.bukkit.Material; import org.bukkit.entity.Player; import org.bukkit.inventory.ItemStack; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.HashMap; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; public class TagFormatter { private HashMap<String, TagFormat> tagFormats = new HashMap<>(); private HashMap<Pattern, DynamicTagFormat> dynamicTagFormats = new HashMap<>(); public TagFormatter() { this.addFormat("%time%", new TagFormat() { @Override public String getValue(Player observer) { Calendar c = Calendar.getInstance(); c.add(Calendar.HOUR_OF_DAY, Settings.TIMEZONE_OFFSET.getValue()); return new SimpleDateFormat("h:mm a" + (Settings.TIMEZONE_SHOW_ZONE_MARKER.getValue() ? " z" : "")).format(c.getTime()); } }); this.addFormat("%mctime%", new TagFormat() { @Override public String getValue(Player observer) { return TimeUtil.format12(observer.getWorld().getTime()); } }); this.addFormat("%name%", new TagFormat() { @Override public String getValue(Player observer) { return observer.getName(); } }); this.addFormat("%displayname%", new TagFormat() { @Override public String getValue(Player observer) { return observer.getDisplayName(); } }); this.addFormat("%balance%", new TagFormat() { @Override public String getValue(Player observer) { return HoloAPI.getVaultProvider().getBalance(observer); } }); this.addFormat("%rank%", new TagFormat() { @Override public String getValue(Player observer) { return HoloAPI.getVaultProvider().getRank(observer); } }); this.addFormat("%world%", new TagFormat() { @Override public String getValue(Player observer) { return observer.getWorld().getName(); } }); this.addFormat("%health%", new TagFormat() { @Override public String getValue(Player observer) { return String.valueOf(observer.getHealth() == (int) observer.getHealth() ? (int) observer.getHealth() : observer.getHealth()); } }); this.addFormat("%playercount%", new TagFormat() { @Override public String getValue(Player observer) { return String.valueOf(ServerUtil.getOnlinePlayers().size()); } }); this.addFormat("%maxplayers%", new TagFormat() { @Override public String getValue(Player observer) { return String.valueOf(Bukkit.getMaxPlayers()); } }); this.addFormat(Pattern.compile("%date:(.+?)%"), new DynamicTagFormat() { @Override public String match(Matcher matcher, String lineContent, com.dsh105.holoapi.api.Hologram h, Player observer) { SimpleDateFormat format = new SimpleDateFormat(matcher.group(1)); Calendar calendar = Calendar.getInstance(); calendar.add(Calendar.HOUR_OF_DAY, Settings.TIMEZONE_OFFSET.getValue()); return format.format(calendar.getTime()); } }); this.addFormat(Pattern.compile("%serveronline:(.+?)%"), new DynamicTagFormat() { @Override public String match(Matcher matcher, String lineContent, com.dsh105.holoapi.api.Hologram h, Player observer) { return String.valueOf(HoloAPI.getBungeeProvider().getPlayerCount(matcher.group(1))); } }); this.addFormat(Settings.MULTICOLOR_CHARACTER.getValue(), new TagFormat() { @Override public String getValue(Player observer) { return HoloAPI.getHoloUpdater().getCurrentMultiColorFormat(); } }); } /** * Adds a formatter for all Holograms to utilise * * @param tag tag to be formatted (replaced) * @param format format to apply */ public void addFormat(String tag, TagFormat format) { this.tagFormats.put(tag, format); } /** * Removes a formatter from the list of applied formats * * @param tag tag of the format to remove */ public void removeFormat(String tag) { this.tagFormats.remove(tag); } /** * Adds a dynamic formatter for all Holograms to utilise * * @param pattern regex pattern to apply * @param format format to apply */ public void addFormat(Pattern pattern, DynamicTagFormat format) { this.dynamicTagFormats.put(pattern, format); } /** * Removes a formatter from the list of applied formats * * @param pattern pattern of the format to remove */ public void removeFormat(Pattern pattern) { this.dynamicTagFormats.remove(pattern); } public String formatForOldClient(String content) { int limit = 64; if (content.length() > limit && !MinecraftReflection.isUsingNetty()) { // 1.6.x client crashes if a name tag is longer than 64 characters // Unfortunate, but it must be accounted for content = content.substring(limit / 4, limit - (limit / 4)); } return content; } public String formatBasic(String content) { content = ChatColor.translateAlternateColorCodes('&', content); content = UnicodeFormatter.replaceAll(content); content = formatForOldClient(content); return content; } public String formatTags(Hologram h, Player observer, String content) { for (Map.Entry<String, TagFormat> entry : this.tagFormats.entrySet()) { if (entry.getKey() != null && entry.getValue() != null) { String replacement = entry.getValue().getValue(h, observer); if (replacement != null) { content = content.replace(entry.getKey(), replacement); } } } for (Map.Entry<Pattern, DynamicTagFormat> entry : this.dynamicTagFormats.entrySet()) { Matcher matcher = entry.getKey().matcher(content); while (matcher.find()) { content = content.replace(matcher.group(), entry.getValue().match(matcher, content, h, observer)); } } //content = matchDate(content); content = formatForOldClient(content); return content; } public String format(Hologram h, Player observer, String content) { content = formatTags(h, observer, content); content = formatBasic(content); return content; } public ItemStack matchItem(String content) { Matcher matcher = Pattern.compile("%item:([0-9]+)(?:,([0-9]+))?%").matcher(content); while (matcher.find()) { try { int id = Integer.parseInt(matcher.group(1)); int durability = matcher.group(2) == null ? 0 : Integer.parseInt(matcher.group(2)); return new ItemStack(id, 1, (short) durability); } catch (NumberFormatException ignored) { } } Matcher matcherStr = Pattern.compile("%item:([^0-9%]+)%").matcher(content); while (matcherStr.find()) { Material m = Material.matchMaterial(matcherStr.group(1)); if (m != null) { return new ItemStack(m); } } return null; } }
8,791
Java
.java
DSH105/HoloAPI
31
16
21
2014-02-21T21:30:11Z
2014-12-24T12:52:54Z
HologramFactory.java
/FileExtraction/Java_unseen/DSH105_HoloAPI/src/main/java/com/dsh105/holoapi/api/HologramFactory.java
/* * This file is part of HoloAPI. * * HoloAPI is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * HoloAPI is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with HoloAPI. If not, see <http://www.gnu.org/licenses/>. */ package com.dsh105.holoapi.api; import com.dsh105.holoapi.HoloAPI; import com.dsh105.holoapi.api.visibility.Visibility; import com.dsh105.holoapi.image.ImageGenerator; import org.bukkit.Location; import org.bukkit.plugin.Plugin; import org.bukkit.util.Vector; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; /** * A HologramFactory is responsible for creating an {@link com.dsh105.holoapi.api.Hologram} which can be managed by * HoloAPI * <p> * The HologramFactory implements a fluid hologram builder, allowing parameters to be set as an extension to the * constructor */ public class HologramFactory extends HoloFactory { private ArrayList<String> tags = new ArrayList<>(); protected HashMap<TagSize, String> imageIdMap = new HashMap<>(); /** * Constructs a HologramFactory * * @param owningPlugin plugin to register constructed holograms under * @throws java.lang.IllegalArgumentException if the owning plugin is null */ public HologramFactory(Plugin owningPlugin) { super(owningPlugin); } /** * Gets the emptiness state of the stored lines for constructed Holograms * * @return true if no tags exist */ public boolean isEmpty() { return this.tags.isEmpty(); } /** * Clears existing content (text and images) from the factory * * @return This object */ public HologramFactory clearContent() { this.tags.clear(); return this; } /** * Adds text to constructed Holograms * * @param text Text to add to constructed holograms * @return This object */ public HologramFactory withText(String... text) { Collections.addAll(this.tags, text); return this; } /** * Adds an image to constructed Holograms * <p> * * @param imageGenerator image generator used to prepare Holograms * @return This object * @throws java.lang.IllegalArgumentException if the generator is null * @see com.dsh105.holoapi.image.ImageGenerator */ public HologramFactory withImage(ImageGenerator imageGenerator) { if (imageGenerator == null) { throw new IllegalArgumentException("Image generator cannot be null"); } int first = this.tags.size() - 1; if (first < 0) first = 0; int length = imageGenerator.getLines().length - 1; if (imageGenerator.getKey() != null) { this.imageIdMap.put(new TagSize(first, first + length), imageGenerator.getKey()); } return this.withText(imageGenerator.getLines()); } /** * Adds image frames to constructed AnimatedHolograms * * @param customImageKey key of the image generator to search for. If a generator is not found, the image will not * be added * @return This object */ public HologramFactory withImage(String customImageKey) { ImageGenerator generator = HoloAPI.getImageLoader().getGenerator(customImageKey); if (generator != null) { this.withImage(generator); } return this; } @Override public boolean canBuild() { return !this.isEmpty(); } @Override public Hologram prepareHologram() { String[] content = this.tags.toArray(new String[this.tags.size()]); Hologram hologram; if (this.withTagId) { hologram = new HologramImpl(this.tagId, this.saveId, this.worldName, this.locX, this.locY, this.locZ, content); } else { hologram = new HologramImpl(this.saveId, this.worldName, this.locX, this.locY, this.locZ, content); } ((HologramImpl) hologram).setImageTagMap(this.imageIdMap); return hologram; } @Override public HologramFactory withLocation(Location location) { return (HologramFactory) super.withLocation(location); } @Override public HologramFactory withLocation(Vector vectorLocation, String worldName) { return (HologramFactory) super.withLocation(vectorLocation, worldName); } @Override public HologramFactory withVisibility(Visibility visibility) { return (HologramFactory) super.withVisibility(visibility); } @Override public HologramFactory withSaveId(String saveId) { return (HologramFactory) super.withSaveId(saveId); } @Override public HologramFactory withSimplicity(boolean simple) { return (HologramFactory) super.withSimplicity(simple); } @Override protected HologramFactory withFirstTagId(int tagId) { return (HologramFactory) super.withFirstTagId(tagId); } }
5,391
Java
.java
DSH105/HoloAPI
31
16
21
2014-02-21T21:30:11Z
2014-12-24T12:52:54Z
StoredTag.java
/FileExtraction/Java_unseen/DSH105_HoloAPI/src/main/java/com/dsh105/holoapi/api/StoredTag.java
/* * This file is part of HoloAPI. * * HoloAPI is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * HoloAPI is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with HoloAPI. If not, see <http://www.gnu.org/licenses/>. */ package com.dsh105.holoapi.api; public class StoredTag { private String content; private boolean isImage; public StoredTag(String content, boolean isImage) { this.content = content; this.isImage = isImage; } public String getContent() { return content; } public boolean isImage() { return isImage; } }
1,045
Java
.java
DSH105/HoloAPI
31
16
21
2014-02-21T21:30:11Z
2014-12-24T12:52:54Z
TagSize.java
/FileExtraction/Java_unseen/DSH105_HoloAPI/src/main/java/com/dsh105/holoapi/api/TagSize.java
/* * This file is part of HoloAPI. * * HoloAPI is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * HoloAPI is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with HoloAPI. If not, see <http://www.gnu.org/licenses/>. */ package com.dsh105.holoapi.api; public class TagSize { private int first; private int last; public TagSize(int first, int last) { this.first = first; this.last = last; } public int getFirst() { return first; } public int getLast() { return last; } }
993
Java
.java
DSH105/HoloAPI
31
16
21
2014-02-21T21:30:11Z
2014-12-24T12:52:54Z
AnimatedHologram.java
/FileExtraction/Java_unseen/DSH105_HoloAPI/src/main/java/com/dsh105/holoapi/api/AnimatedHologram.java
package com.dsh105.holoapi.api; import com.dsh105.holoapi.image.Frame; import org.bukkit.Location; import org.bukkit.entity.Player; import org.bukkit.util.Vector; import java.util.ArrayList; public interface AnimatedHologram extends Hologram { /** * Gets whether this hologram is image or text based * * @return true if the hologram is image based, false if text based */ public boolean isImageGenerated(); /** * Gets the animation key of the hologram * <p> * If the hologram is image based, the animation will have an animation key, as defined by the {@link * com.dsh105.holoapi.image.AnimatedImageGenerator} used to create it * * @return key of the animation used to create the hologram. Returns null if the hologram is text-based */ public String getAnimationKey(); /** * Gets the current frame of the animated hologram * * @return the current frame of the animated hologram */ public Frame getCurrent(); /** * Gets the next frame of the animated hologram * * @return the next frame of the animated hologram */ public Frame getNext(); /** * Gets the frame by its index * * @param index index of the frame to get * @return frame of the animated hologram by its index * @throws java.lang.IndexOutOfBoundsException if the frame of the specified index doesn't exist */ public Frame getFrame(int index); /** * Gets all frames of the animated hologram * * @return frames of the animated hologram */ public ArrayList<Frame> getFrames(); @Override public void updateLine(int index, String content); /** * Begin the animation of the hologram */ public void animate(); /** * Gets whether the animated hologram has an active animation * * @return true if the hologram is currently animating */ public boolean isAnimating(); /** * Cancels the current animation */ public void cancelAnimation(); @Override public void refreshDisplay(); /** * Updates the animation for an observer * <p> * Important to note: This method may yield unexpected results if not used properly * * @param observer Player to update the animation for * @param lines Lines to display */ public void updateAnimation(Player observer, String... lines); @Override public void show(Player observer); @Override public void show(Player observer, Location location); @Override public void show(Player observer, double x, double y, double z); /** * Shows the the animation to an observer * <p> * Important to note: This method may yield unexpected results if not used properly * * @param observer Player to show the animation to * @param lines Lines to display */ public void showAnimation(Player observer, String... lines); /** * Shows the the animation to an observer at a position * <p> * Important to note: This method may yield unexpected results if not used properly * * @param observer Player to show the animation to * @param v Position to show the animation at * @param lines Lines to display */ public void showAnimation(Player observer, Vector v, String... lines); }
3,399
Java
.java
DSH105/HoloAPI
31
16
21
2014-02-21T21:30:11Z
2014-12-24T12:52:54Z
TagFormat.java
/FileExtraction/Java_unseen/DSH105_HoloAPI/src/main/java/com/dsh105/holoapi/api/TagFormat.java
/* * This file is part of HoloAPI. * * HoloAPI is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * HoloAPI is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with HoloAPI. If not, see <http://www.gnu.org/licenses/>. */ package com.dsh105.holoapi.api; import org.bukkit.entity.Player; public abstract class TagFormat implements ITagFormat { @Override public abstract String getValue(Player observer); @Override public String getValue(Hologram hologram, Player observer) { return getValue(observer); } }
989
Java
.java
DSH105/HoloAPI
31
16
21
2014-02-21T21:30:11Z
2014-12-24T12:52:54Z
Hologram.java
/FileExtraction/Java_unseen/DSH105_HoloAPI/src/main/java/com/dsh105/holoapi/api/Hologram.java
/* * This file is part of HoloAPI. * * HoloAPI is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * HoloAPI is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with HoloAPI. If not, see <http://www.gnu.org/licenses/>. */ package com.dsh105.holoapi.api; import com.dsh105.holoapi.api.touch.TouchAction; import com.dsh105.holoapi.api.visibility.Visibility; import org.bukkit.Location; import org.bukkit.entity.Player; import org.bukkit.util.Vector; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; /** * Represents an Hologram that consists of either image or text */ public interface Hologram { /** * Gets whether the hologram is simple * * @return true if the hologram is simple */ public boolean isSimple(); /** * Sets the simplicity of the hologram * <p> * Save files will automatically be updated upon calling this method. That is, if setting to true, the hologram * will * be removed from file; if false, it will be saved to file * * @param flag The state of simplicity to set the hologram to */ public void setSimplicity(boolean flag); /** * Gets the number of lines in the hologram * * @return number of lines in the hologram */ public int getTagCount(); /** * Gets the default X coordinate of the hologram * * @return default X coordinate */ public double getDefaultX(); /** * Gets the default Y coordinate of the hologram * * @return default Y coordinate */ public double getDefaultY(); /** * Gets the default Z coordinate of the hologram * * @return default Z coordinate */ public double getDefaultZ(); /** * Gets the World name the hologram is visible in * * @return world name the hologram is in */ public String getWorldName(); /** * Gets the default location of the hologram * * @return default location of the hologram */ public Location getDefaultLocation(); /** * Gets a map of all players who are viewing the hologram * <p> * Positions the hologram is viewed from may be different according to different players * * @return player name to {@link org.bukkit.util.Vector} map of all viewed positions */ public HashMap<String, Vector> getPlayerViews(); /** * Gets whether a Player is able to see the hologram * * @param player player to check * @return true if it can be seen */ public boolean canBeSeenBy(Player player); /** * Gets the position the hologram is seen from for a certain Player * <p> * Unless modified externally, this will be identical to the normal hologram position * * @param player player to retrieve the view for * @return a Vector representing the position the hologram is seen from */ public Vector getPlayerView(Player player); /** * Refreshes the display of the hologram * * @param obeyVisibility whether to obey the assigned {@link com.dsh105.holoapi.api.visibility.Visibility} */ public void refreshDisplay(final boolean obeyVisibility); /** * Refreshes the display of the hologram to a certain player * * @param obeyVisibility whether to obey the assigned {@link com.dsh105.holoapi.api.visibility.Visibility} * @param observer player to refresh the hologram for */ public void refreshDisplay(final boolean obeyVisibility, final Player observer); /** * Refreshes the display of the hologram * * @param observer player to refresh the hologram for */ public void refreshDisplay(Player observer); /** * Refreshes the display of the hologram */ public void refreshDisplay(); /** * Gets the lines that the hologram consists of * <p> * Important: Images will be returned as block characters in amidst the text characters * * @return lines of the hologram */ public String[] getLines(); /** * Gets the visibility of the hologram * * @return visibility of the hologram */ public Visibility getVisibility(); /** * Sets the visibility of the hologram * * @param visibility visibility of the hologram */ public void setVisibility(Visibility visibility); /** * Gets the save id of the hologram * <p> * Used to save the hologram to the HoloAPI save files * * @return key the represents the hologram in save files */ public String getSaveId(); /** * Sets the save id of the hologram * <p> * Any existing save data will be cleared and overwritten with the new assigned id * * @param saveId save id to be assigned to this hologram * @throws com.dsh105.holoapi.exceptions.DuplicateSaveIdException if the save ID is already registered */ public void setSaveId(String saveId); /** * Gets whether the hologram is touch enabled * <p> * If a hologram is touch enabled, it either has active {@link com.dsh105.holoapi.api.touch.TouchAction}s or it has * been set to fire touch events * * @return True if hologram is touch enabled */ public boolean isTouchEnabled(); /** * Sets whether the hologram is touch enabled * <p> * If a hologram has TouchActions, it is automatically considered to be touch-enabled. Setting this to true will * force the touch events to be fired even if the hologram has no active {@link * com.dsh105.holoapi.api.touch.TouchAction}s * * @param touchEnabled boolean */ public void setTouchEnabled(boolean touchEnabled); /** * Gets a serialised map of the hologram * * @return serialised map of the hologram */ public ArrayList<StoredTag> serialise(); /** * Changes the world the hologram is visible in * <p> * Hologram coordinates will remain the same if the world is changed * * @param worldName name of of the destination world * @param obeyVisibility whether to obey the assigned {@link com.dsh105.holoapi.api.visibility.Visibility} */ public void changeWorld(String worldName, boolean obeyVisibility); /** * Changes the world the hologram is visible in * <p> * Hologram coordinates will remain the same if the world is changed * * @param worldName name of of the destination world */ public void changeWorld(String worldName); /** * Clears all views of the hologram, making it invisible to all players who could previously see it */ public void clearAllPlayerViews(); /** * Gets the viewpoint for a player * * @param player player to retrieve the viewpoint for * @return {@link org.bukkit.util.Vector} representing a player's viewpoint of the hologram */ public Vector getLocationFor(Player player); /** * Sets the content of a line of the hologram * * @param index index of the line to set * @param content new content for the hologram line * @throws java.lang.IllegalArgumentException if the index is greater than the number of tags in the hologram */ public void updateLine(int index, String content); /** * Sets the content of a line of the hologram for a certain player * * @param index index of the line to set * @param content new content for the hologram line * @param observer player to show the changes to * @throws java.lang.IllegalArgumentException if the index is greater than the number of tags in the hologram */ public void updateLine(int index, String content, Player observer); /** * Updates the current display of the hologram * <p> * This method simply sends the existing display to the specified player. It is most appropriate for updating new * tag formats that have been recently applied using the TagFormatter API (see {@link * com.dsh105.holoapi.api.TagFormatter} * * @param observer player to update the display for */ public void updateDisplay(Player observer); /** * Updates the current display of the hologram * <p> * This method simply sends the existing display to all players that can currently see the hologram. It is most * appropriate for updating new tag formats that have been recently applied using the TagFormatter API (see {@link * com.dsh105.holoapi.api.TagFormatter} */ public void updateDisplay(); /** * Sets the entire content of the hologram * * @param content new content for the hologram * @throws java.lang.IllegalArgumentException if the new content is empty * @deprecated This operation should not be accessed directly. See {@link com.dsh105.holoapi.api.HoloManager#setLineContent(Hologram, * String...)} */ @Deprecated public void updateLines(String... content); /** * Sets the entire content of the hologram for a certain player * * @param observer player to show the changes to * @param content new content for the hologram * @throws java.lang.IllegalArgumentException if the new content is empty */ @Deprecated public void updateLines(Player observer, String... content); /** * Adds an action for when the hologram is touched * * @param action action to perform when the hologram is touched */ public void addTouchAction(TouchAction action); /** * Removes an action that is set to fire when the hologram is touched * * @param action action to remove */ public void removeTouchAction(TouchAction action); /** * Clears all touch actions for this hologram */ public void clearAllTouchActions(); /** * Gets a copy of all the touch actions for the hologram * * @return copy of all touch actions for the hologram */ public ArrayList<TouchAction> getAllTouchActions(); /** * Gets all the registered NMS entity IDs for the hologram * * @return all entity IDs used for the tags in the hologram */ public int[] getAllEntityIds(); public void show(Player observer, boolean obeyVisibility); /** * Shows the hologram to a player at the default location * * @param observer player to show the hologram to */ public void show(Player observer); /** * Shows the hologram to a player at a specific location * * @param observer player to clear the hologram display for * @param location location to show the hologram at * @param obeyVisibility whether to obey the assigned {@link com.dsh105.holoapi.api.visibility.Visibility} */ public void show(Player observer, Location location, boolean obeyVisibility); /** * Shows the hologram to a player at a location * * @param observer player to show the hologram to * @param location location that the hologram is visible at */ public void show(Player observer, Location location); /** * Shows the hologram to a player at a specific location * * @param observer player to clear the hologram display for * @param x x coordinate of the location to show the hologram at * @param y y coordinate of the location to show the hologram at * @param z z coordinate of the location to show the hologram at * @param obeyVisibility whether to obey the assigned {@link com.dsh105.holoapi.api.visibility.Visibility} */ public void show(Player observer, double x, double y, double z, boolean obeyVisibility); /** * Shows the hologram to a player at a location * * @param observer player to show the hologram to * @param x x coordinate of the location the hologram is visible at * @param y y coordinate of the location the hologram is visible at * @param z z coordinate of the location the hologram is visible at */ public void show(Player observer, double x, double y, double z); /** * Shows the hologram to all nearby players within the given radius * * @param origin centre location * @param obeyVisibility whether to obey the assigned {@link com.dsh105.holoapi.api.visibility.Visibility} * @param radius radius to search for nearby players in */ public void showNearby(Location origin, boolean obeyVisibility, int radius); /** * Shows the hologram to all nearby players within the given radius * * @param origin centre location * @param radius radius to search for nearby players in */ public void showNearby(Location origin, int radius); /** * Shows the hologram to all nearby players within the given radius * * @param obeyVisibility whether to obey the assigned {@link com.dsh105.holoapi.api.visibility.Visibility} * @param radius radius to search for nearby players in */ public void showNearby(boolean obeyVisibility, int radius); /** * Shows the hologram to all nearby players within the given radius * <p> * The origin location will be at the default location of the hologram * * @param radius radius to search for nearby players in */ public void showNearby(int radius); /** * Shows the hologram to all in the world of the hologram * <p> * The origin location will be at the default location of the hologram * * @param obeyVisibility whether to obey the assigned {@link com.dsh105.holoapi.api.visibility.Visibility} */ public void showNearby(boolean obeyVisibility); /** * Shows the hologram to all players in the world of the hologram * <p> * The origin location will be at the default location of the hologram */ public void showNearby(); /** * Shows the hologram to all nearby players within the given radius * <p> * The origin location will be at the default location of the hologram * * @param x x coordinate of the centre location (origin) * @param y y coordinate of the centre location (origin) * @param z z coordinate of the centre location (origin) * @param obeyVisibility whether to obey the assigned {@link com.dsh105.holoapi.api.visibility.Visibility} * @param radius radius to search for nearby players in */ public void showNearby(double x, double y, double z, boolean obeyVisibility, int radius); /** * Shows the hologram to all nearby players within the given radius * * @param x x coordinate of the centre location (origin) * @param y y coordinate of the centre location (origin) * @param z z coordinate of the centre location (origin) * @param radius radius to search for nearby players in */ public void showNearby(double x, double y, double z, int radius); /** * Moves the hologram to a new location * <p> * Also moves the hologram position for all players currently viewing the hologram * * @param to position to move to */ public void move(Location to); /** * Moves the hologram to a new location * <p> * Also moves the hologram position for all players currently viewing the hologram * * @param to position to move to */ public void move(Vector to); /** * Moves the hologram to a new location for one player only * * @param observer player to move the hologram display for * @param to position to move to */ public void move(Player observer, Vector to); /** * Clears the view of the hologram for a player * * @param observer player to clear the hologram display for */ public void clear(Player observer); }
16,495
Java
.java
DSH105/HoloAPI
31
16
21
2014-02-21T21:30:11Z
2014-12-24T12:52:54Z
HoloUpdater.java
/FileExtraction/Java_unseen/DSH105_HoloAPI/src/main/java/com/dsh105/holoapi/api/HoloUpdater.java
/* * This file is part of HoloAPI. * * HoloAPI is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * HoloAPI is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with HoloAPI. If not, see <http://www.gnu.org/licenses/>. */ package com.dsh105.holoapi.api; import com.dsh105.commodus.GeneralUtil; import com.dsh105.holoapi.HoloAPI; import com.dsh105.holoapi.config.Settings; import org.bukkit.scheduler.BukkitRunnable; import java.util.ArrayList; import java.util.Collections; import java.util.List; /** * Handles both time/date updates and multi-colour formatting updates */ public class HoloUpdater extends BukkitRunnable { private static String[] UPDATE_TAGS; public ArrayList<Hologram> tracked = new ArrayList<>(); /* * Stuff for colour updating */ private String[] colours; private int index; public HoloUpdater() { this.colours = Settings.MULTICOLOR_COLOURS.getValue().split(","); UPDATE_TAGS = new String[]{"%time%", "%date:", Settings.MULTICOLOR_CHARACTER.getValue()}; this.runTaskTimer(HoloAPI.getCore(), 0, Settings.MULTICOLOR_DELAY.getValue().longValue()); } @Override public void run() { if (++index >= colours.length) { index = 0; } for (Hologram h : getTrackedHolograms()) { h.updateDisplay(); } } public List<Hologram> getTrackedHolograms() { return Collections.unmodifiableList(tracked); } public boolean track(Hologram hologram) { return track(hologram, true); } public boolean track(Hologram hologram, boolean checkIfTrackable) { if (tracked.contains(hologram)) { return true; } if (!checkIfTrackable || shouldTrack(hologram)) { tracked.add(hologram); return true; } return false; } public boolean shouldTrack(Hologram hologram) { return shouldTrack(hologram.getLines()); } public boolean shouldTrack(String... content) { for (String line : content) { for (String tag : UPDATE_TAGS) { if (line.contains(tag)) { return true; } } } return false; } public boolean remove(Hologram hologram) { if (tracked.contains(hologram)) { tracked.remove(hologram); return true; } return false; } public String getCurrentMultiColorFormat() { return colours[index]; } }
2,980
Java
.java
DSH105/HoloAPI
31
16
21
2014-02-21T21:30:11Z
2014-12-24T12:52:54Z
DynamicTagFormat.java
/FileExtraction/Java_unseen/DSH105_HoloAPI/src/main/java/com/dsh105/holoapi/api/DynamicTagFormat.java
/* * This file is part of HoloAPI. * * HoloAPI is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * HoloAPI is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with HoloAPI. If not, see <http://www.gnu.org/licenses/>. */ package com.dsh105.holoapi.api; import org.bukkit.entity.Player; import java.util.regex.Matcher; /** * Represents a regex supported tag format for use in the {@link com.dsh105.holoapi.api.TagFormatter} */ public abstract class DynamicTagFormat extends TagFormat { public abstract String match(Matcher matcher, String lineContent, Hologram h, Player observer); @Override public String getValue(Player observer) { return null; } @Override public String getValue(Hologram hologram, Player observer) { return null; } }
1,241
Java
.java
DSH105/HoloAPI
31
16
21
2014-02-21T21:30:11Z
2014-12-24T12:52:54Z
ITagFormat.java
/FileExtraction/Java_unseen/DSH105_HoloAPI/src/main/java/com/dsh105/holoapi/api/ITagFormat.java
/* * This file is part of HoloAPI. * * HoloAPI is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * HoloAPI is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with HoloAPI. If not, see <http://www.gnu.org/licenses/>. */ package com.dsh105.holoapi.api; import org.bukkit.entity.Player; public interface ITagFormat { /** * Gets the value to use in the hologram instead of the registered key * * @param observer player viewing the hologram * @deprecated use {@link com.dsh105.holoapi.api.ITagFormat#getValue(com.dsh105.holoapi.api.Hologram, * org.bukkit.entity.Player)} * @return Value to use in Hologram */ @Deprecated public String getValue(Player observer); /** * Gets the value to use in the hologram instead of the registered key. If not overridden, this will return {@link * com.dsh105.holoapi.api.ITagFormat#getValue(org.bukkit.entity.Player)} * * @param hologram hologram using this function * @param observer player viewing the hologram * @return Value to use in Hologram */ public String getValue(Hologram hologram, Player observer); }
1,591
Java
.java
DSH105/HoloAPI
31
16
21
2014-02-21T21:30:11Z
2014-12-24T12:52:54Z
AnimatedHologramFactory.java
/FileExtraction/Java_unseen/DSH105_HoloAPI/src/main/java/com/dsh105/holoapi/api/AnimatedHologramFactory.java
/* * This file is part of HoloAPI. * * HoloAPI is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * HoloAPI is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with HoloAPI. If not, see <http://www.gnu.org/licenses/>. */ package com.dsh105.holoapi.api; import com.dsh105.holoapi.HoloAPI; import com.dsh105.holoapi.api.visibility.Visibility; import com.dsh105.holoapi.image.AnimatedImageGenerator; import com.dsh105.holoapi.image.AnimatedTextGenerator; import org.bukkit.Location; import org.bukkit.plugin.Plugin; import org.bukkit.util.Vector; /** * An AnimatedHologramFactory is responsible for creating an {@link com.dsh105.holoapi.api.AnimatedHologram} which can * be managed by HoloAPI * <p> * The AnimatedHologramFactory implements a fluid hologram builder, allowing parameters to be set as an extension to * the * constructor */ public class AnimatedHologramFactory extends HoloFactory { private AnimatedImageGenerator animatedImage; private AnimatedTextGenerator textGenerator; private boolean imageGenerated; /** * Constructs an AnimatedHologramFactory * * @param owningPlugin plugin to register constructed holograms under * @throws java.lang.IllegalArgumentException if the owning plugin is null */ public AnimatedHologramFactory(Plugin owningPlugin) { super(owningPlugin); } /** * Adds frames of text to constructed AnimatedHolograms * <p> * * @param textGenerator text generator used to prepare AnimatedHolograms * @return This object * @see com.dsh105.holoapi.image.AnimatedTextGenerator */ public AnimatedHologramFactory withText(AnimatedTextGenerator textGenerator) { this.textGenerator = textGenerator; this.imageGenerated = false; return this; } /** * Adds image frames to constructed AnimatedHolograms * <p> * * @param animatedImage animation generator used to prepare AnimatedHolograms * @return This object * @see com.dsh105.holoapi.image.AnimatedImageGenerator */ public AnimatedHologramFactory withImage(AnimatedImageGenerator animatedImage) { this.animatedImage = animatedImage; this.imageGenerated = true; return this; } /** * * Adds image frames to constructed AnimatedHolograms * * @param animatedImageKey key of the animation generator to search for. If a generator is not found, the animation * will not be added * @return This object */ public AnimatedHologramFactory withImage(String animatedImageKey) { AnimatedImageGenerator generator = HoloAPI.getAnimationLoader().getGenerator(animatedImageKey); if (generator != null) { this.withImage(generator); } return this; } @Override public boolean canBuild() { return this.imageGenerated ? this.animatedImage == null : this.textGenerator == null; } @Override public AnimatedHologram prepareHologram() { if (this.imageGenerated) { return new AnimatedHologramImpl(this.saveId, this.worldName, this.locX, this.locY, this.locZ, this.animatedImage); } return new AnimatedHologramImpl(this.saveId, this.worldName, this.locX, this.locY, this.locZ, this.textGenerator); } @Override public AnimatedHologramFactory withLocation(Location location) { return (AnimatedHologramFactory) super.withLocation(location); } @Override public AnimatedHologramFactory withLocation(Vector vectorLocation, String worldName) { return (AnimatedHologramFactory) super.withLocation(vectorLocation, worldName); } @Override public AnimatedHologramFactory withVisibility(Visibility visibility) { return (AnimatedHologramFactory) super.withVisibility(visibility); } @Override public AnimatedHologramFactory withSaveId(String saveId) { return (AnimatedHologramFactory) super.withSaveId(saveId); } @Override public AnimatedHologramFactory withSimplicity(boolean simple) { return (AnimatedHologramFactory) super.withSimplicity(simple); } @Override public AnimatedHologram build() { return (AnimatedHologram) super.build(); } @Override protected AnimatedHologramFactory withFirstTagId(int tagId) { return (AnimatedHologramFactory) super.withFirstTagId(tagId); } }
4,903
Java
.java
DSH105/HoloAPI
31
16
21
2014-02-21T21:30:11Z
2014-12-24T12:52:54Z
HoloManager.java
/FileExtraction/Java_unseen/DSH105_HoloAPI/src/main/java/com/dsh105/holoapi/api/HoloManager.java
/* * This file is part of HoloAPI. * * HoloAPI is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * HoloAPI is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with HoloAPI. If not, see <http://www.gnu.org/licenses/>. */ package com.dsh105.holoapi.api; import org.bukkit.Location; import org.bukkit.plugin.Plugin; import org.bukkit.util.Vector; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; public interface HoloManager { /** * Gets all the stored holograms, including simple holograms * <p> * Simple holograms include chat bubbles and indicators if the server has them enabled * * @return all stored holograms */ public Map<Hologram, Plugin> getAllHolograms(); /** * Gets all the stored holograms which are not simple * * @return all stored holograms */ public Map<Hologram, Plugin> getAllComplexHolograms(); /** * Gets all the stored holograms which are simple * <p> * Simple holograms include chat bubbles and indicators if the server has them enabled * * @return all stored holograms */ public Map<Hologram, Plugin> getAllSimpleHolograms(); /** * Gets all stored holograms for a plugin * * @param owningPlugin plugin to retrieve holograms for * @return holograms registered under a plugin */ public List<Hologram> getHologramsFor(Plugin owningPlugin); /** * Gets a hologram of an ID * * @param hologramId hologram ID to search with * @return hologram of an ID */ public Hologram getHologram(String hologramId); /** * Tracks and registers a hologram * * @param hologram hologram to register * @param owningPlugin plugin to register hologram under */ public void track(Hologram hologram, Plugin owningPlugin); void remove(Hologram hologram); void remove(String hologramId); /** * Stops tracking a hologram and clears all player views * <p> * This does not clear the hologram data from file * * @param hologram hologram to stop tracking */ public void stopTracking(Hologram hologram); /** * Stops tracking a hologram and clears all player views * <p> * This does not clear the hologram data from file * * @param hologramId ID of hologram to stop tracking */ public void stopTracking(String hologramId); /** * Saves hologram data to file * * @param hologramId ID of hologram to save */ public void saveToFile(String hologramId); /** * Saves hologram data to file * * @param hologram hologram to save */ public void saveToFile(Hologram hologram); /** * Clears hologram data from file * * @param hologramId ID of hologram to clear */ public void clearFromFile(String hologramId); /** * Clears hologram data from file * * @param hologram hologram to clear */ public void clearFromFile(Hologram hologram); /** * Copies a hologram from the provided original * * @param original original hologram * @param copyLocation location to copy the hologram to * @return copied hologram */ public Hologram copy(Hologram original, Location copyLocation); /** * Sets the new line content for an existing hologram, accounting for new lines added. * <p> * This method is more expensive IF there are more lines in the new content then already present in the hologram * <p> * If the above condition is met, the original hologram will be copied and new lines added * * @param original Hologram to set the content of * @param newContent new content to apply to the hologram * @return Hologram to which lines were updated */ public Hologram setLineContent(Hologram original, String... newContent); /** * Copies a hologram from the provided original and adds lines * * @param original original hologram * @param linesToAdd lines to copy to the copied hologram * @return copied hologram * @throws IllegalArgumentException if the hologram is an {@link com.dsh105.holoapi.api.AnimatedHologram}. Lines * cannot be * dynamically added to animated holograms */ public Hologram copyAndAddLineTo(Hologram original, String... linesToAdd); /** * Creates a simple hologram. Simple holograms are automatically removed after a certain period of time, are not * saved to file and can only include text content. * * @param location position to place the simple hologram * @param secondsUntilRemoved time in seconds until the hologram is removed * @param lines content of the hologram * @return The constructed simple Hologram */ public Hologram createSimpleHologram(Location location, int secondsUntilRemoved, List<String> lines); /** * Creates a simple hologram. Simple holograms are automatically removed after a certain period of time, are not * saved to file and can only include text content. * * @param location position to place the simple hologram * @param secondsUntilRemoved time in seconds until the hologram is removed * @param lines content of the hologram * @return The constructed simple hologram */ public Hologram createSimpleHologram(Location location, int secondsUntilRemoved, String... lines); /** * Creates a simple hologram. Simple holograms are automatically removed after a certain period of time, are not * saved to file and can only include text content. * * @param location position to place the simple hologram * @param secondsUntilRemoved time in seconds until the hologram is removed * @param rise if true, the hologram will automatically rise upwards at a predefined speed * @param lines content of the hologram * @return The constrctued simple Hologram */ public Hologram createSimpleHologram(Location location, int secondsUntilRemoved, boolean rise, List<String> lines); /** * Creates a simple hologram. Simple holograms are automatically removed after a certain period of time, are not * saved to file and can only include text content. * * @param location position to place the simple hologram * @param secondsUntilRemoved time in seconds until the hologram is removed * @param rise if true, the hologram will automatically rise upwards at a predefined speed * @param lines content of the hologram * @return The constucted simple Hologram */ public Hologram createSimpleHologram(Location location, int secondsUntilRemoved, boolean rise, String... lines); /** * Creates a simple hologram. Simple holograms are automatically removed after a certain period of time, are not * saved to file and can only include text content. * * @param location position to place the simple hologram * @param secondsUntilRemoved time in seconds until the hologram is removed * @param velocity velocity to apply to the hologram * @param lines content of the hologram * @return The constructed simple Hologram */ public Hologram createSimpleHologram(Location location, int secondsUntilRemoved, Vector velocity, List<String> lines); /** * Creates a simple hologram. Simple holograms are automatically removed after a certain period of time, are not * saved to file and can only include text content. * * @param location position to place the simple hologram * @param secondsUntilRemoved time in seconds until the hologram is removed * @param velocity velocity to apply to the hologram * @param lines content of the hologram * @return The constructed simple Hologram */ public Hologram createSimpleHologram(Location location, int secondsUntilRemoved, final Vector velocity, String... lines); }
8,733
Java
.java
DSH105/HoloAPI
31
16
21
2014-02-21T21:30:11Z
2014-12-24T12:52:54Z
VisibilityDefault.java
/FileExtraction/Java_unseen/DSH105_HoloAPI/src/main/java/com/dsh105/holoapi/api/visibility/VisibilityDefault.java
/* * This file is part of HoloAPI. * * HoloAPI is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * HoloAPI is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with HoloAPI. If not, see <http://www.gnu.org/licenses/>. */ package com.dsh105.holoapi.api.visibility; import org.bukkit.entity.Player; import java.util.LinkedHashMap; /** * Represents a visibility in which all players can see the hologram */ public class VisibilityDefault implements Visibility { @Override public boolean isVisibleTo(Player player, String hologramId) { return true; } @Override public String getSaveKey() { return null; } @Override public LinkedHashMap<String, Object> getDataToSave() { return null; } }
1,205
Java
.java
DSH105/HoloAPI
31
16
21
2014-02-21T21:30:11Z
2014-12-24T12:52:54Z
VisibilityPermission.java
/FileExtraction/Java_unseen/DSH105_HoloAPI/src/main/java/com/dsh105/holoapi/api/visibility/VisibilityPermission.java
/* * This file is part of HoloAPI. * * HoloAPI is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * HoloAPI is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with HoloAPI. If not, see <http://www.gnu.org/licenses/>. */ package com.dsh105.holoapi.api.visibility; import org.bukkit.entity.Player; import java.util.LinkedHashMap; /** * Represents a visibility in which only players with a certain permission can see the hologram */ public class VisibilityPermission implements Visibility { private String permission; public VisibilityPermission() { } public VisibilityPermission(String permission) { this.permission = permission; } public String getPermission() { return permission; } @Override public boolean isVisibleTo(Player player, String hologramId) { return this.permission == null ? (player.hasPermission("holoapi.holo.see." + hologramId) || player.hasPermission("holoapi.holo.see.all")) : player.hasPermission(this.permission); } @Override public String getSaveKey() { return "perm"; } @Override public LinkedHashMap<String, Object> getDataToSave() { LinkedHashMap<String, Object> dataMap = new LinkedHashMap<String, Object>(); dataMap.put("permission", this.getPermission() == null ? "unidentified" : this.getPermission()); return dataMap; } }
1,839
Java
.java
DSH105/HoloAPI
31
16
21
2014-02-21T21:30:11Z
2014-12-24T12:52:54Z
Visibility.java
/FileExtraction/Java_unseen/DSH105_HoloAPI/src/main/java/com/dsh105/holoapi/api/visibility/Visibility.java
/* * This file is part of HoloAPI. * * HoloAPI is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * HoloAPI is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with HoloAPI. If not, see <http://www.gnu.org/licenses/>. */ package com.dsh105.holoapi.api.visibility; import org.bukkit.entity.Player; import java.util.LinkedHashMap; /** * Represents the visibility of the hologram */ public interface Visibility { /** * Gets whether a hologram can be shown to a certain player * * @param player player in question * @param hologramId Hologram ID * @return true if hologram can be shown to the player, false if it should be kept hidden */ public boolean isVisibleTo(Player player, String hologramId); /** * Gets the String the represents the Visibility. The save key is used in hologram information lists and data files * within HoloAPI * * @return string that represents the Visibility */ public String getSaveKey(); /** * Gets a map of the Visibility data to save to file. * <p> * HoloAPI uses this data for saving Hologram Visibility data to file so that it can be loaded again when the * hologram is recreated from the save file. See {@link com.dsh105.holoapi.api.events.HoloVisibilityLoadEvent} for * information on how to load TouchAction data back into holograms * * @return a map of all data to save to file. See {@link com.dsh105.holoapi.api.touch.CommandTouchAction} for a * working example of this */ public LinkedHashMap<String, Object> getDataToSave(); }
2,049
Java
.java
DSH105/HoloAPI
31
16
21
2014-02-21T21:30:11Z
2014-12-24T12:52:54Z
VisibilityMatcher.java
/FileExtraction/Java_unseen/DSH105_HoloAPI/src/main/java/com/dsh105/holoapi/api/visibility/VisibilityMatcher.java
/* * This file is part of HoloAPI. * * HoloAPI is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * HoloAPI is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with HoloAPI. If not, see <http://www.gnu.org/licenses/>. */ package com.dsh105.holoapi.api.visibility; import java.util.Collections; import java.util.HashMap; import java.util.Map; public class VisibilityMatcher { private HashMap<String, Visibility> visibilities = new HashMap<>(); public VisibilityMatcher() { Visibility def = new VisibilityDefault(); this.visibilities.put("all", def); this.visibilities.put("default", def); Visibility perm = new VisibilityPermission(); this.visibilities.put("perm", perm); this.visibilities.put("permission", perm); } public Map<String, Visibility> getValidVisibilities() { return Collections.unmodifiableMap(this.visibilities); } /** * Registers a visibility under a certain key * * @param key key to register the visibility under * @param visibility visibility to register */ public void add(String key, Visibility visibility) { this.visibilities.put(key, visibility); } /** * Removes a registration of a visibility * * @param key key of the registered visibility to remove */ public void remove(String key) { this.visibilities.remove(key); } /** * Gets a visibility registered under a certain key * * @param key key to search for visibility with * @return Visibility that matches the specified key, null if it is not registered */ public Visibility get(String key) { return this.visibilities.get(key); } /** * Gets the key of a registered visibility * * @param visibility visibility to search with * @return Key of the specified visibility, null if it is not registered */ public String getKeyOf(Visibility visibility) { for (Map.Entry<String, Visibility> entry : this.visibilities.entrySet()) { if (visibility.equals(entry.getValue())) { return entry.getKey(); } } return null; } }
2,660
Java
.java
DSH105/HoloAPI
31
16
21
2014-02-21T21:30:11Z
2014-12-24T12:52:54Z
CommandTouchAction.java
/FileExtraction/Java_unseen/DSH105_HoloAPI/src/main/java/com/dsh105/holoapi/api/touch/CommandTouchAction.java
/* * This file is part of HoloAPI. * * HoloAPI is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * HoloAPI is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with HoloAPI. If not, see <http://www.gnu.org/licenses/>. */ package com.dsh105.holoapi.api.touch; import com.dsh105.commodus.StringUtil; import com.dsh105.holoapi.HoloAPI; import org.bukkit.entity.Player; import java.io.ByteArrayOutputStream; import java.io.DataOutputStream; import java.io.IOException; import java.util.LinkedHashMap; /** * Represents a command-based action that is performed when a Hologram is touched */ public class CommandTouchAction implements TouchAction { private String command; private boolean performAsConsole; /** * Constructs a new CommandTouchAction * * @param command command to perform when the hologram is touched * @param performAsConsole true if command is to be performed as the console, false if it is to be performed as the * player that touched the hologram */ public CommandTouchAction(String command, boolean performAsConsole) { this.command = command; this.performAsConsole = performAsConsole; } /** * Gets the command that is to be performed * * @return command to be performed */ public String getCommand() { return command; } /** * Gets whether the command should be executed from the console or on behalf of the player that touched the * hologram * * @return true if command is to be performed as the console, false if it is to be performed as the player that * touched the hologram */ public boolean shouldPerformAsConsole() { return performAsConsole; } @Override public void onTouch(Player who, Action action) { String command = this.command.replace("%name%", who.getName()); command = command.replace("%world%", who.getWorld().getName()); if (command.startsWith("server ")) { String serverName = StringUtil.combineSplit(1, command.split(" "), " "); ByteArrayOutputStream byteOutput = new ByteArrayOutputStream(); DataOutputStream out = new DataOutputStream(byteOutput); try { out.writeUTF("Connect"); out.writeUTF(serverName); who.sendPluginMessage(HoloAPI.getCore(), "BungeeCord", byteOutput.toByteArray()); return; } catch (IOException ignored) { } } if (this.shouldPerformAsConsole()) { HoloAPI.getCore().getServer().dispatchCommand(HoloAPI.getCore().getServer().getConsoleSender(), command); } else { who.performCommand(command); } } @Override public String getSaveKey() { return "command_" + this.command + "_" + this.shouldPerformAsConsole(); } @Override public LinkedHashMap<String, Object> getDataToSave() { LinkedHashMap<String, Object> dataMap = new LinkedHashMap<String, Object>(); dataMap.put("command", this.getCommand()); dataMap.put("asConsole", this.shouldPerformAsConsole()); return dataMap; } }
3,672
Java
.java
DSH105/HoloAPI
31
16
21
2014-02-21T21:30:11Z
2014-12-24T12:52:54Z
TouchAction.java
/FileExtraction/Java_unseen/DSH105_HoloAPI/src/main/java/com/dsh105/holoapi/api/touch/TouchAction.java
/* * This file is part of HoloAPI. * * HoloAPI is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * HoloAPI is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with HoloAPI. If not, see <http://www.gnu.org/licenses/>. */ package com.dsh105.holoapi.api.touch; import org.bukkit.entity.Player; import java.util.LinkedHashMap; /** * Represents an action that is performed when a Hologram is touched */ public interface TouchAction { /** * Action to perform when a Hologram that the action is attached to is touched * * @param who Player interacting with the Hologram * @param action Action to perform */ public void onTouch(Player who, Action action); /** * Gets the String the represents the TouchAction. The serialised key is used in hologram information lists within * HoloAPI * * @return string that represents the TouchAction */ public String getSaveKey(); /** * Gets a map of the TouchAction data to save to file. * <p> * HoloAPI uses this data for saving Hologram TouchAction data to file so that it can be loaded again when the * hologram is recreated from the save file. See {@link com.dsh105.holoapi.api.events.HoloTouchActionLoadEvent} for * information on how to load TouchAction data back into holograms * * @return a map of all data to save to file. See {@link com.dsh105.holoapi.api.touch.CommandTouchAction} for a * working example of this */ public LinkedHashMap<String, Object> getDataToSave(); }
1,992
Java
.java
DSH105/HoloAPI
31
16
21
2014-02-21T21:30:11Z
2014-12-24T12:52:54Z
Action.java
/FileExtraction/Java_unseen/DSH105_HoloAPI/src/main/java/com/dsh105/holoapi/api/touch/Action.java
package com.dsh105.holoapi.api.touch; public enum Action { LEFT_CLICK, RIGHT_CLICK, UNKNOWN; public static Action getFromId(int id) { switch (id) { case 0: return RIGHT_CLICK; case 1: return LEFT_CLICK; default: return UNKNOWN; } } }
357
Java
.java
DSH105/HoloAPI
31
16
21
2014-02-21T21:30:11Z
2014-12-24T12:52:54Z
HoloVisibilityLoadEvent.java
/FileExtraction/Java_unseen/DSH105_HoloAPI/src/main/java/com/dsh105/holoapi/api/events/HoloVisibilityLoadEvent.java
/* * This file is part of HoloAPI. * * HoloAPI is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * HoloAPI is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with HoloAPI. If not, see <http://www.gnu.org/licenses/>. */ package com.dsh105.holoapi.api.events; import com.dsh105.holoapi.api.Hologram; import java.util.Map; /** * Called when Visibility data is loaded from a HoloAPI data file */ public class HoloVisibilityLoadEvent extends HoloDataLoadEvent { public HoloVisibilityLoadEvent(Hologram hologram, String saveKey, Map<String, Object> configMap) { super(hologram, saveKey, configMap); } }
1,074
Java
.java
DSH105/HoloAPI
31
16
21
2014-02-21T21:30:11Z
2014-12-24T12:52:54Z
HoloEvent.java
/FileExtraction/Java_unseen/DSH105_HoloAPI/src/main/java/com/dsh105/holoapi/api/events/HoloEvent.java
/* * This file is part of HoloAPI. * * HoloAPI is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * HoloAPI is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with HoloAPI. If not, see <http://www.gnu.org/licenses/>. */ package com.dsh105.holoapi.api.events; import com.dsh105.holoapi.api.Hologram; import org.bukkit.event.Cancellable; import org.bukkit.event.Event; import org.bukkit.event.HandlerList; /** * Represents a base Event. */ public class HoloEvent extends Event implements Cancellable { private static final HandlerList handlers = new HandlerList(); private boolean cancelled = false; private final Hologram hologram; public HoloEvent(Hologram hologram) { this.hologram = hologram; } /** * Get the modifiable {@link com.dsh105.holoapi.api.Hologram} involved in this Event. * * @return Hologram. */ public Hologram getHologram() { return this.hologram; } /** * Checks if the event has been cancelled. * * @return true if cancelled, otherwise false. */ public boolean isCancelled() { return this.cancelled; } /** * Sets the cancel status to this state. * * @param cancel - whether or not the event should be cancelled. */ public void setCancelled(boolean cancel) { this.cancelled = cancel; } @Override public HandlerList getHandlers() { return this.handlers; } public static HandlerList getHandlerList() { return handlers; } }
1,990
Java
.java
DSH105/HoloAPI
31
16
21
2014-02-21T21:30:11Z
2014-12-24T12:52:54Z
HoloLineUpdateEvent.java
/FileExtraction/Java_unseen/DSH105_HoloAPI/src/main/java/com/dsh105/holoapi/api/events/HoloLineUpdateEvent.java
/* * This file is part of HoloAPI. * * HoloAPI is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * HoloAPI is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with HoloAPI. If not, see <http://www.gnu.org/licenses/>. */ package com.dsh105.holoapi.api.events; import com.dsh105.holoapi.api.Hologram; import org.bukkit.event.Cancellable; /** * Called when a line of a hologram is updated. Only called when new content is applied to the hologram */ public class HoloLineUpdateEvent extends HoloEvent implements Cancellable { private boolean cancelled = false; private String newLineContent; private String oldLineContent; private int lineIndex; public HoloLineUpdateEvent(Hologram hologram, String oldLineContent, String newLineContent, int lineIndex) { super(hologram); this.newLineContent = newLineContent; this.oldLineContent = oldLineContent; this.lineIndex = lineIndex; } /** * Gets the index of the line that is being updated * * @return index of the line being updated */ public int getLineIndex() { return lineIndex; } /** * Gets the content being applied to the hologram line * * @return content being applied */ public String getNewLineContent() { return newLineContent; } /** * Gets the old content of the hologram line being updated * * @return old line content of the hologram */ public String getOldLineContent() { return oldLineContent; } /** * Sets the content to be applied to the hologram line * * @param content content to be applied */ public void setNewLineContent(String content) { this.newLineContent = content; } @Override public boolean isCancelled() { return this.cancelled; } @Override public void setCancelled(boolean cancel) { this.cancelled = cancel; } }
2,405
Java
.java
DSH105/HoloAPI
31
16
21
2014-02-21T21:30:11Z
2014-12-24T12:52:54Z
HoloTouchActionLoadEvent.java
/FileExtraction/Java_unseen/DSH105_HoloAPI/src/main/java/com/dsh105/holoapi/api/events/HoloTouchActionLoadEvent.java
/* * This file is part of HoloAPI. * * HoloAPI is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * HoloAPI is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with HoloAPI. If not, see <http://www.gnu.org/licenses/>. */ package com.dsh105.holoapi.api.events; import com.dsh105.holoapi.api.Hologram; import java.util.Map; /** * Called when TouchAction data is loaded from file. */ public class HoloTouchActionLoadEvent extends HoloDataLoadEvent { public HoloTouchActionLoadEvent(Hologram hologram, String saveKey, Map<String, Object> configMap) { super(hologram, saveKey, configMap); } /** * Gets the save key of the saved data * * @return key of the saved data * @deprecated use {@link HoloDataLoadEvent#getSaveKey()} */ @Deprecated public String getLoadedTouchActionKey() { return getSaveKey(); } }
1,327
Java
.java
DSH105/HoloAPI
31
16
21
2014-02-21T21:30:11Z
2014-12-24T12:52:54Z
HoloDataLoadEvent.java
/FileExtraction/Java_unseen/DSH105_HoloAPI/src/main/java/com/dsh105/holoapi/api/events/HoloDataLoadEvent.java
/* * This file is part of HoloAPI. * * HoloAPI is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * HoloAPI is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with HoloAPI. If not, see <http://www.gnu.org/licenses/>. */ package com.dsh105.holoapi.api.events; import com.dsh105.holoapi.api.Hologram; import java.util.Map; /** * Called when data is loaded from file. The event can be used to recreate TouchActions or a certain Visibility and add * them to * loaded holograms. See {@link com.dsh105.holoapi.listeners.HoloDataLoadListener} for an example of this */ public class HoloDataLoadEvent extends HoloEvent { private final String saveKey; private final Map<String, Object> configMap; public HoloDataLoadEvent(Hologram hologram, String saveKey, Map<String, Object> configMap) { super(hologram); this.saveKey = saveKey; this.configMap = configMap; } /** * Gets the save key of the saved data * * @return key of the saved data */ public String getSaveKey() { return saveKey; } /** * A map of all saved data for the appropriate key * * @return map of all saved data for the TouchAction */ public Map<String, Object> getConfigMap() { return configMap; } }
1,741
Java
.java
DSH105/HoloAPI
31
16
21
2014-02-21T21:30:11Z
2014-12-24T12:52:54Z
HoloTouchEvent.java
/FileExtraction/Java_unseen/DSH105_HoloAPI/src/main/java/com/dsh105/holoapi/api/events/HoloTouchEvent.java
/* * This file is part of HoloAPI. * * HoloAPI is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * HoloAPI is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with HoloAPI. If not, see <http://www.gnu.org/licenses/>. */ package com.dsh105.holoapi.api.events; import com.dsh105.holoapi.api.Hologram; import com.dsh105.holoapi.api.touch.Action; import com.dsh105.holoapi.api.touch.TouchAction; import org.bukkit.entity.Player; /** * Called when a hologram is touched. The onTouch function in a {@link com.dsh105.holoapi.api.touch.TouchAction} is * called if the event is not cancelled */ public class HoloTouchEvent extends HoloEvent { private final Player who; private final TouchAction touchAction; private final Action clickAction; public HoloTouchEvent(Hologram hologram, Player who, TouchAction touchAction, Action clickAction) { super(hologram); this.who = who; this.touchAction = touchAction; this.clickAction = clickAction; } /** * Gets the player that touched the hologram * * @return player that touched the hologram */ public Player getPlayer() { return who; } /** * Gets the TouchAction instance representing the event * * @return TouchAction representing the event */ public TouchAction getTouchAction() { return touchAction; } /** * Gets the action the player performed when touching the hologram * * @return action performed when touching the hologram */ public Action getClickAction() { return clickAction; } }
2,061
Java
.java
DSH105/HoloAPI
31
16
21
2014-02-21T21:30:11Z
2014-12-24T12:52:54Z
HoloCreateEvent.java
/FileExtraction/Java_unseen/DSH105_HoloAPI/src/main/java/com/dsh105/holoapi/api/events/HoloCreateEvent.java
/* * This file is part of HoloAPI. * * HoloAPI is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * HoloAPI is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with HoloAPI. If not, see <http://www.gnu.org/licenses/>. */ package com.dsh105.holoapi.api.events; import com.dsh105.holoapi.api.Hologram; /** * Called before a hologram is created. */ public class HoloCreateEvent extends HoloEvent { public HoloCreateEvent(Hologram hologram) { super(hologram); } }
935
Java
.java
DSH105/HoloAPI
31
16
21
2014-02-21T21:30:11Z
2014-12-24T12:52:54Z
HoloDeleteEvent.java
/FileExtraction/Java_unseen/DSH105_HoloAPI/src/main/java/com/dsh105/holoapi/api/events/HoloDeleteEvent.java
/* * This file is part of HoloAPI. * * HoloAPI is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * HoloAPI is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with HoloAPI. If not, see <http://www.gnu.org/licenses/>. */ package com.dsh105.holoapi.api.events; import com.dsh105.holoapi.api.Hologram; /** * Called before a hologram is deleted. */ public class HoloDeleteEvent extends HoloEvent { public HoloDeleteEvent(Hologram hologram) { super(hologram); } }
936
Java
.java
DSH105/HoloAPI
31
16
21
2014-02-21T21:30:11Z
2014-12-24T12:52:54Z
IndicatorListener.java
/FileExtraction/Java_unseen/DSH105_HoloAPI/src/main/java/com/dsh105/holoapi/listeners/IndicatorListener.java
/* * This file is part of HoloAPI. * * HoloAPI is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * HoloAPI is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with HoloAPI. If not, see <http://www.gnu.org/licenses/>. */ package com.dsh105.holoapi.listeners; import com.dsh105.commodus.RomanNumeral; import com.dsh105.commodus.StringUtil; import com.dsh105.holoapi.HoloAPI; import com.dsh105.holoapi.api.Hologram; import com.dsh105.holoapi.config.Settings; import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.bukkit.Location; import org.bukkit.Material; import org.bukkit.entity.Entity; import org.bukkit.entity.EntityType; import org.bukkit.entity.LivingEntity; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.Listener; import org.bukkit.event.entity.EntityDamageEvent; import org.bukkit.event.entity.EntityRegainHealthEvent; import org.bukkit.event.entity.PotionSplashEvent; import org.bukkit.event.player.AsyncPlayerChatEvent; import org.bukkit.event.player.PlayerExpChangeEvent; import org.bukkit.event.player.PlayerItemConsumeEvent; import org.bukkit.potion.Potion; import org.bukkit.potion.PotionEffect; import org.bukkit.scheduler.BukkitRunnable; import org.bukkit.util.Vector; import java.text.DecimalFormat; import java.util.*; public class IndicatorListener implements Listener { private static final char HEART_CHARACTER = '\u2764'; private static final DecimalFormat DAMAGE_FORMAT = new DecimalFormat("#.0"); private static final HashMap<String, ArrayList<String>> CHAT_BUBBLES = new HashMap<>(); private static final List<EntityDamageEvent.DamageCause> SUPPORTED_DAMAGE_TYPES = Arrays.asList(EntityDamageEvent.DamageCause.DROWNING, EntityDamageEvent.DamageCause.LAVA, EntityDamageEvent.DamageCause.MAGIC, EntityDamageEvent.DamageCause.POISON, EntityDamageEvent.DamageCause.THORNS, EntityDamageEvent.DamageCause.WITHER); @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) public void onDamage(EntityDamageEvent event) { // Check if damage indicators are enabled if (!Settings.INDICATOR_ENABLE.getValue("damage")) { return; } // Don't show damage indicators for void damage if (event.getCause() == EntityDamageEvent.DamageCause.VOID) { return; } // Make sure that indicators are enabled for this entity type if (event.getEntity().getType() == EntityType.PLAYER) { if (!Settings.INDICATOR_SHOW_FOR_PLAYERS.getValue("damage")) { return; } } else if (event.getEntity() instanceof LivingEntity) { if (!Settings.INDICATOR_SHOW_FOR_MOBS.getValue("damage")) { return; } } else { return; // We only show indicators for players and mobs. } final LivingEntity entity = (LivingEntity) event.getEntity(); if (entity.getNoDamageTicks() > entity.getMaximumNoDamageTicks() / 2.0F) { return; } String damagePrefix = Settings.INDICATOR_FORMAT.getValue("damage", "default"); // Get our DamageCause-specific damagePrefix, if any if (SUPPORTED_DAMAGE_TYPES.contains(event.getCause())) { String type = event.getCause().toString().toLowerCase(); if (event.getCause() == EntityDamageEvent.DamageCause.LAVA) { type = "fire"; } damagePrefix = Settings.INDICATOR_FORMAT.getValue("damage", type); if (!Settings.INDICATOR_ENABLE_TYPE.getValue("damage", type)) { return; // This type of indicator is disabled } } // Build the message prefix and suffix (i.e. the portions without the damage) final String indicatorPrefix = damagePrefix + "-"; final String indicatorSuffix = " " + HEART_CHARACTER; final double healthBefore = entity.getHealth(); Bukkit.getScheduler().runTask(HoloAPI.getCore(), new Runnable() { @Override public void run() { double damageTaken = healthBefore - entity.getHealth(); if (damageTaken > 0) { // Round to the nearest .5 damageTaken = Math.round(damageTaken * 2.0D) / 2.0D; String text = indicatorPrefix + DAMAGE_FORMAT.format(damageTaken) + indicatorSuffix; Location loc = entity.getLocation(); loc.setY(loc.getY() + Settings.INDICATOR_Y_OFFSET.getValue("damage")); HoloAPI.getManager().createSimpleHologram(loc, Settings.INDICATOR_TIME_VISIBLE.getValue("damage"), true, text); } } }); } @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) public void onExpGain(PlayerExpChangeEvent event) { if (Settings.INDICATOR_ENABLE.getValue("exp")) { Location l = event.getPlayer().getLocation().clone(); l.setY(l.getY() + Settings.INDICATOR_Y_OFFSET.getValue("exp")); HoloAPI.getManager().createSimpleHologram(l, Settings.INDICATOR_TIME_VISIBLE.getValue("exp"), true, Settings.INDICATOR_FORMAT.getValue("exp", "default") + "+" + event.getAmount() + " exp"); } } @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) public void onEntityRegainHealth(EntityRegainHealthEvent event) { if (Settings.INDICATOR_ENABLE.getValue("gainHealth")) { if ((event.getEntity() instanceof Player && Settings.INDICATOR_SHOW_FOR_PLAYERS.getValue("gainHealth")) || Settings.INDICATOR_SHOW_FOR_MOBS.getValue("gainHealth")) { Location l = event.getEntity().getLocation().clone(); l.setY(l.getY() + Settings.INDICATOR_Y_OFFSET.getValue("gainHealth")); HoloAPI.getManager().createSimpleHologram(l, Settings.INDICATOR_TIME_VISIBLE.getValue("gainHealth"), true, Settings.INDICATOR_FORMAT.getValue("gainHealth", "default") + "+" + event.getAmount() + " " + HEART_CHARACTER); } } } @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) public void onConsumePotion(PlayerItemConsumeEvent event) { if (Settings.INDICATOR_ENABLE.getValue("potion")) { if (event.getItem().getType() == Material.POTION) { Potion potion = Potion.fromItemStack(event.getItem()); if (potion != null) { this.showPotionHologram(event.getPlayer(), potion.getEffects()); } } else if (event.getItem().getType() == Material.GOLDEN_APPLE) { String msg = Settings.INDICATOR_FORMAT.getValue("potion", "goldenapple"); if (event.getItem().getDurability() == 1) { msg = Settings.INDICATOR_FORMAT.getValue("potion", "godapple"); } Location l = event.getPlayer().getLocation().clone(); l.setY(l.getY() + Settings.INDICATOR_Y_OFFSET.getValue("potion")); HoloAPI.getManager().createSimpleHologram(l, Settings.INDICATOR_TIME_VISIBLE.getValue("potion"), true, msg.replace("%effect%", "Golden Apple")); } } } @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) public void onSplashPotion(PotionSplashEvent event) { if (Settings.INDICATOR_ENABLE.getValue("potion")) { for (Entity e : event.getAffectedEntities()) { if ((event.getEntity() instanceof Player && Settings.INDICATOR_SHOW_FOR_PLAYERS.getValue("potion")) || Settings.INDICATOR_SHOW_FOR_MOBS.getValue("potion")) { this.showPotionHologram(e, event.getPotion().getEffects()); } } } } private void showPotionHologram(Entity e, Collection<PotionEffect> effects) { for (PotionEffect effect : effects) { int amp = (effect.getAmplifier() < 1 ? 1 : effect.getAmplifier()) + 1; String content = Settings.INDICATOR_FORMAT.getValue("potion", effect.getType().getName().toLowerCase()); content = content.replace("%effect%", StringUtil.capitalise(effect.getType().getName().replace("_", " "))).replace("%amp%", "" + new RomanNumeral(amp)); Location l = e.getLocation().clone(); l.setY(l.getY() + Settings.INDICATOR_Y_OFFSET.getValue("potion")); HoloAPI.getManager().createSimpleHologram(l, Settings.INDICATOR_TIME_VISIBLE.getValue("potion"), true, content); } } @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) public void onAsyncPlayerChat(AsyncPlayerChatEvent event) { if (!event.isCancelled()) { final Player p = event.getPlayer(); if (!HoloAPI.getVanishProvider().isVanished(p)) { final String msg = event.getMessage(); if (event.isAsynchronous()) { HoloAPI.getCore().getServer().getScheduler().scheduleSyncDelayedTask(HoloAPI.getCore(), new BukkitRunnable() { @Override public void run() { showChatHologram(p, msg); } }); } else { this.showChatHologram(p, msg); } } } } private void showChatHologram(final Player p, String msg) { //YAMLConfig config = HoloAPI.getConfig(HoloAPI.ConfigType.MAIN); if (Settings.CHATBUBBLES_SHOW.getValue()) { Location loc = p.getEyeLocation().clone(); loc.add(0D, Settings.CHATBUBBLES_DISTANCE_ABOVE.getValue(), 0D); final int duration = Settings.CHATBUBBLES_DISPLAY_DURATION.getValue(); final boolean rise = Settings.CHATBUBBLES_RISE.getValue(); final boolean followPlayer = Settings.CHATBUBBLES_FOLLOW_PLAYER.getValue(); int charsPerLine = Settings.CHATBUBBLES_CHARACTERS_PER_LINE.getValue(); ArrayList<String> lines = new ArrayList<>(); if (Settings.CHATBUBBLES_SHOW_PLAYER_NAME.getValue()) { lines.add(Settings.CHATBUBBLES_NAME_FORMAT.getValue() + p.getName() + ":"); } int index = 0; while (index < msg.length()) { lines.add(ChatColor.WHITE + msg.substring(index, Math.min(index + charsPerLine, msg.length()))); index += charsPerLine; } if (CHAT_BUBBLES.containsKey(p.getName())) { ArrayList<String> hologramIds = CHAT_BUBBLES.get(p.getName()); if (!hologramIds.isEmpty()) { Hologram last = null; // Iterate from bottom to top for (int j = hologramIds.size() - 1; j >= 0; j--) { Hologram h = HoloAPI.getManager().getHologram(hologramIds.get(j)); if (h != null) { double totalSize = (h.getLines().length * Settings.VERTICAL_LINE_SPACING.getValue()); double minY = h.getDefaultY() - totalSize; if (last != null && minY < last.getDefaultY()) { h.move(new Vector(h.getDefaultX(), h.getDefaultY() + (last.getLines().length * Settings.VERTICAL_LINE_SPACING.getValue()), h.getDefaultZ())); } else { if (minY < loc.getY()) { h.move(new Vector(h.getDefaultX(), h.getDefaultY() + totalSize, h.getDefaultZ())); last = h; } } } } } } final Hologram hologram = HoloAPI.getManager().createSimpleHologram(loc, duration, !followPlayer, lines); ArrayList<String> list; if (CHAT_BUBBLES.containsKey(p.getName())) { list = CHAT_BUBBLES.get(p.getName()); } else { list = new ArrayList<>(); } list.add(hologram.getSaveId()); CHAT_BUBBLES.put(p.getName(), list); new BukkitRunnable() { @Override public void run() { ArrayList<String> list = CHAT_BUBBLES.get(p.getName()); if (list != null) { list.remove(hologram.getSaveId()); } CHAT_BUBBLES.put(p.getName(), list); } }.runTaskLater(HoloAPI.getCore(), duration * 20); if (followPlayer) { class FollowPlayer extends BukkitRunnable { private int i; private double riseDiff = 0.0D; @Override public void run() { if (p == null || ++i >= ((duration * 20) - 1)) { this.cancel(); } Location l = p.getEyeLocation(); if (rise) { riseDiff += 0.02D; } hologram.move(new Vector(l.getX(), l.getY() + 0.5D + riseDiff, l.getZ())); } } new FollowPlayer().runTaskTimer(HoloAPI.getCore(), 10L, 10L); } } } }
14,014
Java
.java
DSH105/HoloAPI
31
16
21
2014-02-21T21:30:11Z
2014-12-24T12:52:54Z
WorldListener.java
/FileExtraction/Java_unseen/DSH105_HoloAPI/src/main/java/com/dsh105/holoapi/listeners/WorldListener.java
/* * This file is part of HoloAPI. * * HoloAPI is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * HoloAPI is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with HoloAPI. If not, see <http://www.gnu.org/licenses/>. */ package com.dsh105.holoapi.listeners; import com.dsh105.holoapi.HoloAPI; import com.dsh105.holoapi.HoloAPICore; import com.dsh105.holoapi.api.SimpleHoloManager; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.Listener; import org.bukkit.event.world.WorldLoadEvent; import java.util.HashMap; import java.util.Map; import java.util.logging.Level; public class WorldListener implements Listener { private static HashMap<String, String> UNLOADED_HOLOGRAMS = new HashMap<String, String>(); @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) public void onWorldLoad(WorldLoadEvent event) { for (Map.Entry<String, String> entry : new HashMap<>(UNLOADED_HOLOGRAMS).entrySet()) { if (entry.getValue().equals(event.getWorld().getName())) { HoloAPI.LOG.info("Loading hologram " + entry.getKey() + " into world " + entry.getValue() + "."); if (((SimpleHoloManager) HoloAPI.getManager()).loadFromFile(entry.getKey()) != null) { UNLOADED_HOLOGRAMS.remove(entry.getKey()); } } } } public static void store(String hologramId, String worldName) { UNLOADED_HOLOGRAMS.put(hologramId, worldName); } }
1,975
Java
.java
DSH105/HoloAPI
31
16
21
2014-02-21T21:30:11Z
2014-12-24T12:52:54Z
HoloListener.java
/FileExtraction/Java_unseen/DSH105_HoloAPI/src/main/java/com/dsh105/holoapi/listeners/HoloListener.java
/* * This file is part of HoloAPI. * * HoloAPI is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * HoloAPI is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with HoloAPI. If not, see <http://www.gnu.org/licenses/>. */ package com.dsh105.holoapi.listeners; import com.dsh105.holoapi.HoloAPI; import com.dsh105.holoapi.api.AnimatedHologram; import com.dsh105.holoapi.api.Hologram; import com.dsh105.holoapi.api.events.HoloLineUpdateEvent; import com.dsh105.holoapi.config.Settings; import org.bukkit.entity.Entity; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.Listener; import org.bukkit.event.player.PlayerChangedWorldEvent; import org.bukkit.event.player.PlayerJoinEvent; import org.bukkit.event.player.PlayerQuitEvent; import org.bukkit.event.player.PlayerTeleportEvent; import org.bukkit.event.world.ChunkLoadEvent; import org.bukkit.event.world.ChunkUnloadEvent; import org.bukkit.scheduler.BukkitRunnable; public class HoloListener implements Listener { @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) public void onHoloLineUpdate(HoloLineUpdateEvent event) { if (HoloAPI.getHoloUpdater().getTrackedHolograms().contains(event.getHologram())) { if (!HoloAPI.getHoloUpdater().shouldTrack(event.getNewLineContent())) { HoloAPI.getHoloUpdater().track(event.getHologram(), false); } } else { HoloAPI.getHoloUpdater().track(event.getHologram()); } } @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) public void onPlayerTeleport(PlayerTeleportEvent event) { Player player = event.getPlayer(); for (Hologram h : HoloAPI.getManager().getAllHolograms().keySet()) { if (event.getTo().getWorld().getName().equals(h.getWorldName())) { if (h.getLocationFor(player) != null && h.getVisibility().isVisibleTo(player, h.getSaveId())) { h.show(player, true); } } } } @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) public void onPlayerQuit(PlayerQuitEvent event) { Player player = event.getPlayer(); for (Hologram h : HoloAPI.getManager().getAllHolograms().keySet()) { if (h.getLocationFor(player) != null) { h.clear(player); } } } @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) public void onPlayerJoin(PlayerJoinEvent event) { final Player player = event.getPlayer(); for (final Hologram h : HoloAPI.getManager().getAllHolograms().keySet()) { if (player.getLocation().getWorld().getName().equals(h.getWorldName()) && h.getVisibility().isVisibleTo(player, h.getSaveId())) { new BukkitRunnable() { @Override public void run() { if (h instanceof AnimatedHologram && !((AnimatedHologram) h).isAnimating()) { ((AnimatedHologram) h).animate(); } h.show(player, true); } }.runTaskLater(HoloAPI.getCore(), 40L); } } } @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) public void onWorldChange(PlayerChangedWorldEvent event) { final Player player = event.getPlayer(); for (final Hologram h : HoloAPI.getManager().getAllHolograms().keySet()) { if (player.getLocation().getWorld().getName().equals(h.getWorldName()) && h.getVisibility().isVisibleTo(player, h.getSaveId())) { if (h instanceof AnimatedHologram && !((AnimatedHologram) h).isAnimating()) { ((AnimatedHologram) h).animate(); } h.show(player, true); } else if (event.getFrom().getName().equals(h.getWorldName()) && h.getLocationFor(player) != null) { new BukkitRunnable() { @Override public void run() { h.clear(player); } }.runTaskLater(HoloAPI.getCore(), 20L); } } } @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) public void onChunkLoad(ChunkLoadEvent event) { for (Hologram h : HoloAPI.getManager().getAllHolograms().keySet()) { if (h.getDefaultLocation().getChunk().equals(event.getChunk())) { for (Entity e : h.getDefaultLocation().getWorld().getEntities()) { if (e instanceof Player) { if (h.getVisibility().isVisibleTo((Player) e, h.getSaveId())) { h.show((Player) e, true); } } } } } } }
5,416
Java
.java
DSH105/HoloAPI
31
16
21
2014-02-21T21:30:11Z
2014-12-24T12:52:54Z
HoloDataLoadListener.java
/FileExtraction/Java_unseen/DSH105_HoloAPI/src/main/java/com/dsh105/holoapi/listeners/HoloDataLoadListener.java
/* * This file is part of HoloAPI. * * HoloAPI is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * HoloAPI is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with HoloAPI. If not, see <http://www.gnu.org/licenses/>. */ package com.dsh105.holoapi.listeners; import com.dsh105.holoapi.HoloAPI; import com.dsh105.holoapi.HoloAPICore; import com.dsh105.holoapi.api.events.HoloTouchActionLoadEvent; import com.dsh105.holoapi.api.events.HoloVisibilityLoadEvent; import com.dsh105.holoapi.api.touch.CommandTouchAction; import com.dsh105.holoapi.api.visibility.VisibilityPermission; import org.bukkit.event.EventHandler; import org.bukkit.event.Listener; import java.util.logging.Level; public class HoloDataLoadListener implements Listener { @EventHandler public void onTouchActionLoad(HoloTouchActionLoadEvent event) { // Make sure it's what we're looking for if (event.getSaveKey().startsWith("command_")) { // Just in-case (for some reason) the command data didn't actually save if (event.getConfigMap().get("command") != null) { try { Object asConsole = event.getConfigMap().get("asConsole"); event.getHologram().addTouchAction(new CommandTouchAction((String) event.getConfigMap().get("command"), (asConsole != null && asConsole instanceof Boolean) ? (Boolean) asConsole : false)); } catch (ClassCastException e) { HoloAPI.LOG.severe("Failed to load command touch action data for hologram (" + event.getHologram().getSaveId() + "). Maybe the save data was edited?"); } } } } @EventHandler public void onVisibilityLoad(HoloVisibilityLoadEvent event) { if (event.getSaveKey().equalsIgnoreCase("perm")) { Object o = event.getConfigMap().get("permission"); if (o != null) { String perm = (String) o; event.getHologram().setVisibility(new VisibilityPermission(perm.equalsIgnoreCase("unidentified") ? null : perm)); } } } }
2,551
Java
.java
DSH105/HoloAPI
31
16
21
2014-02-21T21:30:11Z
2014-12-24T12:52:54Z
LogicUtil.java
/FileExtraction/Java_unseen/DSH105_HoloAPI/src/main/java/com/dsh105/holoapi/util/LogicUtil.java
/* * This file is part of HoloAPI. * * HoloAPI is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * HoloAPI is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with HoloAPI. If not, see <http://www.gnu.org/licenses/>. */ package com.dsh105.holoapi.util; import com.dsh105.holoapi.ModuleLogger; import com.google.common.collect.BiMap; import java.lang.reflect.Array; import java.util.Collection; import java.util.Map; public class LogicUtil { public static String toString(final Object object) { return object == null ? "" : object.toString(); } public static boolean nullOrEmpty(Object[] array) { return array == null || array.length != 0; } public static boolean nullOrEmpty(Collection<?> collection) { return collection == null || collection.isEmpty(); } public static <T> T notNull(T object, String messageWhenNull, ModuleLogger logger) { if (object == null) { logger.warning(messageWhenNull); return null; } else { return object; } } public static <T> T[] createArray(Class<T> type, int length) { return (T[]) Array.newInstance(type, length); } public static <T> T[] appendArray(T[] array, T... values) { if (nullOrEmpty(array)) { return values; } if (nullOrEmpty(values)) { return array; } T[] rval = createArray((Class<T>) array.getClass().getComponentType(), array.length + values.length); System.arraycopy(array, 0, rval, 0, array.length); System.arraycopy(values, 0, rval, array.length, values.length); return rval; } public static <K, V> K getKeyAtValue(Map<K, V> map, V value) { if (map instanceof BiMap) { return ((BiMap<K, V>) map).inverse().get(value); } for (Map.Entry<K, V> entry : map.entrySet()) { if (entry.getValue().equals(value)) { return entry.getKey(); } } return null; } }
2,490
Java
.java
DSH105/HoloAPI
31
16
21
2014-02-21T21:30:11Z
2014-12-24T12:52:54Z
Debugger.java
/FileExtraction/Java_unseen/DSH105_HoloAPI/src/main/java/com/dsh105/holoapi/util/Debugger.java
/* * This file is part of HoloAPI. * * HoloAPI is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * HoloAPI is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with HoloAPI. If not, see <http://www.gnu.org/licenses/>. */ package com.dsh105.holoapi.util; import org.bukkit.ChatColor; import org.bukkit.command.CommandSender; public class Debugger { private static ChatColor LOG_COLOR = ChatColor.AQUA; public static Debugger instance; private int level; private CommandSender output; private transient boolean enabled; public Debugger() { instance = this; level = 0; } public static synchronized Debugger getInstance() { if (instance == null) new Debugger(); return instance; } public void shutdown() { instance = null; } public boolean isEnabled() { return this.enabled; } public synchronized void setEnabled(boolean state) { this.enabled = state; } public void setOutput(final CommandSender commandSender) { this.output = commandSender; } public CommandSender getOutput() { return this.output; } public int getLevel() { return this.level; } public void setLevel(int level) { this.level = level; } public void log(String message, Object... params) { this.log(1, message, params); } public void log(int level, String message, Object... params) { if (level <= this.level && this.output != null && this.enabled) { this.output.sendMessage(LOG_COLOR + format(message, params)); } } private static String format(String message, Object... params) { message = String.valueOf(message); StringBuilder builder = new StringBuilder(message.length() + (16 * params.length)); int messageStart = 0; int index = 0; if (params.length == 0) { return builder.append(message).toString(); } while (index < params.length) { int place = message.indexOf("%s"); if(place == -1) { break; } builder.append(message.substring(messageStart, place)); builder.append(params[index++]); messageStart = place + 2; } if(index < params.length) { builder.append(" {"); while(index < params.length) { builder.append(", "); builder.append(params[index++]); } builder.append("}"); } return builder.toString(); } }
3,182
Java
.java
DSH105/HoloAPI
31
16
21
2014-02-21T21:30:11Z
2014-12-24T12:52:54Z
TagIdGenerator.java
/FileExtraction/Java_unseen/DSH105_HoloAPI/src/main/java/com/dsh105/holoapi/util/TagIdGenerator.java
/* * This file is part of HoloAPI. * * HoloAPI is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * HoloAPI is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with HoloAPI. If not, see <http://www.gnu.org/licenses/>. */ package com.dsh105.holoapi.util; import com.dsh105.holoapi.HoloAPI; import com.dsh105.holoapi.api.HologramImpl; public class TagIdGenerator { // yay, negative IDs private volatile static int SHARED_HOLO_ID = 0; public static int next(int counter) { return SHARED_HOLO_ID -= counter * HologramImpl.TAG_ENTITY_MULTIPLIER; } }
1,026
Java
.java
DSH105/HoloAPI
31
16
21
2014-02-21T21:30:11Z
2014-12-24T12:52:54Z
SaveIdGenerator.java
/FileExtraction/Java_unseen/DSH105_HoloAPI/src/main/java/com/dsh105/holoapi/util/SaveIdGenerator.java
/* * This file is part of HoloAPI. * * HoloAPI is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * HoloAPI is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with HoloAPI. If not, see <http://www.gnu.org/licenses/>. */ package com.dsh105.holoapi.util; import com.dsh105.holoapi.HoloAPI; import com.dsh105.holoapi.config.ConfigType; public class SaveIdGenerator { private static int nextId = 0; public static int nextId() { int i = ++nextId; if (HoloAPI.getConfig(ConfigType.DATA).getConfigurationSection("holograms." + i) != null) { return nextId(); } return i; } }
1,081
Java
.java
DSH105/HoloAPI
31
16
21
2014-02-21T21:30:11Z
2014-12-24T12:52:54Z
MiscUtil.java
/FileExtraction/Java_unseen/DSH105_HoloAPI/src/main/java/com/dsh105/holoapi/util/MiscUtil.java
/* * This file is part of HoloAPI. * * HoloAPI is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * HoloAPI is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with HoloAPI. If not, see <http://www.gnu.org/licenses/>. */ package com.dsh105.holoapi.util; import com.dsh105.command.CommandEvent; import com.dsh105.commodus.GeneralUtil; import com.dsh105.holoapi.config.Lang; import net.minecraft.util.io.netty.buffer.ByteBuf; import org.bukkit.Bukkit; import org.bukkit.Location; import org.bukkit.World; import java.io.BufferedReader; import java.io.InputStreamReader; import java.net.URL; import java.net.URLConnection; import java.nio.charset.Charset; import java.util.ArrayList; public class MiscUtil { public static String[] readWebsiteContentsSoWeCanUseTheText(String link) { try { URL url = new URL(link); URLConnection con = url.openConnection(); BufferedReader reader = new BufferedReader(new InputStreamReader(con.getInputStream())); ArrayList<String> list = new ArrayList<String>(); String line; while ((line = reader.readLine()) != null) { list.add(line); } return list.toArray(new String[list.size()]); } catch (Exception e) { e.printStackTrace(); } return null; } public static String readPrefixedString(ByteBuf buf) { int length = buf.readShort(); byte[] bytes = new byte[length]; buf.readBytes(bytes); return new String(bytes, Charset.forName("UTF8")); } public static void writePrefixedString(ByteBuf buf, String str) { byte[] bytes = str.getBytes(Charset.forName("UTF8")); buf.writeShort(bytes.length); buf.writeBytes(bytes); } public static Location getLocation(CommandEvent event) { Location location; try { World world = Bukkit.getWorld(event.variable("world")); if (world == null) { throw new IllegalArgumentException(); } location = new Location(world, GeneralUtil.toInteger(event.variable("x")), GeneralUtil.toInteger(event.variable("y")), GeneralUtil.toInteger(event.variable("z"))); } catch (IllegalArgumentException e) { event.respond(Lang.NOT_LOCATION.getValue()); return null; } return location; } }
2,861
Java
.java
DSH105/HoloAPI
31
16
21
2014-02-21T21:30:11Z
2014-12-24T12:52:54Z
UnicodeFormatter.java
/FileExtraction/Java_unseen/DSH105_HoloAPI/src/main/java/com/dsh105/holoapi/util/UnicodeFormatter.java
/* * This file is part of HoloAPI. * * HoloAPI is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * HoloAPI is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with HoloAPI. If not, see <http://www.gnu.org/licenses/>. */ package com.dsh105.holoapi.util; import com.dsh105.commodus.config.YAMLConfig; import com.dsh105.holoapi.HoloAPI; import com.dsh105.holoapi.config.ConfigType; import org.apache.commons.lang.StringEscapeUtils; import org.bukkit.configuration.ConfigurationSection; public class UnicodeFormatter { public static String replaceAll(String s) { YAMLConfig config = HoloAPI.getConfig(ConfigType.MAIN); ConfigurationSection cs = config.getConfigurationSection("specialCharacters"); if (cs != null) { for (String key : cs.getKeys(false)) { if (s.contains(key)) { s = s.replace(key, StringEscapeUtils.unescapeJava("\\u" + config.getString("specialCharacters." + key))); } } } return s; } }
1,481
Java
.java
DSH105/HoloAPI
31
16
21
2014-02-21T21:30:11Z
2014-12-24T12:52:54Z
ImageUtil.java
/FileExtraction/Java_unseen/DSH105_HoloAPI/src/main/java/com/dsh105/holoapi/util/ImageUtil.java
package com.dsh105.holoapi.util; /** * * @author Frostalf */ public class ImageUtil { public int[] resizePixels(int[] pixels,int w1,int h1,int w2,int h2) { int[] temp = new int[w2*h2] ; double x_ratio = w1/(double)w2 ; double y_ratio = h1/(double)h2 ; double px, py ; for (int i=0;i<h2;i++) { for (int j=0;j<w2;j++) { px = Math.floor(j*x_ratio) ; py = Math.floor(i*y_ratio) ; temp[(i*w2)+j] = pixels[(int)((py*w1)+px)] ; } } return temp ; } }
538
Java
.java
DSH105/HoloAPI
31
16
21
2014-02-21T21:30:11Z
2014-12-24T12:52:54Z
InjectionManager.java
/FileExtraction/Java_unseen/DSH105_HoloAPI/src/main/java/com/dsh105/holoapi/protocol/InjectionManager.java
/* * This file is part of HoloAPI. * * HoloAPI is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * HoloAPI is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with HoloAPI. If not, see <http://www.gnu.org/licenses/>. */ package com.dsh105.holoapi.protocol; import com.captainbern.minecraft.wrapper.EnumWrappers; import com.captainbern.minecraft.wrapper.WrappedPacket; import com.dsh105.commodus.ServerUtil; import com.dsh105.holoapi.HoloAPI; import com.dsh105.holoapi.api.Hologram; import com.dsh105.holoapi.api.events.HoloTouchEvent; import com.dsh105.holoapi.api.touch.Action; import com.dsh105.holoapi.api.touch.TouchAction; import com.dsh105.holoapi.protocol.netty.PlayerInjector; import com.google.common.collect.MapMaker; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.Listener; import org.bukkit.event.player.PlayerJoinEvent; import org.bukkit.event.player.PlayerQuitEvent; import org.bukkit.plugin.Plugin; import java.util.concurrent.ConcurrentMap; public class InjectionManager { protected Plugin plugin; // We're using weak-keys here so don't worry about player instances not being GC'ed. protected static ConcurrentMap<Player, Injector> injections = new MapMaker().weakKeys().makeMap(); private boolean isClosed = false; public InjectionManager(Plugin plugin) { if (plugin == null) throw new IllegalArgumentException("Plugin cannot be NULL!"); this.plugin = plugin; this.isClosed = false; for (Player player : ServerUtil.getOnlinePlayers()) { inject(player); } plugin.getServer().getPluginManager().registerEvents(new Listener() { @EventHandler(priority = EventPriority.MONITOR) public void onJoin(PlayerJoinEvent event) { inject(event.getPlayer()); } }, plugin); plugin.getServer().getPluginManager().registerEvents(new Listener() { @EventHandler(priority = EventPriority.MONITOR) public void onQuit(PlayerQuitEvent event) { unInject(event.getPlayer()); } }, plugin); } public Plugin getPlugin() { return this.plugin; } public Injector getInjectorFor(Player player) { Injector injector = injections.get(player); if (injector == null) { injector = inject(player); if (injector == null) throw new RuntimeException("Failed to inject player: " + player); } return injector; } public Injector inject(Player player) { if (this.isClosed()) return null; Injector injector; if (injections.containsKey(player)) { injector = injections.get(player); injector.setPlayer(player); } else { injector = new PlayerInjector(player, this); injector.inject(); injections.put(player, injector); } return injector; } public void unInject(Player player) { if (getInjectorFor(player) == null) return; Injector injector = getInjectorFor(player); if (injector.isInjected()) injector.close(); injections.remove(player); // To make sure there are no left-overs } public void close() { if (isClosed()) return; for (Player player : injections.keySet()) { unInject(player); } this.isClosed = true; } public boolean isClosed() { return this.isClosed; } public void handlePacket(WrappedPacket packet, PlayerInjector injector) { EnumWrappers.EntityUseAction useAction = packet.getEntityUseActions().read(0); for (Hologram hologram : HoloAPI.getManager().getAllHolograms().keySet()) { for (int entityId : hologram.getAllEntityIds()) { if (entityId == packet.getIntegers().read(0)) { for (TouchAction touchAction : hologram.getAllTouchActions()) { Action action = useAction == EnumWrappers.EntityUseAction.INTERACT ? Action.RIGHT_CLICK : Action.LEFT_CLICK; HoloTouchEvent touchEvent = new HoloTouchEvent(hologram, injector.getPlayer(), touchAction, action); HoloAPI.getCore().getServer().getPluginManager().callEvent(touchEvent); if (!touchEvent.isCancelled()) { touchAction.onTouch(injector.getPlayer(), action); } } } } } } }
5,148
Java
.java
DSH105/HoloAPI
31
16
21
2014-02-21T21:30:11Z
2014-12-24T12:52:54Z
Injector.java
/FileExtraction/Java_unseen/DSH105_HoloAPI/src/main/java/com/dsh105/holoapi/protocol/Injector.java
/* * This file is part of HoloAPI. * * HoloAPI is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * HoloAPI is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with HoloAPI. If not, see <http://www.gnu.org/licenses/>. */ package com.dsh105.holoapi.protocol; import org.bukkit.entity.Player; public interface Injector { public void inject(); public void close(); public boolean isInjected(); public boolean isClosed(); public void sendPacket(Object packet); public void receivePacket(Object packet); public Player getPlayer(); public void setPlayer(Player player); }
1,062
Java
.java
DSH105/HoloAPI
31
16
21
2014-02-21T21:30:11Z
2014-12-24T12:52:54Z
PlayerInjector.java
/FileExtraction/Java_unseen/DSH105_HoloAPI/src/main/java/com/dsh105/holoapi/protocol/netty/PlayerInjector.java
/* * This file is part of HoloAPI. * * HoloAPI is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * HoloAPI is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with HoloAPI. If not, see <http://www.gnu.org/licenses/>. */ package com.dsh105.holoapi.protocol.netty; import com.captainbern.minecraft.conversion.BukkitUnwrapper; import com.captainbern.minecraft.protocol.PacketType; import com.captainbern.minecraft.reflection.MinecraftFields; import com.captainbern.minecraft.reflection.MinecraftReflection; import com.captainbern.minecraft.wrapper.WrappedPacket; import com.captainbern.reflection.Reflection; import com.captainbern.reflection.accessor.FieldAccessor; import com.dsh105.holoapi.HoloAPI; import com.dsh105.holoapi.protocol.InjectionManager; import com.dsh105.holoapi.protocol.Injector; import com.google.common.base.Preconditions; import net.minecraft.util.io.netty.channel.Channel; import net.minecraft.util.io.netty.channel.ChannelDuplexHandler; import net.minecraft.util.io.netty.channel.ChannelHandlerContext; import org.bukkit.Bukkit; import org.bukkit.entity.Player; import java.util.concurrent.Callable; import java.util.NoSuchElementException; public class PlayerInjector extends ChannelDuplexHandler implements Injector { // "Cache" the field to speed up the whole process. private static FieldAccessor<Channel> CHANNEL_FIELD; protected Player player; protected volatile InjectionManager injectionManager; protected Object nmsHandle; protected Object playerConnection; protected Object networkManager; protected Channel channel; private boolean isInjected = false; private boolean isClosed = false; public PlayerInjector(Player player, InjectionManager injectionManager) { Preconditions.checkNotNull(player); Preconditions.checkNotNull(injectionManager); this.injectionManager = injectionManager; this.initialize(player); } @Override public void inject() { synchronized (this.networkManager) { if (isInjected()) throw new IllegalStateException("Cannot inject twice!"); if (this.channel == null) throw new IllegalStateException("Channel is NULL! Perhaps we failed to find it?"); try { this.channel.pipeline().addBefore("packet_handler", "holoapi_packet_handler", this); } catch (NoSuchElementException e){ //ignore exception, we know about it, so remove spam ;) } this.isInjected = true; } } @Override public void close() { if (!this.isClosed) { this.isClosed = true; if (this.isInjected) { // Avoid dead-locks, thanks Comphenix getChannel().eventLoop().submit(new Callable<Object>() { @Override public Object call() throws Exception { getChannel().pipeline().remove(PlayerInjector.this); return null; } }); this.isInjected = false; } } } @Override public boolean isInjected() { return this.isInjected; } @Override public boolean isClosed() { return this.isClosed; } @Override public void sendPacket(Object packet) { if (this.isClosed()) throw new IllegalStateException("The PlayerInjector is closed!"); this.getChannel().pipeline().writeAndFlush(packet); } @Override public void receivePacket(Object packet) { if (this.isClosed()) throw new IllegalStateException("The PlayerInjector is closed!"); this.getChannel().pipeline().context("encoder").fireChannelRead(packet); } @Override public Player getPlayer() { return this.player; } @Override public void setPlayer(Player player) { this.initialize(player); } private void initialize(Player player) { if (player == null) throw new IllegalArgumentException("Player can't be NULL!"); // This should never happen, but in case it does... try { this.player = player; this.nmsHandle = BukkitUnwrapper.getInstance().unwrap(player); Reflection reflection = new Reflection(); this.playerConnection = MinecraftFields.getPlayerConnection(player); this.networkManager = MinecraftFields.getNetworkManager(player); if (CHANNEL_FIELD == null) { try { CHANNEL_FIELD = reflection.reflect(MinecraftReflection.getNetworkManagerClass()).getSafeFieldByType(Channel.class).getAccessor(); } catch (Exception e) { // Oops throw new RuntimeException("Failed to get the Channel accessor!", e); } } this.channel = CHANNEL_FIELD.get(this.networkManager); } catch (Exception e) { // Oops throw new RuntimeException("Failed to initialize the PlayerInjector for: " + player, e); } } private Channel getChannel() { if (this.channel == null) throw new IllegalStateException("The Channel is NULL!"); return this.channel; } @Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { // Handle the packet final WrappedPacket packet = new WrappedPacket(msg); if (packet.getPacketType().equals(PacketType.Play.Client.USE_ENTITY)) Bukkit.getScheduler().scheduleSyncDelayedTask(HoloAPI.getCore(), new Runnable() { @Override public void run() { PlayerInjector.this.injectionManager.handlePacket(packet, PlayerInjector.this); } }); super.channelRead(ctx, msg); } }
6,423
Java
.java
DSH105/HoloAPI
31
16
21
2014-02-21T21:30:11Z
2014-12-24T12:52:54Z
BungeeProvider.java
/FileExtraction/Java_unseen/DSH105_HoloAPI/src/main/java/com/dsh105/holoapi/hook/BungeeProvider.java
package com.dsh105.holoapi.hook; import com.dsh105.commodus.ServerUtil; import com.dsh105.holoapi.config.Settings; import com.dsh105.holoapi.util.MiscUtil; import net.minecraft.util.io.netty.buffer.ByteBuf; import net.minecraft.util.io.netty.buffer.Unpooled; import org.bukkit.entity.Player; import org.bukkit.plugin.Plugin; import org.bukkit.plugin.messaging.PluginMessageListener; import java.util.HashMap; import java.util.Map; public class BungeeProvider implements PluginMessageListener, Runnable { private final Plugin plugin; private final Map<String, Integer> playerCounts = new HashMap<String, Integer>(); private boolean disabled = false; public BungeeProvider(Plugin plugin) { this.plugin = plugin; if (!Settings.USE_BUNGEE.getValue()) { disabled = true; return; // BungeeCord is disabled } // Register BungeeCord channels plugin.getServer().getMessenger().registerIncomingPluginChannel(plugin, "BungeeCord", this); plugin.getServer().getMessenger().registerOutgoingPluginChannel(plugin, "BungeeCord"); // Register our repeating task to get player counts plugin.getServer().getScheduler().runTaskTimer(plugin, this, 100L, 100L); // Run at five-second intervals } @Override public void onPluginMessageReceived(String channel, Player player, byte[] bytes) { ByteBuf buf = Unpooled.wrappedBuffer(bytes); String operation = MiscUtil.readPrefixedString(buf); if (operation.equals("GetServers")) { String[] serverList = MiscUtil.readPrefixedString(buf).split(", "); for (String server : serverList) { requestPlayerCount(server); } } else if (operation.equals("PlayerCount")) { String server = MiscUtil.readPrefixedString(buf); int playerCount = buf.readInt(); playerCounts.put(server, playerCount); } buf.release(); } private void requestPlayerCount(String serverName) { if (ServerUtil.getOnlinePlayers().size() == 0) { return; // No players online; we can't send this request yet. } ByteBuf buf = Unpooled.buffer(); MiscUtil.writePrefixedString(buf, "PlayerCount"); MiscUtil.writePrefixedString(buf, serverName); byte[] bytes = new byte[buf.readableBytes()]; buf.readBytes(bytes); ServerUtil.getOnlinePlayer(0).sendPluginMessage(plugin, "BungeeCord", bytes); buf.release(); } // Request the server list. // Receiving the server list will trigger player count requests @Override public void run() { if (ServerUtil.getOnlinePlayers().size() == 0) { return; } ByteBuf buf = Unpooled.buffer(); MiscUtil.writePrefixedString(buf, "GetServers"); byte[] bytes = new byte[buf.readableBytes()]; buf.readBytes(bytes); ServerUtil.getOnlinePlayer(0).sendPluginMessage(plugin, "BungeeCord", bytes); buf.release(); } public int getPlayerCount(String server) { if (disabled) { return 0; } if (server.equalsIgnoreCase("all")) { // Special case for all servers int total = 0; for (int num : playerCounts.values()) { total += num; } return total; } if (playerCounts.containsKey(server)) { return playerCounts.get(server); } return 0; } }
3,544
Java
.java
DSH105/HoloAPI
31
16
21
2014-02-21T21:30:11Z
2014-12-24T12:52:54Z
VanishProvider.java
/FileExtraction/Java_unseen/DSH105_HoloAPI/src/main/java/com/dsh105/holoapi/hook/VanishProvider.java
/* * This file is part of HoloAPI. * * HoloAPI is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * HoloAPI is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with HoloAPI. If not, see <http://www.gnu.org/licenses/>. */ package com.dsh105.holoapi.hook; import org.bukkit.entity.Player; import org.bukkit.plugin.Plugin; import org.kitteh.vanish.VanishPlugin; public class VanishProvider extends PluginDependencyProvider<VanishPlugin> { public VanishProvider(Plugin myPluginInstance) { super(myPluginInstance, "VanishNoPacket"); } @Override public void onHook() { } @Override public void onUnhook() { } public boolean isVanished(Player player) { return this.isVanished(player.getName()); } public boolean isVanished(String player) { return this.isHooked() && this.getDependency().getManager().isVanished(player); } }
1,350
Java
.java
DSH105/HoloAPI
31
16
21
2014-02-21T21:30:11Z
2014-12-24T12:52:54Z
PluginDependencyProvider.java
/FileExtraction/Java_unseen/DSH105_HoloAPI/src/main/java/com/dsh105/holoapi/hook/PluginDependencyProvider.java
/* * This file is part of HoloAPI. * * HoloAPI is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * HoloAPI is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with HoloAPI. If not, see <http://www.gnu.org/licenses/>. */ package com.dsh105.holoapi.hook; import com.dsh105.holoapi.HoloAPI; import com.dsh105.holoapi.HoloAPICore; import org.bukkit.Bukkit; import org.bukkit.event.EventHandler; import org.bukkit.event.Listener; import org.bukkit.event.server.PluginDisableEvent; import org.bukkit.event.server.PluginEnableEvent; import org.bukkit.plugin.Plugin; /** * Needs some optimization */ public abstract class PluginDependencyProvider<T extends Plugin> { protected PluginDependencyProvider<T> instance; private T dependency; protected boolean hooked; private Plugin myPluginInstance; private String dependencyName; // TODO: add more utils, plugin stuff mostly. public PluginDependencyProvider(Plugin myPluginInstance, String dependencyName) { this.instance = this; this.myPluginInstance = myPluginInstance; this.dependencyName = dependencyName; if (dependency == null && !this.hooked) { try { dependency = (T) Bukkit.getPluginManager().getPlugin(getDependencyName()); if (this.dependency != null && this.dependency.isEnabled()) { this.hooked = true; onHook(); HoloAPI.LOG.info("[" + this.dependency.getName() + "] Successfully hooked"); } } catch (Exception e) { HoloAPI.LOG.warning("Could not create a PluginDependencyProvider for: " + getDependencyName() + "! (Are you sure the type is valid?)"); } } Bukkit.getPluginManager().registerEvents(new Listener() { @EventHandler protected void onEnable(PluginEnableEvent event) { if ((dependency == null) && (event.getPlugin().getName().equalsIgnoreCase(getDependencyName()))) { try { dependency = (T) event.getPlugin(); hooked = true; onHook(); HoloAPI.LOG.info("[" + getDependencyName() + "] Successfully hooked"); } catch (Exception e) { throw new RuntimeException("Failed to hook plugin: " + event.getPlugin().getName()); } } } @EventHandler protected void onDisable(PluginDisableEvent event) { if ((dependency != null) && (event.getPlugin().getName().equalsIgnoreCase(getDependencyName()))) { dependency = null; hooked = false; onUnhook(); HoloAPI.LOG.info("[" + getDependencyName() + "] Successfully unhooked"); } } @Override public int hashCode() { return super.hashCode(); } }, getHandlingPlugin()); } public abstract void onHook(); public abstract void onUnhook(); public T getDependency() { if (this.dependency == null) { throw new RuntimeException("Dependency is NULL!"); } return this.dependency; } public boolean isHooked() { return this.hooked; } public Plugin getHandlingPlugin() { if (this.myPluginInstance == null) { throw new RuntimeException("HandlingPlugin is NULL!"); } return this.myPluginInstance; } public String getDependencyName() { if (this.dependencyName == null) { throw new RuntimeException("Dependency name is NULL!"); } return this.dependencyName; } }
4,260
Java
.java
DSH105/HoloAPI
31
16
21
2014-02-21T21:30:11Z
2014-12-24T12:52:54Z
VaultProvider.java
/FileExtraction/Java_unseen/DSH105_HoloAPI/src/main/java/com/dsh105/holoapi/hook/VaultProvider.java
/* * This file is part of HoloAPI. * * HoloAPI is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * HoloAPI is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with HoloAPI. If not, see <http://www.gnu.org/licenses/>. */ package com.dsh105.holoapi.hook; import net.milkbowl.vault.Vault; import net.milkbowl.vault.economy.Economy; import net.milkbowl.vault.permission.Permission; import org.bukkit.entity.Player; import org.bukkit.plugin.Plugin; import org.bukkit.plugin.RegisteredServiceProvider; public class VaultProvider extends PluginDependencyProvider<Vault> { public static Permission permission = null; public static Economy economy = null; public VaultProvider(Plugin myPluginInstance) { super(myPluginInstance, "Vault"); } @Override public void onHook() { setupEconomy(); setupPermissions(); } @Override public void onUnhook() { // Ignore } // Vault supplied methods private boolean setupPermissions() { RegisteredServiceProvider<Permission> permissionProvider = this.getHandlingPlugin().getServer().getServicesManager().getRegistration(net.milkbowl.vault.permission.Permission.class); if (permissionProvider != null) { permission = permissionProvider.getProvider(); } return (permission != null); } private boolean setupEconomy() { RegisteredServiceProvider<Economy> economyProvider = this.getHandlingPlugin().getServer().getServicesManager().getRegistration(net.milkbowl.vault.economy.Economy.class); if (economyProvider != null) { economy = economyProvider.getProvider(); } return (economy != null); } public String getBalance(Player observer) { String balance; if (economy == null) { return "%balance%"; } try { double bal = economy.getBalance(observer.getName()); if (bal == (int) bal) { balance = String.valueOf((int) bal); } else { balance = String.valueOf(bal); } return balance; } catch (Exception ex) { return "%balance%"; } } public String getRank(Player observer) { if (permission == null) { return "%rank%"; } try { return permission.getPrimaryGroup(observer); } catch (Exception ex) { return "%rank"; } } }
2,936
Java
.java
DSH105/HoloAPI
31
16
21
2014-02-21T21:30:11Z
2014-12-24T12:52:54Z
PSGroupRegion.java
/FileExtraction/Java_unseen/espidev_ProtectionStones/src/main/java/dev/espi/protectionstones/PSGroupRegion.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package dev.espi.protectionstones; import com.sk89q.worldguard.protection.managers.RegionManager; import com.sk89q.worldguard.protection.regions.ProtectedRegion; import dev.espi.protectionstones.utils.MiscUtil; import dev.espi.protectionstones.utils.Objs; import org.bukkit.Material; import org.bukkit.World; import org.bukkit.entity.Player; import java.time.Duration; import java.util.*; import java.util.stream.Collectors; /** * Represents a region that exists but is a group of merged {@link PSStandardRegion}s. * Contains multiple {@link PSMergedRegion} representing the individual merged regions (which don't technically exist in WorldGuard). */ public class PSGroupRegion extends PSStandardRegion { PSGroupRegion(ProtectedRegion wgregion, RegionManager rgmanager, World world) { super(wgregion, rgmanager, world); assert getWGRegion().getFlag(FlagHandler.PS_MERGED_REGIONS) != null; } @Override public double getTaxRate() { double taxRate = 0; for (PSMergedRegion r : getMergedRegions()) { taxRate += r.getTaxRate(); } return taxRate; } @Override public String getTaxPeriod() { Set<String> s = new HashSet<>(); getMergedRegions().forEach(r -> s.add(r.getTaxPeriod())); return MiscUtil.concatWithoutLast(new ArrayList<>(s), ", "); } @Override public String getTaxPaymentPeriod() { Set<String> s = new HashSet<>(); getMergedRegions().forEach(r -> s.add(r.getTaxPaymentPeriod())); return MiscUtil.concatWithoutLast(new ArrayList<>(s), ", "); } @Override public void updateTaxPayments() { long currentTime = System.currentTimeMillis(); List<TaxPayment> payments = Objs.replaceNull(getTaxPaymentsDue(), new ArrayList<>()); List<LastRegionTaxPaymentEntry> lastAdded = Objs.replaceNull(getRegionLastTaxPaymentAddedEntries(), new ArrayList<>()); // loop over merged regions for (PSMergedRegion r : getMergedRegions()) { // taxes disabled if (getTypeOptions().taxPeriod == -1) continue; boolean found = false; for (LastRegionTaxPaymentEntry last : lastAdded) { // if the last region payment entry refers to this region if (last.getRegionId().equals(r.getId())) { found = true; // if it's time to pay if (last.getLastPaymentAdded() + Duration.ofSeconds(r.getTypeOptions().taxPeriod).toMillis() < currentTime) { payments.add(new TaxPayment(currentTime + Duration.ofSeconds(r.getTypeOptions().taxPaymentTime).toMillis(), r.getTaxRate(), r.getId())); last.setLastPaymentAdded(currentTime); } break; } } if (!found) { payments.add(new TaxPayment(currentTime + Duration.ofSeconds(r.getTypeOptions().taxPaymentTime).toMillis(), r.getTaxRate(), r.getId())); lastAdded.add(new LastRegionTaxPaymentEntry(r.getId(), currentTime)); } } setTaxPaymentsDue(payments); setRegionLastTaxPaymentAddedEntries(lastAdded); } @Override public boolean hide() { for (PSMergedRegion r : getMergedRegions()) r.hide(); return true; } @Override public boolean unhide() { for (PSMergedRegion r : getMergedRegions()) r.unhide(); return true; } @Override public boolean deleteRegion(boolean deleteBlock, Player cause) { List<PSMergedRegion> l = getMergedRegions(); if (super.deleteRegion(deleteBlock, cause)) { for (PSMergedRegion r : l) { if (deleteBlock && !r.isHidden()) { r.getProtectBlock().setType(Material.AIR); } } return true; } else { return false; } } /** * Get the merged region whose ID is the same as the group region ID. * @return the root region */ public PSMergedRegion getRootRegion() { for (PSMergedRegion r : getMergedRegions()) { if (r.getId().equals(getId())) return r; } return null; } /** * Check if this region contains a specific merged region * @param id the psID that would've been generated if the merged region was a standard region * @return whether or not the id is a merged region */ public boolean hasMergedRegion(String id) { return getWGRegion().getFlag(FlagHandler.PS_MERGED_REGIONS).contains(id); } /** * Removes the merged region's information from the object. * Note: This DOES NOT remove the actual PSMergedRegion object, you have to call deleteRegion() on that as well. * @param id the id of the merged region */ public void removeMergedRegionInfo(String id) { getWGRegion().getFlag(FlagHandler.PS_MERGED_REGIONS).remove(id); // remove from ps merged region types Iterator<String> i = getWGRegion().getFlag(FlagHandler.PS_MERGED_REGIONS_TYPES).iterator(); while (i.hasNext()) { String[] spl = i.next().split(" "); String rid = spl[0]; if (rid.equals(id)) { i.remove(); break; } } // remove from taxes if (getWGRegion().getFlag(FlagHandler.PS_TAX_LAST_PAYMENT_ADDED) != null) { String entry = ""; for (String e : getWGRegion().getFlag(FlagHandler.PS_TAX_LAST_PAYMENT_ADDED)) { if (e.startsWith(id)) entry = e; } getWGRegion().getFlag(FlagHandler.PS_TAX_LAST_PAYMENT_ADDED).remove(entry); } } /** * Get the list of {@link PSMergedRegion} objects of the regions that were merged into this region. * @return the list of regions merged into this region */ public List<PSMergedRegion> getMergedRegions() { return getMergedRegionsUnsafe().stream() .filter(r -> r.getTypeOptions() != null) .collect(Collectors.toList()); } /** * Get the list of {@link PSMergedRegion} objects of the regions that were merged into this region. * Note: This is unsafe as it includes {@link PSMergedRegion}s that are of types not configured in the config. * @return the list of regions merged into this region */ public List<PSMergedRegion> getMergedRegionsUnsafe() { List<PSMergedRegion> l = new ArrayList<>(); for (String line : getWGRegion().getFlag(FlagHandler.PS_MERGED_REGIONS_TYPES)) { String[] spl = line.split(" "); String id = spl[0], type = spl[1]; l.add(new PSMergedRegion(id, this, getWGRegionManager(), getWorld())); } return l; } }
7,556
Java
.java
espidev/ProtectionStones
64
30
90
2018-09-17T22:12:12Z
2023-11-13T03:14:47Z
BlockHandler.java
/FileExtraction/Java_unseen/espidev_ProtectionStones/src/main/java/dev/espi/protectionstones/BlockHandler.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package dev.espi.protectionstones; import com.sk89q.worldedit.math.BlockVector3; import com.sk89q.worldguard.LocalPlayer; import com.sk89q.worldguard.bukkit.WorldGuardPlugin; import com.sk89q.worldguard.protection.flags.Flag; import com.sk89q.worldguard.protection.flags.Flags; import com.sk89q.worldguard.protection.flags.StateFlag; import com.sk89q.worldguard.protection.managers.RegionManager; import com.sk89q.worldguard.protection.regions.ProtectedCuboidRegion; import com.sk89q.worldguard.protection.regions.ProtectedRegion; import dev.espi.protectionstones.commands.ArgMerge; import dev.espi.protectionstones.event.PSCreateEvent; import dev.espi.protectionstones.utils.LimitUtil; import dev.espi.protectionstones.utils.MiscUtil; import dev.espi.protectionstones.utils.WGMerge; import dev.espi.protectionstones.utils.WGUtils; import net.md_5.bungee.api.chat.TextComponent; import net.milkbowl.vault.economy.EconomyResponse; import org.bukkit.*; import org.bukkit.block.Block; import org.bukkit.entity.Player; import org.bukkit.event.block.BlockPlaceEvent; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; public class BlockHandler { private static HashMap<Player, Double> lastProtectStonePlaced = new HashMap<>(); private static String checkCooldown(Player p) { double currentTime = System.currentTimeMillis(); if (lastProtectStonePlaced.containsKey(p)) { double cooldown = ProtectionStones.getInstance().getConfigOptions().placingCooldown; // seconds double lastPlace = lastProtectStonePlaced.get(p); // milliseconds if (lastPlace + cooldown * 1000 > currentTime) { // if cooldown has not been finished return String.format("%.1f", cooldown - ((currentTime - lastPlace) / 1000)); } lastProtectStonePlaced.remove(p); } lastProtectStonePlaced.put(p, currentTime); return null; } private static boolean isFarEnoughFromOtherClaims(PSProtectBlock blockOptions, World w, LocalPlayer lp, double bx, double by, double bz) { BlockVector3 min = WGUtils.getMinVector(bx, by, bz, blockOptions.distanceBetweenClaims, blockOptions.distanceBetweenClaims, blockOptions.distanceBetweenClaims); BlockVector3 max = WGUtils.getMaxVector(bx, by, bz, blockOptions.distanceBetweenClaims, blockOptions.distanceBetweenClaims, blockOptions.distanceBetweenClaims); ProtectedRegion td = new ProtectedCuboidRegion("regionRadiusTest" + (long) (bx + by + bz), true, min, max); td.setPriority(blockOptions.priority); RegionManager rgm = WGUtils.getRegionManagerWithWorld(w); // if the radius test region overlaps an unowned region if (rgm.overlapsUnownedRegion(td, lp)) { for (ProtectedRegion rg : rgm.getApplicableRegions(td)) { // skip if the user is already an owner if (rg.isOwner(lp)) continue; if (ProtectionStones.isPSRegion(rg) && rg.getFlag(Flags.PASSTHROUGH) != StateFlag.State.ALLOW) { // if it is a PS region, and "passthrough allow" is not set, then it is not far enough return false; } else if (rg.getPriority() >= td.getPriority()) { // if the priorities are the same for plain WorldGuard regions, it is not far enough return false; } } } return true; } // create PS region from a block place event public static void createPSRegion(BlockPlaceEvent e) { Player p = e.getPlayer(); Block b = e.getBlock(); // check if the block is a protection stone if (!ProtectionStones.isProtectBlockType(b)) return; PSProtectBlock blockOptions = ProtectionStones.getBlockOptions(b); // check if the item was created by protection stones (stored in custom tag) // block must have restrictObtaining enabled for blocking place if (blockOptions.restrictObtaining && !ProtectionStones.isProtectBlockItem(e.getItemInHand(), true)) return; // check if player has toggled off placement of protection stones if (ProtectionStones.toggleList.contains(p.getUniqueId())) return; // check if player can place block in that area if (!WorldGuardPlugin.inst().createProtectionQuery().testBlockPlace(p, b.getLocation(), b.getType())) { PSL.msg(p, PSL.CANT_PROTECT_THAT.msg()); e.setCancelled(true); return; } // check if it is in a WorldGuard region RegionManager rgm = WGUtils.getRegionManagerWithPlayer(p); if (!blockOptions.allowPlacingInWild && rgm.getApplicableRegions(BlockVector3.at(b.getLocation().getX(), b.getLocation().getY(), b.getLocation().getZ())).size() == 0) { PSL.msg(p, PSL.MUST_BE_PLACED_IN_EXISTING_REGION.msg()); e.setCancelled(true); return; } // create region, and cancel if it fails if (!createPSRegion(p, b.getLocation(), blockOptions)) { e.setCancelled(true); } } // create a PS region (no checks for items) public static boolean createPSRegion(Player p, Location l, PSProtectBlock blockOptions) { // check permission if (!p.hasPermission("protectionstones.create")) { PSL.msg(p, PSL.NO_PERMISSION_CREATE.msg()); return false; } if (!blockOptions.permission.equals("") && !p.hasPermission(blockOptions.permission)) { PSL.msg(p, PSL.NO_PERMISSION_CREATE_SPECIFIC.msg()); return false; } // check cooldown if (ProtectionStones.getInstance().getConfigOptions().placingCooldown != -1) { String time = checkCooldown(p); if (time != null) { PSL.msg(p, PSL.COOLDOWN.msg().replace("%time%", time)); return false; } } // check if player reached region limit if (!LimitUtil.check(p, blockOptions)) { return false; } // non-admin checks if (!p.hasPermission("protectionstones.admin")) { // check if in world blacklist or not in world whitelist boolean containsWorld = blockOptions.worlds.contains(p.getLocation().getWorld().getName()); if ((containsWorld && blockOptions.worldListType.equalsIgnoreCase("blacklist")) || (!containsWorld && blockOptions.worldListType.equalsIgnoreCase("whitelist"))) { if (blockOptions.preventBlockPlaceInRestrictedWorld) { PSL.msg(p, PSL.WORLD_DENIED_CREATE.msg()); return false; } else { return true; } } } // end of non-admin checks // check if player has enough money if (ProtectionStones.getInstance().isVaultSupportEnabled() && blockOptions.costToPlace != 0 && !ProtectionStones.getInstance().getVaultEconomy().has(p, blockOptions.costToPlace)) { PSL.msg(p, PSL.NOT_ENOUGH_MONEY.msg().replace("%price%", String.format("%.2f", blockOptions.costToPlace))); return false; } // debug message if (!ProtectionStones.getInstance().isVaultSupportEnabled() && blockOptions.costToPlace != 0) { ProtectionStones.getPluginLogger().info("Vault is not enabled but there is a price set on the protection stone placement! It will not work!"); } if (createActualRegion(p, l, blockOptions)) { // region creation successful // take money if (ProtectionStones.getInstance().isVaultSupportEnabled() && blockOptions.costToPlace != 0) { EconomyResponse er = ProtectionStones.getInstance().getVaultEconomy().withdrawPlayer(p, blockOptions.costToPlace); if (!er.transactionSuccess()) { PSL.msg(p, er.errorMessage); return true; } PSL.msg(p, PSL.PAID_MONEY.msg().replace("%price%", String.format("%.2f", blockOptions.costToPlace))); } return true; } else { // region creation failed return false; } } // create the actual WG region for PS region public static boolean createActualRegion(Player p, Location l, PSProtectBlock blockOptions) { // create region double bx = l.getX(), by = l.getY(), bz = l.getZ(); RegionManager rm = WGUtils.getRegionManagerWithPlayer(p); LocalPlayer lp = WorldGuardPlugin.inst().wrapPlayer(p); String id = WGUtils.createPSID(bx, by, bz); // if the region's id already exists, possibly placing block where a region is hidden if (rm.hasRegion(id)) { PSL.msg(p, PSL.REGION_ALREADY_IN_LOCATION_IS_HIDDEN.msg()); return false; } // check for minimum distance between claims by using fake region if (blockOptions.distanceBetweenClaims != -1 && !p.hasPermission("protectionstones.superowner")) { if (!isFarEnoughFromOtherClaims(blockOptions, p.getWorld(), lp, bx, by, bz)) { PSL.msg(p, PSL.REGION_TOO_CLOSE.msg().replace("%num%", "" + blockOptions.distanceBetweenClaims)); return false; } } // create actual region ProtectedRegion region = WGUtils.getDefaultProtectedRegion(blockOptions, WGUtils.parsePSRegionToLocation(id)); region.getOwners().addPlayer(p.getUniqueId()); region.setPriority(blockOptions.priority); rm.addRegion(region); // added to the region manager, be careful in implementing checks // check if new region overlaps more powerful region if (!blockOptions.allowOverlapUnownedRegions && !p.hasPermission("protectionstones.superowner") && WGUtils.overlapsStrongerRegion(p.getWorld(), region, lp)) { rm.removeRegion(id); PSL.msg(p, PSL.REGION_OVERLAP.msg()); return false; } // add corresponding flags to new region by cloning blockOptions default flags HashMap<Flag<?>, Object> flags = new HashMap<>(blockOptions.regionFlags); // replace greeting and farewell messages with player name FlagHandler.initDefaultFlagPlaceholders(flags, p); // set flags try { region.setFlags(flags); } catch (Exception e) { ProtectionStones.getPluginLogger().severe(String.format("Region flags have failed to initialize for: %s (%s)", blockOptions.alias, blockOptions.type)); throw e; } FlagHandler.initCustomFlagsForPS(region, l, blockOptions); // check for player's number of adjacent region groups if (ProtectionStones.getInstance().getConfigOptions().regionsMustBeAdjacent) { if (MiscUtil.getPermissionNumber(p, "protectionstones.adjacent.", 1) >= 0 && !p.hasPermission("protectionstones.admin")) { HashMap<String, ArrayList<String>> adjGroups = WGUtils.getPlayerAdjacentRegionGroups(p, rm); int permNum = MiscUtil.getPermissionNumber(p, "protectionstones.adjacent.", 1); if (adjGroups.size() > permNum && permNum != -1) { PSL.msg(p, PSL.REGION_NOT_ADJACENT.msg()); rm.removeRegion(id); return false; } } } // fire event and check if cancelled PSCreateEvent event = new PSCreateEvent(PSRegion.fromWGRegion(p.getWorld(), region), p); Bukkit.getPluginManager().callEvent(event); if (event.isCancelled()) { rm.removeRegion(id); return false; } PSL.msg(p, PSL.PROTECTED.msg()); // hide block if auto hide is enabled if (blockOptions.autoHide) { PSL.msg(p, PSL.REGION_HIDDEN.msg()); // run on next tick so placing tile entities don't complain Bukkit.getScheduler().runTask(ProtectionStones.getInstance(), () -> l.getBlock().setType(Material.AIR)); } if (blockOptions.startWithTaxAutopay) { // set tax auto-pay (even if taxing is not enabled) region.setFlag(FlagHandler.PS_TAX_AUTOPAYER, p.getUniqueId().toString()); } // show merge menu if (ProtectionStones.getInstance().getConfigOptions().allowMergingRegions && blockOptions.allowMerging && p.hasPermission("protectionstones.merge")) { PSRegion r = PSRegion.fromWGRegion(p.getWorld(), region); if (r != null) playerMergeTask(p, r); } return true; } // merge behaviour after a region is created private static void playerMergeTask(Player p, PSRegion r) { boolean showGUI = true; // auto merge to nearest region if only one exists if (r.getTypeOptions().autoMerge) { PSRegion mergeTo = null; for (PSRegion psr : r.getMergeableRegions(p)) { if (mergeTo == null) { mergeTo = psr; showGUI = false; } else { showGUI = true; break; } } // actually do auto merge if (!showGUI) { PSRegion finalMergeTo = mergeTo; Bukkit.getScheduler().runTaskAsynchronously(ProtectionStones.getInstance(), () -> { try { WGMerge.mergeRealRegions(p.getWorld(), r.getWGRegionManager(), finalMergeTo, Arrays.asList(finalMergeTo, r)); PSL.msg(p, PSL.MERGE_AUTO_MERGED.msg().replace("%region%", finalMergeTo.getId())); } catch (WGMerge.RegionHoleException e) { PSL.msg(p, PSL.NO_REGION_HOLES.msg()); // TODO github issue #120, prevent holes even if showGUI is true } catch (WGMerge.RegionCannotMergeWhileRentedException e) { // don't need to tell player that you can't merge } }); } } // show merge gui if (showGUI) { List<TextComponent> tc = ArgMerge.getGUI(p, r); if (!tc.isEmpty()) { // if there are regions you can merge into p.sendMessage(ChatColor.WHITE + ""); // send empty line PSL.msg(p, PSL.MERGE_INTO.msg()); PSL.msg(p, PSL.MERGE_HEADER.msg().replace("%region%", r.getId())); for (TextComponent t : tc) p.spigot().sendMessage(t); p.sendMessage(ChatColor.WHITE + ""); // send empty line } } } }
15,408
Java
.java
espidev/ProtectionStones
64
30
90
2018-09-17T22:12:12Z
2023-11-13T03:14:47Z
PSCommand.java
/FileExtraction/Java_unseen/espidev_ProtectionStones/src/main/java/dev/espi/protectionstones/PSCommand.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package dev.espi.protectionstones; import dev.espi.protectionstones.commands.*; import org.bukkit.ChatColor; import org.bukkit.command.Command; import org.bukkit.command.CommandSender; import org.bukkit.command.ConsoleCommandSender; import org.bukkit.entity.Player; import org.bukkit.util.StringUtil; import java.util.ArrayList; import java.util.HashMap; import java.util.List; public class PSCommand extends Command { PSCommand(String name) { super(name); } static void addDefaultArguments() { ProtectionStones.getInstance().addCommandArgument(new ArgAddRemove()); ProtectionStones.getInstance().addCommandArgument(new ArgAdmin()); ProtectionStones.getInstance().addCommandArgument(new ArgBuySell()); ProtectionStones.getInstance().addCommandArgument(new ArgCount()); ProtectionStones.getInstance().addCommandArgument(new ArgFlag()); ProtectionStones.getInstance().addCommandArgument(new ArgGet()); ProtectionStones.getInstance().addCommandArgument(new ArgGive()); ProtectionStones.getInstance().addCommandArgument(new ArgHideUnhide()); ProtectionStones.getInstance().addCommandArgument(new ArgHome()); ProtectionStones.getInstance().addCommandArgument(new ArgInfo()); ProtectionStones.getInstance().addCommandArgument(new ArgList()); ProtectionStones.getInstance().addCommandArgument(new ArgMerge()); ProtectionStones.getInstance().addCommandArgument(new ArgName()); ProtectionStones.getInstance().addCommandArgument(new ArgPriority()); ProtectionStones.getInstance().addCommandArgument(new ArgRegion()); ProtectionStones.getInstance().addCommandArgument(new ArgReload()); ProtectionStones.getInstance().addCommandArgument(new ArgRent()); ProtectionStones.getInstance().addCommandArgument(new ArgSethome()); ProtectionStones.getInstance().addCommandArgument(new ArgSetparent()); ProtectionStones.getInstance().addCommandArgument(new ArgTax()); ProtectionStones.getInstance().addCommandArgument(new ArgToggle()); ProtectionStones.getInstance().addCommandArgument(new ArgToggle.ArgToggleOn()); ProtectionStones.getInstance().addCommandArgument(new ArgToggle.ArgToggleOff()); ProtectionStones.getInstance().addCommandArgument(new ArgTp()); ProtectionStones.getInstance().addCommandArgument(new ArgUnclaim()); ProtectionStones.getInstance().addCommandArgument(new ArgView()); ProtectionStones.getInstance().addCommandArgument(new ArgHelp()); } @Override public List<String> tabComplete(CommandSender sender, String alias, String[] args) { if (args.length == 1) { List<String> l = new ArrayList<>(); for (PSCommandArg ps : ProtectionStones.getInstance().getCommandArguments()) { boolean hasPerm = false; if (ps.getPermissionsToExecute() == null) { hasPerm = true; } else { for (String perm : ps.getPermissionsToExecute()) { if (sender.hasPermission(perm)) { hasPerm = true; break; } } } if (hasPerm) l.addAll(ps.getNames()); } return StringUtil.copyPartialMatches(args[0], l, new ArrayList<>()); } else if (args.length >= 2) { for (PSCommandArg ps : ProtectionStones.getInstance().getCommandArguments()) { for (String arg : ps.getNames()) { if (arg.equalsIgnoreCase(args[0])) { return ps.tabComplete(sender, alias, args); } } } } return null; } @Override public boolean execute(CommandSender s, String label, String[] args) { if (args.length == 0) { // no arguments if (s instanceof ConsoleCommandSender) { s.sendMessage(ChatColor.RED + "You can only use /ps reload, /ps admin, /ps give from console."); } else { new ArgHelp().executeArgument(s, args, null); } return true; } for (PSCommandArg command : ProtectionStones.getInstance().getCommandArguments()) { if (command.getNames().contains(args[0])) { if (command.allowNonPlayersToExecute() || s instanceof Player) { // extract flags List<String> nArgs = new ArrayList<>(); HashMap<String, String> flags = new HashMap<>(); for (int i = 0; i < args.length; i++) { if (command.getRegisteredFlags() != null && command.getRegisteredFlags().containsKey(args[i])) { if (command.getRegisteredFlags().get(args[i])) { // has value after if (i != args.length-1) { flags.put(args[i], args[++i]); } } else { flags.put(args[i], null); } } else { nArgs.add(args[i]); } } return command.executeArgument(s, nArgs.toArray(new String[0]), flags); } else if (!command.allowNonPlayersToExecute()) { s.sendMessage(ChatColor.RED + "You can only use /ps reload, /ps admin, /ps give from console."); return true; } } } PSL.msg(s, PSL.NO_SUCH_COMMAND.msg()); return true; } }
6,450
Java
.java
espidev/ProtectionStones
64
30
90
2018-09-17T22:12:12Z
2023-11-13T03:14:47Z
PSMergedRegion.java
/FileExtraction/Java_unseen/espidev_ProtectionStones/src/main/java/dev/espi/protectionstones/PSMergedRegion.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package dev.espi.protectionstones; import com.sk89q.worldedit.math.BlockVector2; import com.sk89q.worldedit.math.BlockVector3; import com.sk89q.worldguard.protection.managers.RegionManager; import com.sk89q.worldguard.protection.regions.ProtectedRegion; import dev.espi.protectionstones.event.PSRemoveEvent; import dev.espi.protectionstones.utils.MiscUtil; import dev.espi.protectionstones.utils.WGMerge; import dev.espi.protectionstones.utils.WGUtils; import net.milkbowl.vault.economy.EconomyResponse; import org.bukkit.Bukkit; import org.bukkit.Location; import org.bukkit.Material; import org.bukkit.World; import org.bukkit.block.Block; import org.bukkit.entity.Player; import java.time.Duration; import java.util.ArrayList; import java.util.List; import java.util.Set; import java.util.UUID; import static com.google.common.base.Preconditions.checkNotNull; /** * Represents an instance of a PS region that has been merged into another region. There is no actual WG region that * this contains, and instead takes properties from its parent region (see {@link PSGroupRegion}). */ public class PSMergedRegion extends PSRegion { private PSGroupRegion mergedGroup; private String id, type; PSMergedRegion(String id, PSGroupRegion mergedGroup, RegionManager rgmanager, World world) { super(rgmanager, world); // null checks are in super constructor this.id = checkNotNull(id); this.mergedGroup = checkNotNull(mergedGroup); // get type // stored instead of fetched on the fly because unmerge algorithm removes the flag causing getType to return null for (String s : mergedGroup.getWGRegion().getFlag(FlagHandler.PS_MERGED_REGIONS_TYPES)) { String[] spl = s.split(" "); String did = spl[0], type = spl[1]; if (did.equals(getId())) { this.type = type; break; } } } // ~~~~~~~~~~~ static ~~~~~~~~~~~~~~~~ /** * Finds the {@link PSMergedRegion} at a location if the block at that location is the source protection block for it. * * @param l location to look at * @return the {@link PSMergedRegion} of the source block location, or null if not applicable */ public static PSMergedRegion getMergedRegion(Location l) { String psID = WGUtils.createPSID(l); RegionManager rgm = WGUtils.getRegionManagerWithWorld(l.getWorld()); if (rgm == null) return null; for (ProtectedRegion pr : rgm.getApplicableRegions(BlockVector3.at(l.getX(), l.getY(), l.getZ()))) { // if the region has the merged region Set<String> mergedIds = pr.getFlag(FlagHandler.PS_MERGED_REGIONS); if (mergedIds != null && mergedIds.contains(psID)) { return new PSMergedRegion(psID, new PSGroupRegion(pr, rgm, l.getWorld()), rgm, l.getWorld()); } } return null; } // ~~~~~~~~~~~ instance ~~~~~~~~~~~~~~~~ /** * Get the group region that contains this region. * * @return the group region */ public PSGroupRegion getGroupRegion() { return mergedGroup; } @Override public String getId() { return id; } @Override public String getName() { return mergedGroup.getName(); } @Override public void setName(String name) { mergedGroup.setName(name); } @Override public void setParent(PSRegion r) throws ProtectedRegion.CircularInheritanceException { mergedGroup.setParent(r); } @Override public PSRegion getParent() { return mergedGroup.getParent(); } @Override public Location getHome() { return mergedGroup.getHome(); } @Override public void setHome(double blockX, double blockY, double blockZ) { mergedGroup.setHome(blockX, blockY, blockZ); } @Override public void setHome(double blockX, double blockY, double blockZ, float yaw, float pitch) { mergedGroup.setHome(blockX, blockY, blockZ, yaw, pitch); } @Override public boolean forSale() { return mergedGroup.forSale(); } @Override public void setSellable(boolean forSale, UUID landlord, double price) { mergedGroup.setSellable(forSale, landlord, price); } @Override public void sell(UUID player) { mergedGroup.sell(player); } @Override public RentStage getRentStage() { return mergedGroup.getRentStage(); } @Override public UUID getLandlord() { return mergedGroup.getLandlord(); } @Override public void setLandlord(UUID landlord) { mergedGroup.setLandlord(landlord); } @Override public UUID getTenant() { return mergedGroup.getTenant(); } @Override public void setTenant(UUID tenant) { mergedGroup.setTenant(tenant); } @Override public String getRentPeriod() { return mergedGroup.getRentPeriod(); } @Override public void setRentPeriod(String s) { mergedGroup.setRentPeriod(s); } @Override public Double getPrice() { return mergedGroup.getPrice(); } @Override public void setPrice(Double price) { mergedGroup.setPrice(price); } @Override public void setRentLastPaid(Long timestamp) { mergedGroup.setRentLastPaid(timestamp); } @Override public Long getRentLastPaid() { return mergedGroup.getRentLastPaid(); } @Override public void setRentable(UUID landlord, String rentPeriod, double rentPrice) { mergedGroup.setRentable(landlord, rentPeriod, rentPrice); } @Override public void rentOut(UUID landlord, UUID tenant, String rentPeriod, double rentPrice) { mergedGroup.rentOut(landlord, tenant, rentPeriod, rentPrice); } @Override public void removeRenting() { mergedGroup.removeRenting(); } @Override public String getTaxPeriod() { return MiscUtil.describeDuration(Duration.ofSeconds(getTypeOptions().taxPeriod)); } @Override public String getTaxPaymentPeriod() { return MiscUtil.describeDuration(Duration.ofSeconds(getTypeOptions().taxPaymentTime)); } @Override public List<TaxPayment> getTaxPaymentsDue() { return mergedGroup.getTaxPaymentsDue(); } @Override public void setTaxPaymentsDue(List<TaxPayment> taxPayments) { mergedGroup.setTaxPaymentsDue(taxPayments); } @Override public List<LastRegionTaxPaymentEntry> getRegionLastTaxPaymentAddedEntries() { return mergedGroup.getRegionLastTaxPaymentAddedEntries(); } @Override public void setRegionLastTaxPaymentAddedEntries(List<LastRegionTaxPaymentEntry> entries) { mergedGroup.setRegionLastTaxPaymentAddedEntries(entries); } @Override public UUID getTaxAutopayer() { return mergedGroup.getTaxAutopayer(); } @Override public void setTaxAutopayer(UUID uuid) { mergedGroup.setTaxAutopayer(uuid); } @Override public EconomyResponse payTax(PSPlayer p, double amount) { return mergedGroup.payTax(p, amount); } @Override public boolean isTaxPaymentLate() { return mergedGroup.isTaxPaymentLate(); } @Override public void updateTaxPayments() { mergedGroup.updateTaxPayments(); } @Override public Block getProtectBlock() { PSLocation psl = WGUtils.parsePSRegionToLocation(id); return world.getBlockAt(psl.x, psl.y, psl.z); } @Override public PSProtectBlock getTypeOptions() { return ProtectionStones.getBlockOptions(getType()); } @Override public String getType() { return type; } @Override public void setType(PSProtectBlock type) { super.setType(type); // has to be after isHidden query this.type = type.type; Set<String> flag = mergedGroup.getWGRegion().getFlag(FlagHandler.PS_MERGED_REGIONS_TYPES); String original = null; for (String s : flag) { String[] spl = s.split(" "); String id = spl[0]; if (id.equals(getId())) { original = s; break; } } if (original != null) { flag.remove(original); flag.add(getId() + " " + type.type); } } @Override public boolean isOwner(UUID uuid) { return mergedGroup.isOwner(uuid); } @Override public boolean isMember(UUID uuid) { return mergedGroup.isMember(uuid); } @Override public ArrayList<UUID> getOwners() { return mergedGroup.getOwners(); } @Override public ArrayList<UUID> getMembers() { return mergedGroup.getMembers(); } @Override public void addOwner(UUID uuid) { mergedGroup.addOwner(uuid); } @Override public void addMember(UUID uuid) { mergedGroup.addMember(uuid); } @Override public void removeOwner(UUID uuid) { mergedGroup.removeOwner(uuid); } @Override public void removeMember(UUID uuid) { mergedGroup.removeMember(uuid); } @Override public List<BlockVector2> getPoints() { return WGUtils.getDefaultProtectedRegion(getTypeOptions(), WGUtils.parsePSRegionToLocation(id)).getPoints(); } @Override public List<PSRegion> getMergeableRegions(Player p) { return mergedGroup.getMergeableRegions(p); } @Override public boolean deleteRegion(boolean deleteBlock) { return deleteRegion(deleteBlock, null); } @Override public boolean deleteRegion(boolean deleteBlock, Player cause) { PSRemoveEvent event = new PSRemoveEvent(this, cause); Bukkit.getPluginManager().callEvent(event); if (event.isCancelled()) { // if event was cancelled, prevent execution return false; } if (deleteBlock && !this.isHidden()) { this.getProtectBlock().setType(Material.AIR); } try { WGMerge.unmergeRegion(getWorld(), getWGRegionManager(), this); } catch (WGMerge.RegionHoleException | WGMerge.RegionCannotMergeWhileRentedException e) { this.unhide(); return false; } return true; } @Override public ProtectedRegion getWGRegion() { return WGUtils.getDefaultProtectedRegion(getTypeOptions(), WGUtils.parsePSRegionToLocation(id)); } }
11,246
Java
.java
espidev/ProtectionStones
64
30
90
2018-09-17T22:12:12Z
2023-11-13T03:14:47Z
PSStandardRegion.java
/FileExtraction/Java_unseen/espidev_ProtectionStones/src/main/java/dev/espi/protectionstones/PSStandardRegion.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package dev.espi.protectionstones; import com.sk89q.worldedit.math.BlockVector2; import com.sk89q.worldguard.protection.managers.RegionManager; import com.sk89q.worldguard.protection.managers.RemovalStrategy; import com.sk89q.worldguard.protection.regions.ProtectedRegion; import dev.espi.protectionstones.event.PSRemoveEvent; import dev.espi.protectionstones.utils.MiscUtil; import dev.espi.protectionstones.utils.Objs; import dev.espi.protectionstones.utils.WGUtils; import net.milkbowl.vault.economy.EconomyResponse; import org.bukkit.*; import org.bukkit.block.Block; import org.bukkit.entity.Player; import java.time.Duration; import java.time.Instant; import java.util.*; import java.util.stream.Collectors; import static com.google.common.base.Preconditions.checkNotNull; /** * Represents an instance of a standard PS region, that has not been merged or contains merged regions. */ public class PSStandardRegion extends PSRegion { private ProtectedRegion wgregion; PSStandardRegion(ProtectedRegion wgregion, RegionManager rgmanager, World world) { super(rgmanager, world); this.wgregion = checkNotNull(wgregion); } // ~~~~~~~~~~~ instance ~~~~~~~~~~~~~~~~ @Override public String getId() { return wgregion.getId(); } @Override public String getName() { return wgregion.getFlag(FlagHandler.PS_NAME); } @Override public void setName(String name) { HashMap<String, ArrayList<String>> m = ProtectionStones.regionNameToID.get(getWorld().getUID()); if (m == null) { // if the world has not been added ProtectionStones.regionNameToID.put(getWorld().getUID(), new HashMap<>()); m = ProtectionStones.regionNameToID.get(getWorld().getUID()); } if (m.get(getName()) != null) { m.get(getName()).remove(getId()); } if (name != null) { if (m.containsKey(name)) { m.get(name).add(getId()); } else { m.put(name, new ArrayList<>(Collections.singletonList(getId()))); } } wgregion.setFlag(FlagHandler.PS_NAME, name); } @Override public void setParent(PSRegion r) throws ProtectedRegion.CircularInheritanceException { wgregion.setParent(r == null ? null : r.getWGRegion()); } @Override public PSRegion getParent() { return wgregion.getParent() == null ? null : fromWGRegion(world, wgregion.getParent()); } @Override public Location getHome() { String oPos = wgregion.getFlag(FlagHandler.PS_HOME); if (oPos == null) return null; String[] pos = oPos.split(" "); double x = Double.parseDouble(pos[0]), y = Double.parseDouble(pos[1]), z = Double.parseDouble(pos[2]); float yaw = pos.length >= 4 ? Float.parseFloat(pos[3]) : 0, pitch = pos.length >= 4 ? Float.parseFloat(pos[4]) : 0; return new Location(world, x, y, z, yaw, pitch); } @Override public void setHome(double blockX, double blockY, double blockZ) { wgregion.setFlag(FlagHandler.PS_HOME, blockX + " " + blockY + " " + blockZ); } @Override public void setHome(double blockX, double blockY, double blockZ, float yaw, float pitch) { wgregion.setFlag(FlagHandler.PS_HOME, blockX + " " + blockY + " " + blockZ + " " + yaw + " " + pitch); } @Override public boolean forSale() { return wgregion.getFlag(FlagHandler.PS_FOR_SALE) != null && wgregion.getFlag(FlagHandler.PS_FOR_SALE); } @Override public void setSellable(boolean forSale, UUID landlord, double price) { if (!forSale) { wgregion.setFlag(FlagHandler.PS_LANDLORD, null); wgregion.setFlag(FlagHandler.PS_PRICE, null); wgregion.setFlag(FlagHandler.PS_FOR_SALE, null); } else { wgregion.setFlag(FlagHandler.PS_LANDLORD, landlord.toString()); wgregion.setFlag(FlagHandler.PS_PRICE, price); wgregion.setFlag(FlagHandler.PS_FOR_SALE, true); } } @Override public void sell(UUID player) { PSPlayer.fromUUID(player).pay(PSPlayer.fromUUID(getLandlord()), getPrice()); setSellable(false, null, 0); getWGRegion().getOwners().removeAll(); getWGRegion().getMembers().removeAll(); addOwner(player); } @Override public RentStage getRentStage() { if (getLandlord() == null && getTenant() == null) { return RentStage.NOT_RENTING; } else if (getTenant() == null && !forSale()) { return RentStage.LOOKING_FOR_TENANT; } else if (getPrice() != null && !forSale()) { return RentStage.RENTING; } return RentStage.NOT_RENTING; } @Override public UUID getLandlord() { return wgregion.getFlag(FlagHandler.PS_LANDLORD) == null ? null : UUID.fromString(wgregion.getFlag(FlagHandler.PS_LANDLORD)); } @Override public void setLandlord(UUID landlord) { wgregion.setFlag(FlagHandler.PS_LANDLORD, landlord == null ? null : landlord.toString()); } @Override public UUID getTenant() { return wgregion.getFlag(FlagHandler.PS_TENANT) == null ? null : UUID.fromString(wgregion.getFlag(FlagHandler.PS_TENANT)); } @Override public void setTenant(UUID tenant) { wgregion.setFlag(FlagHandler.PS_TENANT, tenant == null ? null : tenant.toString()); } @Override public String getRentPeriod() { return wgregion.getFlag(FlagHandler.PS_RENT_PERIOD); } @Override public void setRentPeriod(String s) { wgregion.setFlag(FlagHandler.PS_RENT_PERIOD, s); } @Override public Double getPrice() { return wgregion.getFlag(FlagHandler.PS_PRICE); } @Override public void setPrice(Double price) { wgregion.setFlag(FlagHandler.PS_PRICE, price); } @Override public void setRentLastPaid(Long timestamp) { wgregion.setFlag(FlagHandler.PS_RENT_LAST_PAID, timestamp == null ? null : timestamp.doubleValue()); } @Override public Long getRentLastPaid() { return wgregion.getFlag(FlagHandler.PS_RENT_LAST_PAID) == null ? null : wgregion.getFlag(FlagHandler.PS_RENT_LAST_PAID).longValue(); } @Override public void setRentable(UUID landlord, String rentPeriod, double rentPrice) { setLandlord(landlord); setTenant(null); setRentPeriod(rentPeriod); setPrice(rentPrice); } @Override public void rentOut(UUID landlord, UUID tenant, String rentPeriod, double rentPrice) { setLandlord(landlord); setTenant(tenant); setRentPeriod(rentPeriod); setPrice(rentPrice); setRentLastPaid(Instant.now().getEpochSecond()); ProtectionStones.getEconomy().getRentedList().add(this); if (!getTypeOptions().landlordStillOwner) { getWGRegion().getOwners().removeAll(); getWGRegion().getMembers().removeAll(); } if (getTypeOptions().tenantRentRole.equals("member")) { addMember(tenant); } else if (getTypeOptions().tenantRentRole.equals("owner")) { addOwner(tenant); } } @Override public void removeRenting() { getWGRegion().getOwners().removeAll(); getWGRegion().getMembers().removeAll(); addOwner(getLandlord()); setLandlord(null); setTenant(null); setRentPeriod(null); setPrice(null); setRentLastPaid(null); ProtectionStones.getEconomy().getRentedList().remove(this); } @Override public String getTaxPeriod() { return MiscUtil.describeDuration(Duration.ofSeconds(getTypeOptions().taxPeriod)); } @Override public String getTaxPaymentPeriod() { return MiscUtil.describeDuration(Duration.ofSeconds(getTypeOptions().taxPaymentTime)); } @Override public List<TaxPayment> getTaxPaymentsDue() { // taxes disabled if (getTypeOptions().taxPeriod == -1) return new ArrayList<>(); Set<String> s = wgregion.getFlag(FlagHandler.PS_TAX_PAYMENTS_DUE); if (s == null) return new ArrayList<>(); // convert to TaxPayment objects List<TaxPayment> taxPayments = s.stream() .map(TaxPayment::fromString) .filter(Objects::nonNull) .collect(Collectors.toList()); // correct for any invalid entries setTaxPaymentsDue(taxPayments); return taxPayments; } @Override public void setTaxPaymentsDue(List<TaxPayment> taxPayments) { WGUtils.setFlagIfNeeded(wgregion, FlagHandler.PS_TAX_PAYMENTS_DUE, taxPayments.stream().map(TaxPayment::toFlagEntry).collect(Collectors.toSet())); } @Override public List<LastRegionTaxPaymentEntry> getRegionLastTaxPaymentAddedEntries() { // taxes disabled if (getTypeOptions().taxPeriod == -1) return new ArrayList<>(); Set<String> s = wgregion.getFlag(FlagHandler.PS_TAX_LAST_PAYMENT_ADDED); if (s == null) return new ArrayList<>(); // convert string entries to object List<LastRegionTaxPaymentEntry> entries = s.stream() .map(LastRegionTaxPaymentEntry::fromString) .filter(Objects::nonNull) .collect(Collectors.toList()); // correct for invalid entries setRegionLastTaxPaymentAddedEntries(entries); return entries; } @Override public void setRegionLastTaxPaymentAddedEntries(List<LastRegionTaxPaymentEntry> entries) { Set<String> set = entries.stream().map(LastRegionTaxPaymentEntry::toFlagEntry).collect(Collectors.toSet()); WGUtils.setFlagIfNeeded(wgregion, FlagHandler.PS_TAX_LAST_PAYMENT_ADDED, set); } @Override public UUID getTaxAutopayer() { return wgregion.getFlag(FlagHandler.PS_TAX_AUTOPAYER) == null ? null : UUID.fromString(wgregion.getFlag(FlagHandler.PS_TAX_AUTOPAYER)); } @Override public void setTaxAutopayer(UUID player) { WGUtils.setFlagIfNeeded(wgregion, FlagHandler.PS_TAX_AUTOPAYER, player == null ? null : player.toString()); } @Override public EconomyResponse payTax(PSPlayer p, double amount) { List<TaxPayment> paymentList = getTaxPaymentsDue(); Collections.sort(paymentList); // sort by date due double paymentAmount = 0; for (int i = 0; i < paymentList.size(); i++) { TaxPayment tp = paymentList.get(i); if (tp.amount > amount) { // if the amount cannot fully pay the tax tp.amount -= amount; paymentAmount += amount; break; } else { // if the amount being paid can fully pay off this tax amount -= tp.amount; paymentAmount += tp.amount; paymentList.remove(i); i--; } } // update with corrected tax payments setTaxPaymentsDue(paymentList); return p.withdrawBalance(paymentAmount); } @Override public boolean isTaxPaymentLate() { // check if taxes disabled for block if (getTypeOptions().taxPeriod == -1) return false; // update first updateTaxPayments(); long currentTime = System.currentTimeMillis(); // loop through pending tax payments and see if the payment due date has passed for (TaxPayment tp : getTaxPaymentsDue()) { if (tp.whenPaymentIsDue < currentTime) return true; } return false; } @Override public void updateTaxPayments() { // taxes disabled if (getTypeOptions().taxPeriod == -1) return; long currentTime = System.currentTimeMillis(); List<TaxPayment> payments = Objs.replaceNull(getTaxPaymentsDue(), new ArrayList<>()); List<LastRegionTaxPaymentEntry> lastAdded = Objs.replaceNull(getRegionLastTaxPaymentAddedEntries(), new ArrayList<>()); lastAdded = lastAdded.stream() // remove entries that are not for this region .filter(e -> e.getRegionId().equals(getId())) // add payment if it is time for the next payment cycle .peek(e -> { if (e.getLastPaymentAdded() + Duration.ofSeconds(getTypeOptions().taxPeriod).toMillis() < currentTime) { e.setLastPaymentAdded(currentTime); payments.add(new TaxPayment(currentTime + Duration.ofSeconds(getTypeOptions().taxPaymentTime).toMillis(), getTaxRate(), getId())); } }).collect(Collectors.toList()); // if no entry was found, add a tax payment if (lastAdded.isEmpty()) { lastAdded.add(new LastRegionTaxPaymentEntry(getId(), currentTime)); payments.add(new TaxPayment(currentTime + Duration.ofSeconds(getTypeOptions().taxPaymentTime).toMillis(), getTaxRate(), getId())); } setTaxPaymentsDue(payments); setRegionLastTaxPaymentAddedEntries(lastAdded); } @Override public Block getProtectBlock() { PSLocation psl = WGUtils.parsePSRegionToLocation(wgregion.getId()); return world.getBlockAt(psl.x, psl.y, psl.z); } @Override public PSProtectBlock getTypeOptions() { return ProtectionStones.getBlockOptions(getType()); } @Override public String getType() { return wgregion.getFlag(FlagHandler.PS_BLOCK_MATERIAL); } @Override public void setType(PSProtectBlock type) { super.setType(type); getWGRegion().setFlag(FlagHandler.PS_BLOCK_MATERIAL, type.type); } @Override public boolean isOwner(UUID uuid) { return wgregion.getOwners().contains(uuid); } @Override public boolean isMember(UUID uuid) { return wgregion.getMembers().contains(uuid); } @Override public ArrayList<UUID> getOwners() { return new ArrayList<>(wgregion.getOwners().getUniqueIds()); } @Override public ArrayList<UUID> getMembers() { return new ArrayList<>(wgregion.getMembers().getUniqueIds()); } @Override public void addOwner(UUID uuid) { if (uuid == null) return; wgregion.getOwners().addPlayer(uuid); } @Override public void addMember(UUID uuid) { if (uuid == null) return; wgregion.getMembers().addPlayer(uuid); } @Override public void removeOwner(UUID uuid) { if (uuid == null) return; // remove tax autopayer if the player is the autopayer if (getTaxAutopayer() != null && getTaxAutopayer().equals(uuid)) { setTaxAutopayer(null); } if (getLandlord() != null && getLandlord().equals(uuid)) { // remove rents if the player is the landlord if (getRentStage() == RentStage.LOOKING_FOR_TENANT || getRentStage() == RentStage.RENTING) { if (getTenant() != null) { PSPlayer tenant = PSPlayer.fromUUID(getTenant()); if (tenant.getOfflinePlayer().isOnline()) { PSL.msg(Bukkit.getPlayer(getTenant()), PSL.RENT_TENANT_STOPPED_TENANT.msg() .replace("%region%", getName() != null ? getName() : getId())); } } removeRenting(); // this needs to be called before removing the player, since it adds the player back } setLandlord(null); // in case the player was selling the region } if (wgregion.getOwners().contains(uuid)) wgregion.getOwners().removePlayer(uuid); } @Override public void removeMember(UUID uuid) { if (uuid == null) return; if (wgregion.getMembers().contains(uuid)) wgregion.getMembers().removePlayer(uuid); } @Override public List<BlockVector2> getPoints() { return wgregion.getPoints(); } @Override public List<PSRegion> getMergeableRegions(Player p) { return WGUtils.findOverlapOrAdjacentRegions(getWGRegion(), getWGRegionManager(), getWorld()) .stream() .map(r -> PSRegion.fromWGRegion(getWorld(), r)) .filter(r -> r != null && r.getTypeOptions() != null && !r.getId().equals(getId())) .filter(r -> r.getTypeOptions().allowMerging) .filter(r -> r.isOwner(p.getUniqueId()) || p.hasPermission("protectionstones.admin")) .filter(r -> WGUtils.canMergeRegionTypes(getTypeOptions(), r)) .collect(Collectors.toList()); } @Override public boolean deleteRegion(boolean deleteBlock) { return deleteRegion(deleteBlock, null); } @Override public boolean deleteRegion(boolean deleteBlock, Player cause) { PSRemoveEvent event = new PSRemoveEvent(this, cause); Bukkit.getPluginManager().callEvent(event); if (event.isCancelled()) { // if event was cancelled, prevent execution return false; } // set the physical block to air if (deleteBlock && !this.isHidden()) { this.getProtectBlock().setType(Material.AIR); } // remove name from cache if (getName() != null) { HashMap<String, ArrayList<String>> rIds = ProtectionStones.regionNameToID.get(getWorld().getUID()); if (rIds != null && rIds.containsKey(getName())) { if (rIds.get(getName()).size() == 1) { rIds.remove(getName()); } else { rIds.get(getName()).remove(getId()); } } } // remove region from WorldGuard // specify UNSET_PARENT_IN_CHILDREN removal strategy so that region children don't get deleted rgmanager.removeRegion(wgregion.getId(), RemovalStrategy.UNSET_PARENT_IN_CHILDREN); return true; } @Override public ProtectedRegion getWGRegion() { return wgregion; } }
18,824
Java
.java
espidev/ProtectionStones
64
30
90
2018-09-17T22:12:12Z
2023-11-13T03:14:47Z
PSRegion.java
/FileExtraction/Java_unseen/espidev_ProtectionStones/src/main/java/dev/espi/protectionstones/PSRegion.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package dev.espi.protectionstones; import com.sk89q.worldedit.math.BlockVector2; import com.sk89q.worldguard.protection.managers.RegionManager; import com.sk89q.worldguard.protection.regions.ProtectedRegion; import dev.espi.protectionstones.utils.BlockUtil; import dev.espi.protectionstones.utils.WGUtils; import net.milkbowl.vault.economy.EconomyResponse; import org.bukkit.Bukkit; import org.bukkit.Location; import org.bukkit.Material; import org.bukkit.World; import org.bukkit.block.Block; import org.bukkit.entity.Player; import javax.annotation.Nullable; import java.util.*; import static com.google.common.base.Preconditions.checkNotNull; /** * Represents an instance of a ProtectionStones protected region. */ public abstract class PSRegion { RegionManager rgmanager; World world; PSRegion(RegionManager rgmanager, World world) { this.rgmanager = checkNotNull(rgmanager); this.world = checkNotNull(world); } // ~~~~~~~~~~~~~~~~~ static ~~~~~~~~~~~~~~~~~ /** * Get the protection stone region that the location is in, or the closest one if there are overlapping regions. * Returns either {@link PSGroupRegion}, {@link PSStandardRegion} or {@link PSMergedRegion}. * * @param l the location * @return the {@link PSRegion} object if the location is in a region, or null if the location is not in a region */ public static PSRegion fromLocation(Location l) { PSRegion r = fromLocationUnsafe(l); return r == null || r.getTypeOptions() == null ? null : r; } /** * Get the protection stone region that the location is in, or the closest one if there are overlapping regions. * May return a region with an unconfigured block type (getTypeOptions returns null). * Returns either {@link PSGroupRegion}, {@link PSStandardRegion} or {@link PSMergedRegion}. * * @param l the location * @return the {@link PSRegion} object if the location is in a region, or null if the location is not in a region */ public static PSRegion fromLocationUnsafe(Location l) { checkNotNull(checkNotNull(l).getWorld()); RegionManager rgm = WGUtils.getRegionManagerWithWorld(l.getWorld()); if (rgm == null) return null; // check exact location first for merged region block PSMergedRegion pr = PSMergedRegion.getMergedRegion(l); if (pr != null) return pr; return fromLocationGroupUnsafe(l); } /** * Get the protection stone parent region that the location is in. * Returns either {@link PSGroupRegion} or {@link PSStandardRegion}. * * @param l the location * @return the {@link PSRegion} object if the location is in a region, or null if the location is not in a region */ public static PSRegion fromLocationGroup(Location l) { PSRegion r = fromLocationGroupUnsafe(l); return r == null || r.getTypeOptions() == null ? null : r; } /** * Get the protection stone parent region that the location is in. * May return a region with an unconfigured block type (getTypeOptions returns null). * Returns either {@link PSGroupRegion} or {@link PSStandardRegion}. * * @param l the location * @return the {@link PSRegion} object if the location is in a region, or null if the location is not in a region */ public static PSRegion fromLocationGroupUnsafe(Location l) { checkNotNull(checkNotNull(l).getWorld()); RegionManager rgm = WGUtils.getRegionManagerWithWorld(l.getWorld()); if (rgm == null) return null; // check if location is in a region String psID = WGUtils.matchLocationToPSID(l); ProtectedRegion r = rgm.getRegion(psID); if (r == null) { return null; } else if (r.getFlag(FlagHandler.PS_MERGED_REGIONS) != null) { return new PSGroupRegion(r, rgm, l.getWorld()); } else { return new PSStandardRegion(r, rgm, l.getWorld()); } } /** * Get the protection stone region with the world and region. * It returns a WGRegion with a null type if the block type isn't configured in the config. * * @param w the world * @param r the WorldGuard region * @return the {@link PSRegion} based on the parameters, or null if the region given is not a protectionstones region */ public static PSRegion fromWGRegion(World w, ProtectedRegion r) { if (!ProtectionStones.isPSRegionFormat(r)) return null; if (r.getFlag(FlagHandler.PS_MERGED_REGIONS) != null) { return new PSGroupRegion(r, WGUtils.getRegionManagerWithWorld(checkNotNull(w)), w); } else { return new PSStandardRegion(r, WGUtils.getRegionManagerWithWorld(checkNotNull(w)), w); } } /** * Get the protection stones regions that have the given name as their set nickname (/ps name) * * @param w the world to look for regions in * @param name the nickname of the region * @return the list of regions that have that name */ public static List<PSRegion> fromName(World w, String name) { RegionManager rgm = WGUtils.getRegionManagerWithWorld(w); if (rgm == null) return new ArrayList<>(); List<PSRegion> l = new ArrayList<>(); List<String> rIds = ProtectionStones.regionNameToID.get(w.getUID()).get(name); if (rIds == null) return l; for (int i = 0; i < rIds.size(); i++) { String id = rIds.get(i); if (rgm.getRegion(id) == null) { // cleanup cache rIds.remove(i); i--; } else { l.add(fromWGRegion(w, rgm.getRegion(id))); } } return l; } /** * Get the protection stones regions that have the given name as their set nickname (/ps name), from all worlds. * * @param name the nickname of the regions * @return the map of worlds, to the regions that have the name */ public static HashMap<World, List<PSRegion>> fromName(String name) { HashMap<World, List<PSRegion>> regions = new HashMap<>(); for (UUID worldUid : ProtectionStones.regionNameToID.keySet()) { World w = Bukkit.getWorld(worldUid); regions.put(w, fromName(w, name)); } return regions; } // ~~~~~~~~~~~ instance ~~~~~~~~~~~~~~~~ /** * @return gets the world that the region is in */ public World getWorld() { return world; } @Deprecated public String getID() { return getId(); } /** * Get the WorldGuard ID of the region. Note that this is not guaranteed to be unique between worlds. * @return the id of the region */ public abstract String getId(); /** * Get the name (nickname) of the region from /ps name. * @return the name of the region, or null if the region does not have a name */ public abstract String getName(); /** * Set the name of the region (from /ps name). * @param name new name, or null to remove the name */ public abstract void setName(String name); /** * Set the parent of this region. * @param r the region to be the parent, or null for no parent * @throws ProtectedRegion.CircularInheritanceException thrown when the parent already inherits from the child */ public abstract void setParent(PSRegion r) throws ProtectedRegion.CircularInheritanceException; /** * Get the parent of this region, if there is one. * @return the parent of the region, or null if there isn't one */ public abstract PSRegion getParent(); /** * Get the location of the set home the region has (for /ps tp). * @return the location of the home, or null if the ps_home flag is not set. */ public abstract Location getHome(); /** * Set the home of the region (internally changes the flag). * @param blockX block x location * @param blockY block y location * @param blockZ block z location */ public abstract void setHome(double blockX, double blockY, double blockZ); /** * Set the home of the region (internally changes the flag). * @param blockX block x location * @param blockY block y location * @param blockZ block z location * @param yaw location yaw * @param pitch location pitch */ public abstract void setHome(double blockX, double blockY, double blockZ, float yaw, float pitch); // -=-=-=-=- Selling, Buying, Renting -=-=-=-=- public enum RentStage { NOT_RENTING, LOOKING_FOR_TENANT, RENTING } /** * @return whether or not the region is for sale */ public abstract boolean forSale(); /** * MUST BE CALLED when setting up the region to be sold or cancelling sale * * @param forSale whether or not the region is for sale * @param landlord the owner of the region * @param price the price to sell for */ public abstract void setSellable(boolean forSale, UUID landlord, double price); /** * Sells the region to a player at the price listed. * @param player player to transfer the region to */ public abstract void sell(UUID player); /** * @return get the stage of the renting process */ public abstract RentStage getRentStage(); /** * Get the landlord of the region. * @return returns the UUID of the landlord, or null if there is none. */ public abstract UUID getLandlord(); /** * Set the landlord of the region. * @param landlord uuid of landlord, or null to remove */ public abstract void setLandlord(UUID landlord); /** * Get the tenant of the region. * @return returns the UUID of the tenant, or null if there is none. */ public abstract UUID getTenant(); /** * Set the tenant of the region * @param tenant uuid of tenant, or null to remove */ public abstract void setTenant(UUID tenant); /** * Get the rent period of the region * @return returns the rent duration, or null if there is none */ public abstract String getRentPeriod(); /** * Set the rent period of the region * @param s the duration between rent payments (d h m s), or null to remove */ public abstract void setRentPeriod(String s); /** * Get the price of the region * This applies to either the rent or the full purchase of a region. * * @return the price of the region during rent payments, or null if there is no rent */ public abstract Double getPrice(); /** * Set the price of the region. * This applies to either the rent or the full purchase of a region. * * @param price the price of the region, or null if there is no rent */ public abstract void setPrice(Double price); /** * Set the unix timestamp of when rent was last paid. * @param timestamp the unix timestamp of when rent was last paid, or null */ public abstract void setRentLastPaid(Long timestamp); /** * Get the unix timestamp of when rent was last paid. * @return the unix timestamp of when rent was last paid, or null if not renting */ public abstract Long getRentLastPaid(); /** * MUST BE CALLED when the region is looking for a tenant. * * @param landlord the landlord of the region * @param rentPeriod the rent period (d h m s) of the region * @param rentPrice the price to charge during each rent payment */ public abstract void setRentable(UUID landlord, String rentPeriod, double rentPrice); /** * Starts renting process (adds to rent queue) tenant. * MUST BE CALLED when renting the region out to a tenant. * * @param landlord the landlord of the region * @param tenant the tenant of the region * @param rentPeriod the rent period (d h m s) of the region * @param rentPrice the price to charge during each rent payment */ public abstract void rentOut(UUID landlord, UUID tenant, String rentPeriod, double rentPrice); /** * Stop renting process and remove tenant. * MUST BE CALLED when removing rent. */ public abstract void removeRenting(); // -=-=-=-=- Taxes -=-=-=-=- public static class TaxPayment implements Comparable<TaxPayment> { long whenPaymentIsDue; double amount; String regionId; // the region that caused the payment (especially applicable for group regions); also used since hashsets don't have duplicates public TaxPayment(long whenPaymentIsDue, double amount, String regionId) { this.whenPaymentIsDue = whenPaymentIsDue; this.amount = amount; this.regionId = regionId; } /** * Convert a flag entry to a tax payment object. The flag entry is in the form "timestamp amount regionId". * @param s the flag value * @return the tax payment object, or null if the string was invalid */ public static TaxPayment fromString(String s) { String[] arr = s.split(" "); if (arr.length < 3) return null; try { return new TaxPayment(Long.parseLong(arr[0]), Double.parseDouble(arr[1]), arr[2]); } catch (NumberFormatException e) { return null; } } /** * Converts the tax payment object into its flag representation. * @return the flag representation of this object */ public String toFlagEntry() { return whenPaymentIsDue + " " + amount + " " + regionId; } @Override public int compareTo(TaxPayment t) { return Long.compare(whenPaymentIsDue, t.whenPaymentIsDue); } public long getWhenPaymentIsDue() { return this.whenPaymentIsDue; } public double getAmount() { return this.amount; } public String getRegionId() { return this.regionId; } public void setWhenPaymentIsDue(long whenPaymentIsDue) { this.whenPaymentIsDue = whenPaymentIsDue; } public void setAmount(double amount) { this.amount = amount; } public void setRegionId(String regionId) { this.regionId = regionId; } } public static class LastRegionTaxPaymentEntry { String regionId; long lastPaymentAdded; public LastRegionTaxPaymentEntry(String regionId, long lastPaymentAdded) { this.regionId = regionId; this.lastPaymentAdded = lastPaymentAdded; } /** * Convert a flag entry to a last region tax payment entry object. The flag entry is in the form "regionId timestamp". * @param s the flag value * @return the last region tax payment entry object, or null if the string was invalid */ public static LastRegionTaxPaymentEntry fromString(String s) { String[] arr = s.split(" "); if (arr.length < 2) return null; try { return new LastRegionTaxPaymentEntry(arr[0], Long.parseLong(arr[1])); } catch (NumberFormatException e) { return null; } } /** * Converts the last region tax payment entry object into its flag representation. * @return the flag representation of this object */ public String toFlagEntry() { return regionId + " " + lastPaymentAdded; } public String getRegionId() { return this.regionId; } public long getLastPaymentAdded() { return this.lastPaymentAdded; } public void setRegionId(String regionId) { this.regionId = regionId; } public void setLastPaymentAdded(long lastPaymentAdded) { this.lastPaymentAdded = lastPaymentAdded; } } /** * Get the tax rate for this region type. * @return the tax rate */ public double getTaxRate() { return getTypeOptions().taxAmount; } /** * Get the formatted period(s) between tax payments for this region type. * If you simply wanted the number of seconds, use getTypeOptions().taxPeriod * @return the duration between tax payments, or multiple if there are several different ones */ public abstract String getTaxPeriod(); /** * Get the formatted period(s) allowed for the payment of tax. * If you simply wanted the number of seconds, use getTypeOptions().taxPaymentTime * @return the duration of time allowed to pay a tax, or multiple if there are several different ones */ public abstract String getTaxPaymentPeriod(); /** * Get the list of tax payments that are due. * @return the list of tax payments outstanding */ public abstract List<TaxPayment> getTaxPaymentsDue(); /** * Save the list of tax payments due onto the region. * @param taxPayments the full list of tax payments that are due */ public abstract void setTaxPaymentsDue(List<TaxPayment> taxPayments); /** * Get the list of timestamps of the last time regions and sub regions have added to the tax payments list. * @return the list of the last time regions and sub regions have added to the tax payment list */ public abstract List<LastRegionTaxPaymentEntry> getRegionLastTaxPaymentAddedEntries(); /** * Save the list of timestamps of the last time regions and sub regions have added to the tax payments list on to the base region. * @param entries the full list of {@link LastRegionTaxPaymentEntry} entries. */ public abstract void setRegionLastTaxPaymentAddedEntries(List<LastRegionTaxPaymentEntry> entries); /** * Get the player that is set to autopay the tax amount. * @return the player that is set as the autopayer, or null if no player is set */ public abstract UUID getTaxAutopayer(); /** * Set a player to auto-pay taxes for this region. * @param player the player to use to auto-pay taxes */ public abstract void setTaxAutopayer(UUID player); /** * Pay outstanding taxes. * It will only withdraw the amount required to pay the taxes, and will take up to the amount * specified if the outstanding payments are larger. * * @param p the player to take money from * @param amount the amount to take * @return the {@link EconomyResponse} returned by Vault */ public abstract EconomyResponse payTax(PSPlayer p, double amount); /** * Check if any tax payments are now late (exceeded tax payment time shown in config). * @return whether or not any tax payments are now late */ public abstract boolean isTaxPaymentLate(); /** * Update with the current time and calculate any tax payments that are now due. */ public abstract void updateTaxPayments(); // -=-=-=-=- Other -=-=-=-=-=- /** * Must be run sync (calls Bukkit API) * @return whether or not the protection block is hidden (/ps hide) */ public boolean isHidden() { return !this.getType().equals(BlockUtil.getProtectBlockType(this.getProtectBlock())); } /** * Hides the protection block, if it is not hidden. * @return whether or not the block was hidden */ public boolean hide() { if (!isHidden()) { getProtectBlock().setType(Material.AIR); return true; } else { return false; } } /** * Unhides the protection block, if it is hidden. * @return whether or not the block was unhidden */ public boolean unhide() { if (isHidden()) { if (getType().startsWith("PLAYER_HEAD")) { getProtectBlock().setType(Material.PLAYER_HEAD); if (getType().split(":").length > 1) { BlockUtil.setHeadType(getType(), getProtectBlock()); } } else { getProtectBlock().setType(Material.getMaterial(getType())); } return true; } else { return false; } } /** * Toggle whether or not the protection block is hidden. */ public void toggleHide() { if (!hide()) unhide(); } /** * This method returns the block that is supposed to contain the protection block. * Warning: If the protection stone is hidden, this will give the block that took its place! * * @return returns the block that may contain the protection stone */ public abstract Block getProtectBlock(); /** * @return returns the type, or null if the type is not configured */ @Nullable public abstract PSProtectBlock getTypeOptions(); /** * @return returns the protect block type (may include custom player heads PLAYER_HEAD:playername) that the region is */ public abstract String getType(); /** * Change the type of the protection region. * @param type the type of protection region to switch to */ public void setType(PSProtectBlock type) { if (!isHidden()) { Material set = Material.matchMaterial(type.type) == null ? Material.PLAYER_HEAD : Material.matchMaterial(type.type); getProtectBlock().setType(set); if (type.type.startsWith("PLAYER_HEAD") && type.type.split(":").length > 1) { BlockUtil.setHeadType(type.type, getProtectBlock()); } } } /** * Get whether or not a player is an owner of this region. * @param uuid the player's uuid * @return whether or not the player is a member */ public abstract boolean isOwner(UUID uuid); /** * Get whether or not a player is a member of this region. * @param uuid the player's uuid * @return whether or not the player is a member */ public abstract boolean isMember(UUID uuid); /** * @return returns a list of the owners of the protected region */ public abstract ArrayList<UUID> getOwners(); /** * @return returns a list of the members of the protected region */ public abstract ArrayList<UUID> getMembers(); /** * Add an owner to the region. * @param uuid the uuid of the player to add */ public abstract void addOwner(UUID uuid); /** * Add a member to the region. * @param uuid the uuid of the player to add */ public abstract void addMember(UUID uuid); /** * Remove an owner of the region, and deal with side-effects. * Examples of side-effects: removing player as landlord, removing player as auto taxpayer * @param uuid the uuid of the player to remove */ public abstract void removeOwner(UUID uuid); /** * Remove a member of the region, and deal with side-effects * @param uuid the uuid of the player to remove */ public abstract void removeMember(UUID uuid); /** * @return returns a list of the bounding points of the protected region */ public abstract List<BlockVector2> getPoints(); /** * Get a list of regions that the current region can merge into, taking into account a player's permissions. * * @param p the player to compare permissions with * @return the list of regions that the current region can merge into */ public abstract List<PSRegion> getMergeableRegions(Player p); /** * Deletes the region forever. Can be cancelled by event cancellation. * * @param deleteBlock whether or not to also set the protection block to air (if not hidden) * @return whether or not the region was able to be successfully removed */ public abstract boolean deleteRegion(boolean deleteBlock); /** * Deletes the region forever. Can be cancelled by event cancellation. * * @param deleteBlock whether or not to also set the protection block to air (if not hidden) * @param cause the player that caused the region to break * @return whether or not the region was able to be successfully removed */ public abstract boolean deleteRegion(boolean deleteBlock, Player cause); /** * @return returns the WorldGuard region object directly */ public abstract ProtectedRegion getWGRegion(); /** * @return returns the WorldGuard region manager that stores this region */ public RegionManager getWGRegionManager() { return rgmanager; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; PSRegion psRegion = (PSRegion) o; return Objects.equals(getId(), psRegion.getId()) && Objects.equals(getWorld(), psRegion.getWorld()); } @Override public int hashCode() { return Objects.hash(getId(), getWorld()); } }
25,920
Java
.java
espidev/ProtectionStones
64
30
90
2018-09-17T22:12:12Z
2023-11-13T03:14:47Z
PSLocation.java
/FileExtraction/Java_unseen/espidev_ProtectionStones/src/main/java/dev/espi/protectionstones/PSLocation.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package dev.espi.protectionstones; public class PSLocation { public int x, y, z; public PSLocation(int x, int y, int z) { this.x = x; this.y = y; this.z = z; } }
854
Java
.java
espidev/ProtectionStones
64
30
90
2018-09-17T22:12:12Z
2023-11-13T03:14:47Z
PSProtectBlock.java
/FileExtraction/Java_unseen/espidev_ProtectionStones/src/main/java/dev/espi/protectionstones/PSProtectBlock.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package dev.espi.protectionstones; import com.electronwill.nightconfig.core.conversion.Path; import com.electronwill.nightconfig.core.conversion.SpecDoubleInRange; import com.electronwill.nightconfig.core.conversion.SpecIntInRange; import com.sk89q.worldguard.protection.flags.Flag; import org.bukkit.inventory.ItemStack; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.List; /** * Object to represent a protection block as defined in config (blocks folder). The fields are the exact same as * the ones in the config. */ public class PSProtectBlock { // Annotations are for types that have names that aren't the same as the config name // Check here for help: https://github.com/TheElectronWill/Night-Config // main section public String type, alias; @Path("description") public String description; @Path("restrict_obtaining") public boolean restrictObtaining; @Path("world_list_type") public String worldListType; @Path("worlds") public List<String> worlds; @Path("prevent_block_place_in_restricted_world") public boolean preventBlockPlaceInRestrictedWorld; @Path("allow_placing_in_wild") public boolean allowPlacingInWild; @Path("placing_bypasses_wg_passthrough") public Boolean placingBypassesWGPassthrough; // region section @Path("region.distance_between_claims") public int distanceBetweenClaims; @Path("region.x_radius") @SpecIntInRange(min = 0, max = Integer.MAX_VALUE) public int xRadius; @Path("region.y_radius") @SpecIntInRange(min = -1, max = Integer.MAX_VALUE) public int yRadius; @Path("region.z_radius") @SpecIntInRange(min = 0, max = Integer.MAX_VALUE) public int zRadius; @Path("region.chunk_radius") @SpecIntInRange(min = -1, max = Integer.MAX_VALUE) public int chunkRadius; @Path("region.home_x_offset") public double homeXOffset; @Path("region.home_y_offset") public double homeYOffset; @Path("region.home_z_offset") public double homeZOffset; @Path("region.flags") public List<String> flags; @Path("region.allowed_flags") public List<String> allowedFlagsRaw; @Path("region.hidden_flags_from_info") public List<String> hiddenFlagsFromInfo; @Path("region.priority") public int priority; @Path("region.allow_overlap_unowned_regions") public boolean allowOverlapUnownedRegions; @Path("region.allow_other_regions_to_overlap") public String allowOtherRegionsToOverlap; @Path("region.allow_merging") public boolean allowMerging; @Path("region.allowed_merging_into_types") public List<String> allowedMergingIntoTypes; // block data section @Path("block_data.display_name") public String displayName; @Path("block_data.lore") public List<String> lore; @Path("block_data.enchanted_effect") public boolean enchantedEffect; @Path("block_data.price") @SpecDoubleInRange(min = 0.0, max = Double.MAX_VALUE) public double price; @Path("block_data.allow_craft_with_custom_recipe") public boolean allowCraftWithCustomRecipe; @Path("block_data.custom_recipe") public List<List<String>> customRecipe; @Path("block_data.recipe_amount") @SpecIntInRange(min = 0, max = 64) public int recipeAmount; @Path("block_data.custom_model_data") public int customModelData; // economy section @Path("economy.tax_amount") public double taxAmount; @Path("economy.tax_period") @SpecIntInRange(min = -1, max = Integer.MAX_VALUE) public int taxPeriod; @Path("economy.tax_payment_time") @SpecIntInRange(min = 1, max = Integer.MAX_VALUE) public int taxPaymentTime; @Path("economy.start_with_tax_autopay") public boolean startWithTaxAutopay; @Path("economy.tenant_rent_role") public String tenantRentRole; @Path("economy.landlord_still_owner") public boolean landlordStillOwner; // behaviour section @Path("behaviour.auto_hide") public boolean autoHide; @Path("behaviour.auto_merge") public boolean autoMerge; @Path("behaviour.no_drop") public boolean noDrop; @Path("behaviour.prevent_piston_push") public boolean preventPistonPush; @Path("behaviour.prevent_explode") public boolean preventExplode; @Path("behaviour.destroy_region_when_explode") public boolean destroyRegionWhenExplode; @Path("behaviour.prevent_silk_touch") public boolean preventSilkTouch; @Path("behaviour.cost_to_place") @SpecDoubleInRange(min = 0.0, max = Double.MAX_VALUE) public double costToPlace; @Path("behaviour.allow_smelt_item") public boolean allowSmeltItem; @Path("behaviour.allow_use_in_crafting") public boolean allowUseInCrafting; // player section @Path("player.allow_shift_right_break") public boolean allowShiftRightBreak; @Path("player.prevent_teleport_in") public boolean preventTeleportIn; @Path("player.no_moving_when_tp_waiting") public boolean noMovingWhenTeleportWaiting; @Path("player.tp_waiting_seconds") @SpecIntInRange(min = 0, max = Integer.MAX_VALUE) public int tpWaitingSeconds; @Path("player.prevent_ps_get") public boolean preventPsGet; @Path("player.prevent_ps_home") public boolean preventPsHome; @Path("player.permission") public String permission; // event section @Path("event.enable") public boolean eventsEnabled; @Path("event.on_region_create") public List<String> regionCreateCommands; @Path("event.on_region_destroy") public List<String> regionDestroyCommands; // non-config items public HashMap<Flag<?>, Object> regionFlags = new HashMap<>(); public LinkedHashMap<String, List<String>> allowedFlags = new LinkedHashMap<>(); /** * Get the protection block item for this specific protection block. * * @return the item with NBT and other metadata to signify that it was created by protection stones */ public ItemStack createItem() { return ProtectionStones.createProtectBlockItem(this); } }
6,772
Java
.java
espidev/ProtectionStones
64
30
90
2018-09-17T22:12:12Z
2023-11-13T03:14:47Z
PSL.java
/FileExtraction/Java_unseen/espidev_ProtectionStones/src/main/java/dev/espi/protectionstones/PSL.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package dev.espi.protectionstones; import org.apache.commons.lang.StringUtils; import org.bukkit.ChatColor; import org.bukkit.command.CommandSender; import org.bukkit.configuration.file.YamlConfiguration; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.io.File; import java.io.IOException; import java.util.Arrays; import java.util.Objects; import java.util.regex.Matcher; import java.util.regex.Pattern; public enum PSL { // messages.yml COOLDOWN("cooldown", ChatColor.GOLD + "Warning: " + ChatColor.GRAY + "Please wait for %time% seconds before placing again!"), NO_SUCH_COMMAND("no_such_command", ChatColor.RED + "No such command. please type /ps help for more info"), NO_ACCESS("no_access", ChatColor.RED + "You are not allowed to do that here."), NO_ROOM_IN_INVENTORY("no_room_in_inventory", ChatColor.RED + "You don't have enough room in your inventory."), NO_ROOM_DROPPING_ON_FLOOR("no_room_dropping_on_floor", ChatColor.RED + "You don't have enough room in your inventory. Dropping item on floor."), INVALID_BLOCK("invalid_block", ChatColor.RED + "Invalid protection block."), NOT_ENOUGH_MONEY("not_enough_money", ChatColor.RED + "You don't have enough money! The price is %price%."), PAID_MONEY("paid_money", ChatColor.AQUA + "You've paid $%price%."), INVALID_WORLD("invalid_world", ChatColor.RED + "Invalid world."), MUST_BE_PLAYER("must_be_player", ChatColor.RED + "You must be a player to execute this command."), GO_BACK_PAGE("go_back_page", "Go back a page."), GO_NEXT_PAGE("go_next_page", "Go to next page."), PAGE_DOES_NOT_EXIST("page_does_not_exist", ChatColor.RED + "Page does not exist."), HELP("help", ChatColor.DARK_GRAY + "" + ChatColor.STRIKETHROUGH + "=====" + ChatColor.RESET + " PS Help " + ChatColor.DARK_GRAY + ChatColor.STRIKETHROUGH + "=====\n" + ChatColor.AQUA + "> " + ChatColor.GRAY + "/ps help"), HELP_NEXT("help_next", ChatColor.GRAY + "Do /ps help %page% to go to the next page!"), COMMAND_REQUIRES_PLAYER_NAME("command_requires_player_name", ChatColor.RED + "This command requires a player name."), NO_PERMISSION_TOGGLE("no_permission_toggle", ChatColor.RED + "You don't have permission to use the toggle command."), NO_PERMISSION_CREATE("no_permission_create", ChatColor.RED + "You don't have permission to place a protection block."), NO_PERMISSION_CREATE_SPECIFIC("no_permission_create_specific", ChatColor.RED + "You don't have permission to place this protection block type."), NO_PERMISSION_DESTROY("no_permission_destroy", ChatColor.RED + "You don't have permission to destroy a protection block."), NO_PERMISSION_MEMBERS("no_permission_members", "&cYou don't have permission to use member commands."), NO_PERMISSION_OWNERS("no_permission_owners", "&cYou don't have permission to use owner commands."), NO_PERMISSION_ADMIN("no_permission_admin", ChatColor.RED + "You do not have permission to use that command."), NO_PERMISSION_COUNT("no_permission_count", ChatColor.RED + "You do not have permission to use that command."), NO_PERMISSION_COUNT_OTHERS("no_permission_count_others", ChatColor.RED + "You do not have permission to use that command."), NO_PERMISSION_FLAGS("no_permission_flags", "&cYou do not have permission to use flag commands."), NO_PERMISSION_PER_FLAG("no_permission_per_flag", ChatColor.RED + "You do not have permission to use that flag."), NO_PERMISSION_RENT("no_permission_rent", ChatColor.RED + "You do not have permission for renting."), NO_PERMISSION_TAX("no_permission_tax", ChatColor.RED + "You do not have permission to use the tax command."), NO_PERMISSION_BUYSELL("no_permission_buysell", ChatColor.RED + "You do not have permission to buy and sell regions."), NO_PERMISSION_UNHIDE("no_permission_unhide", ChatColor.RED + "You do not have permission to unhide protection blocks."), NO_PERMISSION_HIDE("no_permission_hide", ChatColor.RED + "You do not have permission to hide protection blocks."), NO_PERMISSION_INFO("no_permission_info", ChatColor.RED + "You do not have permission to use the region info command."), NO_PERMISSION_PRIORITY("no_permission_priority", ChatColor.RED + "You do not have permission to use the priority command."), NO_PERMISSION_REGION("no_permission_region", ChatColor.RED + "You do not have permission to use region commands."), NO_PERMISSION_TP("no_permission_tp", ChatColor.RED + "You do not have permission to teleport to other players' protection blocks."), NO_PERMISSION_HOME("no_permission_home", ChatColor.RED + "You do not have permission to teleport to your protection blocks."), NO_PERMISSION_UNCLAIM("no_permission_unclaim", ChatColor.RED + "You do not have permission to use the unclaim command."), NO_PERMISSION_UNCLAIM_REMOTE("no_permission_unclaim_remote", ChatColor.RED + "You do not have permission to use the unclaim remote command."), NO_PERMISSION_VIEW("no_permission_view", ChatColor.RED + "You do not have permission to use the view command."), NO_PERMISSION_GIVE("no_permission_give", ChatColor.RED + "You do not have permission to use the give command."), NO_PERMISSION_GET("no_permission_get", ChatColor.RED + "You do not have permission to use the get command."), NO_PERMISSION_SETHOME("no_permission_sethome", ChatColor.RED + "You do not have permission to use the sethome command."), NO_PERMISSION_LIST("no_permission_list", ChatColor.RED + "You do not have permission to use the list command."), NO_PERMISSION_LIST_OTHERS("no_permission_list_others", ChatColor.RED + "You do not have permission to use the list command for others."), NO_PERMISSION_NAME("no_permission_name", ChatColor.RED + "You do not have permission to use the name command."), NO_PERMISSION_SETPARENT("no_permission_setparent", ChatColor.RED + "You do not have permission to use the setparent command."), NO_PERMISSION_SETPARENT_OTHERS("no_permission_setparent_others", ChatColor.RED + "You do not have permission to inherit from regions you don't own."), NO_PERMISSION_MERGE("no_permission_merge", ChatColor.RED + "You do not have permission to use /ps merge."), ADDED_TO_REGION("psregion.added_to_region", ChatColor.AQUA + "%player%" + ChatColor.GRAY + " has been added to this region."), ADDED_TO_REGION_SPECIFIC("psregion.added_to_region_specific", ChatColor.AQUA + "%player%" + ChatColor.GRAY + " has been added to region %region%."), REMOVED_FROM_REGION("psregion.removed_from_region", ChatColor.AQUA + "%player%" + ChatColor.GRAY + " has been removed from region."), REMOVED_FROM_REGION_SPECIFIC("psregion.removed_from_region_specific", ChatColor.AQUA + "%player%" + ChatColor.GRAY + " has been removed from region %region%."), NOT_IN_REGION("psregion.not_in_region", ChatColor.RED + "You are not in a protection stones region!"), PLAYER_NOT_FOUND("psregion.player_not_found", ChatColor.RED + "Player not found."), NOT_PS_REGION("psregion.not_ps_region", ChatColor.RED + "Not a protection stones region."), REGION_DOES_NOT_EXIST("psregion.region_does_not_exist", ChatColor.RED + "Region does not exist."), NO_REGIONS_OWNED("psregion.no_regions_owned", ChatColor.RED + "You don't own any protected regions in this world!"), NO_REGION_PERMISSION("psregion.no_region_permission", ChatColor.RED + "You do not have permission to do this in this region."), PROTECTED("psregion.protected", ChatColor.AQUA + "This area is now protected."), NO_LONGER_PROTECTED("psregion.no_longer_protected", ChatColor.YELLOW + "This area is no longer protected."), CANT_PROTECT_THAT("psregion.cant_protect_that", ChatColor.RED + "You can't protect that area."), REACHED_REGION_LIMIT("psregion.reached_region_limit", ChatColor.RED + "You can not have any more protected regions (%limit%)."), REACHED_PER_BLOCK_REGION_LIMIT("psregion.reached_per_block_region_limit", ChatColor.RED + "You can not have any more regions of this type (%limit%)."), WORLD_DENIED_CREATE("psregion.world_denied_create", ChatColor.RED + "You can not create protections in this world."), REGION_OVERLAP("psregion.region_overlap", ChatColor.RED + "You can not place a protection block here as it overlaps another region."), REGION_TOO_CLOSE("psregion.region_too_close", ChatColor.RED + "Your protection block must be a minimum of %num% blocks from the edge of other regions!"), REGION_CANT_TELEPORT("psregion.cant_teleport", ChatColor.RED + "Your teleportation was blocked by a protection region!"), SPECIFY_ID_INSTEAD_OF_ALIAS("psregion.specify_id_instead_of_alias", ChatColor.GRAY + "There were multiple regions found with this name! Please use an ID instead.\n Regions with this name: " + ChatColor.AQUA + "%regions%"), REGION_NOT_ADJACENT("psregion.region_not_adjacent", ChatColor.RED + "You've passed the limit of non-adjacent regions! Try putting your protection block closer to other regions you already own."), REGION_NOT_OVERLAPPING("psregion.not_overlapping", ChatColor.RED + "These regions don't overlap each other!"), MULTI_REGION_DOES_NOT_EXIST("psregion.multi_region_does_not_exist", "One of these regions don't exist!"), NO_REGION_HOLES("psregion.no_region_holes", ChatColor.RED + "Unprotected area detected inside region! This is not allowed!"), DELETE_REGION_PREVENTED_NO_HOLES("psregion.delete_region_prevented", ChatColor.GRAY + "The region could not be removed, possibly because it creates a hole in the existing region."), NOT_OWNER("psregion.not_owner", ChatColor.RED + "You are not an owner of this region!"), CANNOT_MERGE_RENTED_REGION("psregion.cannot_merge_rented_region", ChatColor.RED + "Cannot merge regions because region %region% is in the process of being rented out!"), NO_PERMISSION_REGION_TYPE("psregion.no_permission_region_type", ChatColor.RED + "You do not have permission to have this region type."), REGION_HIDDEN("psregion.hidden", ChatColor.GRAY + "The protection block is now hidden."), MUST_BE_PLACED_IN_EXISTING_REGION("psregion.must_be_placed_in_existing_region", ChatColor.RED + "This must be placed inside of an existing region!"), REGION_ALREADY_IN_LOCATION_IS_HIDDEN("psregion.already_in_location_is_hidden", ChatColor.RED + "A region already exists in this location (is the protection block hidden?)"), CANNOT_REMOVE_YOURSELF_LAST_OWNER("psregion.cannot_remove_yourself_last_owner", ChatColor.RED + "You cannot remove yourself as you are the last owner."), CANNOT_REMOVE_YOURSELF_FROM_ALL_REGIONS("psregion.cannot_remove_yourself_all_regions", ChatColor.RED + "You cannot remove yourself from all of your regions at once, for safety reasons."), // ps toggle TOGGLE_HELP("toggle.help", ChatColor.AQUA + "> " + ChatColor.GRAY + "/ps toggle|on|off"), TOGGLE_HELP_DESC("toggle.help_desc", "Use this command to turn on or off placement of protection blocks."), TOGGLE_ON("toggle.toggle_on", ChatColor.AQUA + "Protection block placement turned on."), TOGGLE_OFF("toggle.toggle_off", ChatColor.AQUA + "Protection block placement turned off."), // ps count COUNT_HELP("count.count_help", ChatColor.AQUA + "> " + ChatColor.GRAY + "/ps count [player (optional)]"), COUNT_HELP_DESC("count.count_help_desc", "Count the number of regions you own or another player."), PERSONAL_REGION_COUNT("count.personal_region_count", ChatColor.GRAY + "Your region count in this world: " + ChatColor.AQUA + "%num%"), PERSONAL_REGION_COUNT_MERGED("count.personal_region_count_merged", ChatColor.GRAY + "- Including each merged region: " + ChatColor.AQUA + "%num%"), OTHER_REGION_COUNT("count.other_region_count", ChatColor.GRAY + "%player%'s region count in this world: " + ChatColor.AQUA + "%num%"), OTHER_REGION_COUNT_MERGED("count.other_region_count_merged", ChatColor.GRAY + "- Including each merged region: " + ChatColor.AQUA + "%num%"), // ps flag FLAG_HELP("flag.help", ChatColor.AQUA + "> " + ChatColor.GRAY + "/ps flag [flagname] [value|null|default]"), FLAG_HELP_DESC("flag.help_desc", "Use this command to set a flag in your protected region."), FLAG_SET("flag.flag_set", ChatColor.AQUA + "%flag%" + ChatColor.GRAY + " flag has been set."), FLAG_NOT_SET("flag.flag_not_set", ChatColor.AQUA + "%flag%" + ChatColor.GRAY + " flag has " + ChatColor.RED + "not" + ChatColor.GRAY + " been set. Check your values again."), FLAG_PREVENT_EXPLOIT("flag.flag_prevent_exploit", ChatColor.RED + "This has been disabled to prevent exploits."), FLAG_PREVENT_EXPLOIT_HOVER("flag.flag_prevent_exploit_hover", ChatColor.RED + "Disabled for security reasons."), FLAG_GUI_HEADER("flag.gui_header", ChatColor.DARK_GRAY + "" + ChatColor.STRIKETHROUGH + "=====" + ChatColor.RESET + " Flags (click to change) " + ChatColor.DARK_GRAY + ChatColor.STRIKETHROUGH + "====="), FLAG_GUI_HOVER_SET("flag.gui_hover_set", ChatColor.AQUA + "Click to set."), FLAG_GUI_HOVER_SET_TEXT("flag.gui_hover_set_text", ChatColor.AQUA + "Click to change." + ChatColor.WHITE + "\nCurrent value:\n%value%"), FLAG_GUI_HOVER_CHANGE_GROUP("flag.hover_change_group", "Click to set this flag to apply to only %group%."), FLAG_GUI_HOVER_CHANGE_GROUP_NULL("flag.hover_change_group_null", ChatColor.RED + "You must set this flag to a value before changing the group."), // ps rent RENT_HELP("rent.help", ChatColor.AQUA + "> " + ChatColor.GRAY + "/ps rent"), RENT_HELP_DESC("rent.help_desc", "Use this command to manage rents (buying and selling)."), RENT_HELP_HEADER("rent.help_header", ChatColor.DARK_GRAY + "" + ChatColor.STRIKETHROUGH + "=====" + ChatColor.RESET + " Rent Help " + ChatColor.DARK_GRAY + ChatColor.STRIKETHROUGH + "====="), RENT_ALREADY_RENTING("rent.already_renting", ChatColor.RED + "The region is already being rented out! You must stop leasing the region first."), RENT_NOT_RENTED("rent.not_rented", ChatColor.RED + "This region is not being rented."), RENT_LEASE_SUCCESS("rent.lease_success", ChatColor.AQUA + "Region leasing terms set:\n" + ChatColor.AQUA + "Price: " + ChatColor.GRAY + "%price%\n" + ChatColor.AQUA + "Payment Term: " + ChatColor.GRAY + "%period%"), RENT_STOPPED("rent.stopped", ChatColor.AQUA + "Leasing stopped."), RENT_EVICTED("rent.evicted", ChatColor.GRAY + "Evicted tenant %tenant%."), RENT_NOT_RENTING("rent.not_renting", ChatColor.RED + "This region is not being rented out to tenants."), RENT_PAID_LANDLORD("rent.paid_landlord", ChatColor.AQUA + "%tenant%" + ChatColor.GRAY + " has paid " + ChatColor.AQUA + "$%price%" + ChatColor.GRAY + " for renting out " + ChatColor.AQUA + "%region%" + ChatColor.GRAY + "."), RENT_PAID_TENANT("rent.paid_tenant", ChatColor.GRAY + "Paid " + ChatColor.AQUA + "$%price%" + ChatColor.GRAY + " to " + ChatColor.AQUA + "%landlord%" + ChatColor.GRAY + " for region " + ChatColor.AQUA + "%region%" + ChatColor.GRAY + "."), RENT_RENTING_LANDLORD("rent.renting_landlord", ChatColor.AQUA + "%player%" + ChatColor.GRAY + " is now renting out region " + ChatColor.AQUA + "%region%" + ChatColor.GRAY + "."), RENT_RENTING_TENANT("rent.renting_tenant", ChatColor.GRAY + "You are now renting out region " + ChatColor.AQUA + "%region%" + ChatColor.GRAY + " for " + ChatColor.AQUA + "%price%" + ChatColor.GRAY + " per " + ChatColor.AQUA + "%period%" + ChatColor.GRAY + "."), RENT_NOT_TENANT("rent.not_tenant", ChatColor.RED + "You are not the tenant of this region!"), RENT_TENANT_STOPPED_LANDLORD("rent.tenant_stopped_landlord", ChatColor.AQUA + "%player%" + ChatColor.GRAY + " has stopped renting out region " + ChatColor.AQUA + "%region%" + ChatColor.GRAY + ". It is now available for others to rent."), RENT_TENANT_STOPPED_TENANT("rent.tenant_stopped_tenant", ChatColor.AQUA + "You have stopped renting out region %region%."), RENT_BEING_SOLD("rent.being_sold", ChatColor.RED + "The region is being sold! Do /ps sell stop first."), RENT_EVICT_NO_MONEY_TENANT("rent.evict_no_money_tenant", ChatColor.GRAY + "You have been " + ChatColor.RED + "evicted" + ChatColor.GRAY + " from region " + ChatColor.AQUA + "%region%" + ChatColor.GRAY + " because you do not have enough money (%price%) to pay for rent."), RENT_EVICT_NO_MONEY_LANDLORD("rent.evict_no_money_landlord", ChatColor.AQUA + "%tenant%" + ChatColor.GRAY + " has been " + ChatColor.RED + "evicted" + ChatColor.GRAY + " from region " + ChatColor.AQUA + "%region%" + ChatColor.GRAY + " because they are unable to afford rent."), RENT_CANNOT_RENT_OWN_REGION("rent.cannot_rent_own_region", ChatColor.RED + "You cannot rent your own region!"), RENT_REACHED_LIMIT("rent.reached_limit", ChatColor.RED + "You've reached the limit of regions you are allowed to rent!"), RENT_PRICE_TOO_LOW("rent.price_too_low", ChatColor.RED + "The rent price is too low (must be larger than %price%)."), RENT_PRICE_TOO_HIGH("rent.price_too_high", ChatColor.RED + "The rent price is too high (must be lower than %price%)."), RENT_PERIOD_TOO_SHORT("rent.period_too_short", ChatColor.RED + "The rent period is too short (must be longer than %period% seconds)."), RENT_PERIOD_TOO_LONG("rent.period_too_long", ChatColor.RED + "The rent period is too long (must be shorter than %period% seconds)."), RENT_PERIOD_INVALID("rent.period_invalid", ChatColor.RED + "Invalid period format! Example: 24h for once a day."), RENT_CANNOT_BREAK_WHILE_RENTING("rent.cannot_break_while_renting", ChatColor.RED + "You cannot break the region when it is being rented out."), // ps tax TAX_HELP("tax.help", ChatColor.AQUA + "> " + ChatColor.GRAY + "/ps tax"), TAX_HELP_DESC("tax.help_desc", "Use this command to manage and pay taxes."), TAX_HELP_HEADER("tax.help_header", ChatColor.DARK_GRAY + "" + ChatColor.STRIKETHROUGH + "=====" + ChatColor.RESET + " Taxes Help " + ChatColor.DARK_GRAY + ChatColor.STRIKETHROUGH + "====="), TAX_DISABLED_REGION("tax.disabled_region", ChatColor.RED + "Taxes are disabled for this region."), TAX_SET_AS_AUTOPAYER("tax.set_as_autopayer", ChatColor.GRAY + "Taxes for region " + ChatColor.AQUA + "%region%" + ChatColor.GRAY + " will now be automatically paid by you."), TAX_SET_NO_AUTOPAYER("tax.set_no_autopayer", ChatColor.GRAY + "Taxes for region " + ChatColor.AQUA + "%region%" + ChatColor.GRAY + " now have to be manually paid for."), TAX_PAID("tax.paid", ChatColor.GRAY + "Paid " + ChatColor.AQUA + "$%amount%" + ChatColor.GRAY + " in taxes for region " + ChatColor.AQUA + "%region%" + ChatColor.GRAY + "."), TAX_INFO_HEADER("tax.info_header", ChatColor.DARK_GRAY + "" + ChatColor.STRIKETHROUGH + "=====" + ChatColor.RESET + " Tax Info (click for more info) " + ChatColor.DARK_GRAY + ChatColor.STRIKETHROUGH + "====="), TAX_JOIN_MSG_PENDING_PAYMENTS("tax.join_msg_pending_payments", ChatColor.GRAY + "You have " + ChatColor.AQUA + "$%money%" + ChatColor.GRAY + " in tax payments due on your regions!\nView them with /ps tax info."), TAX_PLAYER_REGION_INFO("tax.player_region_info", ChatColor.GRAY + "> " + ChatColor.AQUA + "%region%" + ChatColor.GRAY + " - " + ChatColor.DARK_AQUA + "$%money% due"), TAX_PLAYER_REGION_INFO_AUTOPAYER("tax.player_region_info_autopayer", ChatColor.GRAY + "> " + ChatColor.AQUA + "%region%" + ChatColor.GRAY + " - " + ChatColor.DARK_AQUA + "$%money% due" + ChatColor.GRAY + " (you autopay)"), TAX_CLICK_TO_SHOW_MORE_INFO("tax.click_to_show_more_info", "Click to show more information."), TAX_REGION_INFO_HEADER("tax.region_info_header", ChatColor.DARK_GRAY + "" + ChatColor.STRIKETHROUGH + "=====" + ChatColor.RESET + " %region% Tax Info " + ChatColor.DARK_GRAY + ChatColor.STRIKETHROUGH + "====="), TAX_REGION_INFO("tax.region_info", ChatColor.BLUE + "Tax Rate: " + ChatColor.GRAY + "$%taxrate% (sum of all merged regions)" + "\n" + ChatColor.BLUE + "Time between tax cycles: " + ChatColor.GRAY + "%taxperiod%" + "\n" + ChatColor.BLUE + "Time to pay taxes after cycle: " + ChatColor.GRAY + "%taxpaymentperiod%" + "\n" + ChatColor.BLUE + "Tax Autopayer: " + ChatColor.GRAY + "%taxautopayer%" + "\n" + ChatColor.BLUE + "Taxes Owed: " + ChatColor.GRAY + "$%taxowed%"), TAX_NEXT("tax.next_page", ChatColor.GRAY + "Do /ps tax info -p %page% to go to the next page!"), // ps buy BUY_HELP("buy.help", ChatColor.AQUA + "> " + ChatColor.GRAY + "/ps buy"), BUY_HELP_DESC("buy.help_desc", "Buy the region you are currently in."), BUY_NOT_FOR_SALE("buy.not_for_sale", ChatColor.RED + "This region is not for sale."), BUY_STOP_SELL("buy.stop_sell", ChatColor.GRAY + "The region is now not for sale."), BUY_SOLD_BUYER("buy.sold_buyer", ChatColor.GRAY + "Bought region " + ChatColor.AQUA + "%region%" + ChatColor.GRAY + " for " + ChatColor.AQUA + "$%price%" + ChatColor.GRAY + " from " + ChatColor.AQUA + "%player%" + ChatColor.GRAY + "."), BUY_SOLD_SELLER("buy.sold_seller", ChatColor.GRAY + "Sold region " + ChatColor.AQUA + "%region%" + ChatColor.GRAY + " for " + ChatColor.AQUA + "$%price%" + ChatColor.GRAY + " to " + ChatColor.AQUA + "%player%" + ChatColor.GRAY + "."), // ps sell SELL_HELP("sell.help", ChatColor.AQUA + "> " + ChatColor.GRAY + "/ps sell [price|stop]"), SELL_HELP_DESC("sell.help_desc", "Sell the region you are currently in."), SELL_RENTED_OUT("sell.rented_out", ChatColor.RED + "The region is being rented out! You must stop renting it out to sell."), SELL_FOR_SALE("sell.for_sale", ChatColor.GRAY + "The region is now for sale for " + ChatColor.AQUA + "$%price%" + ChatColor.GRAY + "."), // ps hide/unhide VISIBILITY_HIDE_HELP("visibility.hide_help", ChatColor.AQUA + "> " + ChatColor.GRAY + "/ps hide"), VISIBILITY_HIDE_HELP_DESC("visibility.hide_help_desc", "Use this command to hide or unhide your protection block."), VISIBILITY_UNHIDE_HELP("visibility.unhide_help", ChatColor.AQUA + "> " + ChatColor.GRAY + "/ps unhide"), VISIBILITY_UNHIDE_HELP_DESC("visibility.unhide_help_desc", "Use this command to hide or unhide your protection block."), ALREADY_NOT_HIDDEN("visibility.already_not_hidden", ChatColor.GRAY + "The protection stone doesn't appear hidden..."), ALREADY_HIDDEN("visibility.already_hidden", ChatColor.GRAY + "The protection stone appears to already be hidden..."), // ps info INFO_HELP("info.help", ChatColor.AQUA + "> " + ChatColor.GRAY + "/ps info members|owners|flags"), INFO_HELP_DESC("info.help_desc", "Use this command inside a ps region to see more information about it."), INFO_HEADER("info.header", ChatColor.DARK_GRAY + "" + ChatColor.STRIKETHROUGH + "=====" + ChatColor.RESET + " PS Info " + ChatColor.DARK_GRAY + ChatColor.STRIKETHROUGH + "====="), INFO_TYPE2("info.type2", "&9Type: &7%type%", "%type%"), INFO_MAY_BE_MERGED("info.may_be_merged", "(may be merged with other types)"), INFO_MERGED2("info.merged2", ChatColor.BLUE + "Merged regions: " + ChatColor.GRAY + "%merged%", "%merged%"), INFO_MEMBERS2("info.members2", "&9Members: &7%members%", "%members%"), INFO_NO_MEMBERS("info.no_members", ChatColor.RED + "(no members)"), INFO_OWNERS2("info.owners2", "&9Owners: &7%owners%", "%owners%"), INFO_NO_OWNERS("info.no_owners", ChatColor.RED + "(no owners)"), INFO_FLAGS2("info.flags2", "&9Flags: &7%flags%", "%flags%"), INFO_NO_FLAGS("info.no_flags", "(none)"), INFO_REGION2("info.region2", "&9Region: &b%region%", "%region%"), INFO_PRIORITY2("info.priority2", "&9Priority: &b%priority%", "%priority%"), INFO_PARENT2("info.parent2", "&9Parent: &b%parentregion%", "%parentregion%"), INFO_BOUNDS_XYZ("info.bounds_xyz", "&9Bounds: &b(%minx%,%miny%,%minz%) -> (%maxx%,%maxy%,%maxz%)", "%minx%", "%miny%", "%minz%", "%maxx%", "%maxy%", "%maxz%" ), INFO_BOUNDS_XZ("info.bounds_xz", "&9Bounds: &b(%minx%, %minz%) -> (%maxx%, %maxz%)", "%minx%", "%minz%", "%maxx%", "%maxz%" ), INFO_SELLER2("info.seller2", "&9Seller: &7%seller%", "%seller%"), INFO_PRICE2("info.price2", "&9Price: &7%price%", "%price%"), INFO_TENANT2("info.tenant2", "&9Tenant: &7%tenant%", "%tenant%"), INFO_LANDLORD2("info.landlord2", "&9Landlord: &7%landlord%", "%landlord%"), INFO_RENT2("info.rent2", "&9Rent: &7%rent%", "%rent%"), INFO_AVAILABLE_FOR_SALE("info.available_for_sale", ChatColor.AQUA + "Region available for sale!"), INFO_AVAILABLE_FOR_RENT("info.available_for_rent", ChatColor.AQUA + "Region available for rent!"), // ps priority PRIORITY_HELP("priority.help", ChatColor.AQUA + "> " + ChatColor.GRAY + "/ps priority [number|null]"), PRIORITY_HELP_DESC("priority.help_desc", "Use this command to set your region's priority."), PRIORITY_INFO("priority.info", ChatColor.GRAY + "Priority: %priority%"), PRIORITY_SET("priority.set", ChatColor.YELLOW + "Priority has been set."), PRIORITY_ERROR("priority.error", ChatColor.RED + "Error parsing input, check it again?"), // ps region REGION_HELP("region.help", ChatColor.AQUA + "> " + ChatColor.GRAY + "/ps region [list|remove|disown] [playername]"), REGION_HELP_DESC("region.help_desc", "Use this command to find information or edit other players' (or your own) protected regions."), REGION_NOT_FOUND_FOR_PLAYER("region.not_found_for_player", ChatColor.GRAY + "No regions found for %player% in this world."), REGION_LIST("region.list", ChatColor.GRAY + "%player%'s regions in this world: " + ChatColor.AQUA + "%regions%"), REGION_REMOVE("region.remove", ChatColor.YELLOW + "%player%'s regions have been removed in this world, and they have been removed from regions they co-owned."), REGION_DISOWN("region.disown", ChatColor.YELLOW + "%player% has been removed as owner from all regions on this world."), REGION_ERROR_SEARCH("region.error_search", ChatColor.RED + "Error while searching for %player%'s regions. Please make sure you have entered the correct name."), // ps tp TP_HELP("tp.help", ChatColor.AQUA + "> " + ChatColor.GRAY + "/ps tp [id/player] [num (optional)]"), TP_HELP_DESC("tp.help_desc", "Teleports you to one of a given player's regions."), NUMBER_ABOVE_ZERO("tp.number_above_zero", ChatColor.RED + "Please enter a number above 0."), TP_VALID_NUMBER("tp.valid_number", ChatColor.RED + "Please enter a valid number."), ONLY_HAS_REGIONS("tp.only_has_regions", ChatColor.RED + "%player% only has %num% protected regions in this world!"), TPING("tp.tping", ChatColor.GREEN + "Teleporting..."), TP_ERROR_NAME("tp.error_name", ChatColor.RED + "Error in teleporting to protected region! (parsing WG region name error)"), TP_ERROR_TP("tp.error_tp", ChatColor.RED + "Error in finding the region to teleport to!"), TP_IN_SECONDS("tp.in_seconds", ChatColor.GRAY + "Teleporting in " + ChatColor.AQUA + "%seconds%" + ChatColor.GRAY + " seconds."), TP_CANCELLED_MOVED("tp.cancelled_moved", ChatColor.RED + "Teleport cancelled. You moved!"), // ps home HOME_HELP("home.help", ChatColor.AQUA + "> " + ChatColor.GRAY + "/ps home [name/id]"), HOME_HELP_DESC("home.help_desc", "Teleports you to one of your protected regions."), HOME_HEADER("home.header", ChatColor.DARK_GRAY + "" + ChatColor.STRIKETHROUGH + "=====" + ChatColor.RESET + " Homes (click to teleport) " + ChatColor.DARK_GRAY + ChatColor.STRIKETHROUGH + "====="), HOME_CLICK_TO_TP("home.click_to_tp", "Click to teleport!"), HOME_NEXT("home.next_page", ChatColor.GRAY + "Do /ps home -p %page% to go to the next page!"), // ps unclaim UNCLAIM_HELP("unclaim.help", ChatColor.AQUA + "> " + ChatColor.GRAY + "/ps unclaim"), UNCLAIM_HELP_DESC("unclaim.help_desc", "Use this command to pickup a placed protection stone and remove the region."), UNCLAIM_HEADER("unclaim.header",ChatColor.DARK_GRAY + "" + ChatColor.STRIKETHROUGH + "=====" + ChatColor.RESET + " Unclaim (click to unclaim) " + ChatColor.DARK_GRAY + ChatColor.STRIKETHROUGH + "====="), // ps view VIEW_HELP("view.help", ChatColor.AQUA + "> " + ChatColor.GRAY + "/ps view"), VIEW_HELP_DESC("view.help_desc", "Use this command to view the borders of a protected region."), VIEW_COOLDOWN("view.cooldown", ChatColor.RED + "Please wait a while before using /ps view again."), VIEW_GENERATING("view.generating", ChatColor.GRAY + "Generating border..."), VIEW_GENERATE_DONE("view.generate_done", ChatColor.GREEN + "Done! The border will disappear after 30 seconds!"), VIEW_REMOVING("view.removing", ChatColor.AQUA + "Removing border...\n" + ChatColor.GREEN + "If you still see ghost blocks, relog!"), // ps admin ADMIN_HELP("admin.help", ChatColor.AQUA + "> " + ChatColor.GRAY + "/ps admin"), ADMIN_HELP_DESC("admin.help_desc", "Do /ps admin help for more information."), ADMIN_CLEANUP_HEADER("admin.cleanup_header", ChatColor.YELLOW + "Cleanup %arg% %days% days\n================"), ADMIN_CLEANUP_FOOTER("admin.cleanup_footer", ChatColor.YELLOW + "================\nCompleted %arg% cleanup."), ADMIN_HIDE_TOGGLED("admin.hide_toggled", ChatColor.YELLOW + "All protection stones have been %message% in this world."), ADMIN_LAST_LOGON("admin.last_logon", ChatColor.YELLOW + "%player% last played %days% days ago."), ADMIN_IS_BANNED("admin.is_banned", ChatColor.YELLOW + "%player% is banned."), ADMIN_ERROR_PARSING("admin.error_parsing", ChatColor.RED + "Error parsing days, are you sure it is a number?"), ADMIN_CONSOLE_WORLD("admin.console_world", ChatColor.RED + "Please specify the world as the last parameter."), ADMIN_LASTLOGONS_HEADER("admin.lastlogons_header", ChatColor.YELLOW + "%days% Days Plus:\n================"), ADMIN_LASTLOGONS_LINE("admin.lastlogons_line", ChatColor.YELLOW + "%player% %time% days"), ADMIN_LASTLOGONS_FOOTER("admin.lastlogons_footer", ChatColor.YELLOW + "================\n%count% Total Players Shown\n%checked% Total Players Checked"), // ps reload RELOAD_HELP("reload.help", ChatColor.AQUA + "> " + ChatColor.GRAY + "/ps reload"), RELOAD_HELP_DESC("reload.help_desc", "Reload settings from the config."), RELOAD_START("reload.start", ChatColor.AQUA + "Reloading config..."), RELOAD_COMPLETE("reload.complete", ChatColor.AQUA + "Completed config reload!"), // ps add/remove ADDREMOVE_HELP("addremove.help", ChatColor.AQUA + "> " + ChatColor.GRAY + "/ps add|remove [playername]"), ADDREMOVE_HELP_DESC("addremove.help_desc", "Use this command to add or remove a member of your protected region."), ADDREMOVE_OWNER_HELP("addremove.owner_help", ChatColor.AQUA + "> " + ChatColor.GRAY + "/ps addowner|removeowner [playername]"), ADDREMOVE_OWNER_HELP_DESC("addremove.owner_help_desc", "Use this command to add or remove an owner of your protected region."), ADDREMOVE_PLAYER_REACHED_LIMIT("addremove.player_reached_limit", ChatColor.RED + "This player has reached their region limit."), ADDREMOVE_PLAYER_NEEDS_TO_BE_ONLINE("addremove.player_needs_to_be_online", ChatColor.RED + "The player needs to be online to add them."), // ps get GET_HELP("get.help", ChatColor.AQUA + "> " + ChatColor.GRAY + "/ps get [block]"), GET_HELP_DESC("get.help_desc", "Use this command to get or purchase a protection block."), GET_GOTTEN("get.gotten", ChatColor.AQUA + "Added protection block to inventory!"), GET_NO_PERMISSION_BLOCK("get.no_permission_block", ChatColor.RED + "You don't have permission to get this block."), GET_HEADER("get.header", ChatColor.DARK_GRAY + "" + ChatColor.STRIKETHROUGH + "=====" + ChatColor.RESET + " Protect Blocks (click to get) " + ChatColor.DARK_GRAY + ChatColor.STRIKETHROUGH + "====="), GET_GUI_BLOCK("get.gui_block", ChatColor.GRAY + "> " + ChatColor.AQUA + "%alias% " + ChatColor.GRAY + "- %description% (" + ChatColor.WHITE + "$%price%" + ChatColor.GRAY + ")"), GET_GUI_HOVER("get.gui_hover", "Click to buy a %alias%!"), // ps give GIVE_HELP("give.help", ChatColor.AQUA + "> " + ChatColor.GRAY + "/ps give [block] [player] [amount (optional)]"), GIVE_HELP_DESC("give.help_desc", "Use this command to give a player a protection block."), GIVE_GIVEN("give.given", ChatColor.GRAY + "Gave " + ChatColor.AQUA + "%block%" + ChatColor.GRAY + " to " + ChatColor.AQUA + "%player%" + ChatColor.GRAY + "."), GIVE_NO_INVENTORY_ROOM("give.no_inventory_room", ChatColor.RED + "The player does not have enough inventory room."), // ps sethome SETHOME_HELP("sethome.help", ChatColor.AQUA + "> " + ChatColor.GRAY + "/ps sethome"), SETHOME_HELP_DESC("sethome.help_desc", "Use this command to set the home of a region to where you are right now."), SETHOME_SET("sethome.set", ChatColor.GRAY + "The home for " + ChatColor.AQUA + "%psid%" + ChatColor.GRAY + " has been set to your location."), // ps list LIST_HELP("list.help", ChatColor.AQUA + "> " + ChatColor.GRAY + "/ps list [player (optional)]"), LIST_HELP_DESC("list.help_desc", "Use this command to list the regions you, or another player owns."), LIST_HEADER("list.header", ChatColor.DARK_GRAY + "" + ChatColor.STRIKETHROUGH + "=====" + ChatColor.RESET + " %player%'s Regions " + ChatColor.DARK_GRAY + ChatColor.STRIKETHROUGH + "====="), LIST_OWNER("list.owner", ChatColor.GRAY + "Owner of:"), LIST_MEMBER("list.member", ChatColor.GRAY + "Member of:"), LIST_NO_REGIONS("list.no_regions", ChatColor.GRAY + "You currently do not own and are not a member of any regions."), LIST_NO_REGIONS_PLAYER("list.no_regions_player", ChatColor.AQUA + "%player% " + ChatColor.GRAY + "does not own and is not a member of any regions."), // ps name NAME_HELP("name.help", ChatColor.AQUA + "> " + ChatColor.GRAY + "/ps name [name|none]"), NAME_HELP_DESC("name.help_desc", "Use this command to give a nickname to your region, to make identifying your region easier."), NAME_REMOVED("name.removed", ChatColor.GRAY + "Removed the name for %id%."), NAME_SET_NAME("name.set_name", ChatColor.GRAY + "Set the name of %id% to " + ChatColor.AQUA + "%name%" + ChatColor.GRAY + "."), NAME_TAKEN("name.taken", ChatColor.GRAY + "The region name " + ChatColor.AQUA + "%name%" + ChatColor.GRAY + " has already been taken! Try another one."), // ps setparent SETPARENT_HELP("setparent.help", ChatColor.AQUA + "> " + ChatColor.GRAY + "/ps setparent [region|none]"), SETPARENT_HELP_DESC("setparent.help_desc", "Use this command to allow this region to inherit properties from another region (owners, members, flags, etc.)."), SETPARENT_SUCCESS("setparent.success", ChatColor.GRAY + "Successfully set the parent of " + ChatColor.AQUA + "%id%" + ChatColor.GRAY + " to " + ChatColor.AQUA + "%parent%" + ChatColor.GRAY + "."), SETPARENT_SUCCESS_REMOVE("setparent.success_remove", ChatColor.GRAY + "Successfully removed the parent of " + ChatColor.AQUA + "%id%" + ChatColor.GRAY + "."), SETPARENT_CIRCULAR_INHERITANCE("setparent.circular_inheritance", ChatColor.RED + "Detected circular inheritance (the parent already inherits from this region?). Parent not set."), // ps merge MERGE_HELP("merge.help", ChatColor.AQUA + "> " + ChatColor.GRAY + "/ps merge"), MERGE_HELP_DESC("merge.help_desc", "Use this command to merge the region you are in with other overlapping regions."), MERGE_DISABLED("merge.disabled", "Merging regions is disabled in the config!"), MERGE_MERGED("merge.merged", ChatColor.AQUA + "Regions were successfully merged!"), MERGE_HEADER("merge.header", ChatColor.DARK_GRAY + "" + ChatColor.STRIKETHROUGH + "=====" + ChatColor.RESET + " Merge %region% (click to merge) " + ChatColor.DARK_GRAY + ChatColor.STRIKETHROUGH + "====="), MERGE_WARNING("merge.warning", ChatColor.GRAY + "Note: This will delete all of the settings for the current region!"), MERGE_NOT_ALLOWED("merge.not_allowed", ChatColor.RED + "You are not allowed to merge this protection region type."), MERGE_INTO("merge.into", ChatColor.AQUA + "This region overlaps other regions you can merge into!"), MERGE_NO_REGIONS("merge.no_region", ChatColor.GRAY + "There are no overlapping regions to merge into."), MERGE_CLICK_TO_MERGE("merge.click_to_merge", "Click to merge with %region%!"), MERGE_AUTO_MERGED("merge.auto_merged", ChatColor.GRAY + "Region automatically merged with " + ChatColor.AQUA + "%region%" + ChatColor.GRAY + "."), ; private final String path; private final String defaultMessage; private final String[] placeholders; private final int placeholdersCount; private String message; private boolean isEmpty; private static final File conf = new File(ProtectionStones.getInstance().getDataFolder(), "messages.yml"); PSL(String path, String defaultMessage, String... placeholders) { this.path = path; this.defaultMessage = defaultMessage; this.placeholders = placeholders; this.placeholdersCount = placeholders.length; this.message = defaultMessage; this.isEmpty = message.isEmpty(); } public String msg() { return message; } public boolean isEmpty() { return isEmpty; } @Nullable public String format(final Object... args) { if (isEmpty) { return null; } if (this.placeholdersCount == 0) { return this.message; } if (this.placeholdersCount != args.length) { throw new IllegalArgumentException("Expected " + this.placeholdersCount + " arguments but got " + args.length); } return StringUtils.replaceEach( this.message, this.placeholders, Arrays.stream(args).filter(Objects::nonNull).map(Object::toString).toArray(String[]::new) ); } public boolean send(@NotNull final CommandSender receiver, @NotNull final Object... args) { final String msg = this.format(args); if (msg != null) { receiver.sendMessage(msg); } return true; } public void append(@NotNull final StringBuilder builder, @NotNull final Object... args) { final String msg = this.format(args); if (msg != null) { builder.append(msg); } } // Sends a message to a commandsender if the string is not empty public static boolean msg(CommandSender p, String str) { if (str != null && !str.isEmpty() && p != null) { p.sendMessage(str); } return true; } public static boolean msg(PSPlayer p, String str) { return msg(p.getPlayer(), str); } public static void loadConfig() { YamlConfiguration yml = new YamlConfiguration(); // check if messages.yml exists if (!conf.exists()) { try { conf.createNewFile(); } catch (IOException e) { e.printStackTrace(); } } // load config try { yml.load(conf); // can throw error for (PSL psl : PSL.values()) { // fix message if need be if (yml.getString(psl.path) == null) { // if msg not found in config yml.set(psl.path, applyConfigColours(psl.defaultMessage)); } else { // perform message upgrades messageUpgrades(psl, yml); } // load message psl.message = applyInGameColours(yml.getString(psl.path)); psl.isEmpty = psl.message.isEmpty(); } try { yml.save(conf); } catch (IOException e) { e.printStackTrace(); } } catch (Exception e) { // prevent bad messages.yml file from resetting the file e.printStackTrace(); } } // message upgrades over time private static void messageUpgrades(PSL psl, YamlConfiguration yml) { String value = yml.getString(psl.path); assert(value != null); // psl upgrade conversions if (psl == PSL.REACHED_REGION_LIMIT && value.equals("&cYou can not create any more protected regions.")) { yml.set(psl.path, psl.defaultMessage); } else if (psl == PSL.REACHED_PER_BLOCK_REGION_LIMIT && value.equals("&cYou can not create any more regions of this type.")) { yml.set(psl.path, psl.defaultMessage); } else if (value.contains("§")) { yml.set(psl.path, applyConfigColours(value)); } } // match all %#123abc#% format for hex private static final Pattern hexPatternLong = Pattern.compile("(?<!\\\\\\\\)(%#[a-fA-F0-9]{8}%)"), hexPatternShort = Pattern.compile("(?<!\\\\\\\\)(%#[a-fA-F0-9]{6}%)"); private static String applyInGameColours(String msg) { Matcher matcher = hexPatternLong.matcher(msg); while (matcher.find()) { String color = msg.substring(matcher.start() + 1, matcher.end() - 1); msg = msg.replace(msg.substring(matcher.start(), matcher.end()), "" + net.md_5.bungee.api.ChatColor.of(color)); } matcher = hexPatternShort.matcher(msg); while (matcher.find()) { String color = msg.substring(matcher.start() + 1, matcher.end() - 1); msg = msg.replace(msg.substring(matcher.start(), matcher.end()), "" + net.md_5.bungee.api.ChatColor.of(color)); } return msg.replace('&', '§'); } private static String applyConfigColours(String msg) { return msg.replace('§', '&'); } }
42,303
Java
.java
espidev/ProtectionStones
64
30
90
2018-09-17T22:12:12Z
2023-11-13T03:14:47Z
ProtectionStones.java
/FileExtraction/Java_unseen/espidev_ProtectionStones/src/main/java/dev/espi/protectionstones/ProtectionStones.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package dev.espi.protectionstones; import com.electronwill.nightconfig.core.Config; import com.electronwill.nightconfig.core.file.CommentedFileConfig; import com.electronwill.nightconfig.toml.TomlFormat; import com.sk89q.worldguard.protection.managers.RegionManager; import com.sk89q.worldguard.protection.regions.ProtectedRegion; import dev.espi.protectionstones.commands.ArgHelp; import dev.espi.protectionstones.commands.PSCommandArg; import dev.espi.protectionstones.placeholders.PSPlaceholderExpansion; import dev.espi.protectionstones.utils.BlockUtil; import dev.espi.protectionstones.utils.RecipeUtil; import dev.espi.protectionstones.utils.upgrade.LegacyUpgrade; import dev.espi.protectionstones.utils.UUIDCache; import dev.espi.protectionstones.utils.WGUtils; import net.milkbowl.vault.economy.Economy; import org.bstats.bukkit.Metrics; import org.bukkit.*; import org.bukkit.block.Block; import org.bukkit.command.CommandMap; import org.bukkit.enchantments.Enchantment; import org.bukkit.entity.Player; import org.bukkit.inventory.ItemFlag; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.meta.ItemMeta; import org.bukkit.inventory.meta.SkullMeta; import org.bukkit.inventory.meta.tags.CustomItemTagContainer; import org.bukkit.inventory.meta.tags.ItemTagType; import org.bukkit.plugin.RegisteredServiceProvider; import org.bukkit.plugin.java.JavaPlugin; import net.luckperms.api.LuckPerms; import java.io.File; import java.lang.reflect.Field; import java.util.*; import java.util.logging.Logger; import static com.google.common.base.Preconditions.checkNotNull; /** * The base class for the plugin. Some utilities are static, and others are instance methods, so they need to * be accessed through getInstance(). */ public class ProtectionStones extends JavaPlugin { // change this when the config version goes up public static final int CONFIG_VERSION = 16; private boolean debug = false; public static File configLocation, blockDataFolder; public static CommentedFileConfig config; private static List<PSCommandArg> commandArgs = new ArrayList<>(); private static ProtectionStones plugin; private PSEconomy economy; // all configuration file options are stored in here private PSConfig configOptions; static HashMap<String, PSProtectBlock> protectionStonesOptions = new HashMap<>(); // ps alias to id cache // <world-name, <alias, [ids]>> static HashMap<UUID, HashMap<String, ArrayList<String>>> regionNameToID = new HashMap<>(); // vault economy integration private boolean vaultSupportEnabled = false; private Economy vaultEconomy; // luckperms integration private boolean luckPermsSupportEnabled = false; private LuckPerms luckPerms; private boolean placeholderAPISupportEnabled = false; // ps toggle/on/off list public static Set<UUID> toggleList = new HashSet<>(); /* ~~~~~~~~~~ Instance methods ~~~~~~~~~~~~ */ /** * Add a command argument to /ps. * * @param psca PSCommandArg object to be added */ public void addCommandArgument(PSCommandArg psca) { commandArgs.add(psca); } /** * @return the list of command arguments for /ps */ public List<PSCommandArg> getCommandArguments() { return commandArgs; } /** * @return whether PlaceholderAPI support is enabled */ public boolean isPlaceholderAPISupportEnabled() { return placeholderAPISupportEnabled; } /** * @return whether vault support is enabled */ public boolean isVaultSupportEnabled() { return vaultSupportEnabled; } /** * @return returns this instance's vault economy hook */ public Economy getVaultEconomy() { return vaultEconomy; } /** * @return the instance's {@link PSEconomy} instance */ public PSEconomy getPSEconomy() { return economy; } public boolean isLuckPermsSupportEnabled() { return luckPermsSupportEnabled; } public LuckPerms getLuckPerms() { return luckPerms; } /** * @param debug whether the plugin should be in debug mode */ public void setDebug(boolean debug) { this.debug = debug; } /** * @return whether the plugin is in debug mode */ public boolean isDebug() { return debug; } /** * Print a debug message (only prints if the plugin is in debug mode). * @param msg the message to print */ public void debug(String msg) { if (debug) { getLogger().info("[DEBUG] " + msg); } } /** * @return returns the config options of this instance of ProtectionStones */ public PSConfig getConfigOptions() { return configOptions; } /** * @param conf config object to replace current config */ public void setConfigOptions(PSConfig conf) { this.configOptions = conf; } /** * Returns the list of PSProtectBlocks configured through the config. * * @return the list of PSProtectBlocks configured */ public List<PSProtectBlock> getConfiguredBlocks() { List<PSProtectBlock> l = new ArrayList<>(); for (PSProtectBlock b : protectionStonesOptions.values()) { if (!l.contains(b)) l.add(b); } return l; } /* ~~~~~~~~~~ Static methods ~~~~~~~~~~~~~~ */ /** * @return the plugin instance that is currently being used */ public static ProtectionStones getInstance() { return plugin; } /** * @return the plugin's logger */ public static Logger getPluginLogger() { return plugin.getLogger(); } /** * @return the PSEconomy object adapter */ public static PSEconomy getEconomy() { return getInstance().getPSEconomy(); } /** * Get the protection block config options for the block specified. * * @param block the block to get the block options of * @return the config options for the protect block specified (null if not found) */ public static PSProtectBlock getBlockOptions(Block block) { if (block == null) return null; return getBlockOptions(BlockUtil.getProtectBlockType(block)); } /** * Get the protection block config options for the item specified. * * If the options has restrict-obtaining enabled, and the item does not contain the required NBT tag, null will * be returned. * * @param item the item to get the block options of * @return the config options for the protect item specified (null if not found) */ public static PSProtectBlock getBlockOptions(ItemStack item) { if (!isProtectBlockItem(item)) return null; return getBlockOptions(BlockUtil.getProtectBlockType(item)); } /** * Gets the config options for the protection block type specified. It is recommended to use the block parameter overloaded * method instead if possible, since it deals better with heads. * * @param blockType the material type name (Bukkit) of the protect block to get the options for, or "PLAYER_HEAD name" for heads * @return the config options for the protect block specified (null if not found) */ public static PSProtectBlock getBlockOptions(String blockType) { return protectionStonesOptions.get(blockType); } public static boolean isProtectBlockType(Block b) { return getBlockOptions(b) != null; } /** * Get whether or not a material is used as a protection block. It is recommended to use the block * parameter overloaded method if possible since player heads have a different format. * * @param material material type to check (Bukkit material name), or "PLAYER_HEAD name" for heads * @return whether or not that material is being used for a protection block */ public static boolean isProtectBlockType(String material) { return protectionStonesOptions.containsKey(material); } /** * Check whether or not a given block is a protection block, and actually protects a region. * @param b the block to look at * @return whether or not the block is a protection block responsible for a region. */ public static boolean isProtectBlock(Block b) { if (!isProtectBlockType(b)) return false; RegionManager rgm = WGUtils.getRegionManagerWithWorld(b.getWorld()); if (rgm == null) return false; return rgm.getRegion(WGUtils.createPSID(b.getLocation())) != null || PSMergedRegion.getMergedRegion(b.getLocation()) != null; } /** * Check if a WorldGuard {@link ProtectedRegion} is a ProtectionStones region, and is configured in the config. * * @param r the region to check * @return true if the WorldGuard region is a ProtectionStones region, and false if it isn't */ public static boolean isPSRegion(ProtectedRegion r) { return isPSRegionFormat(r) && getBlockOptions(r.getFlag(FlagHandler.PS_BLOCK_MATERIAL)) != null; } /** * Check if a WorldGuard {@link ProtectedRegion} has the format of a ProtectionStones region, but is not necessarily configured * in the config. * * @param r the region to check * @return true if the WorldGuard region is a ProtectionStones region, and false if it isn't */ public static boolean isPSRegionFormat(ProtectedRegion r) { return r != null && r.getId().startsWith("ps") && r.getFlag(FlagHandler.PS_BLOCK_MATERIAL) != null; } /** * Check if a ProtectionStones name is already used by a region globally (from /ps name) * * @param name the name to search for * @return whether or not there is a region with this name */ public static boolean isPSNameAlreadyUsed(String name) { for (UUID worldUid : regionNameToID.keySet()) { RegionManager rgm = WGUtils.getRegionManagerWithWorld(Bukkit.getWorld(worldUid)); List<String> l = regionNameToID.get(worldUid).get(name); if (l == null) continue; for (int i = 0; i < l.size(); i++) { // remove outdated cache if (rgm.getRegion(l.get(i)) == null) { l.remove(i); i--; } } if (!l.isEmpty()) return true; } return false; } /** * Get protection stone regions using an ID or alias. * * @param w the world to search in (only if it is an id; aliases/names are global) * @param identifier id or alias of the region * @return a list of psregions that match the id or alias; will be empty if no regions were found */ public static List<PSRegion> getPSRegions(World w, String identifier) { RegionManager rgm = WGUtils.getRegionManagerWithWorld(w); if (rgm == null) return new ArrayList<>(); PSRegion r = PSRegion.fromWGRegion(w, rgm.getRegion(identifier)); if (r != null) { // return id based query return new ArrayList<>(Collections.singletonList(r)); } else { // return alias based query List<PSRegion> regions = new ArrayList<>(); PSRegion.fromName(identifier).values().forEach(regions::addAll); return regions; } } /** * Removes a protection stone region given its ID, and the region manager it is stored in * Note: Does not remove the PS block. * * @param w the world that the region is in * @param psID the worldguard region ID of the region * @return whether or not the event was cancelled */ public static boolean removePSRegion(World w, String psID) { PSRegion r = PSRegion.fromWGRegion(checkNotNull(w), checkNotNull(WGUtils.getRegionManagerWithWorld(w).getRegion(psID))); return r != null && r.deleteRegion(false); } /** * Removes a protection stone region given its ID, and the region manager it is stored in, with a player as its cause * Note: Does not remove the PS block, and does not check if the player (cause) has permission to do this. * * @param w the world that the region is in * @param psID the worldguard region ID of the region * @param cause the player that caused the removal * @return whether or not the event was cancelled */ public static boolean removePSRegion(World w, String psID, Player cause) { PSRegion r = PSRegion.fromWGRegion(checkNotNull(w), checkNotNull(WGUtils.getRegionManagerWithWorld(w).getRegion(psID))); return r != null && r.deleteRegion(false, cause); } /** * Get the config options for a protect block based on its alias * * @param name the alias of the protection block * @return the protect block options, or null if it wasn't found */ public static PSProtectBlock getProtectBlockFromAlias(String name) { if (name == null) return null; for (PSProtectBlock cpb : ProtectionStones.protectionStonesOptions.values()) { if (cpb.alias.equalsIgnoreCase(name) || cpb.type.equalsIgnoreCase(name)) return cpb; } return null; } /** * Check if an item is a valid protection block, and if checkNBT is true, check if it was created by * ProtectionStones. Be aware that blocks may have restrict-obtaining off, meaning that it is ignored whether or not * the item is created by ProtectionStones (in this case have checkNBT false). * * @param item the item to check * @param checkNBT whether or not to check if the plugin signed off on the item (restrict-obtaining) * @return whether or not the item is a valid protection block item, and was created by protection stones */ public static boolean isProtectBlockItem(ItemStack item, boolean checkNBT) { if (item == null) return false; // check basic item if (!ProtectionStones.isProtectBlockType(BlockUtil.getProtectBlockType(item))) return false; // check for player heads if (!checkNBT) return true; // if not checking nbt, you only need to check type boolean tag = false; // otherwise, check if the item was created by protection stones (stored in custom tag) if (item.getItemMeta() != null) { CustomItemTagContainer tagContainer = item.getItemMeta().getCustomTagContainer(); try { // check if tag byte is 1 Byte isPSBlock = tagContainer.getCustomTag(new NamespacedKey(ProtectionStones.getInstance(), "isPSBlock"), ItemTagType.BYTE); tag = isPSBlock != null && isPSBlock == 1; } catch (IllegalArgumentException es) { try { // some nbt data may be using a string (legacy nbt from ps version 2.0.0 -> 2.0.6) String isPSBlock = tagContainer.getCustomTag(new NamespacedKey(ProtectionStones.getInstance(), "isPSBlock"), ItemTagType.STRING); tag = isPSBlock != null && isPSBlock.equals("true"); } catch (IllegalArgumentException ignored) { } } } return tag; // whether or not the nbt tag was found } /** * Check if an item is a valid protection block, and if the block type has restrict-obtaining on, check if it was * created by ProtectionStones (custom NBT tag). Be aware that blocks may have restrict-obtaining * off, meaning that it ignores whether or not the item is created by ProtectionStones. * * @param item the item to check * @return whether or not the item is a valid protection block item, and was created by protection stones */ public static boolean isProtectBlockItem(ItemStack item) { if (item == null) return false; PSProtectBlock b = ProtectionStones.getBlockOptions(BlockUtil.getProtectBlockType(item)); if (b == null) return false; return isProtectBlockItem(item, b.restrictObtaining); } /** * Get a protection block item from a protect block config object. * * @param b the config options for the protection block * @return the item with NBT and other metadata to signify that it was created by protection stones */ public static ItemStack createProtectBlockItem(PSProtectBlock b) { ItemStack is = BlockUtil.getProtectBlockItemFromType(b.type); // add enchant effect if enabled if (b.enchantedEffect) { is.addUnsafeEnchantment(Enchantment.LURE, 0); } ItemMeta im = is.getItemMeta(); // add skull metadata, must be before others since it resets item metadata if (im instanceof SkullMeta && is.getType().equals(Material.PLAYER_HEAD) && b.type.split(":").length > 1) { is = BlockUtil.setHeadType(b.type, is); im = is.getItemMeta(); } // set custom model data if (b.customModelData != -1) { im.setCustomModelData(b.customModelData); } // add display name and lore if (!b.displayName.equals("")) { im.setDisplayName(ChatColor.translateAlternateColorCodes('&', b.displayName)); } List<String> lore = new ArrayList<>(); for (String s : b.lore) lore.add(ChatColor.translateAlternateColorCodes('&', s)); im.setLore(lore); // hide enchant name (cannot call addUnsafeEnchantment here) if (b.enchantedEffect) { im.addItemFlags(ItemFlag.HIDE_ENCHANTS); } // add identifier for protection stone created items im.getCustomTagContainer().setCustomTag(new NamespacedKey(plugin, "isPSBlock"), ItemTagType.BYTE, (byte) 1); is.setItemMeta(im); return is; } // called on first start, and /ps reload public static void loadConfig(boolean isReload) { // remove old ps crafting recipes RecipeUtil.removePSRecipes(); // init config PSConfig.initConfig(); // init messages PSL.loadConfig(); // init help menu ArgHelp.initHelpMenu(); // load economy if (ProtectionStones.getInstance().economy != null) ProtectionStones.getInstance().economy.stop(); ProtectionStones.getInstance().economy = new PSEconomy(); // add command to Bukkit (using reflection) if (!isReload) { try { final Field bukkitCommandMap = Bukkit.getServer().getClass().getDeclaredField("commandMap"); bukkitCommandMap.setAccessible(true); CommandMap commandMap = (CommandMap) bukkitCommandMap.get(Bukkit.getServer()); PSCommand psc = new PSCommand(getInstance().configOptions.base_command); for (String command : getInstance().configOptions.aliases) { // add aliases psc.getAliases().add(command); } commandMap.register(getInstance().configOptions.base_command, psc); // register command } catch (Exception | NoSuchMethodError e) { ProtectionStones.getPluginLogger().severe("Unable to load plugin commands!"); e.printStackTrace(); } } } @Override public void onLoad() { // register WG flags FlagHandler.registerFlags(); } @Override public void onEnable() { FlagHandler.registerHandlers(); // register custom WG flag handlers TomlFormat.instance(); Config.setInsertionOrderPreserved(true); // make sure that config upgrades aren't a complete mess plugin = this; configLocation = new File(this.getDataFolder() + "/config.toml"); blockDataFolder = new File(this.getDataFolder() + "/blocks"); // metrics (bStats) // https://bstats.org/plugin/bukkit/ProtectionStones/4071 new Metrics(this, 4071); // load command arguments PSCommand.addDefaultArguments(); // register event listeners getServer().getPluginManager().registerEvents(new ListenerClass(), this); // check that WorldGuard and WorldEdit are enabled (WorldGuard will only be enabled if there's WorldEdit) if (getServer().getPluginManager().getPlugin("WorldGuard") == null || !getServer().getPluginManager().getPlugin("WorldGuard").isEnabled()) { getLogger().severe("WorldGuard or WorldEdit not enabled! Disabling ProtectionStones..."); getServer().getPluginManager().disablePlugin(this); } // check if Vault is enabled (for economy support) if (getServer().getPluginManager().getPlugin("Vault") != null && getServer().getPluginManager().getPlugin("Vault").isEnabled()) { RegisteredServiceProvider<Economy> econ = getServer().getServicesManager().getRegistration(net.milkbowl.vault.economy.Economy.class); if (econ == null) { getLogger().warning("No economy plugin found by Vault! There will be no economy support!"); vaultSupportEnabled = false; } else { vaultEconomy = econ.getProvider(); vaultSupportEnabled = true; } } else { getLogger().warning("Vault not enabled! There will be no economy support!"); } // check for PlaceholderAPI if (getServer().getPluginManager().getPlugin("PlaceholderAPI") != null && getServer().getPluginManager().getPlugin("PlaceholderAPI").isEnabled()) { getLogger().info("PlaceholderAPI support enabled!"); placeholderAPISupportEnabled = true; new PSPlaceholderExpansion().register(); } else { getLogger().info("PlaceholderAPI not found! There will be no PlaceholderAPI support."); } // check for LuckPerms if (getServer().getPluginManager().getPlugin("LuckPerms") != null && getServer().getPluginManager().getPlugin("LuckPerms").isEnabled()) { try { luckPermsSupportEnabled = true; luckPerms = getServer().getServicesManager().load(LuckPerms.class); getLogger().info("LuckPerms support enabled!"); } catch (NoClassDefFoundError err) { // incompatible luckperms api getLogger().warning("Incompatible LuckPerms version found! Please upgrade your LuckPerms!"); } } // load configuration loadConfig(false); // register protectionstones.flags.edit.[flag] permission FlagHandler.initializePermissions(); // build up region cache getLogger().info("Building region cache..."); HashMap<World, RegionManager> regionManagers = WGUtils.getAllRegionManagers(); for (World w : regionManagers.keySet()) { RegionManager rgm = regionManagers.get(w); HashMap<String, ArrayList<String>> m = new HashMap<>(); for (ProtectedRegion r : rgm.getRegions().values()) { String name = r.getFlag(FlagHandler.PS_NAME); if (isPSRegion(r) && name != null) { if (m.containsKey(name)) { m.get(name).add(r.getId()); } else { m.put(name, new ArrayList<>(Collections.singletonList(r.getId()))); } } } regionNameToID.put(w.getUID(), m); } // uuid cache getLogger().info("Building UUID cache... (if slow change async-load-uuid-cache in the config to true)"); if (configOptions.asyncLoadUUIDCache) { // async load Bukkit.getScheduler().runTaskAsynchronously(plugin, () -> { for (OfflinePlayer op : Bukkit.getOfflinePlayers()) { UUIDCache.storeUUIDNamePair(op.getUniqueId(), op.getName()); } }); } else { // sync load for (OfflinePlayer op : Bukkit.getOfflinePlayers()) { UUIDCache.storeUUIDNamePair(op.getUniqueId(), op.getName()); } } // check if UUIDs have been upgraded already getLogger().info("Checking if PS regions have been updated to UUIDs..."); // update to UUIDs if (configOptions.uuidupdated == null || !configOptions.uuidupdated) LegacyUpgrade.convertToUUID(); if (configOptions.regionNegativeMinMaxUpdated == null || !configOptions.regionNegativeMinMaxUpdated) LegacyUpgrade.upgradeRegionsWithNegativeYValues(); getLogger().info(ChatColor.WHITE + "ProtectionStones has successfully started!"); } }
25,401
Java
.java
espidev/ProtectionStones
64
30
90
2018-09-17T22:12:12Z
2023-11-13T03:14:47Z
FlagHandler.java
/FileExtraction/Java_unseen/espidev_ProtectionStones/src/main/java/dev/espi/protectionstones/FlagHandler.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package dev.espi.protectionstones; import com.sk89q.worldguard.WorldGuard; import com.sk89q.worldguard.protection.flags.*; import com.sk89q.worldguard.protection.flags.registry.FlagConflictException; import com.sk89q.worldguard.protection.flags.registry.FlagRegistry; import com.sk89q.worldguard.protection.regions.ProtectedRegion; import com.sk89q.worldguard.session.SessionManager; import com.sk89q.worldguard.session.handler.ExitFlag; import dev.espi.protectionstones.flags.FarewellFlagHandler; import dev.espi.protectionstones.flags.GreetingFlagHandler; import dev.espi.protectionstones.utils.WGUtils; import me.clip.placeholderapi.PlaceholderAPI; import org.bukkit.Bukkit; import org.bukkit.Location; import org.bukkit.entity.Player; import org.bukkit.permissions.Permission; import org.bukkit.permissions.PermissionDefault; import java.util.*; import java.util.stream.Collectors; public class FlagHandler { public static final List<String> FLAG_GROUPS = Arrays.asList("all", "members", "owners", "nonmembers", "nonowners"); // Custom WorldGuard Flags public static final Flag<String> GREET_ACTION = new StringFlag("greeting-action"); public static final Flag<String> FAREWELL_ACTION = new StringFlag("farewell-action"); // Custom WorldGuard Flags used by ProtectionStones // Added to blocks on BlockPlaceEvent Listener // When adding flags, you may want to add them to the hidden_flags_from_info config option list public static final Flag<String> PS_HOME = new StringFlag("ps-home"); public static final Flag<String> PS_BLOCK_MATERIAL = new StringFlag("ps-block-material"); public static final Flag<String> PS_NAME = new StringFlag("ps-name"); public static final Flag<Set<String>> PS_MERGED_REGIONS = new SetFlag<>("ps-merged-regions", new StringFlag("ps-merged-region")); public static final Flag<Set<String>> PS_MERGED_REGIONS_TYPES = new SetFlag<>("ps-merged-regions-types", new StringFlag("ps-merged-region-type")); // each entry: "[psID] [type]" public static final Flag<String> PS_LANDLORD = new StringFlag("ps-landlord"); public static final Flag<String> PS_TENANT = new StringFlag("ps-tenant"); public static final Flag<String> PS_RENT_PERIOD = new StringFlag("ps-rent-period"); public static final Flag<Double> PS_PRICE = new DoubleFlag("ps-price"); public static final Flag<Double> PS_RENT_LAST_PAID = new DoubleFlag("ps-rent-last-paid"); public static final Flag<Boolean> PS_FOR_SALE = new BooleanFlag("ps-for-sale"); public static final Flag<Set<String>> PS_RENT_SETTINGS = new SetFlag<>("ps-rent-settings", new StringFlag("ps-rent-setting")); // TODO public static final Flag<Set<String>> PS_TAX_PAYMENTS_DUE = new SetFlag<>("ps-tax-payments-due", new StringFlag("ps-tax-payment")); public static final Flag<Set<String>> PS_TAX_LAST_PAYMENT_ADDED = new SetFlag<>("ps-tax-last-payment-added", new StringFlag("ps-tax-last-payment-entry")); public static final Flag<String> PS_TAX_AUTOPAYER = new StringFlag("ps-tax-autopayer"); // called on initial start static void registerFlags() { FlagRegistry registry = WGUtils.getFlagRegistry(); try { registry.register(PS_HOME); registry.register(PS_BLOCK_MATERIAL); registry.register(PS_NAME); registry.register(PS_MERGED_REGIONS); registry.register(PS_MERGED_REGIONS_TYPES); registry.register(PS_LANDLORD); registry.register(PS_TENANT); registry.register(PS_RENT_PERIOD); registry.register(PS_PRICE); registry.register(PS_RENT_LAST_PAID); registry.register(PS_FOR_SALE); registry.register(PS_RENT_SETTINGS); registry.register(PS_TAX_PAYMENTS_DUE); registry.register(PS_TAX_LAST_PAYMENT_ADDED); registry.register(PS_TAX_AUTOPAYER); } catch (FlagConflictException e) { Bukkit.getLogger().severe("Flag conflict found! The plugin will not work properly! Please contact the developers of the plugin."); e.printStackTrace(); } // extra custom flag registration try { registry.register(GREET_ACTION); registry.register(FAREWELL_ACTION); } catch (FlagConflictException ignored) { // ignore if flag conflict } } static void registerHandlers() { SessionManager sessionManager = WorldGuard.getInstance().getPlatform().getSessionManager(); sessionManager.registerHandler(GreetingFlagHandler.FACTORY, ExitFlag.FACTORY); sessionManager.registerHandler(FarewellFlagHandler.FACTORY, ExitFlag.FACTORY); } // adds flag permissions for ALL registered WorldGuard flags // by default, all players have access to it static void initializePermissions() { for (Flag<?> flag : WGUtils.getFlagRegistry().getAll()) { Bukkit.getPluginManager().addPermission(new Permission("protectionstones.flags.edit." + flag.getName(), "Given to all players by default. Remove if you do not want the player to have the ability to edit this flag with /ps flag.", PermissionDefault.TRUE)); } } // Add the correct flags for the ps region static void initCustomFlagsForPS(ProtectedRegion region, Location l, PSProtectBlock cpb) { String home = l.getBlockX() + cpb.homeXOffset + " "; home += (l.getBlockY() + cpb.homeYOffset) + " "; home += (l.getBlockZ() + cpb.homeZOffset); region.setFlag(PS_HOME, home); region.setFlag(PS_BLOCK_MATERIAL, cpb.type); } public static List<String> getPlayerPlaceholderFlags() { return Arrays.asList("greeting", "greeting-title", "greeting-action", "farewell", "farewell-title", "farewell-action"); } // Edit flags that require placeholders (variables) public static void initDefaultFlagPlaceholders(HashMap<Flag<?>, Object> flags, Player p) { for (Flag<?> f : getPlayerPlaceholderFlags().stream().map(WGUtils.getFlagRegistry()::get).collect(Collectors.toList())) { if (flags.get(f) != null) { String s = (String) flags.get(f); // apply placeholders if (ProtectionStones.getInstance().isPlaceholderAPISupportEnabled()) { s = PlaceholderAPI.setPlaceholders(p, s); } flags.put(f, s.replaceAll("%player%", p.getName())); } } } // Initializes user defined default flags for block // also initializes allowed flags list static void initDefaultFlagsForBlock(PSProtectBlock b) { // initialize allowed flags list b.allowedFlags = new LinkedHashMap<>(); for (String f : b.allowedFlagsRaw) { try { String[] spl = f.split(" "); if (spl[0].equals("-g")) { String[] splGroups = spl[1].split(","); List<String> groups = new ArrayList<>(); for (String g : splGroups) { if (FLAG_GROUPS.contains(g)) groups.add(g); } b.allowedFlags.put(spl[2], groups); } else { b.allowedFlags.put(f, FLAG_GROUPS); } } catch (Exception e) { ProtectionStones.getInstance().getLogger().warning("Skipping flag " + f + ". Did you configure the allowed_flags section correctly?"); e.printStackTrace(); } } // initialize default flags b.regionFlags = new HashMap<>(); // loop through default flags for (String flagraw : b.flags) { String[] split = flagraw.split(" "); String settings = "", // flag settings (after flag name) group = "", // -g group flagName = split[0]; boolean isEmpty = false; // whether or not it's the -e flag at beginning try { int startInd = 1; if (split[0].equals("-g")) { // if it's a group flag group = split[1]; flagName = split[2]; startInd = 3; // ex. -g nonmembers tnt deny } else if (split[0].equals("-e")) { // if it's an empty flag isEmpty = true; flagName = split[1]; startInd = 2; // ex. -e deny-message } // get settings (after flag name) for (int i = startInd; i < split.length; i++) settings += split[i] + " "; settings = settings.trim(); // if the setting is set to -e, change to empty flag if (settings.equals("-e")) { isEmpty = true; } // determine worldguard flag object Flag<?> flag = Flags.fuzzyMatchFlag(WGUtils.getFlagRegistry(), flagName); FlagContext fc = FlagContext.create().setInput(settings).build(); // warn if flag setting has already been set if (b.regionFlags.containsKey(flag)) { ProtectionStones.getPluginLogger().warning(String.format("Duplicate default flags found (only one flag setting can be applied for each flag)! Overwriting the previous value set for %s with \"%s\" ...", flagName, flagraw)); } // apply flag if (isEmpty) { // empty flag b.regionFlags.put(flag, ""); } else if (!group.equals("")) { // group flag RegionGroup rGroup = flag.getRegionGroupFlag().detectValue(group); if (rGroup == null) { ProtectionStones.getPluginLogger().severe(String.format("Error parsing flag \"%s\", the group value is invalid!", flagraw)); continue; } b.regionFlags.put(flag, flag.parseInput(fc)); // add flag b.regionFlags.put(flag.getRegionGroupFlag(), rGroup); // apply group } else { // normal flag b.regionFlags.put(flag, flag.parseInput(fc)); } } catch (Exception e) { ProtectionStones.getPluginLogger().warning("Error parsing flag: " + split[0] + "\nError: "); e.printStackTrace(); } } } }
11,174
Java
.java
espidev/ProtectionStones
64
30
90
2018-09-17T22:12:12Z
2023-11-13T03:14:47Z
PSEconomy.java
/FileExtraction/Java_unseen/espidev_ProtectionStones/src/main/java/dev/espi/protectionstones/PSEconomy.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package dev.espi.protectionstones; import com.sk89q.worldguard.protection.managers.RegionManager; import com.sk89q.worldguard.protection.managers.storage.StorageException; import com.sk89q.worldguard.protection.regions.ProtectedRegion; import dev.espi.protectionstones.utils.MiscUtil; import dev.espi.protectionstones.utils.WGUtils; import net.milkbowl.vault.economy.EconomyResponse; import org.bukkit.Bukkit; import org.bukkit.World; import java.time.Duration; import java.time.Instant; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.concurrent.CopyOnWriteArrayList; import java.util.stream.Collectors; /** * Handler for ProtectionStones economy related tasks. */ public class PSEconomy { private List<PSRegion> rentedList = new CopyOnWriteArrayList<>(); private static int rentRunner = -1, taxRunner = -1; public PSEconomy() { if (!ProtectionStones.getInstance().isVaultSupportEnabled()) { ProtectionStones.getInstance().getLogger().warning("Vault is not enabled! Economy functions (renting & buying) will not work!"); return; } // find regions that are being rented out (called on startup or reload) loadRentList(); // start rent rentRunner = Bukkit.getScheduler().runTaskTimerAsynchronously(ProtectionStones.getInstance(), this::updateRents, 0, 200).getTaskId(); // start taxes if (ProtectionStones.getInstance().getConfigOptions().taxEnabled) taxRunner = Bukkit.getScheduler().runTaskTimerAsynchronously(ProtectionStones.getInstance(), this::updateTaxes, 0, 200).getTaskId(); } private synchronized void updateRents() { rentedList = rentedList.stream() .filter(r -> r.getTypeOptions() != null) // remove null regions .filter(r -> r.getRentStage() == PSRegion.RentStage.RENTING) // remove regions not being rented out .peek(r -> { try { Duration rentPeriod = MiscUtil.parseRentPeriod(r.getRentPeriod()); // if tenant needs to pay if (Instant.now().getEpochSecond() > (r.getRentLastPaid() + rentPeriod.getSeconds())) { doRentPayment(r); } } catch (Exception ignored) { } }) .collect(Collectors.toList()); } private void updateTaxes() { WGUtils.getAllRegionManagers() .forEach((w, rgm) -> { for (ProtectedRegion r : rgm.getRegions().values()) { if (ProtectionStones.isPSRegion(r)) { PSRegion psr = PSRegion.fromWGRegion(w, r); processTaxes(psr); } } }); } /** * Stops the economy cycle. Used for reloads when creating a new PSEconomy. */ public void stop() { if (rentRunner != -1) { Bukkit.getScheduler().cancelTask(rentRunner); rentRunner = -1; } if (taxRunner != -1) { Bukkit.getScheduler().cancelTask(taxRunner); taxRunner = -1; } } /** * Load list of regions that are rented into memory. */ public void loadRentList() { rentedList = new ArrayList<>(); HashMap<World, RegionManager> managers = WGUtils.getAllRegionManagers(); for (World w : managers.keySet()) { RegionManager rgm = managers.get(w); for (ProtectedRegion pr : rgm.getRegions().values()) { if (ProtectionStones.isPSRegion(pr)) { rentedList.add(PSRegion.fromWGRegion(w, pr)); } } } } /** * Process taxes for a region. * * @param r the region to process taxes for */ public static void processTaxes(PSRegion r) { // if taxes are enabled for this regions if (r.getTypeOptions() != null && r.getTypeOptions().taxPeriod != -1) { Bukkit.getScheduler().runTask(ProtectionStones.getInstance(), () -> { // update tax payments due r.updateTaxPayments(); // check if a player is set to auto-pay if (!r.getTaxPaymentsDue().isEmpty() && r.getTaxAutopayer() != null) { PSPlayer psp = PSPlayer.fromUUID(r.getTaxAutopayer()); EconomyResponse res = r.payTax(psp, psp.getBalance()); if (psp.getPlayer() != null && res.amount != 0) { PSL.msg(psp.getPlayer(), PSL.TAX_PAID.msg() .replace("%amount%", String.format("%.2f", res.amount)) .replace("%region%", r.getName() == null ? r.getId() : r.getName() + " (" + r.getId() + ")")); } } // late tax payment punishment if (r.isTaxPaymentLate()) { r.deleteRegion(true); // TODO } }); } } /** * Process a rent payment for a region. * It does not do any checks, it is expected to check if the rent time has passed before this function is called. * * @param r the region to perform the rent payment */ public static void doRentPayment(PSRegion r) { PSPlayer tenant = PSPlayer.fromPlayer(Bukkit.getOfflinePlayer(r.getTenant())); PSPlayer landlord = PSPlayer.fromPlayer(Bukkit.getOfflinePlayer(r.getLandlord())); // not enough money for rent if (!tenant.hasAmount(r.getPrice())) { if (tenant.getOfflinePlayer().isOnline()) { PSL.msg(Bukkit.getPlayer(r.getTenant()), PSL.RENT_EVICT_NO_MONEY_TENANT.msg() .replace("%region%", r.getName() != null ? r.getName() : r.getId()) .replace("%price%", String.format("%.2f", r.getPrice()))); } if (landlord.getOfflinePlayer().isOnline()) { PSL.msg(Bukkit.getPlayer(r.getLandlord()), PSL.RENT_EVICT_NO_MONEY_LANDLORD.msg() .replace("%region%", r.getName() != null ? r.getName() : r.getId()) .replace("%tenant%", tenant.getName())); } r.removeRenting(); return; } // send payment messages if (tenant.getOfflinePlayer().isOnline()) { PSL.msg(Bukkit.getPlayer(r.getTenant()), PSL.RENT_PAID_TENANT.msg() .replace("%price%", String.format("%.2f", r.getPrice())) .replace("%landlord%", landlord.getName()) .replace("%region%", r.getName() != null ? r.getName() : r.getId())); } if (landlord.getOfflinePlayer().isOnline()) { PSL.msg(Bukkit.getPlayer(r.getLandlord()), PSL.RENT_PAID_LANDLORD.msg() .replace("%price%", String.format("%.2f", r.getPrice())) .replace("%tenant%", tenant.getName()) .replace("%region%", r.getName() != null ? r.getName() : r.getId())); } // update money must be run in main thread Bukkit.getScheduler().runTask(ProtectionStones.getInstance(), () -> tenant.pay(landlord, r.getPrice())); r.setRentLastPaid(Instant.now().getEpochSecond()); try { // must save region to persist last paid r.getWGRegionManager().saveChanges(); } catch (StorageException e) { e.printStackTrace(); } } /** * Get list of rented regions. * * @return the list of rented regions */ public List<PSRegion> getRentedList() { return rentedList; } }
8,490
Java
.java
espidev/ProtectionStones
64
30
90
2018-09-17T22:12:12Z
2023-11-13T03:14:47Z
PSConfig.java
/FileExtraction/Java_unseen/espidev_ProtectionStones/src/main/java/dev/espi/protectionstones/PSConfig.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package dev.espi.protectionstones; import com.electronwill.nightconfig.core.CommentedConfig; import com.electronwill.nightconfig.core.conversion.ObjectConverter; import com.electronwill.nightconfig.core.conversion.Path; import com.electronwill.nightconfig.core.file.CommentedFileConfig; import dev.espi.protectionstones.utils.BlockUtil; import dev.espi.protectionstones.utils.RecipeUtil; import dev.espi.protectionstones.utils.upgrade.ConfigUpgrades; import dev.espi.protectionstones.utils.upgrade.LegacyUpgrade; import org.bukkit.Material; import org.apache.commons.io.IOUtils; import java.io.*; import java.nio.file.Files; import java.nio.file.Paths; import java.nio.file.StandardCopyOption; import java.util.*; import java.util.logging.Level; import java.util.logging.Logger; /** * Represents the global config (config.toml) settings. */ public class PSConfig { // config options // config.toml will be loaded into these fields // uses autoboxing for primitives to allow for null (because of the way config upgrades work) @Path("config_version") public int configVersion; @Path("uuidupdated") public Boolean uuidupdated; @Path("region_negative_min_max_updated") public Boolean regionNegativeMinMaxUpdated; @Path("placing_cooldown") public Integer placingCooldown; @Path("allow_duplicate_region_names") public Boolean allowDuplicateRegionNames; @Path("async_load_uuid_cache") public Boolean asyncLoadUUIDCache; @Path("ps_view_cooldown") public Integer psViewCooldown; @Path("base_command") public String base_command; @Path("aliases") public List<String> aliases; @Path("drop_item_when_inventory_full") public Boolean dropItemWhenInventoryFull; @Path("regions_must_be_adjacent") public Boolean regionsMustBeAdjacent; @Path("allow_merging_regions") public Boolean allowMergingRegions; @Path("allow_merging_holes") public Boolean allowMergingHoles; @Path("default_protection_block_placement_off") public Boolean defaultProtectionBlockPlacementOff; @Path("allow_addowner_for_offline_players_without_lp") public Boolean allowAddownerForOfflinePlayersWithoutLp; @Path("allow_home_teleport_for_members") public Boolean allowHomeTeleportForMembers; @Path("admin.cleanup_delete_regions_with_members_but_no_owners") public Boolean cleanupDeleteRegionsWithMembersButNoOwners; @Path("economy.max_rent_price") public Double maxRentPrice; @Path("economy.min_rent_price") public Double minRentPrice; @Path("economy.max_rent_period") public Integer maxRentPeriod; @Path("economy.min_rent_period") public Integer minRentPeriod; @Path("economy.tax_enabled") public Boolean taxEnabled; @Path("economy.tax_message_on_join") public Boolean taxMessageOnJoin; static void initConfig() { // check if using config v1 or v2 (config.yml -> config.toml) if (new File(ProtectionStones.getInstance().getDataFolder() + "/config.yml").exists() && !ProtectionStones.configLocation.exists()) { LegacyUpgrade.upgradeFromV1V2(); } // check if config files exist try { if (!ProtectionStones.getInstance().getDataFolder().exists()) { ProtectionStones.getInstance().getDataFolder().mkdir(); } if (!ProtectionStones.blockDataFolder.exists()) { ProtectionStones.blockDataFolder.mkdir(); Files.copy(PSConfig.class.getResourceAsStream("/block1.toml"), Paths.get(ProtectionStones.blockDataFolder.getAbsolutePath() + "/block1.toml"), StandardCopyOption.REPLACE_EXISTING); } if (!ProtectionStones.configLocation.exists()) { Files.copy(PSConfig.class.getResourceAsStream("/config.toml"), Paths.get(ProtectionStones.configLocation.toURI()), StandardCopyOption.REPLACE_EXISTING); } } catch (IOException ex) { Logger.getLogger(ProtectionStones.class.getName()).log(Level.SEVERE, null, ex); } // keep in mind that there is /ps reload, so clear arrays before adding config options! // clear data (for /ps reload) ProtectionStones.protectionStonesOptions.clear(); // create config object if (ProtectionStones.config == null) { ProtectionStones.config = CommentedFileConfig.builder(ProtectionStones.configLocation).sync().build(); } // loop upgrades until the config has been updated to the latest version do { ProtectionStones.config.load(); // load latest settings // load config into configOptions object ProtectionStones.getInstance().setConfigOptions(new ObjectConverter().toObject(ProtectionStones.config, PSConfig::new)); // upgrade config if need be (v3+) boolean leaveLoop = ConfigUpgrades.doConfigUpgrades(); if (leaveLoop) break; // leave loop if config version is correct // save config if upgrading ProtectionStones.config.save(); } while (true); // load protection stones to options map if (ProtectionStones.blockDataFolder.listFiles().length == 0) { ProtectionStones.getPluginLogger().warning("The blocks folder is empty! You do not have any protection blocks configured!"); } else { // temp file to load in default ps block config File tempFile; try { tempFile = File.createTempFile("psconfigtemp", ".toml"); try (FileOutputStream out = new FileOutputStream(tempFile)) { IOUtils.copy(PSConfig.class.getResourceAsStream("/block1.toml"), out); } } catch (IOException e) { e.printStackTrace(); return; } CommentedFileConfig template = CommentedFileConfig.of(tempFile); template.load(); // iterate over block files and load into map ProtectionStones.getPluginLogger().info("Protection Stone Blocks:"); for (File file : ProtectionStones.blockDataFolder.listFiles()) { CommentedFileConfig c = CommentedFileConfig.builder(file).sync().build(); c.load(); // check to make sure all options are not null boolean updated = false; for (String str : template.valueMap().keySet()) { if (c.get(str) == null) { c.set(str, template.get(str)); c.setComment(str, template.getComment(str)); updated = true; } else if (c.get(str) instanceof CommentedConfig) { // no DFS for now (since there's only 2 layers of config) CommentedConfig template2 = template.get(str); CommentedConfig c2 = c.get(str); for (String str2 : template2.valueMap().keySet()) { if (c2.get(str2) == null) { c2.add(str2, template2.get(str2)); c2.setComment(str2, template2.getComment(str2)); updated = true; } } } } if (updated) c.save(); // convert toml data into object PSProtectBlock b = new ObjectConverter().toObject(c, PSProtectBlock::new); // check if material is valid, and is not a player head (since player heads also have the player name after) if (Material.getMaterial(b.type) == null && !(b.type.startsWith(Material.PLAYER_HEAD.toString()))) { ProtectionStones.getPluginLogger().warning("Unrecognized material: " + b.type); ProtectionStones.getPluginLogger().warning("Block will not be added. Please fix this in your config."); continue; } // check for duplicates if (ProtectionStones.isProtectBlockType(b.type)) { ProtectionStones.getPluginLogger().warning("Duplicate block type found! Ignoring the extra block " + b.type); continue; } if (ProtectionStones.getProtectBlockFromAlias(b.alias) != null) { ProtectionStones.getPluginLogger().warning("Duplicate block alias found! Ignoring the extra block " + b.alias); continue; } ProtectionStones.getPluginLogger().info("- " + b.type + " (" + b.alias + ")"); FlagHandler.initDefaultFlagsForBlock(b); // process flags for block and set regionFlags field // for PLAYER_HEAD:base64, we need to change the entry to link to a UUID hash instead of storing the giant base64 if (BlockUtil.isBase64PSHead(b.type)) { String nuuid = BlockUtil.getUUIDFromBase64PS(b); BlockUtil.uuidToBase64Head.put(nuuid, b.type.split(":")[1]); b.type = "PLAYER_HEAD:" + nuuid; } ProtectionStones.protectionStonesOptions.put(b.type, b); // add block } // cleanup temp file template.close(); tempFile.delete(); // setup crafting recipes for all blocks RecipeUtil.setupPSRecipes(); } } }
10,227
Java
.java
espidev/ProtectionStones
64
30
90
2018-09-17T22:12:12Z
2023-11-13T03:14:47Z
PSRentFlag.java
/FileExtraction/Java_unseen/espidev_ProtectionStones/src/main/java/dev/espi/protectionstones/PSRentFlag.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package dev.espi.protectionstones; public enum PSRentFlag { TENANT_IS_OWNER("false"), LANDLORD_IS_OWNER("false"); String val; PSRentFlag(String val) { this.val = val; } public String getVal() { return val; } public void setVal(String val) { this.val = val; } }
983
Java
.java
espidev/ProtectionStones
64
30
90
2018-09-17T22:12:12Z
2023-11-13T03:14:47Z
ListenerClass.java
/FileExtraction/Java_unseen/espidev_ProtectionStones/src/main/java/dev/espi/protectionstones/ListenerClass.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package dev.espi.protectionstones; import com.sk89q.worldedit.bukkit.BukkitAdapter; import com.sk89q.worldedit.math.BlockVector3; import com.sk89q.worldguard.WorldGuard; import com.sk89q.worldguard.bukkit.WorldGuardPlugin; import com.sk89q.worldguard.bukkit.event.block.PlaceBlockEvent; import com.sk89q.worldguard.protection.ApplicableRegionSet; import com.sk89q.worldguard.protection.flags.Flags; import com.sk89q.worldguard.protection.flags.StateFlag; import com.sk89q.worldguard.protection.managers.RegionManager; import com.sk89q.worldguard.protection.regions.ProtectedRegion; import com.sk89q.worldguard.protection.regions.RegionContainer; import dev.espi.protectionstones.event.PSCreateEvent; import dev.espi.protectionstones.event.PSRemoveEvent; import dev.espi.protectionstones.utils.RecipeUtil; import dev.espi.protectionstones.utils.UUIDCache; import dev.espi.protectionstones.utils.WGUtils; import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.bukkit.Material; import org.bukkit.World; import org.bukkit.block.Block; import org.bukkit.block.BlockFace; import org.bukkit.block.BlockState; import org.bukkit.block.Furnace; import org.bukkit.command.CommandSender; import org.bukkit.enchantments.Enchantment; import org.bukkit.entity.EntityType; import org.bukkit.entity.Player; import org.bukkit.event.Event; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.Listener; import org.bukkit.event.block.*; import org.bukkit.event.entity.EntityChangeBlockEvent; import org.bukkit.event.entity.EntityExplodeEvent; import org.bukkit.event.inventory.*; import org.bukkit.event.player.PlayerBucketEmptyEvent; import org.bukkit.event.player.PlayerInteractEvent; import org.bukkit.event.player.PlayerJoinEvent; import org.bukkit.event.player.PlayerTeleportEvent; import org.bukkit.event.player.PlayerTeleportEvent.TeleportCause; import org.bukkit.inventory.GrindstoneInventory; import org.bukkit.inventory.ItemStack; import java.util.List; public class ListenerClass implements Listener { @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) public void onPlayerJoin(PlayerJoinEvent e) { Player p = e.getPlayer(); // update UUID cache UUIDCache.removeUUID(p.getUniqueId()); UUIDCache.removeName(p.getName()); UUIDCache.storeUUIDNamePair(p.getUniqueId(), p.getName()); // allow worldguard to resolve all UUIDs to names Bukkit.getScheduler().runTaskAsynchronously(ProtectionStones.getInstance(), () -> UUIDCache.storeWGProfile(p.getUniqueId(), p.getName())); // add recipes to player's recipe book p.discoverRecipes(RecipeUtil.getRecipeKeys()); PSPlayer psp = PSPlayer.fromPlayer(p); // if by default, players should have protection block placement toggled off if (ProtectionStones.getInstance().getConfigOptions().defaultProtectionBlockPlacementOff) { ProtectionStones.toggleList.add(p.getUniqueId()); } // tax join message if (ProtectionStones.getInstance().getConfigOptions().taxEnabled && ProtectionStones.getInstance().getConfigOptions().taxMessageOnJoin) { Bukkit.getScheduler().runTaskAsynchronously(ProtectionStones.getInstance(), () -> { int amount = 0; for (PSRegion psr : psp.getTaxEligibleRegions()) { for (PSRegion.TaxPayment tp : psr.getTaxPaymentsDue()) { amount += tp.getAmount(); } } if (amount != 0) { PSL.msg(psp, PSL.TAX_JOIN_MSG_PENDING_PAYMENTS.msg().replace("%money%", "" + amount)); } }); } } // specifically add WG passthrough bypass here, so other plugins can see the result @EventHandler(priority = EventPriority.LOWEST) public void onBlockPlaceLowPriority(PlaceBlockEvent event) { var cause = event.getCause().getRootCause(); if (cause instanceof Player player && event.getBlocks().size() >= 1) { var block = event.getBlocks().get(0); if (!ProtectionStones.isProtectBlockItem(player.getInventory().getItemInHand())) { return; } var options = ProtectionStones.getBlockOptions(player.getInventory().getItemInHand()); if (options != null && options.placingBypassesWGPassthrough) { // check if any regions here have the passthrough flag // we can't query unfortunately, since null flags seem to equate to ALLOW, when we want it to be DENY ApplicableRegionSet set = WGUtils.getRegionManagerWithWorld(event.getWorld()).getApplicableRegions(BukkitAdapter.asBlockVector(block.getLocation())); // loop through regions, if any region does not have a passthrough value set, then don't allow for (var region : set.getRegions()) { if (region.getFlag(Flags.PASSTHROUGH) == null) { return; } } // if every region with an explicit passthrough value, then allow passthrough of protection block event.setResult(Event.Result.ALLOW); } } } // we only create the region after other plugins' event handlers have run @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) public void onBlockPlace(BlockPlaceEvent e) { BlockHandler.createPSRegion(e); } // returns the error message, or "" if the player has permission to break the region // TODO: refactor and move this to PSRegion, so that /ps unclaim can use the same checks private String checkPermissionToBreakProtection(Player p, PSRegion r) { // check for destroy permission if (!p.hasPermission("protectionstones.destroy")) { return PSL.NO_PERMISSION_DESTROY.msg(); } // check if player is owner of region if (!r.isOwner(p.getUniqueId()) && !p.hasPermission("protectionstones.superowner")) { return PSL.NO_REGION_PERMISSION.msg(); } // cannot break region being rented (prevents splitting merged regions, and breaking as tenant owner) if (r.getRentStage() == PSRegion.RentStage.RENTING && !p.hasPermission("protectionstones.superowner")) { return PSL.RENT_CANNOT_BREAK_WHILE_RENTING.msg(); } return ""; } // helper method for breaking protection blocks // IMPLEMENTATION NOTES: r may be of a non-configured type private boolean playerBreakProtection(Player p, PSRegion r) { PSProtectBlock blockOptions = r.getTypeOptions(); // check if player has permission to break the protection String error = checkPermissionToBreakProtection(p, r); if (!error.isEmpty()) { PSL.msg(p, error); return false; } // return protection stone if no drop option is off if (blockOptions != null && !blockOptions.noDrop) { if (!p.getInventory().addItem(blockOptions.createItem()).isEmpty()) { // method will return not empty if item couldn't be added if (ProtectionStones.getInstance().getConfigOptions().dropItemWhenInventoryFull) { PSL.msg(p, PSL.NO_ROOM_DROPPING_ON_FLOOR.msg()); p.getWorld().dropItem(r.getProtectBlock().getLocation(), blockOptions.createItem()); } else { PSL.msg(p, PSL.NO_ROOM_IN_INVENTORY.msg()); return false; } } } // check if removing the region and firing region remove event blocked it if (!r.deleteRegion(true, p)) { if (!ProtectionStones.getInstance().getConfigOptions().allowMergingHoles) { // side case if the removing creates a hole and those are prevented PSL.msg(p, PSL.DELETE_REGION_PREVENTED_NO_HOLES.msg()); } return false; } PSL.msg(p, PSL.NO_LONGER_PROTECTED.msg()); return true; } @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) public void onPlayerInteract(PlayerInteractEvent e) { // shift-right click block with hand to break if (e.getAction() == Action.RIGHT_CLICK_BLOCK && !e.isBlockInHand() && e.getClickedBlock() != null && ProtectionStones.isProtectBlock(e.getClickedBlock())) { PSProtectBlock ppb = ProtectionStones.getBlockOptions(e.getClickedBlock()); if (ppb.allowShiftRightBreak && e.getPlayer().isSneaking()) { PSRegion r = PSRegion.fromLocation(e.getClickedBlock().getLocation()); if (r != null && playerBreakProtection(e.getPlayer(), r)) { // successful e.getClickedBlock().setType(Material.AIR); } } } } // this will be the first event handler called in the chain // thus we should cancel the event here if possible (so other plugins don't start acting upon it) @EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = true) public void onBlockBreakLowPriority(BlockBreakEvent e) { Player p = e.getPlayer(); Block pb = e.getBlock(); if (!ProtectionStones.isProtectBlock(pb)) return; // check if player has permission to break the protection PSRegion r = PSRegion.fromLocation(pb.getLocation()); if (r != null) { String error = checkPermissionToBreakProtection(p, r); if (!error.isEmpty()) { PSL.msg(p, error); e.setCancelled(true); } } } @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) public void onBlockBreak(BlockBreakEvent e) { Player p = e.getPlayer(); Block pb = e.getBlock(); PSProtectBlock blockOptions = ProtectionStones.getBlockOptions(pb); // check if block broken is protection stone type if (blockOptions == null) return; // check if that is actually a protection stone block (owns a region) if (!ProtectionStones.isProtectBlock(pb)) { // prevent silk touching of protection stone blocks (that aren't holding a region) if (blockOptions.preventSilkTouch) { ItemStack left = p.getInventory().getItemInMainHand(); ItemStack right = p.getInventory().getItemInOffHand(); if (!left.containsEnchantment(Enchantment.SILK_TOUCH) && !right.containsEnchantment(Enchantment.SILK_TOUCH)) { return; } e.setDropItems(false); } return; } PSRegion r = PSRegion.fromLocation(pb.getLocation()); // break protection if (r != null && playerBreakProtection(p, r)) { // successful e.setDropItems(false); e.setExpToDrop(0); } else { // unsuccessful e.setCancelled(true); } } // -=-=-=- prevent smelting protection blocks -=-=-=- @EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true) public void onFurnaceSmelt(FurnaceSmeltEvent e) { // prevent protect block item to be smelt PSProtectBlock options = ProtectionStones.getBlockOptions(e.getSource()); if (options != null && !options.allowSmeltItem) { e.setCancelled(true); } } @EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true) public void onFurnaceBurnItem(FurnaceBurnEvent e) { // prevent protect block item to be smelt Furnace f = (Furnace) e.getBlock().getState(); if (f.getInventory().getSmelting() != null) { PSProtectBlock options = ProtectionStones.getBlockOptions(f.getInventory().getSmelting()); PSProtectBlock fuelOptions = ProtectionStones.getBlockOptions(f.getInventory().getFuel()); if ((options != null && !options.allowSmeltItem) || (fuelOptions != null && !fuelOptions.allowSmeltItem)) { e.setCancelled(true); } } } // -=-=-=- prevent crafting using protection blocks -=-=-=- @EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true) public void onPrepareItemCraft(PrepareItemCraftEvent e) { for (ItemStack s : e.getInventory().getMatrix()) { PSProtectBlock options = ProtectionStones.getBlockOptions(s); if (options != null && !options.allowUseInCrafting) { e.getInventory().setResult(new ItemStack(Material.AIR)); } } } // -=-=-=- disable grindstone inventory to prevent infinite exp exploit with enchanted_effect option -=-=-=- // see https://github.com/espidev/ProtectionStones/issues/324 @EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true) public void onInventoryClickEvent(InventoryClickEvent e) { if (e.getInventory().getType() == InventoryType.GRINDSTONE) { if (ProtectionStones.isProtectBlockItem(e.getCurrentItem())) { e.setCancelled(true); } } } // -=-=-=- block changes to protection block related events -=-=-=- @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) public void onPlayerBucketFill(PlayerBucketEmptyEvent e) { Block clicked = e.getBlockClicked(); BlockFace bf = e.getBlockFace(); Block check = clicked.getWorld().getBlockAt(clicked.getX() + e.getBlockFace().getModX(), clicked.getY() + bf.getModY(), clicked.getZ() + e.getBlockFace().getModZ()); if (ProtectionStones.isProtectBlock(check)) { e.setCancelled(true); } } @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) public void onBlockIgnite(BlockIgniteEvent e) { if (ProtectionStones.isProtectBlock(e.getBlock())) { e.setCancelled(true); } } @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) public void onBlockBurn(BlockBurnEvent e) { if (ProtectionStones.isProtectBlock(e.getBlock())) { e.setCancelled(true); } } @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) public void onBlockFromTo(BlockFromToEvent e) { if (ProtectionStones.isProtectBlock(e.getToBlock())) { e.setCancelled(true); } } @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) public void onSpongeAbsorb(SpongeAbsorbEvent event) { if (ProtectionStones.isProtectBlock(event.getBlock())) { event.setCancelled(true); } } @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) public void onBlockFade(BlockFadeEvent e) { if (ProtectionStones.isProtectBlock(e.getBlock())) { e.setCancelled(true); } } @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) public void onBlockForm(BlockFormEvent e) { if (ProtectionStones.isProtectBlock(e.getBlock())) { e.setCancelled(true); } } @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) public void onBlockDropItem(BlockDropItemEvent e) { // unfortunately, the below fix does not really work because Spigot only triggers for the source block, despite // what the documentation says: https://hub.spigotmc.org/javadocs/spigot/org/bukkit/event/block/BlockDropItemEvent.html // we want to replace protection blocks that have their protection block broken (ex. signs, banners) // the block may not exist anymore, and so we have to recreate the isProtectBlock method here BlockState bs = e.getBlockState(); if (!ProtectionStones.isProtectBlockType(bs.getType().toString())) return; RegionManager rgm = WGUtils.getRegionManagerWithWorld(bs.getWorld()); if (rgm == null) return; // check if the block is a source block ProtectedRegion br = rgm.getRegion(WGUtils.createPSID(bs.getLocation())); if (!ProtectionStones.isPSRegion(br) && PSMergedRegion.getMergedRegion(bs.getLocation()) == null) return; PSRegion r = PSRegion.fromLocation(bs.getLocation()); if (r == null) return; // puts the block back r.unhide(); e.setCancelled(true); } // -=-=- prevent protection block piston effects -=-=- @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) public void onPistonExtend(BlockPistonExtendEvent e) { pistonUtil(e.getBlocks(), e); } @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) public void onPistonRetract(BlockPistonRetractEvent e) { pistonUtil(e.getBlocks(), e); } private void pistonUtil(List<Block> pushedBlocks, BlockPistonEvent e) { for (Block b : pushedBlocks) { PSProtectBlock cpb = ProtectionStones.getBlockOptions(b); if (cpb != null && ProtectionStones.isProtectBlock(b) && cpb.preventPistonPush) { e.setCancelled(true); } } } // -=-=- prevent protection blocks from exploding -=-=- @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) public void onBlockExplode(BlockExplodeEvent e) { explodeUtil(e.blockList(), e.getBlock().getLocation().getWorld()); } @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) public void onEntityExplode(EntityExplodeEvent e) { explodeUtil(e.blockList(), e.getLocation().getWorld()); } @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) public void onEntityChangeBlock(EntityChangeBlockEvent e) { if (!ProtectionStones.isProtectBlock(e.getBlock())) return; // events like ender dragon block break, wither running into block break, etc. if (!blockExplodeUtil(e.getBlock().getWorld(), e.getBlock())) { // if block shouldn't be exploded, cancel the event e.setCancelled(true); } } private void explodeUtil(List<Block> blockList, World w) { // loop through exploded blocks for (int i = 0; i < blockList.size(); i++) { Block b = blockList.get(i); if (ProtectionStones.isProtectBlock(b)) { // always remove protection block from exploded list blockList.remove(i); i--; } blockExplodeUtil(w, b); } } // returns whether the block is exploded private boolean blockExplodeUtil(World w, Block b) { if (ProtectionStones.isProtectBlock(b)) { String id = WGUtils.createPSID(b.getLocation()); PSProtectBlock blockOptions = ProtectionStones.getBlockOptions(b); // if prevent explode if (blockOptions.preventExplode) { return false; } // manually set to air if exploded so there is no natural item drop b.setType(Material.AIR); // manually add drop if (!blockOptions.noDrop) { b.getWorld().dropItem(b.getLocation(), blockOptions.createItem()); } // remove region from worldguard if destroy_region_when_explode is enabled if (blockOptions.destroyRegionWhenExplode) { ProtectionStones.removePSRegion(w, id); } } return true; } // check player teleporting into region behaviour @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) public void onPlayerTeleport(PlayerTeleportEvent event) { // we only want plugin triggered teleports, ignore natural teleportation if (event.getCause() == TeleportCause.ENDER_PEARL || event.getCause() == TeleportCause.CHORUS_FRUIT) return; if (event.getPlayer().hasPermission("protectionstones.tp.bypassprevent")) return; WorldGuardPlugin wg = WorldGuardPlugin.inst(); RegionManager rgm = WGUtils.getRegionManagerWithWorld(event.getTo().getWorld()); BlockVector3 v = BlockVector3.at(event.getTo().getX(), event.getTo().getY(), event.getTo().getZ()); if (rgm != null) { // check if player can teleport into region (no region with preventTeleportIn = true) ApplicableRegionSet regions = rgm.getApplicableRegions(v); if (regions.getRegions().isEmpty()) return; boolean foundNoTeleport = false; for (ProtectedRegion r : regions) { String f = r.getFlag(FlagHandler.PS_BLOCK_MATERIAL); if (f != null && ProtectionStones.getBlockOptions(f) != null && ProtectionStones.getBlockOptions(f).preventTeleportIn) foundNoTeleport = true; if (r.getOwners().contains(wg.wrapPlayer(event.getPlayer()))) return; } if (foundNoTeleport) { PSL.msg(event.getPlayer(), PSL.REGION_CANT_TELEPORT.msg()); event.setCancelled(true); } } } // -=-=-=- player defined events -=-=-=- private void execEvent(String action, CommandSender s, String player, PSRegion region) { if (player == null) player = ""; // split action_type: action String[] sp = action.split(": "); if (sp.length == 0) return; StringBuilder act = new StringBuilder(sp[1]); for (int i = 2; i < sp.length; i++) act.append(": ").append(sp[i]); // add anything extra that has a colon act = new StringBuilder(act.toString() .replace("%player%", player) .replace("%world%", region.getWorld().getName()) .replace("%region%", region.getName() == null ? region.getId() : region.getName() + " (" + region.getId() + ")") .replace("%block_x%", region.getProtectBlock().getX() + "") .replace("%block_y%", region.getProtectBlock().getY() + "") .replace("%block_z%", region.getProtectBlock().getZ() + "")); switch (sp[0]) { case "player_command": if (s != null) Bukkit.getServer().dispatchCommand(s, act.toString()); break; case "console_command": Bukkit.getServer().dispatchCommand(Bukkit.getServer().getConsoleSender(), act.toString()); break; case "message": if (s != null) s.sendMessage(ChatColor.translateAlternateColorCodes('&', act.toString())); break; case "global_message": for (Player p : Bukkit.getOnlinePlayers()) { p.sendMessage(ChatColor.translateAlternateColorCodes('&', act.toString())); } ProtectionStones.getPluginLogger().info(ChatColor.translateAlternateColorCodes('&', act.toString())); break; case "console_message": ProtectionStones.getPluginLogger().info(ChatColor.translateAlternateColorCodes('&', act.toString())); break; } } @EventHandler public void onPSCreate(PSCreateEvent event) { if (event.isCancelled()) return; if (!event.getRegion().getTypeOptions().eventsEnabled) return; // run on next tick (after the region is created to allow for edits to the region) Bukkit.getServer().getScheduler().runTask(ProtectionStones.getInstance(), () -> { // run custom commands (in config) for (String action : event.getRegion().getTypeOptions().regionCreateCommands) { execEvent(action, event.getPlayer(), event.getPlayer().getName(), event.getRegion()); } }); } @EventHandler public void onPSRemove(PSRemoveEvent event) { if (event.isCancelled()) return; if (event.getRegion().getTypeOptions() == null) return; if (!event.getRegion().getTypeOptions().eventsEnabled) return; // run custom commands (in config) for (String action : event.getRegion().getTypeOptions().regionDestroyCommands) { if (event.getPlayer() == null) { execEvent(action, null, null, event.getRegion()); } else { execEvent(action, event.getPlayer(), event.getPlayer().getName(), event.getRegion()); } } } }
25,232
Java
.java
espidev/ProtectionStones
64
30
90
2018-09-17T22:12:12Z
2023-11-13T03:14:47Z
PSPlayer.java
/FileExtraction/Java_unseen/espidev_ProtectionStones/src/main/java/dev/espi/protectionstones/PSPlayer.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package dev.espi.protectionstones; import com.sk89q.worldguard.protection.managers.RegionManager; import com.sk89q.worldguard.protection.regions.ProtectedRegion; import dev.espi.protectionstones.utils.MiscUtil; import dev.espi.protectionstones.utils.WGUtils; import net.milkbowl.vault.economy.EconomyResponse; import org.bukkit.Bukkit; import org.bukkit.OfflinePlayer; import org.bukkit.World; import org.bukkit.entity.Player; import org.bukkit.permissions.PermissionAttachmentInfo; import java.util.*; import java.util.concurrent.ExecutionException; import java.util.stream.Collectors; import static com.google.common.base.Preconditions.checkNotNull; /** * Wrapper for a Bukkit player that exposes ProtectionStones related methods. */ public class PSPlayer { // TODO implement public enum PlayerRegionRelationship { OWNER, MEMBER, LANDLORD, TENANT, NONMEMBER, } UUID uuid; Player p; /** * Adapt a UUID into a PSPlayer wrapper. * * @param uuid the uuid to wrap * @return the PSPlayer object */ public static PSPlayer fromUUID(UUID uuid) { return new PSPlayer(checkNotNull(uuid)); } /** * Adapt a Bukkit player into a PSPlayer wrapper. * * @param p the player to wrap * @return the PSPlayer object */ public static PSPlayer fromPlayer(Player p) { return new PSPlayer(checkNotNull(p)); } public static PSPlayer fromPlayer(OfflinePlayer p) { if (checkNotNull(p) instanceof Player) { return new PSPlayer((Player) p); } else { return new PSPlayer(p.getUniqueId()); } } public PSPlayer(Player player) { this.p = player; this.uuid = player.getUniqueId(); } public PSPlayer(UUID uuid) { this.uuid = uuid; } /** * Get the wrapped player's uuid. * @return the uuid */ public UUID getUuid() { return this.uuid; } /** * Get the wrapped Bukkit player. * It may return null if the object wraps a UUID that does not exist. * * @return the player, or null */ public Player getPlayer() { if (p == null) return Bukkit.getPlayer(uuid); return p; } /** * Get the wrapped Bukkit offline player. * Safer to use than getPlayer (this does not return a null). * It may return an empty player if the object wraps a UUID that does not exist. * * @return the offline player */ public OfflinePlayer getOfflinePlayer() { if (p == null) return Bukkit.getOfflinePlayer(uuid); return p; } public String getName() { return getOfflinePlayer().getName(); } /** * Get if the player has a certain amount of money. * Vault must be enabled! * * @param amount the amount to check * @return whether the player has this amount of money */ public boolean hasAmount(double amount) { if (!ProtectionStones.getInstance().isVaultSupportEnabled()) return false; return ProtectionStones.getInstance().getVaultEconomy().has(getOfflinePlayer(), amount); } /** * Get the player's balance. * Vault must be enabled! * * @return the amount of money the player has */ public double getBalance() { if (!ProtectionStones.getInstance().isVaultSupportEnabled()) return 0; return ProtectionStones.getInstance().getVaultEconomy().getBalance(getOfflinePlayer()); } /** * Add a certain amount to the player's bank account. * Vault must be enabled! Must be run on main thread! * * @param amount the amount to add * @return the {@link EconomyResponse} that is given by Vault */ public EconomyResponse depositBalance(double amount) { if (ProtectionStones.getInstance().getVaultEconomy() == null) return null; return ProtectionStones.getInstance().getVaultEconomy().depositPlayer(getOfflinePlayer(), amount); } /** * Withdraw a certain amount from the player's bank account. * Vault must be enabled! Must be run on main thread! * * @param amount the amount to withdraw * @return the {@link EconomyResponse} that is given by Vault */ public EconomyResponse withdrawBalance(double amount) { if (ProtectionStones.getInstance().getVaultEconomy() == null) return null; return ProtectionStones.getInstance().getVaultEconomy().withdrawPlayer(getOfflinePlayer(), amount); } /** * Pay another player a certain amount of money. * Vault must be enabled! Must be run on main thread! * * @param payee the player to pay * @param amount the amount to pay */ public void pay(PSPlayer payee, double amount) { withdrawBalance(amount); payee.depositBalance(amount); } static class CannotAccessOfflinePlayerPermissionsException extends RuntimeException {} /** * Get a player's permission limits for each protection block (protectionstones.limit.alias.x) * Protection blocks that aren't specified in the player's permissions will not be returned in the map. * If LuckPerms support isn't enabled and the player is not online, then the method will throw a CannotAccessOfflinePlayerPermissionsException. * * @return a hashmap containing a psprotectblock object to an integer, which is the number of protection regions of that type the player is allowed to place */ public HashMap<PSProtectBlock, Integer> getRegionLimits() { HashMap<PSProtectBlock, Integer> regionLimits = new HashMap<>(); List<String> permissions; if (getPlayer() != null) { permissions = getPlayer().getEffectivePermissions().stream().map(PermissionAttachmentInfo::getPermission).collect(Collectors.toList()); } else if (getOfflinePlayer().getPlayer() != null) { permissions = getOfflinePlayer().getPlayer().getEffectivePermissions().stream().map(PermissionAttachmentInfo::getPermission).collect(Collectors.toList()); } else if (ProtectionStones.getInstance().isLuckPermsSupportEnabled()) { // use luckperms to obtain all of an offline player's permissions (vault and spigot api are unable to do this) try { permissions = MiscUtil.getLuckPermsUserPermissions(getUuid()); } catch (InterruptedException | ExecutionException e) { e.printStackTrace(); throw new CannotAccessOfflinePlayerPermissionsException(); } } else { throw new CannotAccessOfflinePlayerPermissionsException(); } for (String perm : permissions) { if (perm.startsWith("protectionstones.limit")) { String[] spl = perm.split("\\."); if (spl.length == 4 && ProtectionStones.getProtectBlockFromAlias(spl[2]) != null) { PSProtectBlock block = ProtectionStones.getProtectBlockFromAlias(spl[2]); int limit = Integer.parseInt(spl[3]); if (regionLimits.get(block) == null || regionLimits.get(block) < limit) { // only use max limit regionLimits.put(block, limit); } } } } return regionLimits; } /** * Get a player's total protection limit from permission (protectionstones.limit.x) * If there is no attached Player object to this PSPlayer, and LuckPerms is not enabled, this throws a CannotAccessOfflinePlayerPermissionsException. * * @return the number of protection regions the player can have, or -1 if there is no limit set. */ public int getGlobalRegionLimits() { if (getPlayer() != null) { return MiscUtil.getPermissionNumber(getPlayer(), "protectionstones.limit.", -1); } else if (ProtectionStones.getInstance().isLuckPermsSupportEnabled()) { // use LuckPerms to obtain all of an offline player's permissions (vault and spigot api are unable to do this) try { List<String> permissions = MiscUtil.getLuckPermsUserPermissions(getUuid()); return MiscUtil.getPermissionNumber(permissions, "protectionstones.limit.", -1); } catch (InterruptedException | ExecutionException e) { e.printStackTrace(); throw new CannotAccessOfflinePlayerPermissionsException(); } } else { throw new CannotAccessOfflinePlayerPermissionsException(); } } /** * Get the list of regions that a player can pay money for taxes to. * Note: this should be run asynchronously, as it can be very slow with large amounts of regions. * * @return the regions that the player owes tax money to */ public List<PSRegion> getTaxEligibleRegions() { HashMap<World, RegionManager> m = WGUtils.getAllRegionManagers(); List<PSRegion> ret = new ArrayList<>(); for (World w : m.keySet()) { RegionManager rgm = m.get(w); for (ProtectedRegion r : rgm.getRegions().values()) { PSRegion psr = PSRegion.fromWGRegion(w, r); if (psr != null && psr.isOwner(getUuid()) && psr.getTypeOptions() != null && psr.getTypeOptions().taxPeriod != -1) { ret.add(psr); } } } return ret; } /** * Get the list of regions that a player owns, or is a member of. It is recommended to run this asynchronously * since the query can be slow. * * @param w world to search for regions in * @param canBeMember whether or not to add regions where the player is a member, not owner * @return list of regions that the player owns (or is a part of if canBeMember is true) */ public List<PSRegion> getPSRegions(World w, boolean canBeMember) { RegionManager rgm = WGUtils.getRegionManagerWithWorld(w); if (rgm == null) return new ArrayList<>(); return rgm.getRegions().values().stream() .filter(ProtectionStones::isPSRegion) .filter(r -> r.getOwners().contains(uuid) || (canBeMember && r.getMembers().contains(uuid))) .map(r -> PSRegion.fromWGRegion(w, r)) .collect(Collectors.toList()); } /** * Get the list of regions that a player owns, or is a member of. It is recommended to run this asynchronously * since the query can be slow. * * Note: Regions that the player owns that are named will be cross-world, otherwise this only searches in one world. * * @param w world to search for regions in * @param canBeMember whether or not to add regions where the player is a member, not owner * @return list of regions that the player owns (or is a part of if canBeMember is true) */ public List<PSRegion> getPSRegionsCrossWorld(World w, boolean canBeMember) { List<PSRegion> regions = getPSRegions(w, canBeMember); // set entry format: "worldName regionId" Set<String> regionIdAdded = regions.stream().map(r -> w.getName() + " " + r.getId()).collect(Collectors.toSet()); // obtain cross-world named worlds ProtectionStones.regionNameToID.forEach((rw, rs) -> { World world = Bukkit.getWorld(rw); RegionManager rm = WGUtils.getRegionManagerWithWorld(world); if (rm != null) { rs.values().forEach(rIds -> rIds.forEach(rId -> { ProtectedRegion r = rm.getRegion(rId); if (r != null && r.getOwners().contains(uuid) && ProtectionStones.isPSRegion(r)) { // check if it has already been added String setId = world.getName() + " " + r.getId(); if (!world.getName().equals(w.getName()) || !regionIdAdded.contains(setId)) { regions.add(PSRegion.fromWGRegion(world, r)); regionIdAdded.add(setId); } } })); } }); return regions; } /** * Get the list of homes a player owns. It is recommended to run this asynchronously. * * Note: Regions that the player owns that are named will be cross-world, otherwise this only searches in one world. * * @param w world to search for regions in * @return list of regions that are the player's homes */ public List<PSRegion> getHomes(World w) { return getPSRegionsCrossWorld(w, ProtectionStones.getInstance().getConfigOptions().allowHomeTeleportForMembers) .stream() .filter(r -> r.getTypeOptions() != null && !r.getTypeOptions().preventPsHome) .collect(Collectors.toList()); } }
13,639
Java
.java
espidev/ProtectionStones
64
30
90
2018-09-17T22:12:12Z
2023-11-13T03:14:47Z
ChatUtil.java
/FileExtraction/Java_unseen/espidev_ProtectionStones/src/main/java/dev/espi/protectionstones/utils/ChatUtil.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package dev.espi.protectionstones.utils; import dev.espi.protectionstones.PSL; import dev.espi.protectionstones.PSRegion; import org.bukkit.entity.Player; import java.util.List; public class ChatUtil { public static void displayDuplicateRegionAliases(Player p, List<PSRegion> r) { StringBuilder rep = new StringBuilder(r.get(0).getId() + " (" + r.get(0).getWorld().getName() + ")"); for (int i = 1; i < r.size(); i++) { rep.append(String.format(", %s (%s)", r.get(i).getId(), r.get(i).getWorld().getName())); } PSL.msg(p, PSL.SPECIFY_ID_INSTEAD_OF_ALIAS.msg().replace("%regions%", rep.toString())); } }
1,315
Java
.java
espidev/ProtectionStones
64
30
90
2018-09-17T22:12:12Z
2023-11-13T03:14:47Z
TextGUI.java
/FileExtraction/Java_unseen/espidev_ProtectionStones/src/main/java/dev/espi/protectionstones/utils/TextGUI.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package dev.espi.protectionstones.utils; import dev.espi.protectionstones.PSL; import net.md_5.bungee.api.chat.ClickEvent; import net.md_5.bungee.api.chat.ComponentBuilder; import net.md_5.bungee.api.chat.HoverEvent; import net.md_5.bungee.api.chat.TextComponent; import org.bukkit.ChatColor; import org.bukkit.command.CommandSender; import java.util.List; public class TextGUI { // page starts at zero, but displays start at one // pageCommand will be replacing %page% public static void displayGUI(CommandSender s, String header, String pageCommand, int currentPage, int guiSize, List<TextComponent> lines, boolean sendBlankLines) { int currentLine = currentPage * guiSize; if (currentPage < 0 || currentLine > lines.size()) { return; } PSL.msg(s, header); for (int i = currentPage*guiSize; i < Math.min((currentPage+1) * guiSize, lines.size()); i++) { if (sendBlankLines || !lines.get(i).equals(new TextComponent(""))) s.spigot().sendMessage(lines.get(i)); } // footer page buttons TextComponent backPage = new TextComponent(ChatColor.AQUA + " <<"), nextPage = new TextComponent(ChatColor.AQUA + ">> "); backPage.setHoverEvent(new HoverEvent(HoverEvent.Action.SHOW_TEXT, new ComponentBuilder(PSL.GO_BACK_PAGE.msg()).create())); nextPage.setHoverEvent(new HoverEvent(HoverEvent.Action.SHOW_TEXT, new ComponentBuilder(PSL.GO_NEXT_PAGE.msg()).create())); backPage.setClickEvent(new ClickEvent(ClickEvent.Action.RUN_COMMAND, pageCommand.replace("%page%", ""+currentPage))); nextPage.setClickEvent(new ClickEvent(ClickEvent.Action.RUN_COMMAND, pageCommand.replace("%page%", currentPage+2+""))); TextComponent footer = new TextComponent(ChatColor.DARK_GRAY + "" + ChatColor.STRIKETHROUGH + "=====" + ChatColor.RESET); // add back page button if the page isn't 0 if (currentPage != 0) footer.addExtra(backPage); // add page number footer.addExtra(new TextComponent(ChatColor.WHITE + " " + (currentPage + 1) + " ")); // add forward page button if the page isn't last if (currentPage * guiSize + guiSize < lines.size()) footer.addExtra(nextPage); footer.addExtra(ChatColor.DARK_GRAY + "" + ChatColor.STRIKETHROUGH + "====="); // display footer only if there are more than one page of entries if (lines.size() >= guiSize) s.spigot().sendMessage(footer); } }
3,148
Java
.java
espidev/ProtectionStones
64
30
90
2018-09-17T22:12:12Z
2023-11-13T03:14:47Z
ParticlesUtil.java
/FileExtraction/Java_unseen/espidev_ProtectionStones/src/main/java/dev/espi/protectionstones/utils/ParticlesUtil.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package dev.espi.protectionstones.utils; import dev.espi.protectionstones.ProtectionStones; import org.bukkit.Bukkit; import org.bukkit.Location; import org.bukkit.Particle; import org.bukkit.entity.Player; public class ParticlesUtil { public static void persistRedstoneParticle(Player p, Location l, Particle.DustOptions d, int occ) { for (int i = 0; i < occ; i++) { Bukkit.getScheduler().runTaskLater(ProtectionStones.getInstance(), () -> { if (p.isOnline()) p.spawnParticle(Particle.REDSTONE, l, 1, d); }, i*20); } } }
1,243
Java
.java
espidev/ProtectionStones
64
30
90
2018-09-17T22:12:12Z
2023-11-13T03:14:47Z
WGMerge.java
/FileExtraction/Java_unseen/espidev_ProtectionStones/src/main/java/dev/espi/protectionstones/utils/WGMerge.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package dev.espi.protectionstones.utils; import com.sk89q.worldedit.math.BlockVector2; import com.sk89q.worldguard.protection.managers.RegionManager; import com.sk89q.worldguard.protection.managers.RemovalStrategy; import com.sk89q.worldguard.protection.regions.ProtectedPolygonalRegion; import com.sk89q.worldguard.protection.regions.ProtectedRegion; import dev.espi.protectionstones.*; import org.bukkit.Bukkit; import org.bukkit.World; import java.util.*; public class WGMerge { public static class RegionHoleException extends Exception { } public static class RegionCannotMergeWhileRentedException extends Exception { PSRegion rentedRegion; RegionCannotMergeWhileRentedException(PSRegion r) { rentedRegion = r; } public PSRegion getRentedRegion() { return rentedRegion; } } // welcome to giant mess of code that does some bad stuff // :D // more to come in RegionTraverse // build groups of overlapping regions in idToGroup and groupToIDs public static void findOverlappingRegionGroups(World w, List<ProtectedRegion> regions, HashMap<String, String> idToGroup, HashMap<String, ArrayList<String>> groupToIDs) { for (ProtectedRegion iter : regions) { Set<ProtectedRegion> overlapping = WGUtils.findOverlapOrAdjacentRegions(iter, regions, w); // algorithm to find adjacent regions String adjacentGroup = idToGroup.get(iter.getId()); for (ProtectedRegion pr : overlapping) { if (adjacentGroup == null) { // if the region hasn't been found to overlap a region yet if (idToGroup.get(pr.getId()) == null) { // if the overlapped region isn't part of a group yet idToGroup.put(pr.getId(), iter.getId()); idToGroup.put(iter.getId(), iter.getId()); groupToIDs.put(iter.getId(), new ArrayList<>(Arrays.asList(pr.getId(), iter.getId()))); // create new group } else { // if the overlapped region is part of a group String groupID = idToGroup.get(pr.getId()); idToGroup.put(iter.getId(), groupID); groupToIDs.get(groupID).add(iter.getId()); } adjacentGroup = idToGroup.get(iter.getId()); } else { // if the region is part of a group already if (idToGroup.get(pr.getId()) == null) { // if the overlapped region isn't part of a group idToGroup.put(pr.getId(), adjacentGroup); groupToIDs.get(adjacentGroup).add(pr.getId()); } else if (!idToGroup.get(pr.getId()).equals(adjacentGroup)) { // if the overlapped region is part of a group, merge the groups String mergeGroupID = idToGroup.get(pr.getId()); for (String gid : groupToIDs.get(mergeGroupID)) idToGroup.put(gid, adjacentGroup); groupToIDs.get(adjacentGroup).addAll(groupToIDs.get(mergeGroupID)); groupToIDs.remove(mergeGroupID); } } } if (adjacentGroup == null) { idToGroup.put(iter.getId(), iter.getId()); groupToIDs.put(iter.getId(), new ArrayList<>(Collections.singletonList(iter.getId()))); } } } public static void unmergeRegion(World w, RegionManager rm, PSMergedRegion toUnmerge) throws RegionHoleException, RegionCannotMergeWhileRentedException { PSGroupRegion psr = toUnmerge.getGroupRegion(); // group region ProtectedRegion r = psr.getWGRegion(); String blockType = toUnmerge.getType(); try { // remove the actual region info psr.removeMergedRegionInfo(toUnmerge.getId()); // if there is only 1 region now, revert to standard region if (r.getFlag(FlagHandler.PS_MERGED_REGIONS).size() == 1) { String[] spl = r.getFlag(FlagHandler.PS_MERGED_REGIONS_TYPES).iterator().next().split(" "); String id = spl[0], type = spl[1]; ProtectedRegion nRegion = WGUtils.getDefaultProtectedRegion(ProtectionStones.getBlockOptions(type), WGUtils.parsePSRegionToLocation(id)); nRegion.copyFrom(r); nRegion.setFlag(FlagHandler.PS_BLOCK_MATERIAL, type); nRegion.setFlag(FlagHandler.PS_MERGED_REGIONS, null); nRegion.setFlag(FlagHandler.PS_MERGED_REGIONS_TYPES, null); // reapply name cache PSRegion rr = PSRegion.fromWGRegion(w, nRegion); rr.setName(rr.getName()); rm.removeRegion(r.getId()); rm.addRegion(nRegion); } else { // otherwise, remove region // check if unmerge will split the region into pieces HashMap<String, String> idToGroup = new HashMap<>(); HashMap<String, ArrayList<String>> groupToIDs = new HashMap<>(); List<ProtectedRegion> toCheck = new ArrayList<>(); HashMap<String, PSMergedRegion> mergedRegions = new HashMap<>(); // add decomposed regions for (PSMergedRegion ps : psr.getMergedRegions()) { mergedRegions.put(ps.getId(), ps); toCheck.add(WGUtils.getDefaultProtectedRegion(ps.getTypeOptions(), WGUtils.parsePSRegionToLocation(ps.getId()))); } // build set of groups of overlapping regions findOverlappingRegionGroups(w, toCheck, idToGroup, groupToIDs); // check how many groups there are and relabel the original root to be the head ID boolean foundOriginal = false; List<ProtectedRegion> regionsToAdd = new ArrayList<>(); // loop over each set of overlapping region groups and add create full region for each for (String key : groupToIDs.keySet()) { boolean found = false; List<PSRegion> l = new ArrayList<>(); PSRegion newRoot = null; try { // loop over regions in a group // add to cache and and also check if this set contains the original root region for (String id : groupToIDs.get(key)) { if (id.equals(psr.getId())) { // original root region found = true; foundOriginal = true; break; } if (id.equals(key)) { // new root region newRoot = mergedRegions.get(id); } l.add(mergedRegions.get(id)); } if (!found) { // if this set does NOT contain the root ID region // remove id information from base region for (String id : groupToIDs.get(key)) psr.removeMergedRegionInfo(id); // split off from base region ProtectedRegion split = mergeRegions(key, psr, l); split.setFlag(FlagHandler.PS_BLOCK_MATERIAL, newRoot.getType()); // apply new block type regionsToAdd.add(split); // create new region } } catch (Exception e) { e.printStackTrace(); } } // recreate original region with the new set (of removed psmergedregions) if (foundOriginal) { mergeRegions(w, rm, psr, Arrays.asList(psr)); } else { psr.setName(null); // remove name from cache rm.removeRegion(psr.getId(), RemovalStrategy.UNSET_PARENT_IN_CHILDREN); } // add all regions that do NOT contain the root ID region for (ProtectedRegion pr : regionsToAdd) { PSRegion rr = PSRegion.fromWGRegion(w, pr); rr.setName(rr.getName()); // reapply name cache rm.addRegion(pr); } } } catch (RegionHoleException | RegionCannotMergeWhileRentedException e) { // if there is a region hole exception, put back the merged region info psr.getWGRegion().getFlag(FlagHandler.PS_MERGED_REGIONS).add(toUnmerge.getId()); psr.getWGRegion().getFlag(FlagHandler.PS_MERGED_REGIONS_TYPES).add(toUnmerge.getId() + " " + blockType); throw e; } } // additional behaviour for merging region flags private static void mergeRegionFlags(List<PSRegion> baseRegions, PSRegion mergedRegion) { Set<String> taxPaymentsDue = mergedRegion.getWGRegion().getFlag(FlagHandler.PS_TAX_PAYMENTS_DUE); Set<String> lastTaxAdditions = mergedRegion.getWGRegion().getFlag(FlagHandler.PS_TAX_LAST_PAYMENT_ADDED); if (taxPaymentsDue == null) taxPaymentsDue = new HashSet<>(); if (lastTaxAdditions == null) lastTaxAdditions = new HashSet<>(); for (PSRegion r : baseRegions) { // merge owners and members list mergedRegion.getWGRegion().getOwners().addAll(r.getWGRegion().getOwners()); mergedRegion.getWGRegion().getMembers().addAll(r.getWGRegion().getMembers()); // merge tax payments if (r.getWGRegion().getFlag(FlagHandler.PS_TAX_PAYMENTS_DUE) != null) { taxPaymentsDue.addAll(r.getWGRegion().getFlag(FlagHandler.PS_TAX_PAYMENTS_DUE)); } if (r.getWGRegion().getFlag(FlagHandler.PS_TAX_LAST_PAYMENT_ADDED) != null) { lastTaxAdditions.addAll(r.getWGRegion().getFlag(FlagHandler.PS_TAX_LAST_PAYMENT_ADDED)); } } mergedRegion.getWGRegion().setFlag(FlagHandler.PS_TAX_PAYMENTS_DUE, taxPaymentsDue); mergedRegion.getWGRegion().setFlag(FlagHandler.PS_TAX_LAST_PAYMENT_ADDED, lastTaxAdditions); } // the regions in the merge list must actually exist // this is used by player merge interfaces public static PSRegion mergeRealRegions(World w, RegionManager rm, PSRegion root, List<PSRegion> merge) throws RegionHoleException, RegionCannotMergeWhileRentedException { PSRegion r = mergeRegions(w, rm, root, merge); mergeRegionFlags(merge, r); return r; } // each region in merge must not be of type PSMergedRegion private static PSRegion mergeRegions(World w, RegionManager rm, PSRegion root, List<PSRegion> merge) throws RegionHoleException, RegionCannotMergeWhileRentedException { return mergeRegions(root.getId(), w, rm, root, merge); } // merge contains ALL regions to be merged, and must ALL exist // root is the base flags to be copied public static PSRegion mergeRegions(String newID, World w, RegionManager rm, PSRegion root, List<PSRegion> merge) throws RegionHoleException, RegionCannotMergeWhileRentedException { List<PSRegion> decomposedMerge = new ArrayList<>(); // decompose merged regions into their bases for (PSRegion r : merge) { if (r.getRentStage() != PSRegion.RentStage.NOT_RENTING) { throw new RegionCannotMergeWhileRentedException(r); } if (r instanceof PSGroupRegion) { decomposedMerge.addAll(((PSGroupRegion) r).getMergedRegions()); } else { decomposedMerge.add(r); } } // actually merge the base regions PSRegion nRegion = PSRegion.fromWGRegion(w, mergeRegions(newID, root, decomposedMerge)); for (PSRegion r : merge) { if (!r.getId().equals(newID)) { // run delete event for non-root real regions Bukkit.getScheduler().runTask(ProtectionStones.getInstance(), () -> r.deleteRegion(false)); } else { rm.removeRegion(r.getId()); } } try { nRegion.setName(nRegion.getName()); // reapply name cache } catch (NullPointerException ignored) { } // catch nulls rm.addRegion(nRegion.getWGRegion()); return nRegion; } // returns a merged region; root and merge must be overlapping or adjacent // merge parameter must all be decomposed regions (down to cuboids, no polygon) private static ProtectedRegion mergeRegions(String newID, PSRegion root, List<PSRegion> merge) throws RegionHoleException { HashSet<BlockVector2> points = new HashSet<>(); List<ProtectedRegion> regions = new ArrayList<>(); // decompose regions down to their points for (PSRegion r : merge) { points.addAll(WGUtils.getPointsFromDecomposedRegion(r)); regions.add(r.getWGRegion()); } // points of new region List<BlockVector2> vertex = new ArrayList<>(); HashMap<Integer, ArrayList<BlockVector2>> vertexGroups = new HashMap<>(); // traverse region edges for vertex RegionTraverse.traverseRegionEdge(points, regions, tr -> { if (tr.isVertex) { if (vertexGroups.containsKey(tr.vertexGroupID)) { vertexGroups.get(tr.vertexGroupID).add(tr.point); } else { vertexGroups.put(tr.vertexGroupID, new ArrayList<>(Arrays.asList(tr.point))); } } }); // allow_merging_holes option // prevent holes from being formed if (vertexGroups.size() > 1 && !ProtectionStones.getInstance().getConfigOptions().allowMergingHoles) { throw new RegionHoleException(); } // assemble vertex group // draw in and out lines between holes boolean first = true; BlockVector2 backPoint = null; for (List<BlockVector2> l : vertexGroups.values()) { if (first) { first = false; vertex.addAll(l); backPoint = l.get(0); } else { vertex.addAll(l); vertex.add(l.get(0)); } vertex.add(backPoint); } // merge sets of region name flag Set<String> regionNames = new HashSet<>(), regionLines = new HashSet<>(); for (PSRegion r : merge) { if (r.getWGRegion().getFlag(FlagHandler.PS_MERGED_REGIONS) != null) { regionNames.addAll(r.getWGRegion().getFlag(FlagHandler.PS_MERGED_REGIONS)); regionLines.addAll(r.getWGRegion().getFlag(FlagHandler.PS_MERGED_REGIONS_TYPES)); } else { regionNames.add(r.getId()); regionLines.add(r.getId() + " " + r.getType()); } } // create new merged region ProtectedRegion r = new ProtectedPolygonalRegion(newID, vertex, WGUtils.MIN_BUILD_HEIGHT, WGUtils.MAX_BUILD_HEIGHT); r.copyFrom(root.getWGRegion()); // only make it a merged region if there is more than one contained region if (regionNames.size() > 1 && regionLines.size() > 1) { r.setFlag(FlagHandler.PS_MERGED_REGIONS, regionNames); r.setFlag(FlagHandler.PS_MERGED_REGIONS_TYPES, regionLines); } else { r.setFlag(FlagHandler.PS_MERGED_REGIONS, null); r.setFlag(FlagHandler.PS_MERGED_REGIONS_TYPES, null); } return r; } }
16,461
Java
.java
espidev/ProtectionStones
64
30
90
2018-09-17T22:12:12Z
2023-11-13T03:14:47Z
UUIDCache.java
/FileExtraction/Java_unseen/espidev_ProtectionStones/src/main/java/dev/espi/protectionstones/utils/UUIDCache.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package dev.espi.protectionstones.utils; import com.sk89q.worldguard.WorldGuard; import com.sk89q.worldguard.util.profile.Profile; import java.util.HashMap; import java.util.Map; import java.util.UUID; public class UUIDCache { private static Map<UUID, String> uuidToName = new HashMap<>(); private static Map<String, UUID> nameToUUID = new HashMap<>(); // toLowerCase for case insensitive search public static UUID getUUIDFromName(String name) { if (name == null) return null; return nameToUUID.get(name.toLowerCase()); } public static String getNameFromUUID(UUID uuid) { if (uuid == null) return null; return uuidToName.get(uuid); } public static boolean containsName(String name) { if (name == null) return false; return nameToUUID.containsKey(name.toLowerCase()); } public static boolean containsUUID(UUID uuid) { if (uuid == null) return false; return uuidToName.containsKey(uuid); } public static void storeUUIDNamePair(UUID uuid, String name) { if (uuid == null || name == null) return; uuidToName.put(uuid, name); nameToUUID.put(name.toLowerCase(), uuid); } public static void removeUUID(UUID uuid) { if (uuid == null) return; uuidToName.remove(uuid); } public static void removeName(String name) { if (name == null) return; nameToUUID.remove(name.toLowerCase()); } public static void storeWGProfile(UUID uuid, String name) { WorldGuard.getInstance().getProfileCache().put(new Profile(uuid, name)); } }
2,281
Java
.java
espidev/ProtectionStones
64
30
90
2018-09-17T22:12:12Z
2023-11-13T03:14:47Z