Making Txt and Perm completely static utilities.

This commit is contained in:
Olof Larsson 2011-12-28 00:05:07 +01:00
parent 1a8a8e0e21
commit c18a57f17a
11 changed files with 468 additions and 597 deletions

View File

@ -22,9 +22,9 @@ import com.massivecraft.mcore1.cmd.Cmd;
import com.massivecraft.mcore1.lib.gson.GsonBuilder;
import com.massivecraft.mcore1.persist.One;
import com.massivecraft.mcore1.persist.Persist;
import com.massivecraft.mcore1.text.Txt;
import com.massivecraft.mcore1.util.Perm;
import com.massivecraft.mcore1.util.LibLoader;
import com.massivecraft.mcore1.util.PlayerUtil;
import com.massivecraft.mcore1.util.Txt;
public class MCore extends JavaPlugin
{
@ -70,35 +70,6 @@ public class MCore extends JavaPlugin
return false;
}
// -------------------------------------------- //
// TXT
// -------------------------------------------- //
public static Txt txt = new Txt();
private static Map<Object, Txt> txtInstances = new HashMap<Object, Txt>();
public static Map<Object, Txt> getTxtInstances() { return txtInstances; }
public static Txt getTxt(Object owner) { return txtInstances.get(owner); }
public static void removeTxt(Object owner) { txtInstances.remove(owner); }
public static void createTxt(Object owner)
{
if (txtInstances.containsKey(owner)) return;
txtInstances.put(owner, new Txt());
}
// -------------------------------------------- //
// PERM
// -------------------------------------------- //
public static Perm perm = new Perm(txt);
private static Map<Object, Perm> permInstances = new HashMap<Object, Perm>();
public static Map<Object, Perm> getPermInstances() { return permInstances; }
public static Perm getPerm(Object owner) { return permInstances.get(owner); }
public static void removePerm(Object owner) { permInstances.remove(owner); }
public static void createPerm(Object owner)
{
if (permInstances.containsKey(owner)) return;
createTxt(owner);
permInstances.put(owner, new Perm(getTxt(owner)));
}
// -------------------------------------------- //
// ONE
// -------------------------------------------- //
@ -109,10 +80,22 @@ public class MCore extends JavaPlugin
public static void createOne(MPlugin owner)
{
if (oneInstances.containsKey(owner)) return;
createTxt(owner);
oneInstances.put(owner, new One(owner));
}
// -------------------------------------------- //
// LIBLOADER
// -------------------------------------------- //
private static Map<MPlugin, LibLoader> libLoaderInstances = new HashMap<MPlugin, LibLoader>();
public static Map<MPlugin, LibLoader> getLibLoaderInstances() { return libLoaderInstances; }
public static LibLoader getLibLoader(MPlugin owner) { return libLoaderInstances.get(owner); }
public static void removeLibLoader(MPlugin owner) { libLoaderInstances.remove(owner); }
public static void createLibLoader(MPlugin owner)
{
if (libLoaderInstances.containsKey(owner)) return;
libLoaderInstances.put(owner, new LibLoader(owner));
}
// -------------------------------------------- //
// DERP
// -------------------------------------------- //
@ -168,6 +151,6 @@ public class MCore extends JavaPlugin
}
public static void log(Level level, Object... msg)
{
Logger.getLogger("Minecraft").log(level, logPrefix + MCore.txt.implode(msg, " "));
Logger.getLogger("Minecraft").log(level, logPrefix + Txt.implode(msg, " "));
}
}

View File

@ -13,8 +13,8 @@ import com.massivecraft.mcore1.lib.gson.Gson;
import com.massivecraft.mcore1.lib.gson.GsonBuilder;
import com.massivecraft.mcore1.persist.One;
import com.massivecraft.mcore1.persist.Persist;
import com.massivecraft.mcore1.text.Txt;
import com.massivecraft.mcore1.util.Perm;
import com.massivecraft.mcore1.util.LibLoader;
import com.massivecraft.mcore1.util.Txt;
public abstract class MPlugin extends JavaPlugin
@ -23,8 +23,7 @@ public abstract class MPlugin extends JavaPlugin
public Cmd cmd;
public Persist persist;
public One one;
public Txt txt;
public Perm perm;
public LibLoader lib;
// Gson
public Gson gson;
@ -50,15 +49,13 @@ public abstract class MPlugin extends JavaPlugin
MCore.createCmd(this);
MCore.createPersist(this);
MCore.createOne(this);
MCore.createTxt(this);
MCore.createPerm(this);
MCore.createLibLoader(this);
// Assign tool pointers
this.cmd = MCore.getCmd(this);
this.persist = MCore.getPersist(this);
this.one = MCore.getOne(this);
this.txt = MCore.getTxt(this);
this.perm = MCore.getPerm(this);
this.lib = MCore.getLibLoader(this);
return true;
}
@ -78,14 +75,12 @@ public abstract class MPlugin extends JavaPlugin
MCore.removePersist(this);
MCore.removeOne(this);
MCore.removeCmd(this);
MCore.removePerm(this);
MCore.removeTxt(this);
MCore.removeLibLoader(this);
this.cmd = null;
this.persist = null;
this.one = null;
this.txt = null;
this.perm = null;
this.lib = null;
log("Disabled");
}
@ -129,6 +124,6 @@ public abstract class MPlugin extends JavaPlugin
}
public void log(Level level, Object... msg)
{
Logger.getLogger("Minecraft").log(level, this.logPrefix + MCore.txt.implode(msg, " "));
Logger.getLogger("Minecraft").log(level, this.logPrefix + Txt.implode(msg, " "));
}
}

View File

@ -4,6 +4,7 @@ import java.util.ArrayList;
import com.massivecraft.mcore1.MPlugin;
import com.massivecraft.mcore1.cmd.MCommand;
import com.massivecraft.mcore1.util.Txt;
public class HelpCommand extends MCommand
{
@ -23,7 +24,7 @@ public class HelpCommand extends MCommand
ArrayList<String> lines = new ArrayList<String>();
lines.addAll(p().txt.parse(parentCommand.getHelp()));
lines.addAll(Txt.parse(parentCommand.getHelp()));
for(MCommand subCommand : parentCommand.getSubCommands())
{
@ -35,7 +36,7 @@ public class HelpCommand extends MCommand
Integer pagenumber = this.argAs(0, Integer.class, 1);
if (pagenumber == null) return;
sendMessage(p().txt.getPage(lines, pagenumber, "Help for command \""+parentCommand.getAliases().get(0)+"\""));
sendMessage(Txt.getPage(lines, pagenumber, "Help for command \""+parentCommand.getAliases().get(0)+"\""));
}
@Override

View File

@ -14,6 +14,8 @@ import com.massivecraft.mcore1.cmd.arg.IArgHandler;
import com.massivecraft.mcore1.cmd.req.IReq;
import com.massivecraft.mcore1.persist.IClassManager;
import com.massivecraft.mcore1.persist.Persist;
import com.massivecraft.mcore1.util.Perm;
import com.massivecraft.mcore1.util.Txt;
public abstract class MCommand
{
@ -79,7 +81,7 @@ public abstract class MCommand
{
if (this.desc == null)
{
String pdesc = p().perm.getPermissionDescription(this.descPermission);
String pdesc = Perm.getPermissionDescription(this.descPermission);
if (pdesc != null)
{
return pdesc;
@ -271,7 +273,7 @@ public abstract class MCommand
{
// Get the to many string slice
List<String> theToMany = args.subList(this.requiredArgs.size() + this.optionalArgs.size(), args.size());
msg(Lang.commandToManyArgs, p().txt.implode(theToMany, " "));
msg(Lang.commandToManyArgs, Txt.implode(theToMany, " "));
sender.sendMessage(this.getUseageTemplate());
}
return false;
@ -290,16 +292,16 @@ public abstract class MCommand
public String getUseageTemplate(List<MCommand> commandChain, boolean addDesc)
{
StringBuilder ret = new StringBuilder();
ret.append(p().txt.getDesign().getColorCommand());
ret.append(Txt.parse("<c>"));
ret.append('/');
for (MCommand mc : commandChain)
{
ret.append(p().txt.implode(mc.aliases, ","));
ret.append(Txt.implode(mc.aliases, ","));
ret.append(' ');
}
ret.append(p().txt.implode(this.aliases, ","));
ret.append(Txt.implode(this.aliases, ","));
List<String> args = new ArrayList<String>();
@ -324,15 +326,15 @@ public abstract class MCommand
if (args.size() > 0)
{
ret.append(p().txt.getDesign().getColorParameter());
ret.append(Txt.parse("<p>"));
ret.append(' ');
ret.append(p().txt.implode(args, " "));
ret.append(Txt.implode(args, " "));
}
if (addDesc)
{
ret.append(' ');
ret.append(p().txt.getDesign().getColorInfo());
ret.append(Txt.parse("<i>"));
ret.append(this.getDesc());
}
@ -355,12 +357,12 @@ public abstract class MCommand
public void msg(String str, Object... args)
{
sender.sendMessage(p().txt.parse(str, args));
sender.sendMessage(Txt.parse(str, args));
}
public void msg(String str)
{
sender.sendMessage(p().txt.parse(str));
sender.sendMessage(Txt.parse(str));
}
public void sendMessage(String msg)

View File

@ -3,6 +3,7 @@ package com.massivecraft.mcore1.cmd.req;
import org.bukkit.command.CommandSender;
import com.massivecraft.mcore1.cmd.MCommand;
import com.massivecraft.mcore1.util.Perm;
public class ReqHasPerm implements IReq
{
@ -24,7 +25,7 @@ public class ReqHasPerm implements IReq
@Override
public String createErrorMessage(CommandSender sender, MCommand command)
{
return command.p().perm.getForbiddenMessage(this.perm);
return Perm.getForbiddenMessage(this.perm);
}
}

View File

@ -1,419 +0,0 @@
package com.massivecraft.mcore1.text;
import java.util.*;
import java.util.Map.Entry;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.bukkit.ChatColor;
import org.bukkit.Material;
import org.bukkit.craftbukkit.TextWrapper;
public class Txt
{
// Global Default Design TODO: Assign it somehow!
private static TxtDesign defaultDesign = new TxtDesign();
public static TxtDesign getDefaultDesign() { return defaultDesign; }
public static void setDefaultDesign(TxtDesign val) { defaultDesign = val; }
// Local Desgin Choice
private TxtDesign design = null;
public TxtDesign getDesign()
{
if (design != null) return design;
return getDefaultDesign();
}
public void setDesign(TxtDesign design)
{
this.design = design;
}
// -------------------------------------------- //
// CONSTRUCTORS
// -------------------------------------------- //
public Txt()
{
}
public Txt(TxtDesign design)
{
this.design = design;
}
// -------------------------------------------- //
// Top-level parsing functions.
// -------------------------------------------- //
public String parse(String string, Object... args)
{
return String.format(this.parse(string), args);
}
public String parse(String string)
{
return this.parseTags(parseColor(string));
}
public ArrayList<String> parse(Collection<String> strings)
{
return this.parseTags(parseColor(strings));
}
// -------------------------------------------- //
// Tag parsing
// -------------------------------------------- //
public static final transient Pattern patternTag = Pattern.compile("<([a-zA-Z0-9_]*)>");
public String replaceTags(String string, Map<String, String> tags)
{
StringBuffer ret = new StringBuffer();
Matcher matcher = patternTag.matcher(string);
while (matcher.find())
{
String tag = matcher.group(1);
String repl = tags.get(tag);
if (repl == null)
{
matcher.appendReplacement(ret, "<"+tag+">");
}
else
{
matcher.appendReplacement(ret, repl);
}
}
matcher.appendTail(ret);
return ret.toString();
}
public String parseTags(String string)
{
return replaceTags(string, this.getDesign().getTags());
}
public ArrayList<String> parseTags(Collection<String> strings)
{
ArrayList<String> ret = new ArrayList<String>(strings.size());
for (String string : strings)
{
ret.add(this.parseTags(string));
}
return ret;
}
// -------------------------------------------- //
// Color parsing
// -------------------------------------------- //
public String parseColor(String string)
{
string = parseColorAmp(string);
string = parseColorAcc(string);
string = parseColorTags(string);
return string;
}
public ArrayList<String> parseColor(Collection<String> strings)
{
ArrayList<String> ret = new ArrayList<String>(strings.size());
for (String string : strings)
{
ret.add(this.parseColor(string));
}
return ret;
}
public String parseColorAmp(String string)
{
string = string.replaceAll("(§([a-z0-9]))", "\u00A7$2");
string = string.replaceAll("(&([a-z0-9]))", "\u00A7$2");
string = string.replace("&&", "&");
return string;
}
public String parseColorAcc(String string)
{
return string.replace("`e", "")
.replace("`r", ChatColor.RED.toString()) .replace("`R", ChatColor.DARK_RED.toString())
.replace("`y", ChatColor.YELLOW.toString()) .replace("`Y", ChatColor.GOLD.toString())
.replace("`g", ChatColor.GREEN.toString()) .replace("`G", ChatColor.DARK_GREEN.toString())
.replace("`a", ChatColor.AQUA.toString()) .replace("`A", ChatColor.DARK_AQUA.toString())
.replace("`b", ChatColor.BLUE.toString()) .replace("`B", ChatColor.DARK_BLUE.toString())
.replace("`p", ChatColor.LIGHT_PURPLE.toString()) .replace("`P", ChatColor.DARK_PURPLE.toString())
.replace("`k", ChatColor.BLACK.toString()) .replace("`s", ChatColor.GRAY.toString())
.replace("`S", ChatColor.DARK_GRAY.toString()) .replace("`w", ChatColor.WHITE.toString());
}
public String parseColorTags(String string)
{
return string.replace("<empty>", "")
.replace("<black>", "\u00A70")
.replace("<navy>", "\u00A71")
.replace("<green>", "\u00A72")
.replace("<teal>", "\u00A73")
.replace("<red>", "\u00A74")
.replace("<purple>", "\u00A75")
.replace("<gold>", "\u00A76")
.replace("<silver>", "\u00A77")
.replace("<gray>", "\u00A78")
.replace("<blue>", "\u00A79")
.replace("<lime>", "\u00A7a")
.replace("<aqua>", "\u00A7b")
.replace("<rose>", "\u00A7c")
.replace("<pink>", "\u00A7d")
.replace("<yellow>", "\u00A7e")
.replace("<white>", "\u00A7f");
}
// -------------------------------------------- //
// Standard utils like UCFirst, implode and repeat.
// -------------------------------------------- //
public String upperCaseFirst(String string)
{
return string.substring(0, 1).toUpperCase()+string.substring(1);
}
public String repeat(String string, int times)
{
if (times <= 0) return "";
else return string + repeat(string, times-1);
}
public String implode(List<String> list, String glue)
{
return this.implode(list.toArray(new String[0]), glue);
}
public String implode(Object[] list, String glue)
{
StringBuilder ret = new StringBuilder();
for (int i=0; i<list.length; i++)
{
if (i!=0)
{
ret.append(glue);
}
ret.append(list[i]);
}
return ret.toString();
}
public String implodeCommaAnd(List<String> list, String comma, String and)
{
if (list.size() == 0) return "";
if (list.size() == 1) return list.get(0);
String lastItem = list.get(list.size()-1);
String nextToLastItem = list.get(list.size()-2);
String merge = nextToLastItem+and+lastItem;
list.set(list.size()-2, merge);
list.remove(list.size()-1);
return implode(list, comma);
}
public String implodeCommaAnd(List<String> list, String color)
{
return implodeCommaAnd(list, color+", ", color+" and ");
}
public String implodeCommaAnd(List<String> list)
{
return implodeCommaAnd(list, "");
}
// -------------------------------------------- //
// Material name tools
// -------------------------------------------- //
public String getMaterialName(Material material)
{
return material.toString().replace('_', ' ').toLowerCase();
}
public String getMaterialName(int materialId)
{
return getMaterialName(Material.getMaterial(materialId));
}
// -------------------------------------------- //
// Paging and chrome-tools like titleize
// -------------------------------------------- //
private final String titleizeLine = repeat("_", 52);
private final int titleizeBalance = -1;
public String titleize(String str)
{
String center = ".[ "+ this.getDesign().getColorLogo() + str + this.getDesign().getColorArt() + " ].";
int centerlen = ChatColor.stripColor(center).length();
int pivot = titleizeLine.length() / 2;
int eatLeft = (centerlen / 2) - titleizeBalance;
int eatRight = (centerlen - eatLeft) + titleizeBalance;
if (eatLeft < pivot)
return this.getDesign().getColorArt()+titleizeLine.substring(0, pivot - eatLeft) + center + titleizeLine.substring(pivot + eatRight);
else
return this.getDesign().getColorArt()+center;
}
public ArrayList<String> getPage(List<String> lines, int pageHumanBased, String title)
{
ArrayList<String> ret = new ArrayList<String>();
int pageZeroBased = pageHumanBased - 1;
int pageheight = 9;
int pagecount = (lines.size() / pageheight)+1;
ret.add(this.titleize(title+" "+pageHumanBased+"/"+pagecount));
if (pagecount == 0)
{
ret.add(this.parseTags("<i>Sorry. No Pages available."));
return ret;
}
else if (pageZeroBased < 0 || pageHumanBased > pagecount)
{
ret.add(this.parseTags("<i>Invalid page. Must be between 1 and "+pagecount));
return ret;
}
int from = pageZeroBased * pageheight;
int to = from+pageheight;
if (to > lines.size())
{
to = lines.size();
}
ret.addAll(lines.subList(from, to));
return ret;
}
// -------------------------------------------- //
// Describing Time
// -------------------------------------------- //
/**
* Using this function you transform a delta in milliseconds
* to a String like "2 weeks from now" or "7 days ago".
*/
public static final long millisPerSecond = 1000;
public static final long millisPerMinute = 60 * millisPerSecond;
public static final long millisPerHour = 60 * millisPerMinute;
public static final long millisPerDay = 24 * millisPerHour;
public static final long millisPerWeek = 7 * millisPerDay;
public static final long millisPerMonth = 31 * millisPerDay;
public static final long millisPerYear = 365 * millisPerDay;
public static Map<String, Long> unitMillis;
static
{
unitMillis = new LinkedHashMap<String, Long>();
unitMillis.put("years", millisPerYear);
unitMillis.put("months", millisPerMonth);
unitMillis.put("weeks", millisPerWeek);
unitMillis.put("days", millisPerDay);
unitMillis.put("hours", millisPerHour);
unitMillis.put("minutes", millisPerMinute);
unitMillis.put("seconds", millisPerSecond);
}
public String getTimeDeltaDescriptionRelNow(long millis)
{
String ret = "";
double millisLeft = (double) Math.abs(millis);
List<String> unitCountParts = new ArrayList<String>();
for (Entry<String, Long> entry : unitMillis.entrySet())
{
if (unitCountParts.size() == 3 ) break;
String unitName = entry.getKey();
long unitSize = entry.getValue();
long unitCount = (long) Math.floor(millisLeft / unitSize);
if (unitCount < 1) continue;
millisLeft -= unitSize*unitCount;
unitCountParts.add(unitCount+" "+unitName);
}
if (unitCountParts.size() == 0) return "just now";
ret += implodeCommaAnd(unitCountParts);
ret += " ";
if (millis <= 0)
{
ret += "ago";
}
else
{
ret += "from now";
}
return ret;
}
// -------------------------------------------- //
// String comparison
// -------------------------------------------- //
public String getBestCIStart(Collection<String> candidates, String start)
{
String ret = null;
int best = 0;
start = start.toLowerCase();
int minlength = start.length();
for (String candidate : candidates)
{
if (candidate.length() < minlength) continue;
if ( ! candidate.toLowerCase().startsWith(start)) continue;
// The closer to zero the better
int lendiff = candidate.length() - minlength;
if (lendiff == 0)
{
return candidate;
}
if (lendiff < best || best == 0)
{
best = lendiff;
ret = candidate;
}
}
return ret;
}
// -------------------------------------------- //
// Wrapping the Craftbukkit TextWrapper
// -------------------------------------------- //
public ArrayList<String> wrap(final String string)
{
return new ArrayList<String>(Arrays.asList(TextWrapper.wrapText(string)));
}
public ArrayList<String> wrap(final Collection<String> strings)
{
ArrayList<String> ret = new ArrayList<String>();
for (String line : strings)
{
ret.addAll(this.wrap(line));
}
return ret;
}
// -------------------------------------------- //
// Parse and Wrap combo
// -------------------------------------------- //
public ArrayList<String> parseWrap(final String string)
{
return this.wrap(this.parse(string));
}
public ArrayList<String> parseWrap(final Collection<String> strings)
{
return this.wrap(this.parse(strings));
}
}

View File

@ -1,100 +0,0 @@
package com.massivecraft.mcore1.text;
import java.util.HashMap;
import java.util.Map;
import org.bukkit.ChatColor;
// TODO: Add some more cool stuff.. like titelization design.
// TODO: Should they be color-parsed? or cashed color parsed?
public class TxtDesign
{
public TxtDesign()
{
}
// -------------------------------------------- //
// COLOR THEME
// -------------------------------------------- //
private ChatColor logo = ChatColor.DARK_GREEN;
public ChatColor getColorLogo() { return this.logo; }
public void setColorLogo(ChatColor val) { this.logo = val; this.updateTag2Color(); }
private ChatColor art = ChatColor.GOLD;
public ChatColor getColorArt() { return this.art; }
public void setColorArt(ChatColor val) { this.art = val; this.updateTag2Color(); }
private ChatColor notice = ChatColor.GRAY;
public ChatColor getColorNotice() { return this.notice; }
public void setColorNotice(ChatColor val) { this.notice = val; this.updateTag2Color(); }
private ChatColor info = ChatColor.YELLOW;
public ChatColor getColorInfo() { return this.info; }
public void setColorInfo(ChatColor val) { this.info = val; this.updateTag2Color(); }
private ChatColor good = ChatColor.GREEN;
public ChatColor getColorGood() { return this.good; }
public void setColorGood(ChatColor val) { this.good = val; this.updateTag2Color(); }
private ChatColor bad = ChatColor.RED;
public ChatColor getColorBad() { return this.bad; }
public void setColorBad(ChatColor val) { this.bad = val; this.updateTag2Color(); }
private ChatColor hightlight = ChatColor.LIGHT_PURPLE;
public ChatColor getColorHighlight() { return this.hightlight; }
public void setColorHightlight(ChatColor val) { this.hightlight = val; this.updateTag2Color(); }
private ChatColor command = ChatColor.AQUA;
public ChatColor getColorCommand() { return this.command; }
public void setColorCommand(ChatColor val) { this.command = val; this.updateTag2Color(); }
private ChatColor parameter = ChatColor.DARK_AQUA;
public ChatColor getColorParameter() { return this.parameter; }
public void setColorParameter(ChatColor val) { this.parameter = val; this.updateTag2Color(); }
private Map<String, String> tag2color = null;
public Map<String, String> getTags()
{
if (tag2color == null)
{
this.updateTag2Color();
}
return this.tag2color;
}
private void updateTag2Color()
{
if (tag2color == null)
{
this.tag2color = new HashMap<String, String>();
}
this.tag2color.put("l", this.getColorLogo().toString());
this.tag2color.put("logo", this.getColorLogo().toString());
this.tag2color.put("a", this.getColorArt().toString());
this.tag2color.put("art", this.getColorArt().toString());
this.tag2color.put("n", this.getColorNotice().toString());
this.tag2color.put("notice", this.getColorNotice().toString());
this.tag2color.put("i", this.getColorInfo().toString());
this.tag2color.put("info", this.getColorInfo().toString());
this.tag2color.put("g", this.getColorGood().toString());
this.tag2color.put("good", this.getColorGood().toString());
this.tag2color.put("b", this.getColorBad().toString());
this.tag2color.put("bad", this.getColorBad().toString());
this.tag2color.put("h", this.getColorHighlight().toString());
this.tag2color.put("highlight", this.getColorHighlight().toString());
this.tag2color.put("c", this.getColorCommand().toString());
this.tag2color.put("command", this.getColorCommand().toString());
this.tag2color.put("p", this.getColorParameter().toString());
this.tag2color.put("parameter", this.getColorParameter().toString());
}
}

View File

@ -0,0 +1,47 @@
package com.massivecraft.mcore1.util;
import java.io.File;
import com.massivecraft.mcore1.MPlugin;
public class LibLoader
{
MPlugin p;
public LibLoader(MPlugin p)
{
this.p = p;
new File("./lib").mkdirs();
}
public boolean require(String filename, String url)
{
if ( ! include(filename, url))
{
p.log("Failed to load the required library "+filename);
p.suicide();
return false;
}
return true;
}
public boolean include (String filename, String url)
{
File file = getFile(filename);
if ( ! file.exists())
{
p.log("Downloading library "+filename);
if ( ! DiscUtil.downloadUrl(url, file))
{
p.log("Failed to download "+filename);
return false;
}
}
return ClassLoadHack.load(file);
}
private static File getFile(String filename)
{
return new File("./lib/"+filename);
}
}

View File

@ -8,24 +8,17 @@ import org.bukkit.command.CommandSender;
import org.bukkit.permissions.Permission;
import com.massivecraft.mcore1.Lang;
import com.massivecraft.mcore1.text.Txt;
public class Perm
{
private Txt txt;
public Perm(Txt txt)
{
this.txt = txt;
}
public String getPermissionDescription (String perm)
public static String getPermissionDescription (String perm)
{
if (perm == null) return Lang.permDoThat;
Permission permission = Bukkit.getPluginManager().getPermission(perm);
return getPermissionDescription(permission);
}
public String getPermissionDescription (Permission perm)
public static String getPermissionDescription (Permission perm)
{
if (perm == null) return Lang.permDoThat;
String desc = perm.getDescription();
@ -33,18 +26,18 @@ public class Perm
return desc;
}
public String getForbiddenMessage(String perm)
public static String getForbiddenMessage(String perm)
{
return txt.parse(Lang.permForbidden, getPermissionDescription(perm));
return Txt.parse(Lang.permForbidden, getPermissionDescription(perm));
}
public boolean has (CommandSender me, String perm)
public static boolean has (CommandSender me, String perm)
{
if (me == null) return false;
return me.hasPermission(perm);
}
public boolean has (CommandSender me, String perm, boolean verbose)
public static boolean has (CommandSender me, String perm, boolean verbose)
{
if (has(me, perm))
{
@ -52,12 +45,12 @@ public class Perm
}
else if (verbose && me != null)
{
me.sendMessage(this.getForbiddenMessage(perm));
me.sendMessage(getForbiddenMessage(perm));
}
return false;
}
public <T> T pickFirstVal(CommandSender me, Map<String, T> perm2val)
public static <T> T pickFirstVal(CommandSender me, Map<String, T> perm2val)
{
if (perm2val == null) return null;
T ret = null;

View File

@ -12,11 +12,8 @@ public class PlayerUtil
public static Set<String> getAllVisitorNames() { return allVisitorNames; }
public static void populateAllVisitorNames()
{
// What is the name of the default world?
String worldname = Bukkit.getWorlds().get(0).getName();
// Find the player folder
File playerfolder = new File(worldname, "players");
File playerfolder = new File(Bukkit.getWorlds().get(0).getWorldFolder(), "players");
// Populate by removing .dat
for (File playerfile : playerfolder.listFiles())

View File

@ -0,0 +1,371 @@
package com.massivecraft.mcore1.util;
import java.util.*;
import java.util.Map.Entry;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.bukkit.ChatColor;
import org.bukkit.Material;
import org.bukkit.craftbukkit.TextWrapper;
public class Txt
{
// -------------------------------------------- //
// STATIC
// -------------------------------------------- //
public static final Map<String, String> parseReplacements;
public static final Pattern parsePattern;
public static final long millisPerSecond = 1000;
public static final long millisPerMinute = 60 * millisPerSecond;
public static final long millisPerHour = 60 * millisPerMinute;
public static final long millisPerDay = 24 * millisPerHour;
public static final long millisPerWeek = 7 * millisPerDay;
public static final long millisPerMonth = 31 * millisPerDay;
public static final long millisPerYear = 365 * millisPerDay;
public static Map<String, Long> unitMillis;
static
{
unitMillis = new LinkedHashMap<String, Long>();
unitMillis.put("years", millisPerYear);
unitMillis.put("months", millisPerMonth);
unitMillis.put("weeks", millisPerWeek);
unitMillis.put("days", millisPerDay);
unitMillis.put("hours", millisPerHour);
unitMillis.put("minutes", millisPerMinute);
unitMillis.put("seconds", millisPerSecond);
// Create the parce replacements map
parseReplacements = new HashMap<String, String>();
// Color by name
parseReplacements.put("<empty>", "");
parseReplacements.put("<black>", "\u00A70");
parseReplacements.put("<navy>", "\u00A71");
parseReplacements.put("<green>", "\u00A72");
parseReplacements.put("<teal>", "\u00A73");
parseReplacements.put("<red>", "\u00A74");
parseReplacements.put("<purple>", "\u00A75");
parseReplacements.put("<gold>", "\u00A76");
parseReplacements.put("<silver>", "\u00A77");
parseReplacements.put("<gray>", "\u00A78");
parseReplacements.put("<blue>", "\u00A79");
parseReplacements.put("<lime>", "\u00A7a");
parseReplacements.put("<aqua>", "\u00A7b");
parseReplacements.put("<rose>", "\u00A7c");
parseReplacements.put("<pink>", "\u00A7d");
parseReplacements.put("<yellow>", "\u00A7e");
parseReplacements.put("<white>", "\u00A7f");
// Color by semantic functionality
parseReplacements.put("<l>", "\u00A72");
parseReplacements.put("<logo>", "\u00A72");
parseReplacements.put("<a>", "\u00A76");
parseReplacements.put("<art>", "\u00A76");
parseReplacements.put("<n>", "\u00A77");
parseReplacements.put("<notice>", "\u00A77");
parseReplacements.put("<i>", "\u00A7e");
parseReplacements.put("<info>", "\u00A7e");
parseReplacements.put("<g>", "\u00A7a");
parseReplacements.put("<good>", "\u00A7a");
parseReplacements.put("<b>", "\u00A7c");
parseReplacements.put("<bad>", "\u00A7c");
parseReplacements.put("<h>", "\u00A7d");
parseReplacements.put("<highlight>", "\u00A7d");
parseReplacements.put("<c>", "\u00A7b");
parseReplacements.put("<command>", "\u00A7b");
parseReplacements.put("<p>", "\u00A73");
parseReplacements.put("<parameter>", "\u00A73");
parseReplacements.put("&&", "&");
// Color by number/char
for (int i = 48; i <= 122; i++)
{
char c = (char)i;
parseReplacements.put("§"+c, "\u00A7"+c);
parseReplacements.put("&"+c, "\u00A7"+c);
if (i == 57) i = 96;
}
// Build the parse pattern and compile it
StringBuilder patternStringBuilder = new StringBuilder();
for (String find : parseReplacements.keySet())
{
patternStringBuilder.append('(');
patternStringBuilder.append(Pattern.quote(find));
patternStringBuilder.append(")|");
}
String patternString = patternStringBuilder.toString();
patternString = patternString.substring(0, patternString.length()-1); // Remove the last |
parsePattern = Pattern.compile(patternString);
}
// -------------------------------------------- //
// CONSTRUCTOR (FORBIDDEN)
// -------------------------------------------- //
private Txt()
{
}
// -------------------------------------------- //
// PARSE
// -------------------------------------------- //
public static String parse(String string)
{
StringBuffer ret = new StringBuffer();
Matcher matcher = parsePattern.matcher(string);
while (matcher.find())
{
matcher.appendReplacement(ret, parseReplacements.get(matcher.group(0)));
}
matcher.appendTail(ret);
return ret.toString();
}
public static String parse(String string, Object... args)
{
return String.format(parse(string), args);
}
public static ArrayList<String> parse(Collection<String> strings)
{
ArrayList<String> ret = new ArrayList<String>(strings.size());
for (String string : strings)
{
ret.add(parse(string));
}
return ret;
}
// -------------------------------------------- //
// Wrapping the Craftbukkit TextWrapper
// -------------------------------------------- //
public static ArrayList<String> wrap(final String string)
{
return new ArrayList<String>(Arrays.asList(TextWrapper.wrapText(string)));
}
public static ArrayList<String> wrap(final Collection<String> strings)
{
ArrayList<String> ret = new ArrayList<String>();
for (String line : strings)
{
ret.addAll(wrap(line));
}
return ret;
}
// -------------------------------------------- //
// Parse and Wrap combo
// -------------------------------------------- //
public static ArrayList<String> parseWrap(final String string)
{
return wrap(parse(string));
}
public static ArrayList<String> parseWrap(final Collection<String> strings)
{
return wrap(parse(strings));
}
// -------------------------------------------- //
// Standard utils like UCFirst, implode and repeat.
// -------------------------------------------- //
public static String upperCaseFirst(String string)
{
return string.substring(0, 1).toUpperCase()+string.substring(1);
}
public static String repeat(String string, int times)
{
if (times <= 0) return "";
else return string + repeat(string, times-1);
}
public static String implode(List<String> list, String glue)
{
return implode(list.toArray(new String[0]), glue);
}
public static String implode(Object[] list, String glue)
{
StringBuilder ret = new StringBuilder();
for (int i=0; i<list.length; i++)
{
if (i!=0)
{
ret.append(glue);
}
ret.append(list[i]);
}
return ret.toString();
}
public static String implodeCommaAnd(List<String> list, String comma, String and)
{
if (list.size() == 0) return "";
if (list.size() == 1) return list.get(0);
String lastItem = list.get(list.size()-1);
String nextToLastItem = list.get(list.size()-2);
String merge = nextToLastItem+and+lastItem;
list.set(list.size()-2, merge);
list.remove(list.size()-1);
return implode(list, comma);
}
public static String implodeCommaAnd(List<String> list, String color)
{
return implodeCommaAnd(list, color+", ", color+" and ");
}
public static String implodeCommaAnd(List<String> list)
{
return implodeCommaAnd(list, "");
}
// -------------------------------------------- //
// Material name tools
// -------------------------------------------- //
public static String getMaterialName(Material material)
{
return material.toString().replace('_', ' ').toLowerCase();
}
public static String getMaterialName(int materialId)
{
return getMaterialName(Material.getMaterial(materialId));
}
// -------------------------------------------- //
// Paging and chrome-tools like titleize
// -------------------------------------------- //
private final static String titleizeLine = repeat("_", 52);
private final static int titleizeBalance = -1;
public static String titleize(String str)
{
String center = ".[ "+ parse("<l>") + str + parse("<a>") + " ].";
int centerlen = ChatColor.stripColor(center).length();
int pivot = titleizeLine.length() / 2;
int eatLeft = (centerlen / 2) - titleizeBalance;
int eatRight = (centerlen - eatLeft) + titleizeBalance;
if (eatLeft < pivot)
return parse("<a>")+titleizeLine.substring(0, pivot - eatLeft) + center + titleizeLine.substring(pivot + eatRight);
else
return parse("<a>")+center;
}
public static ArrayList<String> getPage(List<String> lines, int pageHumanBased, String title)
{
ArrayList<String> ret = new ArrayList<String>();
int pageZeroBased = pageHumanBased - 1;
int pageheight = 9;
int pagecount = (lines.size() / pageheight)+1;
ret.add(titleize(title+" "+pageHumanBased+"/"+pagecount));
if (pagecount == 0)
{
ret.add(parse("<i>Sorry. No Pages available."));
return ret;
}
else if (pageZeroBased < 0 || pageHumanBased > pagecount)
{
ret.add(parse("<i>Invalid page. Must be between 1 and "+pagecount));
return ret;
}
int from = pageZeroBased * pageheight;
int to = from+pageheight;
if (to > lines.size())
{
to = lines.size();
}
ret.addAll(lines.subList(from, to));
return ret;
}
// -------------------------------------------- //
// Describing Time
// -------------------------------------------- //
public static String getTimeDeltaDescriptionRelNow(long millis)
{
String ret = "";
double millisLeft = (double) Math.abs(millis);
List<String> unitCountParts = new ArrayList<String>();
for (Entry<String, Long> entry : unitMillis.entrySet())
{
if (unitCountParts.size() == 3 ) break;
String unitName = entry.getKey();
long unitSize = entry.getValue();
long unitCount = (long) Math.floor(millisLeft / unitSize);
if (unitCount < 1) continue;
millisLeft -= unitSize*unitCount;
unitCountParts.add(unitCount+" "+unitName);
}
if (unitCountParts.size() == 0) return "just now";
ret += implodeCommaAnd(unitCountParts);
ret += " ";
if (millis <= 0)
{
ret += "ago";
}
else
{
ret += "from now";
}
return ret;
}
// -------------------------------------------- //
// String comparison
// -------------------------------------------- //
public static String getBestCIStart(Collection<String> candidates, String start)
{
String ret = null;
int best = 0;
start = start.toLowerCase();
int minlength = start.length();
for (String candidate : candidates)
{
if (candidate.length() < minlength) continue;
if ( ! candidate.toLowerCase().startsWith(start)) continue;
// The closer to zero the better
int lendiff = candidate.length() - minlength;
if (lendiff == 0)
{
return candidate;
}
if (lendiff < best || best == 0)
{
best = lendiff;
ret = candidate;
}
}
return ret;
}
}