001/* 002 * Copyright (c) 2016-2017 Daniel Ennis (Aikar) - MIT License 003 * 004 * Permission is hereby granted, free of charge, to any person obtaining 005 * a copy of this software and associated documentation files (the 006 * "Software"), to deal in the Software without restriction, including 007 * without limitation the rights to use, copy, modify, merge, publish, 008 * distribute, sublicense, and/or sell copies of the Software, and to 009 * permit persons to whom the Software is furnished to do so, subject to 010 * the following conditions: 011 * 012 * The above copyright notice and this permission notice shall be 013 * included in all copies or substantial portions of the Software. 014 * 015 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, 016 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 017 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND 018 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE 019 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION 020 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION 021 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 022 */ 023 024package co.aikar.commands; 025 026import java.util.*; 027import java.util.regex.Matcher; 028 029/** 030 * Handles formatting Messages and managing colors 031 * @param <C> The platform specific color object 032 */ 033public abstract class MessageFormatter <C> { 034 035 private final List<C> colors = new ArrayList<>(); 036 037 @SafeVarargs 038 public MessageFormatter(C... colors) { 039 this.colors.addAll(Arrays.asList(colors)); 040 041 } 042 public C setColor(int index, C color) { 043 if (index > 0) { 044 index--; 045 } else { 046 index = 0; 047 } 048 if (this.colors.size() <= index) { 049 int needed = index - this.colors.size(); 050 if (needed > 0) { 051 this.colors.addAll(Collections.nCopies(needed, null)); 052 } 053 colors.add(color); 054 return null; 055 } else { 056 return colors.set(index, color); 057 } 058 } 059 060 public C getColor(int index) { 061 if (index > 0) { 062 index--; 063 } else { 064 index = 0; 065 } 066 C color = colors.get(index); 067 if (color == null) { 068 color = getDefaultColor(); 069 } 070 return color; 071 } 072 073 public C getDefaultColor() { 074 return getColor(1); 075 } 076 077 abstract String format(C color, String message); 078 079 public String format(int index, String message) { 080 return format(getColor(index), message); 081 } 082 083 public String format(String message) { 084 String def = format(1, ""); 085 Matcher matcher = ACFPatterns.FORMATTER.matcher(message); 086 StringBuffer sb = new StringBuffer(message.length()); 087 while (matcher.find()) { 088 Integer color = ACFUtil.parseInt(matcher.group("color"), 1); 089 String msg = format(color, matcher.group("msg")) + def; 090 matcher.appendReplacement(sb, Matcher.quoteReplacement(msg)); 091 } 092 matcher.appendTail(sb); 093 return def + sb.toString(); 094 } 095}