Update moonshine, add auto-nickname (#155)

This commit is contained in:
Josua Parks authored and GitHub committed 2021-09-01 12:41:10 -07:00
1 parent 74e83a08a0
commit 3b1987b5a2
71 files changed
+1022 -829

No files matched your search

+297 -285
View File
@@ -1,304 +1,316 @@
<?xml version="1.0" encoding="utf-8" ?> <?xml version="1.0" encoding="utf-8" ?>
<!DOCTYPE module PUBLIC "-//Checkstyle//DTD Checkstyle Configuration 1.3//EN" "https://checkstyle.org/dtds/configuration_1_3.dtd"> <!DOCTYPE module PUBLIC "-//Checkstyle//DTD Checkstyle Configuration 1.3//EN"
"https://checkstyle.org/dtds/configuration_1_3.dtd">
<module name="Checker"> <module name="Checker">
<property name="charset" value="UTF-8"/> <property name="charset" value="UTF-8"/>
<property name="fileExtensions" value="java, properties, xml"/> <property name="fileExtensions" value="java, properties, xml"/>
<property name="severity" value="error"/> <property name="severity" value="error"/>
<!-- https://checkstyle.org/config_filefilters.html#BeforeExecutionExclusionFileFilter --> <!-- https://checkstyle.org/config_filefilters.html#BeforeExecutionExclusionFileFilter -->
<module name="BeforeExecutionExclusionFileFilter"> <module name="BeforeExecutionExclusionFileFilter">
<property name="fileNamePattern" value="module\-info\.java$"/> <property name="fileNamePattern" value="module\-info\.java$"/>
</module>
<!-- https://checkstyle.org/config_whitespace.html#FileTabCharacter -->
<module name="FileTabCharacter">
<property name="eachLine" value="true"/>
</module>
<!-- https://checkstyle.org/config_misc.html#NewlineAtEndOfFile -->
<module name="NewlineAtEndOfFile"/>
<!-- https://checkstyle.org/config_filters.html#SuppressionFilter -->
<module name="SuppressionFilter">
<property name="file" value="${configDirectory}/suppressions.xml"/>
</module>
<!-- https://checkstyle.org/config_filters.html#SuppressWarningsFilter -->
<module name="SuppressWarningsFilter"/>
<!-- carbon -->
<!-- Temporary until https://github.com/checkstyle/checkstyle/issues/5313 -->
<!-- empty line at beginning after class/interface/enum definition -->
<module name="RegexpMultiline">
<property name="format" value="^([^\r\n ]+ )*(class|interface|enum) [^{]*\{\r?\n[^\r\n}]"/>
<property name="message" value="Leave an empty line after class/interface/enum definition!"/>
<property name="fileExtensions" value="groovy,java"/>
</module>
<!-- empty line before the last } of class/interface/enum definition -->
<module name="RegexpMultiline">
<property name="format" value="}\r\n}\r\n\Z"/>
<property name="message" value="Leave an empty line before the last } of class/interface/enum!"/>
<property name="fileExtensions" value="groovy,java"/>
<property name="matchAcrossLines" value="true"/>
</module>
<!-- https://checkstyle.org/config_filters.html#SuppressWithPlainTextCommentFilter -->
<module name="SuppressWithPlainTextCommentFilter"/>
<module name="TreeWalker">
<!-- https://checkstyle.org/config_misc.html#ArrayTypeStyle -->
<module name="ArrayTypeStyle"/>
<!-- https://checkstyle.org/config_javadoc.html#AtclauseOrder -->
<module name="AtclauseOrder">
<property name="violateExecutionOnNonTightHtml" value="true"/>
<property name="tagOrder" value="@author, @deprecated, @exception, @param, @return, @serial, @serialData, @serialField, @throws, @see, @since, @sinceMinecraft, @version"/>
</module> </module>
<!-- https://checkstyle.org/config_imports.html#AvoidStarImport --> <!-- https://checkstyle.org/config_whitespace.html#FileTabCharacter -->
<module name="AvoidStarImport"/> <module name="FileTabCharacter">
<property name="eachLine" value="true"/>
<!-- https://checkstyle.org/config_misc.html#AvoidEscapedUnicodeCharacters -->
<module name="AvoidEscapedUnicodeCharacters">
<property name="allowByTailComment" value="true"/>
<property name="allowEscapesForControlCharacters" value="true"/>
<property name="allowNonPrintableEscapes" value="true"/>
</module> </module>
<!-- https://checkstyle.org/config_misc.html#CommentsIndentation --> <!-- https://checkstyle.org/config_misc.html#NewlineAtEndOfFile -->
<module name="CommentsIndentation"/> <module name="NewlineAtEndOfFile"/>
<!-- https://checkstyle.org/config_imports.html#CustomImportOrder --> <!-- https://checkstyle.org/config_filters.html#SuppressionFilter -->
<module name="CustomImportOrder"> <module name="SuppressionFilter">
<property name="customImportOrderRules" value="THIRD_PARTY_PACKAGE###STATIC"/> <property name="file" value="${configDirectory}/suppressions.xml"/>
<property name="standardPackageRegExp" value="^$"/>
<property name="sortImportsInGroupAlphabetically" value="true"/>
</module>
<!-- https://checkstyle.org/config_whitespace.html#EmptyForInitializerPad -->
<module name="EmptyForInitializerPad"/>
<!-- https://checkstyle.org/config_whitespace.html#EmptyForIteratorPad -->
<module name="EmptyForIteratorPad"/>
<!-- https://checkstyle.org/config_whitespace.html#EmptyLineSeparator -->
<module name="EmptyLineSeparator">
<property name="allowMultipleEmptyLines" value="false"/>
<property name="allowMultipleEmptyLinesInsideClassMembers" value="false"/>
<property name="allowNoEmptyLineBetweenFields" value="true"/>
<property name="tokens" value="CLASS_DEF, CTOR_DEF, ENUM_DEF, IMPORT, INSTANCE_INIT, INTERFACE_DEF, METHOD_DEF, STATIC_IMPORT, STATIC_INIT, VARIABLE_DEF"/> <!-- remove PACKAGE_DEF, temporarily remove COMPACT_CTOR_DEF, RECORD_DEF -->
</module> </module>
<!-- https://checkstyle.org/config_coding.html#FallThrough --> <!-- https://checkstyle.org/config_filters.html#SuppressWarningsFilter -->
<module name="FallThrough"> <module name="SuppressWarningsFilter"/>
<property name="checkLastCaseGroup" value="true"/>
</module>
<!-- https://checkstyle.org/config_design.html#FinalClass -->
<module name="FinalClass"/>
<!-- https://checkstyle.org/config_coding.html#FinalLocalVariable -->
<module name="FinalLocalVariable">
<property name="tokens" value="PARAMETER_DEF, VARIABLE_DEF"/> <!-- add PARAMETER_DEF -->
<property name="validateEnhancedForLoopVariable" value="true"/>
</module>
<!-- https://checkstyle.org/config_whitespace.html#GenericWhitespace -->
<module name="GenericWhitespace"/>
<!-- https://checkstyle.org/config_design.html#HideUtilityClassConstructor -->
<module name="HideUtilityClassConstructor"/>
<!-- https://checkstyle.org/config_imports.html#IllegalImport -->
<module name="IllegalImport">
<property name="illegalPkgs" value="sun, jdk, com.sun"/>
</module>
<!-- https://checkstyle.org/config_coding.html#IllegalTokenText -->
<module name="IllegalTokenText">
<property name="format" value="($|[^\\])\\u00(09|0(a|A)|0(c|C)|0(d|D)|22|27|5(C|c))|\\(0(10|11|12|14|15|42|47)|134)"/>
<property name="message" value="Consider using special escape sequence instead of octal value or Unicode escaped value."/>
<property name="tokens" value="CHAR_LITERAL, STRING_LITERAL"/>
</module>
<!-- https://checkstyle.org/config_misc.html#Indentation -->
<module name="Indentation">
<property name="arrayInitIndent" value="4"/>
<property name="basicOffset" value="4"/>
<property name="braceAdjustment" value="0"/>
<property name="caseIndent" value="4"/>
<property name="lineWrappingIndentation" value="0"/>
<property name="throwsIndent" value="4"/>
</module>
<!-- https://checkstyle.org/config_javadoc.html#InvalidJavadocPosition -->
<module name="InvalidJavadocPosition"/>
<!-- https://checkstyle.org/config_javadoc.html#JavadocContentLocation -->
<module name="JavadocContentLocation"/>
<!-- https://checkstyle.org/config_javadoc.html#JavadocMissingWhitespaceAfterAsterisk -->
<module name="JavadocMissingWhitespaceAfterAsterisk"/>
<!-- https://checkstyle.org/config_javadoc.html#JavadocParagraph -->
<module name="JavadocParagraph"/>
<!-- https://checkstyle.org/config_javadoc.html#JavadocMissingWhitespaceAfterAsterisk -->
<module name="JavadocTagContinuationIndentation"/>
<!-- https://checkstyle.org/config_blocks.html#LeftCurly -->
<module name="LeftCurly"/>
<!-- https://checkstyle.org/config_naming.html#MethodName -->
<module name="MethodName">
<property name="format" value="^(?:(?:.{1,3})|(?:[gs]et[^A-Z].*)|(?:(?:[^gsA-Z]..|.[^e].|..[^t]).+))$"/>
</module>
<!-- https://checkstyle.org/config_whitespace.html#MethodParamPad -->
<module name="MethodParamPad"/>
<!-- https://checkstyle.org/config_javadoc.html#MissingJavadocMethod -->
<module name="MissingJavadocMethod"/>
<!-- https://checkstyle.org/config_javadoc.html#MissingJavadocPackage -->
<module name="MissingJavadocPackage"/>
<!-- https://checkstyle.org/config_javadoc.html#MissingJavadocType -->
<module name="MissingJavadocType"/>
<!-- https://checkstyle.org/config_coding.html#MultipleVariableDeclarations -->
<module name="MultipleVariableDeclarations"/>
<!-- https://checkstyle.org/config_coding.html#NoFinalizer -->
<module name="NoFinalizer"/>
<!-- https://checkstyle.org/config_whitespace.html#NoLineWrap -->
<module name="NoLineWrap"/>
<!-- https://checkstyle.org/config_javadoc.html#NonEmptyAtclauseDescription -->
<module name="NonEmptyAtclauseDescription"/>
<!-- https://checkstyle.org/config_whitespace.html#NoWhitespaceAfter -->
<module name="NoWhitespaceAfter">
<property name="allowLineBreaks" value="false"/>
</module>
<!-- https://checkstyle.org/config_whitespace.html#NoWhitespaceBefore -->
<module name="NoWhitespaceBefore">
<property name="allowLineBreaks" value="true"/>
<property name="tokens" value="COMMA, DOT, LABELED_STAT, METHOD_REF, POST_DEC, POST_INC, SEMI"/> <!-- remove ELLIPSIS -->
</module>
<!-- https://checkstyle.org/config_coding.html#OneStatementPerLine -->
<module name="OneStatementPerLine"/>
<!-- https://checkstyle.org/config_misc.html#OuterTypeFilename -->
<module name="OuterTypeFilename"/>
<!-- https://checkstyle.org/config_imports.html#RedundantImport -->
<module name="RedundantImport"/>
<!-- https://checkstyle.org/config_modifier.html#RedundantModifier -->
<module name="RedundantModifier">
<property name="tokens" value="ANNOTATION_FIELD_DEF, CLASS_DEF, CTOR_DEF, ENUM_DEF, INTERFACE_DEF, VARIABLE_DEF"/> <!-- remove METHOD_DEF and RESOURCE -->
</module>
<!-- https://checkstyle.org/config_javadoc.html#RequireEmptyLineBeforeBlockTagGroup -->
<module name="RequireEmptyLineBeforeBlockTagGroup"/>
<!-- https://checkstyle.org/config_coding.html#RequireThis -->
<module name="RequireThis">
<property name="validateOnlyOverlapping" value="false"/>
</module>
<!-- https://checkstyle.org/config_blocks.html#RightCurly -->
<module name="RightCurly">
<property name="id" value="RightCurlyAlone"/>
<property name="option" value="alone"/>
<property name="tokens" value="ANNOTATION_DEF, CLASS_DEF, CTOR_DEF, ENUM_DEF, INSTANCE_INIT, LITERAL_FOR, LITERAL_WHILE, METHOD_DEF, STATIC_INIT"/>
</module>
<module name="RightCurly">
<property name="id" value="RightCurlySame"/>
<property name="option" value="same"/>
<property name="tokens" value="LITERAL_CATCH, LITERAL_DO, LITERAL_ELSE, LITERAL_FINALLY, LITERAL_IF, LITERAL_TRY"/> <!-- add LITERAL_DO -->
</module>
<!-- https://checkstyle.org/config_whitespace.html#SeparatorWrap -->
<module name="SeparatorWrap">
<property name="id" value="SeparatorWrapEol"/>
<property name="option" value="eol"/>
<property name="tokens" value="COMMA, SEMI, ELLIPSIS, RBRACK, ARRAY_DECLARATOR, METHOD_REF"/>
</module>
<module name="SeparatorWrap">
<property name="id" value="SeparatorWrapNl"/>
<property name="option" value="nl"/>
<property name="tokens" value="DOT, AT"/>
</module>
<!-- https://checkstyle.org/config_coding.html#SimplifyBooleanExpression -->
<module name="SimplifyBooleanExpression"/>
<!-- https://checkstyle.org/config_coding.html#SimplifyBooleanReturn -->
<module name="SimplifyBooleanReturn"/>
<!-- https://checkstyle.org/config_whitespace.html#SingleSpaceSeparator -->
<module name="SingleSpaceSeparator">
<property name="validateComments" value="true"/>
</module>
<!-- https://checkstyle.org/config_javadoc.html#SummaryJavadoc -->
<module name="SummaryJavadoc"/>
<!-- https://checkstyle.org/config_annotation.html#SuppressWarningsHolder -->
<module name="SuppressWarningsHolder"/>
<!-- https://checkstyle.org/config_whitespace.html#TypecastParenPad -->
<module name="TypecastParenPad"/>
<!-- carbon --> <!-- carbon -->
<!-- https://checkstyle.sourceforge.io/config_whitespace.html#ParenPad --> <!-- Temporary until https://github.com/checkstyle/checkstyle/issues/5313 -->
<module name="ParenPad"/> <!-- empty line at beginning after class/interface/enum definition -->
<module name="RegexpMultiline">
<!-- https://checkstyle.org/config_coding.html#UnnecessaryParentheses --> <property name="format" value="^([^\r\n ]+ )*(class|interface|enum) [^{]*\{\r?\n[^\r\n}]"/>
<module name="UnnecessaryParentheses"/> <property name="message" value="Leave an empty line after class/interface/enum definition!"/>
<property name="fileExtensions" value="groovy,java"/>
<!-- https://checkstyle.org/config_imports.html#UnusedImports -->
<module name="UnusedImports"/>
<!-- https://checkstyle.org/config_whitespace.html#WhitespaceAfter -->
<module name="WhitespaceAfter">
<property name="tokens" value="COMMA, SEMI, TYPECAST, LITERAL_IF, LITERAL_ELSE, LITERAL_WHILE, LITERAL_FOR"/>
</module> </module>
<!-- https://checkstyle.org/config_whitespace.html#WhitespaceAround --> <!-- empty line before the last } of class/interface/enum definition -->
<module name="WhitespaceAround"> <module name="RegexpMultiline">
<property name="ignoreEnhancedForColon" value="false"/> <property name="format" value="}\r\n}\r\n\Z"/>
<property name="allowEmptyTypes" value="true"/> <property name="message" value="Leave an empty line before the last } of class/interface/enum!"/>
<property name="allowEmptyLambdas" value="true"/> <property name="fileExtensions" value="groovy,java"/>
<property name="tokens" value="ASSIGN, COLON, BAND, BAND_ASSIGN, BOR, BOR_ASSIGN, BSR, BSR_ASSIGN, BXOR, BXOR_ASSIGN, COLON, DIV, DIV_ASSIGN, EQUAL, GE, GT, LAND, LCURLY, LE, LOR, LT, MINUS, MINUS_ASSIGN, MOD, MOD_ASSIGN, NOT_EQUAL, PLUS, PLUS_ASSIGN, QUESTION, RCURLY, SL, SLIST, SL_ASSIGN, SR, SR_ASSIGN, STAR, STAR_ASSIGN, LITERAL_ASSERT, TYPE_EXTENSION_AND"/> <property name="matchAcrossLines" value="true"/>
</module> </module>
<!-- <!-- https://checkstyle.org/config_filters.html#SuppressWithPlainTextCommentFilter -->
##################### <module name="SuppressWithPlainTextCommentFilter"/>
#### third-party ####
#####################
-->
<!-- https://checkstyle.org/config_javadoc.html#WriteTag --> <module name="TreeWalker">
<!-- https://gitlab.com/stellardrift/stylecheck/-/blob/dev/src/main/java/ca/stellardrift/stylecheck/FilteringWriteTag.java --> <!-- https://checkstyle.org/config_misc.html#ArrayTypeStyle -->
<module name="FilteringWriteTag"> <module name="ArrayTypeStyle"/>
<property name="tag" value="@since\s"/>
<property name="tagFormat" value="\d\.\d+\.\d+"/> <!-- https://checkstyle.org/config_javadoc.html#AtclauseOrder -->
<property name="tagSeverity" value="ignore"/> <module name="AtclauseOrder">
<property name="minimumScope" value="public"/> <property name="violateExecutionOnNonTightHtml" value="true"/>
<property name="tokens" value="INTERFACE_DEF, CLASS_DEF, ENUM_DEF, ANNOTATION_DEF, RECORD_DEF, METHOD_DEF, CTOR_DEF, ANNOTATION_FIELD_DEF, RECORD_DEF, COMPACT_CTOR_DEF"/> <property name="tagOrder"
value="@author, @deprecated, @exception, @param, @return, @serial, @serialData, @serialField, @throws, @see, @since, @sinceMinecraft, @version"/>
</module>
<!-- https://checkstyle.org/config_imports.html#AvoidStarImport -->
<module name="AvoidStarImport"/>
<!-- https://checkstyle.org/config_misc.html#AvoidEscapedUnicodeCharacters -->
<module name="AvoidEscapedUnicodeCharacters">
<property name="allowByTailComment" value="true"/>
<property name="allowEscapesForControlCharacters" value="true"/>
<property name="allowNonPrintableEscapes" value="true"/>
</module>
<!-- https://checkstyle.org/config_misc.html#CommentsIndentation -->
<module name="CommentsIndentation"/>
<!-- https://checkstyle.org/config_imports.html#CustomImportOrder -->
<module name="CustomImportOrder">
<property name="customImportOrderRules" value="THIRD_PARTY_PACKAGE###STATIC"/>
<property name="standardPackageRegExp" value="^$"/>
<property name="sortImportsInGroupAlphabetically" value="true"/>
</module>
<!-- https://checkstyle.org/config_whitespace.html#EmptyForInitializerPad -->
<module name="EmptyForInitializerPad"/>
<!-- https://checkstyle.org/config_whitespace.html#EmptyForIteratorPad -->
<module name="EmptyForIteratorPad"/>
<!-- https://checkstyle.org/config_whitespace.html#EmptyLineSeparator -->
<module name="EmptyLineSeparator">
<property name="allowMultipleEmptyLines" value="false"/>
<property name="allowMultipleEmptyLinesInsideClassMembers" value="false"/>
<property name="allowNoEmptyLineBetweenFields" value="true"/>
<property name="tokens"
value="CLASS_DEF, CTOR_DEF, ENUM_DEF, IMPORT, INSTANCE_INIT, INTERFACE_DEF, METHOD_DEF, STATIC_IMPORT, STATIC_INIT, VARIABLE_DEF"/> <!-- remove PACKAGE_DEF, temporarily remove COMPACT_CTOR_DEF, RECORD_DEF -->
</module>
<!-- https://checkstyle.org/config_coding.html#FallThrough -->
<module name="FallThrough">
<property name="checkLastCaseGroup" value="true"/>
</module>
<!-- https://checkstyle.org/config_design.html#FinalClass -->
<module name="FinalClass"/>
<!-- https://checkstyle.org/config_coding.html#FinalLocalVariable -->
<module name="FinalLocalVariable">
<property name="tokens" value="PARAMETER_DEF, VARIABLE_DEF"/> <!-- add PARAMETER_DEF -->
<property name="validateEnhancedForLoopVariable" value="true"/>
</module>
<!-- https://checkstyle.org/config_whitespace.html#GenericWhitespace -->
<module name="GenericWhitespace"/>
<!-- https://checkstyle.org/config_design.html#HideUtilityClassConstructor -->
<module name="HideUtilityClassConstructor"/>
<!-- https://checkstyle.org/config_imports.html#IllegalImport -->
<module name="IllegalImport">
<property name="illegalPkgs" value="sun, jdk, com.sun"/>
</module>
<!-- https://checkstyle.org/config_coding.html#IllegalTokenText -->
<module name="IllegalTokenText">
<property name="format"
value="($|[^\\])\\u00(09|0(a|A)|0(c|C)|0(d|D)|22|27|5(C|c))|\\(0(10|11|12|14|15|42|47)|134)"/>
<property name="message"
value="Consider using special escape sequence instead of octal value or Unicode escaped value."/>
<property name="tokens" value="CHAR_LITERAL, STRING_LITERAL"/>
</module>
<!-- https://checkstyle.org/config_misc.html#Indentation -->
<module name="Indentation">
<property name="arrayInitIndent" value="4"/>
<property name="basicOffset" value="4"/>
<property name="braceAdjustment" value="0"/>
<property name="caseIndent" value="4"/>
<property name="lineWrappingIndentation" value="0"/>
<property name="throwsIndent" value="4"/>
</module>
<!-- https://checkstyle.org/config_javadoc.html#InvalidJavadocPosition -->
<module name="InvalidJavadocPosition"/>
<!-- https://checkstyle.org/config_javadoc.html#JavadocContentLocation -->
<module name="JavadocContentLocation"/>
<!-- https://checkstyle.org/config_javadoc.html#JavadocMissingWhitespaceAfterAsterisk -->
<module name="JavadocMissingWhitespaceAfterAsterisk"/>
<!-- https://checkstyle.org/config_javadoc.html#JavadocParagraph -->
<module name="JavadocParagraph"/>
<!-- https://checkstyle.org/config_javadoc.html#JavadocMissingWhitespaceAfterAsterisk -->
<module name="JavadocTagContinuationIndentation"/>
<!-- https://checkstyle.org/config_blocks.html#LeftCurly -->
<module name="LeftCurly"/>
<!-- https://checkstyle.org/config_naming.html#MethodName -->
<module name="MethodName">
<property name="format" value="^(?:(?:.{1,3})|(?:[gs]et[^A-Z].*)|(?:(?:[^gsA-Z]..|.[^e].|..[^t]).+))$"/>
</module>
<!-- https://checkstyle.org/config_whitespace.html#MethodParamPad -->
<module name="MethodParamPad"/>
<!-- https://checkstyle.org/config_javadoc.html#MissingJavadocMethod -->
<module name="MissingJavadocMethod"/>
<!-- https://checkstyle.org/config_javadoc.html#MissingJavadocPackage -->
<module name="MissingJavadocPackage"/>
<!-- https://checkstyle.org/config_javadoc.html#MissingJavadocType -->
<module name="MissingJavadocType"/>
<!-- https://checkstyle.org/config_coding.html#MultipleVariableDeclarations -->
<module name="MultipleVariableDeclarations"/>
<!-- https://checkstyle.org/config_coding.html#NoFinalizer -->
<module name="NoFinalizer"/>
<!-- https://checkstyle.org/config_whitespace.html#NoLineWrap -->
<module name="NoLineWrap"/>
<!-- https://checkstyle.org/config_javadoc.html#NonEmptyAtclauseDescription -->
<module name="NonEmptyAtclauseDescription"/>
<!-- https://checkstyle.org/config_whitespace.html#NoWhitespaceAfter -->
<module name="NoWhitespaceAfter">
<property name="allowLineBreaks" value="false"/>
</module>
<!-- https://checkstyle.org/config_whitespace.html#NoWhitespaceBefore -->
<module name="NoWhitespaceBefore">
<property name="allowLineBreaks" value="true"/>
<property name="tokens"
value="COMMA, DOT, LABELED_STAT, METHOD_REF, POST_DEC, POST_INC, SEMI"/> <!-- remove ELLIPSIS -->
</module>
<!-- https://checkstyle.org/config_coding.html#OneStatementPerLine -->
<module name="OneStatementPerLine"/>
<!-- https://checkstyle.org/config_misc.html#OuterTypeFilename -->
<module name="OuterTypeFilename"/>
<!-- https://checkstyle.org/config_imports.html#RedundantImport -->
<module name="RedundantImport"/>
<!-- https://checkstyle.org/config_modifier.html#RedundantModifier -->
<module name="RedundantModifier">
<property name="tokens"
value="ANNOTATION_FIELD_DEF, CLASS_DEF, CTOR_DEF, ENUM_DEF, INTERFACE_DEF, VARIABLE_DEF"/> <!-- remove METHOD_DEF and RESOURCE -->
</module>
<!-- https://checkstyle.org/config_javadoc.html#RequireEmptyLineBeforeBlockTagGroup -->
<module name="RequireEmptyLineBeforeBlockTagGroup"/>
<!-- https://checkstyle.org/config_coding.html#RequireThis -->
<module name="RequireThis">
<property name="validateOnlyOverlapping" value="false"/>
</module>
<!-- https://checkstyle.org/config_blocks.html#RightCurly -->
<module name="RightCurly">
<property name="id" value="RightCurlyAlone"/>
<property name="option" value="alone"/>
<property name="tokens"
value="ANNOTATION_DEF, CLASS_DEF, CTOR_DEF, ENUM_DEF, INSTANCE_INIT, LITERAL_FOR, LITERAL_WHILE, METHOD_DEF, STATIC_INIT"/>
</module>
<module name="RightCurly">
<property name="id" value="RightCurlySame"/>
<property name="option" value="same"/>
<property name="tokens"
value="LITERAL_CATCH, LITERAL_DO, LITERAL_ELSE, LITERAL_FINALLY, LITERAL_IF, LITERAL_TRY"/> <!-- add LITERAL_DO -->
</module>
<!-- https://checkstyle.org/config_whitespace.html#SeparatorWrap -->
<module name="SeparatorWrap">
<property name="id" value="SeparatorWrapEol"/>
<property name="option" value="eol"/>
<property name="tokens" value="COMMA, SEMI, ELLIPSIS, RBRACK, ARRAY_DECLARATOR, METHOD_REF"/>
</module>
<module name="SeparatorWrap">
<property name="id" value="SeparatorWrapNl"/>
<property name="option" value="nl"/>
<property name="tokens" value="DOT, AT"/>
</module>
<!-- https://checkstyle.org/config_coding.html#SimplifyBooleanExpression -->
<module name="SimplifyBooleanExpression"/>
<!-- https://checkstyle.org/config_coding.html#SimplifyBooleanReturn -->
<module name="SimplifyBooleanReturn"/>
<!-- https://checkstyle.org/config_whitespace.html#SingleSpaceSeparator -->
<module name="SingleSpaceSeparator">
<property name="validateComments" value="true"/>
</module>
<!-- https://checkstyle.org/config_javadoc.html#SummaryJavadoc -->
<module name="SummaryJavadoc"/>
<!-- https://checkstyle.org/config_annotation.html#SuppressWarningsHolder -->
<module name="SuppressWarningsHolder"/>
<!-- https://checkstyle.org/config_whitespace.html#TypecastParenPad -->
<module name="TypecastParenPad"/>
<!-- carbon -->
<!-- https://checkstyle.sourceforge.io/config_whitespace.html#ParenPad -->
<module name="ParenPad"/>
<!-- https://checkstyle.org/config_coding.html#UnnecessaryParentheses -->
<module name="UnnecessaryParentheses"/>
<!-- https://checkstyle.org/config_imports.html#UnusedImports -->
<module name="UnusedImports"/>
<!-- https://checkstyle.org/config_whitespace.html#WhitespaceAfter -->
<module name="WhitespaceAfter">
<property name="tokens"
value="COMMA, SEMI, TYPECAST, LITERAL_IF, LITERAL_ELSE, LITERAL_WHILE, LITERAL_FOR"/>
</module>
<!-- https://checkstyle.org/config_whitespace.html#WhitespaceAround -->
<module name="WhitespaceAround">
<property name="ignoreEnhancedForColon" value="false"/>
<property name="allowEmptyTypes" value="true"/>
<property name="allowEmptyLambdas" value="true"/>
<property name="tokens"
value="ASSIGN, COLON, BAND, BAND_ASSIGN, BOR, BOR_ASSIGN, BSR, BSR_ASSIGN, BXOR, BXOR_ASSIGN, COLON, DIV, DIV_ASSIGN, EQUAL, GE, GT, LAND, LCURLY, LE, LOR, LT, MINUS, MINUS_ASSIGN, MOD, MOD_ASSIGN, NOT_EQUAL, PLUS, PLUS_ASSIGN, QUESTION, RCURLY, SL, SLIST, SL_ASSIGN, SR, SR_ASSIGN, STAR, STAR_ASSIGN, LITERAL_ASSERT, TYPE_EXTENSION_AND"/>
</module>
<!--
#####################
#### third-party ####
#####################
-->
<!-- https://checkstyle.org/config_javadoc.html#WriteTag -->
<!-- https://gitlab.com/stellardrift/stylecheck/-/blob/dev/src/main/java/ca/stellardrift/stylecheck/FilteringWriteTag.java -->
<module name="FilteringWriteTag">
<property name="tag" value="@since\s"/>
<property name="tagFormat" value="\d\.\d+\.\d+"/>
<property name="tagSeverity" value="ignore"/>
<property name="minimumScope" value="public"/>
<property name="tokens"
value="INTERFACE_DEF, CLASS_DEF, ENUM_DEF, ANNOTATION_DEF, RECORD_DEF, METHOD_DEF, CTOR_DEF, ANNOTATION_FIELD_DEF, RECORD_DEF, COMPACT_CTOR_DEF"/>
</module>
<!-- what insane person willingly uses this rule? I'll never know. -->
<!-- &lt;!&ndash; https://gitlab.com/stellardrift/stylecheck/-/blob/dev/src/main/java/ca/stellardrift/stylecheck/StatementNoWhitespaceAfter.java &ndash;&gt;-->
<!-- <module name="StatementNoWhitespaceAfter">-->
<!-- <property name="tokens" value="LITERAL_CATCH, LITERAL_FOR, LITERAL_IF, LITERAL_TRY, LITERAL_WHILE"/>-->
<!-- </module>-->
</module> </module>
<!-- what insane person willingly uses this rule? I'll never know. -->
<!-- &lt;!&ndash; https://gitlab.com/stellardrift/stylecheck/-/blob/dev/src/main/java/ca/stellardrift/stylecheck/StatementNoWhitespaceAfter.java &ndash;&gt;-->
<!-- <module name="StatementNoWhitespaceAfter">-->
<!-- <property name="tokens" value="LITERAL_CATCH, LITERAL_FOR, LITERAL_IF, LITERAL_TRY, LITERAL_WHILE"/>-->
<!-- </module>-->
</module>
</module> </module>
+11 -7
View File
@@ -23,12 +23,16 @@
<!-- SOFTWARE.--> <!-- SOFTWARE.-->
<!DOCTYPE suppressions PUBLIC <!DOCTYPE suppressions PUBLIC
"-//Checkstyle//DTD SuppressionFilter Configuration 1.2//EN" "-//Checkstyle//DTD SuppressionFilter Configuration 1.2//EN"
"http://checkstyle.org/dtds/suppressions_1_2.dtd"> "http://checkstyle.org/dtds/suppressions_1_2.dtd">
<suppressions> <suppressions>
<!-- add any necessary suppressions here --> <!-- add any necessary suppressions here -->
<suppress files="src[\\/]main[\\/]java[\\/]net[\\/]draycia[\\/]carbon[\\/](bukkit|sponge|common|velocity)[\\/].*" checks="FilteringWriteTag" /> <suppress files="src[\\/]main[\\/]java[\\/]net[\\/]draycia[\\/]carbon[\\/](bukkit|sponge|common|velocity)[\\/].*"
<suppress files="src[\\/]main[\\/]java[\\/]net[\\/]draycia[\\/]carbon[\\/](bukkit|sponge|common|velocity)[\\/].*" checks="MissingJavadocMethod" /> checks="FilteringWriteTag"/>
<suppress files="src[\\/]main[\\/]java[\\/]net[\\/]draycia[\\/]carbon[\\/](bukkit|sponge|common|velocity)[\\/].*" checks="MissingJavadocPackage" /> <suppress files="src[\\/]main[\\/]java[\\/]net[\\/]draycia[\\/]carbon[\\/](bukkit|sponge|common|velocity)[\\/].*"
<suppress files="src[\\/]main[\\/]java[\\/]net[\\/]draycia[\\/]carbon[\\/](bukkit|sponge|common|velocity)[\\/].*" checks="MissingJavadocType" /> checks="MissingJavadocMethod"/>
<suppress files="src[\\/]main[\\/]java[\\/]net[\\/]draycia[\\/]carbon[\\/](bukkit|sponge|common|velocity)[\\/].*"
checks="MissingJavadocPackage"/>
<suppress files="src[\\/]main[\\/]java[\\/]net[\\/]draycia[\\/]carbon[\\/](bukkit|sponge|common|velocity)[\\/].*"
checks="MissingJavadocType"/>
</suppressions> </suppressions>
+1 -1
View File
@@ -29,5 +29,5 @@ indent_style = space
insert_final_newline = true insert_final_newline = true
max_line_length = off max_line_length = off
[{*.kt,*.kts,*.yml}] [{*.kt, *.kts, *.yml}]
indent_size = 2 indent_size = 2
+7 -7
View File
@@ -1,18 +1,18 @@
--- ---
name: "\U0001F41E Bug report" name: "\U0001F41E Bug report"
about: Describe a bug in Carbon about: Describe a bug in Carbon title: "[Bug]"
title: "[Bug]" labels: unconfirmed bug assignees: ''
labels: unconfirmed bug
assignees: ''
--- ---
<!-- Before continuing, please ensure you are using the latest version of Carbon and the bug you are about to report still exists. --> <!-- Before continuing, please ensure you are using the latest version of Carbon and the bug you are about to report still exists. -->
## Bug Description: ## Bug Description:
### What is not working as it should? ### What is not working as it should?
### Steps to reproduce: ### Steps to reproduce:
<!-- Please describe in as much detail as possible the exact steps needed to reproduce. For example: <!-- Please describe in as much detail as possible the exact steps needed to reproduce. For example:
1. Install Carbon, Vault, and LuckPerms 1. Install Carbon, Vault, and LuckPerms
2. Make a channel called 'uncool' which displays the prefix of a player, using the placeholder %luckperms_prefix% 2. Make a channel called 'uncool' which displays the prefix of a player, using the placeholder %luckperms_prefix%
@@ -20,9 +20,8 @@ assignees: ''
4. The prefix colour is always purple, regardless of any settings. 4. The prefix colour is always purple, regardless of any settings.
--> -->
### System Details: ### System Details:
<!-- Please describe as many system details as you can --> <!-- Please describe as many system details as you can -->
1. Server Type: <!-- Bukkit, Sponge, etc. --> 1. Server Type: <!-- Bukkit, Sponge, etc. -->
@@ -31,8 +30,9 @@ assignees: ''
4. Carbon Version: 4. Carbon Version:
### Pastebins: ### Pastebins:
<!-- If relevant, please include a pastebin of any error logs, startup logs, and Carbon configs. In full, please. --> <!-- If relevant, please include a pastebin of any error logs, startup logs, and Carbon configs. In full, please. -->
### Any other relevant details: ### Any other relevant details:
<!-- Anything else that may be pertinent --> <!-- Anything else that may be pertinent -->
+4 -4
View File
@@ -1,14 +1,14 @@
--- ---
name: "⚡ Feature request" name: "⚡ Feature request"
about: Suggest an idea for Carbon about: Suggest an idea for Carbon title: "[Feature]"
title: "[Feature]" labels: proposed enhancement assignees: ''
labels: proposed enhancement
assignees: ''
--- ---
### Proposed Feature Description: ### Proposed Feature Description:
<!-- Please describe what feature you would like to see added --> <!-- Please describe what feature you would like to see added -->
### Proposed Feature Functionality: ### Proposed Feature Functionality:
<!-- Please describe how the feature would work, what it would do, and if you have considered it, how it might be implemented --> <!-- Please describe how the feature would work, what it would do, and if you have considered it, how it might be implemented -->
+13 -5
View File
@@ -1,28 +1,36 @@
# Carbon # Carbon
### Dev Builds ### Dev Builds
Carbon is currently in early development and as such, developer / preview builds are not offered. Carbon is currently in early development and as such, developer / preview builds are not offered.
### Support ### Support
Support is given through [GitHub Issues](https://github.com/Hexaoxide/Carbon/issues) and [Discord](https://discord.gg/S8s75Yf).
Support is given through [GitHub Issues](https://github.com/Hexaoxide/Carbon/issues)
and [Discord](https://discord.gg/S8s75Yf).
Please use the discord for help setting up the plugin, and use issues for bug reports. Please use the discord for help setting up the plugin, and use issues for bug reports.
### Checkstyle ### Checkstyle
Carbon uses (a fork of) checkstyle to ensure code style is consistent across the entire project. Carbon uses (a fork of) checkstyle to ensure code style is consistent across the entire project.
For checkstyle support in IDEA: For checkstyle support in IDEA:
1) Install the checkstyle plugin (https://github.com/jshiell/checkstyle-idea) 1) Install the checkstyle plugin (https://github.com/jshiell/checkstyle-idea)
2) Compile https://gitlab.com/stellardrift/stylecheck 2) Compile https://gitlab.com/stellardrift/stylecheck
3) `Settings` -> `Tools` -> `Checkstyle` `Third-Party Checks`, add the compiled stylecheck jar 3) `Settings` -> `Tools` -> `Checkstyle` `Third-Party Checks`, add the compiled stylecheck jar
4) While still in the `Checkstyle` tab, go to `Configuration File`, add `.checkstyle/checkstyle.xml` and tick the check box. 4) While still in the `Checkstyle` tab, go to `Configuration File`, add `.checkstyle/checkstyle.xml` and tick the check
box.
### Partner ### Partner
![DedicatedMC](https://i.imgur.com/cbWjWFx.png) ![DedicatedMC](https://i.imgur.com/cbWjWFx.png)
Carbon is proudly partnered with DedicatedMC. Carbon is proudly partnered with DedicatedMC.
DedicatedMC are a hosting company that values transparency and providing an affordable service without sacrificing quality. DedicatedMC are a hosting company that values transparency and providing an affordable service without sacrificing
They provide nodes in various countries, such as the U.S. (New York & Los Angeles), Finland, and Germany. quality. They provide nodes in various countries, such as the U.S. (New York & Los Angeles), Finland, and Germany.
They have kindly provided me with a server to host CarbonChat on, which I'm still working on preparing. They have kindly provided me with a server to host CarbonChat on, which I'm still working on preparing.
If you're interested in a node, you can check them out at https://dedimc.promo/CarbonChat and use promo code **CarbonChat** If you're interested in a node, you can check them out at https://dedimc.promo/CarbonChat and use promo code **
CarbonChat**
+3 -2
View File
@@ -23,14 +23,15 @@ dependencies {
api(libs.kyoriEventApi) api(libs.kyoriEventApi)
api(libs.kyoriRegistry) api(libs.kyoriRegistry)
api(libs.kyoriMoonshine)
api(libs.kyoriMoonshineCore)
api(libs.kyoriMoonshineStandard)
api(libs.cloudCore) api(libs.cloudCore)
api(libs.cloudMinecraftExtras) { api(libs.cloudMinecraftExtras) {
isTransitive = false isTransitive = false
} }
api(libs.moonshine)
// we shade and relocate a newer version than minecraft provides // we shade and relocate a newer version than minecraft provides
api(libs.guava) api(libs.guava)
@@ -12,12 +12,12 @@ import org.checkerframework.framework.qual.DefaultQualifier;
@DefaultQualifier(NonNull.class) @DefaultQualifier(NonNull.class)
public final class CarbonChatProvider { public final class CarbonChatProvider {
private static @Nullable CarbonChat instance;
private CarbonChatProvider() { private CarbonChatProvider() {
} }
private static @Nullable CarbonChat instance;
/** /**
* Registers the {@link CarbonChat} implementation. * Registers the {@link CarbonChat} implementation.
* *
@@ -52,7 +52,7 @@ public interface ChatChannel extends Keyed, ChatComponentRenderer {
/** /**
* Filters the given recipients and removes entries that may not see messages in this channel. * Filters the given recipients and removes entries that may not see messages in this channel.
* *
* @param sender the sender of messages * @param sender the sender of messages
* @param recipients the recipients * @param recipients the recipients
* @return the recipients that may receive messages * @return the recipients that may receive messages
* @since 2.0.0 * @since 2.0.0
@@ -21,8 +21,8 @@ public class CarbonChatEvent implements ResultedCarbonEvent<CarbonChatEvent.Resu
private final List<KeyedRenderer> renderers; private final List<KeyedRenderer> renderers;
private final CarbonPlayer sender; private final CarbonPlayer sender;
private final Component originalMessage; private final Component originalMessage;
private Component message;
private final List<? extends Audience> recipients; private final List<? extends Audience> recipients;
private Component message;
private Result result = Result.ALLOWED; private Result result = Result.ALLOWED;
/** /**
@@ -17,7 +17,7 @@ import org.checkerframework.framework.qual.DefaultQualifier;
public final class CarbonEventHandler { public final class CarbonEventHandler {
private final EventBus<CarbonEvent> eventBus = EventBus.create(CarbonEvent.class, (type, event, subscriber) -> { private final EventBus<CarbonEvent> eventBus = EventBus.create(CarbonEvent.class, (type, event, subscriber) -> {
if (event instanceof ResultedCarbonEvent<?> rce) { if (event instanceof ResultedCarbonEvent<@NonNull ?> rce) {
return !rce.result().cancelled(); return !rce.result().cancelled();
} }
return true; return true;
@@ -33,7 +33,7 @@ public interface CarbonPlayer extends Audience, Identified {
* @return the player's display name * @return the player's display name
* @since 2.0.0 * @since 2.0.0
*/ */
Component displayName(); @Nullable Component displayName();
/** /**
* Sets the player's display name.<br> * Sets the player's display name.<br>
@@ -23,8 +23,8 @@ public interface ChatComponentRenderer {
* may be a player, console, or other Audience implementations * may be a player, console, or other Audience implementations
* @param message the message being sent * @param message the message being sent
* @param originalMessage the original message that was sent * @param originalMessage the original message that was sent
* @return the component to be shown to the recipient, * @return the component to be shown to the recipient,
* or empty if the recipient should not receive the message * or empty if the recipient should not receive the message
* @since 2.0.0 * @since 2.0.0
*/ */
@NonNull @NonNull
@@ -18,6 +18,12 @@ import org.checkerframework.framework.qual.DefaultQualifier;
@DefaultQualifier(NonNull.class) @DefaultQualifier(NonNull.class)
public final class ColorUtils { public final class ColorUtils {
private static final Pattern spigotLegacyRGB =
Pattern.compile("[§&]x[§&]([0-9a-fA-F])[§&]([0-9a-fA-F])[§&]([0-9a-fA-F])[§&]([0-9a-fA-F])[§&]([0-9a-fA-F])[§&]([0-9a-fA-F])");
private static final Pattern pluginRGB =
Pattern.compile("[§&]#([0-9a-fA-F])([0-9a-fA-F])([0-9a-fA-F])([0-9a-fA-F])([0-9a-fA-F])([0-9a-fA-F])");
private static final String hexReplacement = "<#$1$2$3$4$5$6>";
private ColorUtils() { private ColorUtils() {
} }
@@ -50,14 +56,6 @@ public final class ColorUtils {
return TextColor.fromCSSHexString(input); return TextColor.fromCSSHexString(input);
} }
private static final Pattern spigotLegacyRGB =
Pattern.compile("[§&]x[§&]([0-9a-fA-F])[§&]([0-9a-fA-F])[§&]([0-9a-fA-F])[§&]([0-9a-fA-F])[§&]([0-9a-fA-F])[§&]([0-9a-fA-F])");
private static final Pattern pluginRGB =
Pattern.compile("[§&]#([0-9a-fA-F])([0-9a-fA-F])([0-9a-fA-F])([0-9a-fA-F])([0-9a-fA-F])([0-9a-fA-F])");
private static final String hexReplacement = "<#$1$2$3$4$5$6>";
/** /**
* Converts the input legacy, legacy rgb, and alternate color formats to MiniMessage color tags. * Converts the input legacy, legacy rgb, and alternate color formats to MiniMessage color tags.
* *
@@ -6,9 +6,7 @@ import net.kyori.adventure.key.Key;
import net.kyori.adventure.key.Keyed; import net.kyori.adventure.key.Keyed;
import net.kyori.adventure.text.Component; import net.kyori.adventure.text.Component;
import org.checkerframework.checker.nullness.qual.NonNull; import org.checkerframework.checker.nullness.qual.NonNull;
import org.checkerframework.checker.nullness.qual.Nullable;
import org.checkerframework.framework.qual.DefaultQualifier; import org.checkerframework.framework.qual.DefaultQualifier;
import org.jetbrains.annotations.NotNull;
/** /**
* A chat renderer that's identifiable by key. * A chat renderer that's identifiable by key.
@@ -21,7 +19,7 @@ public interface KeyedRenderer extends Keyed, ChatComponentRenderer {
/** /**
* Creates a new renderer with the corresponding key. * Creates a new renderer with the corresponding key.
* *
* @param key the renderer's key * @param key the renderer's key
* @param renderer the chat renderer * @param renderer the chat renderer
* @return the keyed renderer * @return the keyed renderer
* @since 2.0.0 * @since 2.0.0
@@ -35,15 +33,14 @@ public interface KeyedRenderer extends Keyed, ChatComponentRenderer {
* *
* @since 2.0.0 * @since 2.0.0
*/ */
record Impl(@NonNull Key key, ChatComponentRenderer renderer) implements KeyedRenderer { record Impl(Key key, ChatComponentRenderer renderer) implements KeyedRenderer {
@Override @Override
public @Nullable @NotNull public Component render(
Component render( final CarbonPlayer sender,
final CarbonPlayer sender, final Audience recipient,
final Audience recipient, final Component message,
final Component message, final Component originalMessage
final Component originalMessage
) { ) {
return this.renderer.render(sender, recipient, message, originalMessage); return this.renderer.render(sender, recipient, message, originalMessage);
} }
+1 -1
View File
@@ -19,13 +19,13 @@ fun ShadowJar.standardRelocations() {
relocateDependency("net.kyori.adventure.text.minimessage") relocateDependency("net.kyori.adventure.text.minimessage")
relocateDependency("net.kyori.adventure.serializer.configurate4") relocateDependency("net.kyori.adventure.serializer.configurate4")
relocateDependency("net.kyori.event") relocateDependency("net.kyori.event")
relocateDependency("net.kyori.moonshine")
relocateDependency("net.kyori.registry") relocateDependency("net.kyori.registry")
relocateDependency("cloud.commandframework") relocateDependency("cloud.commandframework")
relocateDependency("org.spongepowered.configurate") relocateDependency("org.spongepowered.configurate")
relocateDependency("com.typesafe.config") relocateDependency("com.typesafe.config")
relocateDependency("com.google.common") relocateDependency("com.google.common")
relocateDependency("com.google.thirdparty.publicsuffix") relocateDependency("com.google.thirdparty.publicsuffix")
relocateDependency("com.proximyst.moonshine")
relocateDependency("it.unimi.dsi.fastutil") relocateDependency("it.unimi.dsi.fastutil")
} }
+1 -12
View File
@@ -1,5 +1,3 @@
import net.minecrell.pluginyml.bukkit.BukkitPluginDescription.Permission.Default.TRUE
plugins { plugins {
id("carbon.shadow-platform") id("carbon.shadow-platform")
id("net.minecrell.plugin-yml.bukkit") id("net.minecrell.plugin-yml.bukkit")
@@ -35,8 +33,7 @@ tasks {
relocateDependency("javax.inject") relocateDependency("javax.inject")
} }
runServer { runServer {
minecraftVersion("1.17") minecraftVersion("1.17.1")
jvmArgs("-DLog4jContextSelector=org.apache.logging.log4j.core.selector.ClassLoaderContextSelector") // https://github.com/PaperMC/Paper/issues/4155
} }
} }
@@ -50,12 +47,4 @@ bukkit {
softDepend = listOf("PlaceholderAPI", "Vault") softDepend = listOf("PlaceholderAPI", "Vault")
loadBefore = listOf("Essentials") loadBefore = listOf("Essentials")
website = GITHUB_REPO_URL website = GITHUB_REPO_URL
permissions {
register("carbonchat.channels.global.see") {
default = TRUE
}
register("carbonchat.channels.global.use") {
default = TRUE
}
}
} }
@@ -13,6 +13,7 @@ import net.draycia.carbon.api.channels.ChannelRegistry;
import net.draycia.carbon.api.events.CarbonEventHandler; import net.draycia.carbon.api.events.CarbonEventHandler;
import net.draycia.carbon.api.users.UserManager; import net.draycia.carbon.api.users.UserManager;
import net.draycia.carbon.bukkit.listeners.BukkitChatListener; import net.draycia.carbon.bukkit.listeners.BukkitChatListener;
import net.draycia.carbon.bukkit.listeners.BukkitPlayerJoinListener;
import net.draycia.carbon.bukkit.users.CarbonPlayerBukkit; import net.draycia.carbon.bukkit.users.CarbonPlayerBukkit;
import net.draycia.carbon.common.channels.CarbonChannelRegistry; import net.draycia.carbon.common.channels.CarbonChannelRegistry;
import net.draycia.carbon.common.listeners.DeafenHandler; import net.draycia.carbon.common.listeners.DeafenHandler;
@@ -26,22 +27,24 @@ import org.bukkit.event.Listener;
import org.bukkit.plugin.java.JavaPlugin; import org.bukkit.plugin.java.JavaPlugin;
import org.checkerframework.checker.nullness.qual.MonotonicNonNull; import org.checkerframework.checker.nullness.qual.MonotonicNonNull;
import org.checkerframework.checker.nullness.qual.NonNull; import org.checkerframework.checker.nullness.qual.NonNull;
import org.checkerframework.framework.qual.DefaultQualifier;
@Singleton @Singleton
@DefaultQualifier(NonNull.class)
public final class CarbonChatBukkit extends JavaPlugin implements CarbonChat { public final class CarbonChatBukkit extends JavaPlugin implements CarbonChat {
private static final Set<Class<? extends Listener>> LISTENER_CLASSES = Set.of( private static final Set<Class<? extends Listener>> LISTENER_CLASSES = Set.of(
BukkitChatListener.class BukkitChatListener.class,
BukkitPlayerJoinListener.class
); );
private static final int BSTATS_PLUGIN_ID = 8720; private static final int BSTATS_PLUGIN_ID = 8720;
private final CarbonEventHandler eventHandler = new CarbonEventHandler();
private @MonotonicNonNull Injector injector; private @MonotonicNonNull Injector injector;
private @MonotonicNonNull UserManager userManager;
private UserManager userManager; private @MonotonicNonNull Logger logger;
private Logger logger; private @MonotonicNonNull CarbonServerBukkit carbonServerBukkit;
private CarbonServerBukkit carbonServerBukkit; private @MonotonicNonNull CarbonMessageService messageService;
private CarbonMessageService messageService; private @MonotonicNonNull ChannelRegistry channelRegistry;
private ChannelRegistry channelRegistry;
@Override @Override
public void onLoad() { public void onLoad() {
@@ -134,8 +137,6 @@ public final class CarbonChatBukkit extends JavaPlugin implements CarbonChat {
return this.messageService; return this.messageService;
} }
private final CarbonEventHandler eventHandler = new CarbonEventHandler();
@Override @Override
public final @NonNull CarbonEventHandler eventHandler() { public final @NonNull CarbonEventHandler eventHandler() {
return this.eventHandler; return this.eventHandler;
@@ -1,6 +1,7 @@
package net.draycia.carbon.bukkit; package net.draycia.carbon.bukkit;
import cloud.commandframework.CommandManager; import cloud.commandframework.CommandManager;
import cloud.commandframework.brigadier.CloudBrigadierManager;
import cloud.commandframework.execution.AsynchronousCommandExecutionCoordinator; import cloud.commandframework.execution.AsynchronousCommandExecutionCoordinator;
import cloud.commandframework.paper.PaperCommandManager; import cloud.commandframework.paper.PaperCommandManager;
import com.google.inject.AbstractModule; import com.google.inject.AbstractModule;
@@ -18,6 +19,7 @@ import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.Logger;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
import org.checkerframework.checker.nullness.qual.NonNull; import org.checkerframework.checker.nullness.qual.NonNull;
import org.checkerframework.checker.nullness.qual.Nullable;
import org.checkerframework.framework.qual.DefaultQualifier; import org.checkerframework.framework.qual.DefaultQualifier;
@DefaultQualifier(NonNull.class) @DefaultQualifier(NonNull.class)
@@ -41,7 +43,7 @@ public final class CarbonChatBukkitModule extends AbstractModule {
final PaperCommandManager<Commander> commandManager; final PaperCommandManager<Commander> commandManager;
try { try {
commandManager = new PaperCommandManager<Commander>( commandManager = new PaperCommandManager<>(
this.carbonChat, this.carbonChat,
AsynchronousCommandExecutionCoordinator.<Commander>newBuilder().build(), AsynchronousCommandExecutionCoordinator.<Commander>newBuilder().build(),
commandSender -> { commandSender -> {
@@ -59,7 +61,8 @@ public final class CarbonChatBukkitModule extends AbstractModule {
commandManager.registerAsynchronousCompletions(); commandManager.registerAsynchronousCompletions();
commandManager.registerBrigadier(); commandManager.registerBrigadier();
final var brigadierManager = commandManager.brigadierManager(); final @Nullable CloudBrigadierManager<Commander, ?> brigadierManager =
commandManager.brigadierManager();
if (brigadierManager != null) { if (brigadierManager != null) {
brigadierManager.setNativeNumberSuggestions(false); brigadierManager.setNativeNumberSuggestions(false);
@@ -3,8 +3,10 @@ package net.draycia.carbon.bukkit;
import com.google.inject.Inject; import com.google.inject.Inject;
import com.google.inject.Singleton; import com.google.inject.Singleton;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Map;
import java.util.UUID; import java.util.UUID;
import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ConcurrentHashMap;
import net.draycia.carbon.api.CarbonServer; import net.draycia.carbon.api.CarbonServer;
import net.draycia.carbon.api.users.CarbonPlayer; import net.draycia.carbon.api.users.CarbonPlayer;
import net.draycia.carbon.api.users.ComponentPlayerResult; import net.draycia.carbon.api.users.ComponentPlayerResult;
@@ -29,6 +31,8 @@ public final class CarbonServerBukkit implements CarbonServer, ForwardingAudienc
private final CarbonChatBukkit chatBukkitEntry; private final CarbonChatBukkit chatBukkitEntry;
private final UserManager userManager; private final UserManager userManager;
private final Map<UUID, CarbonPlayerBukkit> userCache = new ConcurrentHashMap<>();
@Inject @Inject
private CarbonServerBukkit(final CarbonChatBukkit chatBukkitEntry, final UserManager userManager) { private CarbonServerBukkit(final CarbonChatBukkit chatBukkitEntry, final UserManager userManager) {
this.chatBukkitEntry = chatBukkitEntry; this.chatBukkitEntry = chatBukkitEntry;
@@ -61,23 +65,36 @@ public final class CarbonServerBukkit implements CarbonServer, ForwardingAudienc
} }
private CompletableFuture<ComponentPlayerResult> wrapPlayer(final UUID uuid) { private CompletableFuture<ComponentPlayerResult> wrapPlayer(final UUID uuid) {
return this.userManager.carbonPlayer(uuid).thenCompose(result -> { return CompletableFuture.supplyAsync(() -> {
return CompletableFuture.supplyAsync(() -> { final @Nullable CarbonPlayerBukkit cachedPlayer = this.userCache.get(uuid);
if (result.player() != null) {
new ComponentPlayerResult(new CarbonPlayerBukkit(result.player()), Component.empty());
}
final @Nullable String name = this.resolveName(uuid).join(); if (cachedPlayer != null) {
return new ComponentPlayerResult(cachedPlayer, Component.empty());
}
if (name != null) { final ComponentPlayerResult result = this.userManager.carbonPlayer(uuid).join();
final CarbonPlayerCommon player = new CarbonPlayerCommon(null,
null, name, uuid);
return new ComponentPlayerResult(new CarbonPlayerBukkit(player), Component.empty()); if (result.player() != null) {
} final CarbonPlayerBukkit carbonPlayerBukkit = new CarbonPlayerBukkit(result.player());
return new ComponentPlayerResult(null, text("Name not found for uuid!")); this.userCache.put(uuid, carbonPlayerBukkit);
});
return new ComponentPlayerResult(carbonPlayerBukkit, Component.empty());
}
final @Nullable String name = this.resolveName(uuid).join();
if (name != null) {
final CarbonPlayerCommon player = new CarbonPlayerCommon(null,
null, name, uuid);
final CarbonPlayerBukkit carbonPlayerBukkit = new CarbonPlayerBukkit(player);
this.userCache.put(uuid, carbonPlayerBukkit);
return new ComponentPlayerResult(carbonPlayerBukkit, Component.empty());
}
return new ComponentPlayerResult(null, text("Name not found for uuid!"));
}); });
} }
@@ -5,30 +5,21 @@ import net.kyori.adventure.audience.Audience;
import net.kyori.adventure.audience.ForwardingAudience; import net.kyori.adventure.audience.ForwardingAudience;
import org.bukkit.command.CommandSender; import org.bukkit.command.CommandSender;
import org.checkerframework.checker.nullness.qual.NonNull; import org.checkerframework.checker.nullness.qual.NonNull;
import org.checkerframework.framework.qual.DefaultQualifier;
@DefaultQualifier(NonNull.class)
public interface BukkitCommander extends Commander, ForwardingAudience.Single { public interface BukkitCommander extends Commander, ForwardingAudience.Single {
@NonNull CommandSender commandSender(); static BukkitCommander from(final CommandSender sender) {
static @NonNull BukkitCommander from(final @NonNull CommandSender sender) {
return new BukkitCommanderImpl(sender); return new BukkitCommanderImpl(sender);
} }
final class BukkitCommanderImpl implements BukkitCommander { CommandSender commandSender();
private final CommandSender commandSender; record BukkitCommanderImpl(CommandSender commandSender) implements BukkitCommander {
private BukkitCommanderImpl(final @NonNull CommandSender commandSender) {
this.commandSender = commandSender;
}
@Override @Override
public @NonNull CommandSender commandSender() { public Audience audience() {
return this.commandSender;
}
@Override
public @NonNull Audience audience() {
return this.commandSender; return this.commandSender;
} }
@@ -14,12 +14,14 @@ import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler; import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener; import org.bukkit.event.Listener;
import org.checkerframework.checker.nullness.qual.NonNull; import org.checkerframework.checker.nullness.qual.NonNull;
import org.checkerframework.framework.qual.DefaultQualifier;
import static java.util.Objects.requireNonNullElse; import static java.util.Objects.requireNonNullElse;
import static net.draycia.carbon.api.util.KeyedRenderer.keyedRenderer; import static net.draycia.carbon.api.util.KeyedRenderer.keyedRenderer;
import static net.kyori.adventure.key.Key.key; import static net.kyori.adventure.key.Key.key;
import static net.kyori.adventure.text.Component.empty; import static net.kyori.adventure.text.Component.empty;
@DefaultQualifier(NonNull.class)
public final class BukkitChatListener implements Listener { public final class BukkitChatListener implements Listener {
private final CarbonChatBukkit carbonChat; private final CarbonChatBukkit carbonChat;
@@ -75,11 +77,15 @@ public final class BukkitChatListener implements Listener {
Component component = message; Component component = message;
for (final var renderer : chatEvent.renderers()) { for (final var renderer : chatEvent.renderers()) {
if (viewer instanceof Player player) { try {
final ComponentPlayerResult targetPlayer = this.carbonChat.server().player(player).join(); if (viewer instanceof Player player) {
component = renderer.render(playerResult.player(), targetPlayer.player(), component, message); final ComponentPlayerResult targetPlayer = this.carbonChat.server().player(player).join();
} else { component = renderer.render(playerResult.player(), targetPlayer.player(), component, message);
component = renderer.render(playerResult.player(), viewer, component, message); } else {
component = renderer.render(playerResult.player(), viewer, component, message);
}
} catch (final Exception e) {
e.printStackTrace();
} }
} }
@@ -0,0 +1,70 @@
package net.draycia.carbon.bukkit.listeners;
import com.google.inject.Inject;
import java.util.Objects;
import net.draycia.carbon.api.CarbonChat;
import net.draycia.carbon.api.users.CarbonPlayer;
import net.draycia.carbon.bukkit.util.BukkitCapabilities;
import net.kyori.adventure.text.Component;
import net.kyori.adventure.text.minimessage.MiniMessage;
import net.kyori.adventure.text.minimessage.Template;
import net.milkbowl.vault.chat.Chat;
import org.bukkit.Bukkit;
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.plugin.Plugin;
import org.checkerframework.checker.nullness.qual.Nullable;
public class BukkitPlayerJoinListener implements Listener {
private final CarbonChat carbonChat;
@Inject
public BukkitPlayerJoinListener(final CarbonChat carbonChat) {
this.carbonChat = carbonChat;
}
@EventHandler(priority = EventPriority.LOWEST)
public void onPlayerLogin(final PlayerJoinEvent event) {
this.carbonChat.server()
.player(event.getPlayer().getUniqueId()).thenAccept(result -> {
if (result.player() == null) {
return;
}
final CarbonPlayer player = result.player();
Bukkit.getScheduler().scheduleSyncDelayedTask((Plugin) this.carbonChat, () -> {
if (player.displayName() != null) {
player.displayName(player.displayName());
} else {
final @Nullable Component nickname = this.createDefaultNickname(player);
if (nickname != null) {
player.displayName(nickname);
}
}
});
});
}
private @Nullable Component createDefaultNickname(final CarbonPlayer player) {
if (BukkitCapabilities.vaultEnabled()) {
final Chat vaultChat = Objects.requireNonNull(BukkitCapabilities.chat());
final Player bukkitPlayer = Bukkit.getPlayer(player.uuid());
final @Nullable String format =
vaultChat.getPlayerInfoString(bukkitPlayer, "autonick", null);
if (format != null) {
return MiniMessage.get().parse(format, Template.of("username", player.username()));
}
}
return null;
}
}
@@ -1,9 +1,9 @@
package net.draycia.carbon.bukkit.users; package net.draycia.carbon.bukkit.users;
import java.util.ArrayList;
import java.util.Arrays; import java.util.Arrays;
import java.util.List; import java.util.List;
import java.util.Locale; import java.util.Locale;
import java.util.Objects;
import java.util.UUID; import java.util.UUID;
import net.draycia.carbon.api.channels.ChatChannel; import net.draycia.carbon.api.channels.ChatChannel;
import net.draycia.carbon.api.users.CarbonPlayer; import net.draycia.carbon.api.users.CarbonPlayer;
@@ -13,22 +13,35 @@ import net.kyori.adventure.audience.Audience;
import net.kyori.adventure.audience.ForwardingAudience; import net.kyori.adventure.audience.ForwardingAudience;
import net.kyori.adventure.identity.Identity; import net.kyori.adventure.identity.Identity;
import net.kyori.adventure.text.Component; import net.kyori.adventure.text.Component;
import net.milkbowl.vault.permission.Permission;
import org.bukkit.Bukkit; import org.bukkit.Bukkit;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.ItemStack;
import org.bukkit.scoreboard.Scoreboard;
import org.checkerframework.checker.nullness.qual.MonotonicNonNull;
import org.checkerframework.checker.nullness.qual.NonNull; import org.checkerframework.checker.nullness.qual.NonNull;
import org.checkerframework.checker.nullness.qual.Nullable; import org.checkerframework.checker.nullness.qual.Nullable;
import org.checkerframework.framework.qual.DefaultQualifier; import org.checkerframework.framework.qual.DefaultQualifier;
import org.jetbrains.annotations.NotNull;
@DefaultQualifier(NonNull.class) @DefaultQualifier(NonNull.class)
public final class CarbonPlayerBukkit extends CarbonPlayerCommon implements ForwardingAudience.Single { public final class CarbonPlayerBukkit extends CarbonPlayerCommon implements ForwardingAudience.Single {
private final CarbonPlayer carbonPlayer; private final CarbonPlayer carbonPlayer;
private @MonotonicNonNull Scoreboard scoreboard = null;
public CarbonPlayerBukkit(final CarbonPlayer carbonPlayer) { public CarbonPlayerBukkit(final CarbonPlayer carbonPlayer) {
this.carbonPlayer = carbonPlayer; this.carbonPlayer = carbonPlayer;
} }
private @NonNull Scoreboard scoreboard() {
if (this.scoreboard == null) {
this.scoreboard = Bukkit.getScoreboardManager().getNewScoreboard();
}
return this.scoreboard;
}
@Override @Override
public void displayName(final @Nullable Component displayName) { public void displayName(final @Nullable Component displayName) {
this.carbonPlayer.displayName(displayName); this.carbonPlayer.displayName(displayName);
@@ -36,7 +49,10 @@ public final class CarbonPlayerBukkit extends CarbonPlayerCommon implements Forw
final @Nullable Player player = this.player(); final @Nullable Player player = this.player();
if (player != null) { if (player != null) {
// Update player's name in chat
player.displayName(displayName); player.displayName(displayName);
// Update player's name in the tab player list
player.playerListName(displayName); player.playerListName(displayName);
} }
} }
@@ -47,7 +63,18 @@ public final class CarbonPlayerBukkit extends CarbonPlayerCommon implements Forw
} }
@Override @Override
public Component displayName() { public @Nullable Component displayName() {
// if (this.carbonPlayer.displayName() != null) {
// return this.carbonPlayer.displayName();
// }
// final @Nullable Player player = this.player();
//
// if (player != null) {
// return player.displayName();
// }
// return null;
return this.carbonPlayer.displayName(); return this.carbonPlayer.displayName();
} }
@@ -57,7 +84,7 @@ public final class CarbonPlayerBukkit extends CarbonPlayerCommon implements Forw
} }
@Override @Override
public @NonNull Audience audience() { public @NotNull Audience audience() {
final @Nullable Player player = this.player(); final @Nullable Player player = this.player();
if (player == null) { if (player == null) {
@@ -73,7 +100,7 @@ public final class CarbonPlayerBukkit extends CarbonPlayerCommon implements Forw
} }
@Override @Override
public @NonNull Component createItemHoverComponent() { public Component createItemHoverComponent() {
final @Nullable Player player = this.player(); // This is temporary (it's not) final @Nullable Player player = this.player(); // This is temporary (it's not)
if (player == null) { if (player == null) {
@@ -124,13 +151,10 @@ public final class CarbonPlayerBukkit extends CarbonPlayerCommon implements Forw
return "default"; return "default";
} }
final String group = BukkitCapabilities.permission().getPrimaryGroup(this.player()); final Permission permission = Objects.requireNonNull(BukkitCapabilities.permission());
final String group = permission.getPrimaryGroup(this.player());
if (group != null) { return Objects.requireNonNullElse(group, "default");
return group;
}
return "default";
} }
@Override @Override
@@ -139,7 +163,8 @@ public final class CarbonPlayerBukkit extends CarbonPlayerCommon implements Forw
return List.of("default"); return List.of("default");
} }
final String[] groups = BukkitCapabilities.permission().getPlayerGroups(this.player()); final Permission permission = Objects.requireNonNull(BukkitCapabilities.permission());
final String[] groups = permission.getPlayerGroups(this.player());
if (groups != null && groups.length != 0) { if (groups != null && groups.length != 0) {
return Arrays.asList(groups); return Arrays.asList(groups);
@@ -204,7 +229,7 @@ public final class CarbonPlayerBukkit extends CarbonPlayerCommon implements Forw
} }
@Override @Override
public @NonNull Identity identity() { public Identity identity() {
return this.carbonPlayer.identity(); return this.carbonPlayer.identity();
} }
@@ -1,17 +1,24 @@
package net.draycia.carbon.bukkit.util; package net.draycia.carbon.bukkit.util;
import net.milkbowl.vault.chat.Chat;
import net.milkbowl.vault.permission.Permission; import net.milkbowl.vault.permission.Permission;
import org.bukkit.Bukkit; import org.bukkit.Bukkit;
import org.bukkit.plugin.RegisteredServiceProvider; import org.bukkit.plugin.RegisteredServiceProvider;
import org.checkerframework.checker.nullness.qual.NonNull;
import org.checkerframework.checker.nullness.qual.Nullable;
import org.checkerframework.framework.qual.DefaultQualifier;
public class BukkitCapabilities { @DefaultQualifier(NonNull.class)
public final class BukkitCapabilities {
private static @Nullable Boolean vaultEnabled = null;
private static @Nullable Permission permission = null;
private static @Nullable Chat chat = null;
private BukkitCapabilities() { private BukkitCapabilities() {
} }
private static Boolean vaultEnabled = null;
public static boolean vaultEnabled() { public static boolean vaultEnabled() {
if (vaultEnabled == null) { if (vaultEnabled == null) {
vaultEnabled = Bukkit.getPluginManager().isPluginEnabled("Vault"); vaultEnabled = Bukkit.getPluginManager().isPluginEnabled("Vault");
@@ -20,21 +27,38 @@ public class BukkitCapabilities {
return vaultEnabled; return vaultEnabled;
} }
private static Permission permission = null; public static @Nullable Permission permission() {
public static Permission permission() {
if (!vaultEnabled()) { if (!vaultEnabled()) {
return null; return null;
} }
if (permission == null) { if (permission == null) {
RegisteredServiceProvider<Permission> rsp = Bukkit.getServer() final @Nullable RegisteredServiceProvider<Permission> rsp = Bukkit.getServer()
.getServicesManager().getRegistration(Permission.class); .getServicesManager().getRegistration(Permission.class);
permission = rsp.getProvider(); if (rsp != null) {
permission = rsp.getProvider();
}
} }
return permission; return permission;
} }
public static @Nullable Chat chat() {
if (!vaultEnabled()) {
return null;
}
if (chat == null) {
final @Nullable RegisteredServiceProvider<Chat> rsp = Bukkit.getServer()
.getServicesManager().getRegistration(Chat.class);
if (rsp != null) {
chat = rsp.getProvider();
}
}
return chat;
}
} }
@@ -14,18 +14,36 @@ import net.kyori.adventure.text.serializer.legacy.LegacyComponentSerializer;
import org.bukkit.OfflinePlayer; import org.bukkit.OfflinePlayer;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
import org.checkerframework.checker.nullness.qual.NonNull; import org.checkerframework.checker.nullness.qual.NonNull;
import org.checkerframework.framework.qual.DefaultQualifier;
import static java.util.Collections.emptyList; import static java.util.Collections.emptyList;
@DefaultQualifier(NonNull.class)
public final class PlaceholderAPIMiniMessageParser { public final class PlaceholderAPIMiniMessageParser {
private final MiniMessage miniMessage; private final MiniMessage miniMessage;
private PlaceholderAPIMiniMessageParser(final @NonNull MiniMessage miniMessage) { private PlaceholderAPIMiniMessageParser(final MiniMessage miniMessage) {
this.miniMessage = miniMessage; this.miniMessage = miniMessage;
} }
public @NonNull Component parse(final @NonNull OfflinePlayer player, final @NonNull String input, final @NonNull Collection<Template> templates) { public static PlaceholderAPIMiniMessageParser create(final MiniMessage backingInstance) {
return new PlaceholderAPIMiniMessageParser(backingInstance);
}
private static boolean containsLegacyColorCodes(final String string) {
final char[] charArray = string.toCharArray();
for (final char c : charArray) {
if (c == LegacyComponentSerializer.SECTION_CHAR) {
return true;
}
}
return false;
}
public Component parse(final OfflinePlayer player, final String input, final Collection<Template> templates) {
return this.parse( return this.parse(
PlaceholderAPI.getPlaceholderPattern(), PlaceholderAPI.getPlaceholderPattern(),
match -> PlaceholderAPI.setPlaceholders(player, match), match -> PlaceholderAPI.setPlaceholders(player, match),
@@ -34,11 +52,11 @@ public final class PlaceholderAPIMiniMessageParser {
); );
} }
public @NonNull Component parse(final @NonNull OfflinePlayer player, final @NonNull String input) { public Component parse(final OfflinePlayer player, final String input) {
return this.parse(player, input, emptyList()); return this.parse(player, input, emptyList());
} }
public @NonNull Component parseRelational(final @NonNull Player one, final @NonNull Player two, final @NonNull String input, final @NonNull Collection<Template> templates) { public Component parseRelational(final Player one, final Player two, final String input, final Collection<Template> templates) {
return this.parse( return this.parse(
PlaceholderAPI.getPlaceholderPattern(), PlaceholderAPI.getPlaceholderPattern(),
match -> PlaceholderAPI.setPlaceholders(one, PlaceholderAPI.setRelationalPlaceholders(one, two, match)), match -> PlaceholderAPI.setPlaceholders(one, PlaceholderAPI.setRelationalPlaceholders(one, two, match)),
@@ -47,23 +65,25 @@ public final class PlaceholderAPIMiniMessageParser {
); );
} }
public @NonNull Component parseRelational(final @NonNull Player one, final @NonNull Player two, final @NonNull String input) { public Component parseRelational(final Player one, final Player two, final String input) {
return this.parseRelational(one, two, input, emptyList()); return this.parseRelational(one, two, input, emptyList());
} }
private @NonNull Component parse( private Component parse(
final @NonNull Pattern pattern, final Pattern pattern,
final @NonNull UnaryOperator<String> placeholderResolver, final UnaryOperator<String> placeholderResolver,
final @NonNull String input, final String input,
final @NonNull Collection<Template> originalTemplates final Collection<Template> originalTemplates
) { ) {
final Matcher matcher = pattern.matcher(input); final Matcher matcher = pattern.matcher(input);
final List<Template> templates = new ArrayList<>(originalTemplates); final List<Template> templates = new ArrayList<>(originalTemplates);
final StringBuilder builder = new StringBuilder(); final StringBuilder builder = new StringBuilder();
int id = 0; int id = 0;
while (matcher.find()) { while (matcher.find()) {
final String match = matcher.group(); final String match = matcher.group();
final String replaced = placeholderResolver.apply(match); final String replaced = placeholderResolver.apply(match);
if (match.equals(replaced) || !containsLegacyColorCodes(replaced)) { if (match.equals(replaced) || !containsLegacyColorCodes(replaced)) {
matcher.appendReplacement(builder, replaced); matcher.appendReplacement(builder, replaced);
} else { } else {
@@ -73,22 +93,10 @@ public final class PlaceholderAPIMiniMessageParser {
matcher.appendReplacement(builder, "<" + key + ">"); matcher.appendReplacement(builder, "<" + key + ">");
} }
} }
matcher.appendTail(builder); matcher.appendTail(builder);
return this.miniMessage.parse(builder.toString(), templates); return this.miniMessage.parse(builder.toString(), templates);
} }
public static @NonNull PlaceholderAPIMiniMessageParser create(final @NonNull MiniMessage backingInstance) {
return new PlaceholderAPIMiniMessageParser(backingInstance);
}
private static boolean containsLegacyColorCodes(final @NonNull String string) {
final char[] charArray = string.toCharArray();
for (int i = 0; i < charArray.length; i++) {
if (charArray[i] == LegacyComponentSerializer.SECTION_CHAR) {
return true;
}
}
return false;
}
} }
@@ -4,7 +4,7 @@ import com.google.inject.AbstractModule;
import com.google.inject.Injector; import com.google.inject.Injector;
import com.google.inject.Provides; import com.google.inject.Provides;
import com.google.inject.Singleton; import com.google.inject.Singleton;
import com.proximyst.moonshine.Moonshine; import io.leangen.geantyref.TypeToken;
import java.io.IOException; import java.io.IOException;
import java.util.UUID; import java.util.UUID;
import net.draycia.carbon.api.channels.ChannelRegistry; import net.draycia.carbon.api.channels.ChannelRegistry;
@@ -12,16 +12,21 @@ import net.draycia.carbon.api.users.UserManager;
import net.draycia.carbon.common.channels.CarbonChannelRegistry; import net.draycia.carbon.common.channels.CarbonChannelRegistry;
import net.draycia.carbon.common.config.ConfigLoader; import net.draycia.carbon.common.config.ConfigLoader;
import net.draycia.carbon.common.config.PrimaryConfig; import net.draycia.carbon.common.config.PrimaryConfig;
import net.draycia.carbon.common.messages.CarbonMessageParser; import net.draycia.carbon.common.messages.CarbonMessageRenderer;
import net.draycia.carbon.common.messages.CarbonMessageSender; import net.draycia.carbon.common.messages.CarbonMessageSender;
import net.draycia.carbon.common.messages.CarbonMessageService; import net.draycia.carbon.common.messages.CarbonMessageService;
import net.draycia.carbon.common.messages.CarbonMessageSource; import net.draycia.carbon.common.messages.CarbonMessageSource;
import net.draycia.carbon.common.messages.ComponentPlaceholderResolver; import net.draycia.carbon.common.messages.ComponentPlaceholderResolver;
import net.draycia.carbon.common.messages.ServerReceiverResolver; import net.draycia.carbon.common.messages.ReceiverResolver;
import net.draycia.carbon.common.messages.StringPlaceholderResolver;
import net.draycia.carbon.common.messages.UUIDPlaceholderResolver; import net.draycia.carbon.common.messages.UUIDPlaceholderResolver;
import net.draycia.carbon.common.users.JSONUserManager; import net.draycia.carbon.common.users.JSONUserManager;
import net.kyori.adventure.audience.Audience; import net.kyori.adventure.audience.Audience;
import net.kyori.adventure.text.Component; import net.kyori.adventure.text.Component;
import net.kyori.moonshine.Moonshine;
import net.kyori.moonshine.exception.scan.UnscannableMethodException;
import net.kyori.moonshine.strategy.StandardPlaceholderResolverStrategy;
import net.kyori.moonshine.strategy.supertype.StandardSupertypeThenInterfaceSupertypeStrategy;
import org.checkerframework.checker.nullness.qual.NonNull; import org.checkerframework.checker.nullness.qual.NonNull;
import org.checkerframework.checker.nullness.qual.Nullable; import org.checkerframework.checker.nullness.qual.Nullable;
import org.checkerframework.framework.qual.DefaultQualifier; import org.checkerframework.framework.qual.DefaultQualifier;
@@ -58,21 +63,24 @@ public final class CarbonCommonModule extends AbstractModule {
@Provides @Provides
@Singleton @Singleton
public CarbonMessageService messageService( public CarbonMessageService messageService(
final ServerReceiverResolver serverReceiverResolver, final ReceiverResolver receiverResolver,
final ComponentPlaceholderResolver<Audience> componentPlaceholderResolver, final ComponentPlaceholderResolver<Audience> componentPlaceholderResolver,
final UUIDPlaceholderResolver<Audience> uuidPlaceholderResolver, final UUIDPlaceholderResolver<Audience> uuidPlaceholderResolver,
final StringPlaceholderResolver<Audience> stringPlaceholderResolver,
final CarbonMessageSource carbonMessageSource, final CarbonMessageSource carbonMessageSource,
final CarbonMessageParser carbonMessageParser, final CarbonMessageSender carbonMessageSender,
final CarbonMessageSender carbonMessageSender final CarbonMessageRenderer carbonMessageRenderer
) { ) throws UnscannableMethodException {
return Moonshine.<Audience>builder() return Moonshine.<CarbonMessageService, Audience>builder(new TypeToken<>() {})
.receiver(serverReceiverResolver) .receiverLocatorResolver(receiverResolver, 0)
.placeholder(Component.class, componentPlaceholderResolver) .sourced(carbonMessageSource)
.placeholder(UUID.class, uuidPlaceholderResolver) .rendered(carbonMessageRenderer)
.source(carbonMessageSource) .sent(carbonMessageSender)
.parser(carbonMessageParser) .resolvingWithStrategy(new StandardPlaceholderResolverStrategy<>(new StandardSupertypeThenInterfaceSupertypeStrategy(false)))
.sender(carbonMessageSender) .weightedPlaceholderResolver(Component.class, componentPlaceholderResolver, 0)
.create(CarbonMessageService.class, this.getClass().getClassLoader()); .weightedPlaceholderResolver(UUID.class, uuidPlaceholderResolver, 0)
.weightedPlaceholderResolver(String.class, stringPlaceholderResolver, 0)
.create(this.getClass().getClassLoader());
} }
@Override @Override
@@ -17,6 +17,7 @@ import net.kyori.adventure.key.Key;
import net.kyori.registry.DefaultedRegistry; import net.kyori.registry.DefaultedRegistry;
import net.kyori.registry.RegistryImpl; import net.kyori.registry.RegistryImpl;
import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.Logger;
import org.checkerframework.checker.nullness.qual.MonotonicNonNull;
import org.checkerframework.checker.nullness.qual.NonNull; import org.checkerframework.checker.nullness.qual.NonNull;
import org.checkerframework.checker.nullness.qual.Nullable; import org.checkerframework.checker.nullness.qual.Nullable;
import org.checkerframework.framework.qual.DefaultQualifier; import org.checkerframework.framework.qual.DefaultQualifier;
@@ -29,14 +30,23 @@ import org.spongepowered.configurate.serialize.SerializationException;
@DefaultQualifier(NonNull.class) @DefaultQualifier(NonNull.class)
public class CarbonChannelRegistry extends RegistryImpl<Key, ChatChannel> implements ChannelRegistry, DefaultedRegistry<Key, ChatChannel> { public class CarbonChannelRegistry extends RegistryImpl<Key, ChatChannel> implements ChannelRegistry, DefaultedRegistry<Key, ChatChannel> {
private static @MonotonicNonNull ObjectMapper<ConfigChatChannel> MAPPER;
static {
try {
MAPPER = ObjectMapper.factory().get(ConfigChatChannel.class);
} catch (final SerializationException e) {
e.printStackTrace();
}
}
private final ConfigLoader configLoader; private final ConfigLoader configLoader;
private final Path dataDirectory; private final Path dataDirectory;
private final Injector injector; private final Injector injector;
private final Logger logger; private final Logger logger;
private final PrimaryConfig primaryConfig; private final PrimaryConfig primaryConfig;
private @MonotonicNonNull Key defaultKey;
private Key defaultKey; private @MonotonicNonNull ChatChannel basicChannel;
private ChatChannel basicChannel;
@Inject @Inject
public CarbonChannelRegistry( public CarbonChannelRegistry(
@@ -102,16 +112,6 @@ public class CarbonChannelRegistry extends RegistryImpl<Key, ChatChannel> implem
} }
} }
private static ObjectMapper<ConfigChatChannel> MAPPER;
static {
try {
MAPPER = ObjectMapper.factory().get(ConfigChatChannel.class);
} catch (final SerializationException e) {
e.printStackTrace();
}
}
public @Nullable ChatChannel loadChannel(final Path channelFile) { public @Nullable ChatChannel loadChannel(final Path channelFile) {
final ConfigurationLoader<?> loader = this.configLoader.configurationLoader(channelFile); final ConfigurationLoader<?> loader = this.configLoader.configurationLoader(channelFile);
@@ -125,17 +125,17 @@ public class CarbonChannelRegistry extends RegistryImpl<Key, ChatChannel> implem
} }
@Override @Override
public @NonNull ChatChannel defaultValue() { public ChatChannel defaultValue() {
return Objects.requireNonNullElse(this.get(this.defaultKey), this.basicChannel); return Objects.requireNonNullElse(this.get(this.defaultKey), this.basicChannel);
} }
@Override @Override
public @NonNull Key defaultKey() { public Key defaultKey() {
return this.defaultKey; return this.defaultKey;
} }
@Override @Override
public @NonNull ChatChannel getOrDefault(@NonNull final Key key) { public ChatChannel getOrDefault(final Key key) {
final @Nullable ChatChannel channel = this.get(key); final @Nullable ChatChannel channel = this.get(key);
if (channel != null) { if (channel != null) {
@@ -1,8 +1,9 @@
package net.draycia.carbon.common.channels; package net.draycia.carbon.common.channels;
import com.proximyst.moonshine.Moonshine; import io.leangen.geantyref.TypeToken;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import java.util.Objects;
import java.util.Set; import java.util.Set;
import java.util.UUID; import java.util.UUID;
import net.draycia.carbon.api.CarbonChatProvider; import net.draycia.carbon.api.CarbonChatProvider;
@@ -10,14 +11,19 @@ import net.draycia.carbon.api.channels.ChatChannel;
import net.draycia.carbon.api.users.CarbonPlayer; import net.draycia.carbon.api.users.CarbonPlayer;
import net.draycia.carbon.common.channels.messages.ConfigChannelMessageService; import net.draycia.carbon.common.channels.messages.ConfigChannelMessageService;
import net.draycia.carbon.common.channels.messages.ConfigChannelMessageSource; import net.draycia.carbon.common.channels.messages.ConfigChannelMessageSource;
import net.draycia.carbon.common.messages.CarbonMessageParser; import net.draycia.carbon.common.messages.CarbonMessageRenderer;
import net.draycia.carbon.common.messages.CarbonMessageSender; import net.draycia.carbon.common.messages.CarbonMessageSender;
import net.draycia.carbon.common.messages.ComponentPlaceholderResolver; import net.draycia.carbon.common.messages.ComponentPlaceholderResolver;
import net.draycia.carbon.common.messages.ServerReceiverResolver; import net.draycia.carbon.common.messages.ReceiverResolver;
import net.draycia.carbon.common.messages.StringPlaceholderResolver;
import net.draycia.carbon.common.messages.UUIDPlaceholderResolver; import net.draycia.carbon.common.messages.UUIDPlaceholderResolver;
import net.kyori.adventure.audience.Audience; import net.kyori.adventure.audience.Audience;
import net.kyori.adventure.key.Key; import net.kyori.adventure.key.Key;
import net.kyori.adventure.text.Component; import net.kyori.adventure.text.Component;
import net.kyori.moonshine.Moonshine;
import net.kyori.moonshine.exception.scan.UnscannableMethodException;
import net.kyori.moonshine.strategy.StandardPlaceholderResolverStrategy;
import net.kyori.moonshine.strategy.supertype.StandardSupertypeThenInterfaceSupertypeStrategy;
import org.checkerframework.checker.nullness.qual.NonNull; import org.checkerframework.checker.nullness.qual.NonNull;
import org.checkerframework.checker.nullness.qual.Nullable; import org.checkerframework.checker.nullness.qual.Nullable;
import org.checkerframework.framework.qual.DefaultQualifier; import org.checkerframework.framework.qual.DefaultQualifier;
@@ -26,6 +32,7 @@ import org.spongepowered.configurate.objectmapping.ConfigSerializable;
import org.spongepowered.configurate.objectmapping.meta.Comment; import org.spongepowered.configurate.objectmapping.meta.Comment;
import org.spongepowered.configurate.objectmapping.meta.Setting; import org.spongepowered.configurate.objectmapping.meta.Setting;
import static java.util.Objects.requireNonNull;
import static net.kyori.adventure.text.Component.text; import static net.kyori.adventure.text.Component.text;
@ConfigSerializable @ConfigSerializable
@@ -37,7 +44,7 @@ public final class ConfigChatChannel implements ChatChannel {
The key can stay "carbon". The key can stay "carbon".
The value is what's used in commands, this is probably what you want to change. The value is what's used in commands, this is probably what you want to change.
""") """)
private Key key = Key.key("carbon", "basic"); private final Key key = Key.key("carbon", "basic");
@Comment(""" @Comment("""
The permission required to use the channel. The permission required to use the channel.
@@ -45,11 +52,11 @@ public final class ConfigChatChannel implements ChatChannel {
To send messages you must have the permission carbon.channel.basic.speak To send messages you must have the permission carbon.channel.basic.speak
If you want to give both, grant carbon.channel.basic or carbon.channel.basic.* If you want to give both, grant carbon.channel.basic or carbon.channel.basic.*
""") """)
private String permission = "carbon.channel.basic"; private final String permission = "carbon.channel.basic";
@Setting("format") @Setting("format")
@Comment("The chat formats for this channel.") @Comment("The chat formats for this channel.")
private ConfigChannelMessageSource messageSource = new ConfigChannelMessageSource(); private final ConfigChannelMessageSource messageSource = new ConfigChannelMessageSource();
private transient @Nullable ConfigChannelMessageService messageService = null; private transient @Nullable ConfigChannelMessageService messageService = null;
@@ -63,7 +70,7 @@ public final class ConfigChatChannel implements ChatChannel {
return this.messageService().chatFormat( return this.messageService().chatFormat(
recipient, recipient,
sender.uuid(), sender.uuid(),
sender.displayName(), Objects.requireNonNullElseGet(sender.displayName(), () -> Component.text(sender.username())),
sender.username(), sender.username(),
message message
); );
@@ -113,21 +120,31 @@ public final class ConfigChatChannel implements ChatChannel {
return this.key; return this.key;
} }
private ConfigChannelMessageService createMessageService() { private @Nullable ConfigChannelMessageService createMessageService() {
final ServerReceiverResolver serverReceiverResolver = new ServerReceiverResolver(CarbonChatProvider.carbonChat().server()); final ReceiverResolver serverReceiverResolver = new ReceiverResolver();
final ComponentPlaceholderResolver<Audience> componentPlaceholderResolver = new ComponentPlaceholderResolver<>(); final ComponentPlaceholderResolver<Audience> componentPlaceholderResolver = new ComponentPlaceholderResolver<>();
final UUIDPlaceholderResolver<Audience> uuidPlaceholderResolver = new UUIDPlaceholderResolver<>(); final UUIDPlaceholderResolver<Audience> uuidPlaceholderResolver = new UUIDPlaceholderResolver<>();
final CarbonMessageParser carbonMessageParser = new CarbonMessageParser(); final StringPlaceholderResolver<Audience> stringPlaceholderResolver = new StringPlaceholderResolver<>();
final CarbonMessageRenderer carbonMessageRenderer = new CarbonMessageRenderer();
final CarbonMessageSender carbonMessageSender = new CarbonMessageSender(); final CarbonMessageSender carbonMessageSender = new CarbonMessageSender();
return Moonshine.<Audience>builder() try {
.receiver(serverReceiverResolver) return Moonshine.<ConfigChannelMessageService, Audience>builder(new TypeToken<>() {
.placeholder(Component.class, componentPlaceholderResolver) })
.placeholder(UUID.class, uuidPlaceholderResolver) .receiverLocatorResolver(serverReceiverResolver, 0)
.source(this.messageSource) .sourced(this.messageSource)
.parser(carbonMessageParser) .rendered(carbonMessageRenderer)
.sender(carbonMessageSender) .sent(carbonMessageSender)
.create(ConfigChannelMessageService.class, this.getClass().getClassLoader()); .resolvingWithStrategy(new StandardPlaceholderResolverStrategy<>(new StandardSupertypeThenInterfaceSupertypeStrategy(false)))
.weightedPlaceholderResolver(Component.class, componentPlaceholderResolver, 0)
.weightedPlaceholderResolver(UUID.class, uuidPlaceholderResolver, 0)
.weightedPlaceholderResolver(String.class, stringPlaceholderResolver, 0)
.create(this.getClass().getClassLoader());
} catch (final UnscannableMethodException e) {
e.printStackTrace();
}
return null;
} }
private ConfigChannelMessageService messageService() { private ConfigChannelMessageService messageService() {
@@ -135,7 +152,7 @@ public final class ConfigChatChannel implements ChatChannel {
this.messageService = this.createMessageService(); this.messageService = this.createMessageService();
} }
return this.messageService; return requireNonNull(this.messageService, "Channel message service must not be null!");
} }
} }
@@ -1,20 +1,22 @@
package net.draycia.carbon.common.channels.messages; package net.draycia.carbon.common.channels.messages;
import com.proximyst.moonshine.annotation.Message;
import com.proximyst.moonshine.annotation.Placeholder;
import com.proximyst.moonshine.annotation.Receiver;
import java.util.UUID; import java.util.UUID;
import net.kyori.adventure.audience.Audience; import net.kyori.adventure.audience.Audience;
import net.kyori.adventure.text.Component; import net.kyori.adventure.text.Component;
import net.kyori.moonshine.annotation.Message;
import net.kyori.moonshine.annotation.Placeholder;
import org.checkerframework.checker.nullness.qual.NonNull;
import org.checkerframework.framework.qual.DefaultQualifier;
@DefaultQualifier(NonNull.class)
public interface ConfigChannelMessageService { public interface ConfigChannelMessageService {
// TODO: locale placeholders? // TODO: locale placeholders?
@Message("channel.format") @Message("channel.format")
Component chatFormat( Component chatFormat(
@Receiver final Audience audience, final Audience audience,
@Placeholder UUID uuid, @Placeholder UUID uuid,
@Placeholder Component displayname, @Placeholder("displayname") Component displayName,
@Placeholder String username, @Placeholder String username,
@Placeholder Component message @Placeholder Component message
); );
@@ -1,10 +1,10 @@
package net.draycia.carbon.common.channels.messages; package net.draycia.carbon.common.channels.messages;
import com.proximyst.moonshine.message.IMessageSource;
import java.util.Locale; import java.util.Locale;
import java.util.Map; import java.util.Map;
import net.draycia.carbon.api.users.CarbonPlayer; import net.draycia.carbon.api.users.CarbonPlayer;
import net.kyori.adventure.audience.Audience; import net.kyori.adventure.audience.Audience;
import net.kyori.moonshine.message.IMessageSource;
import org.checkerframework.checker.nullness.qual.NonNull; import org.checkerframework.checker.nullness.qual.NonNull;
import org.checkerframework.framework.qual.DefaultQualifier; import org.checkerframework.framework.qual.DefaultQualifier;
import org.spongepowered.configurate.objectmapping.ConfigSerializable; import org.spongepowered.configurate.objectmapping.ConfigSerializable;
@@ -13,7 +13,7 @@ import org.spongepowered.configurate.objectmapping.meta.Setting;
@ConfigSerializable @ConfigSerializable
@DefaultQualifier(NonNull.class) @DefaultQualifier(NonNull.class)
public class ConfigChannelMessageSource implements IMessageSource<String, Audience> { public class ConfigChannelMessageSource implements IMessageSource<Audience, String> {
// Map<String, String> -> Map<Group, Format> // Map<String, String> -> Map<Group, Format>
// "default" key will be configurable but let's not worry about that for now // "default" key will be configurable but let's not worry about that for now
@@ -24,7 +24,7 @@ public class ConfigChannelMessageSource implements IMessageSource<String, Audien
The "console" format is what's shown to console. The "console" format is what's shown to console.
The keys are group names, the values are chat formats (MiniMessage). The keys are group names, the values are chat formats (MiniMessage).
""") """)
private Map<String, String> defaults = Map.of("default", "<displayname>: <message>", private final Map<String, String> defaults = Map.of("default", "<displayname>: <message>",
"console", "<username> - <uuid>: <message>"); "console", "<username> - <uuid>: <message>");
// TODO: Move the default to the advanced config? // TODO: Move the default to the advanced config?
@@ -33,34 +33,35 @@ public class ConfigChannelMessageSource implements IMessageSource<String, Audien
You can safely delete this section if you don't want to use this feature. You can safely delete this section if you don't want to use this feature.
Will fall back to the defaults section if no format was found for the player. Will fall back to the defaults section if no format was found for the player.
""") """)
private Map<Locale, Map<String, String>> locales = Map.of(Locale.US, private final Map<Locale, Map<String, String>> locales = Map.of(Locale.US,
Map.of("default", "<displayname>: <message>")); Map.of("default", "<displayname>: <message>"));
@Override @Override
public String message(final String key, final Audience receiver) { public String messageOf(final Audience receiver, final String messageKey) {
if (receiver instanceof CarbonPlayer player) { if (receiver instanceof CarbonPlayer player) {
return this.forPlayer(key, player); return this.forPlayer(messageKey, player);
} else { } else {
return this.forAudience(key, receiver); return this.forAudience(messageKey, receiver);
} }
} }
private String forPlayer(final String key, final CarbonPlayer player) { private String forPlayer(final String key, final CarbonPlayer player) {
final Map<String, String> formats = this.locales.get(player.locale()); // TODO: rewrite and reimplement
// final Map<String, String> formats = this.locales.get(player.locale());
if (formats != null) { //
final String format = formats.get(player.primaryGroup()); // if (formats != null) {
// final String format = formats.get(player.primaryGroup());
if (format != null) { //
return format; // if (format != null) {
} // return format;
// }
final String defaultFormat = formats.get("default"); //
// final String defaultFormat = formats.get("default");
if (defaultFormat != null) { //
return defaultFormat; // if (defaultFormat != null) {
} // return defaultFormat;
} // }
// }
final String format = this.defaults.get(player.primaryGroup()); final String format = this.defaults.get(player.primaryGroup());
@@ -1,7 +1,6 @@
package net.draycia.carbon.common.config; package net.draycia.carbon.common.config;
import com.google.inject.Inject; import com.google.inject.Inject;
import com.google.inject.Injector;
import java.io.IOException; import java.io.IOException;
import java.nio.file.Files; import java.nio.file.Files;
import java.nio.file.Path; import java.nio.file.Path;
@@ -15,24 +14,20 @@ import org.checkerframework.framework.qual.DefaultQualifier;
import org.spongepowered.configurate.ConfigurateException; import org.spongepowered.configurate.ConfigurateException;
import org.spongepowered.configurate.hocon.HoconConfigurationLoader; import org.spongepowered.configurate.hocon.HoconConfigurationLoader;
import org.spongepowered.configurate.loader.ConfigurationLoader; import org.spongepowered.configurate.loader.ConfigurationLoader;
import org.spongepowered.configurate.objectmapping.ObjectMapper;
import org.spongepowered.configurate.objectmapping.guice.GuiceObjectMapperProvider;
@DefaultQualifier(NonNull.class) @DefaultQualifier(NonNull.class)
public class ConfigLoader { public class ConfigLoader {
private final Path dataDirectory; private final Path dataDirectory;
private final ObjectMapper.Factory mapper; private final LocaleSerializerConfigurate locale;
@Inject @Inject
public ConfigLoader( public ConfigLoader(
@ForCarbon final Path dataDirectory, @ForCarbon final Path dataDirectory,
final Injector injector final LocaleSerializerConfigurate locale
) { ) {
this.dataDirectory = dataDirectory; this.dataDirectory = dataDirectory;
this.mapper = ObjectMapper.factoryBuilder() this.locale = locale;
.addDiscoverer(GuiceObjectMapperProvider.injectedObjectDiscoverer(injector))
.build();
} }
public ConfigurationLoader<?> configurationLoader(final Path file) { public ConfigurationLoader<?> configurationLoader(final Path file) {
@@ -43,8 +38,8 @@ public class ConfigLoader {
ConfigurateComponentSerializer.configurate(); ConfigurateComponentSerializer.configurate();
return opts.shouldCopyDefaults(true).serializers(serializerBuilder -> return opts.shouldCopyDefaults(true).serializers(serializerBuilder ->
serializerBuilder.registerAll(serializer.serializers()) serializerBuilder.registerAll(serializer.serializers())
.register(Locale.class, new LocaleSerializerConfigurate()) .register(Locale.class, this.locale)
); );
}) })
.path(file) .path(file)
@@ -62,7 +57,7 @@ public class ConfigLoader {
try { try {
final var node = loader.load(); final var node = loader.load();
final T config = node.get(clazz); final @Nullable T config = node.get(clazz);
if (!Files.exists(file)) { if (!Files.exists(file)) {
node.set(clazz, config); node.set(clazz, config);
@@ -12,22 +12,20 @@ import org.spongepowered.configurate.objectmapping.meta.Comment;
public class PrimaryConfig { public class PrimaryConfig {
@Comment("The default locale for plugin messages.") @Comment("The default locale for plugin messages.")
private Locale defaultLocale = Locale.US; private final Locale defaultLocale = Locale.US;
@Comment("The default channel that new players will be in when they join.")
private final Key defaultChannel = Key.key("carbon", "basic");
@Comment("The service that will be used to store and load player information.")
private final StorageType storageType = StorageType.JSON;
public Locale defaultLocale() { public Locale defaultLocale() {
return this.defaultLocale; return this.defaultLocale;
} }
@Comment("The default channel that new players will be in when they join.")
private Key defaultChannel = Key.key("carbon", "basic");
public Key defaultChannel() { public Key defaultChannel() {
return this.defaultChannel; return this.defaultChannel;
} }
@Comment("The service that will be used to store and load player information.")
private StorageType storageType = StorageType.JSON;
public StorageType storageType() { public StorageType storageType() {
return this.storageType; return this.storageType;
} }
@@ -1,12 +1,10 @@
package net.draycia.carbon.common.listeners; package net.draycia.carbon.common.listeners;
import cloud.commandframework.CommandManager;
import com.google.inject.Inject; import com.google.inject.Inject;
import net.draycia.carbon.api.CarbonChat; import net.draycia.carbon.api.CarbonChat;
import net.draycia.carbon.api.events.CarbonChatEvent; import net.draycia.carbon.api.events.CarbonChatEvent;
import net.draycia.carbon.api.users.CarbonPlayer; import net.draycia.carbon.api.users.CarbonPlayer;
import net.draycia.carbon.api.util.KeyedRenderer; import net.draycia.carbon.api.util.KeyedRenderer;
import net.draycia.carbon.common.command.Commander;
import net.draycia.carbon.common.messages.CarbonMessageService; import net.draycia.carbon.common.messages.CarbonMessageService;
import net.kyori.adventure.key.Key; import net.kyori.adventure.key.Key;
import org.checkerframework.checker.nullness.qual.NonNull; import org.checkerframework.checker.nullness.qual.NonNull;
@@ -23,13 +21,12 @@ public class MuteHandler {
private final KeyedRenderer renderer = private final KeyedRenderer renderer =
keyedRenderer(this.muteKey, (sender, recipient, message, originalMessage) -> keyedRenderer(this.muteKey, (sender, recipient, message, originalMessage) ->
this.messageService.muteSpyPrefix().append(message)); this.messageService.muteSpyPrefix(recipient).append(message));
@Inject @Inject
public MuteHandler( public MuteHandler(
final CarbonChat carbonChat, final CarbonChat carbonChat,
final CarbonMessageService messageService, final CarbonMessageService messageService
final CommandManager<Commander> commandManager
) { ) {
this.messageService = messageService; this.messageService = messageService;
@@ -1,17 +0,0 @@
package net.draycia.carbon.common.messages;
import com.google.inject.Singleton;
import com.proximyst.moonshine.message.IMessageParser;
import com.proximyst.moonshine.message.ParsingContext;
import net.kyori.adventure.audience.Audience;
import net.kyori.adventure.text.Component;
import net.kyori.adventure.text.minimessage.MiniMessage;
@Singleton
public class CarbonMessageParser implements IMessageParser<String, Component, Audience> {
public Component parse(final String message, final ParsingContext<Audience> parsingContext) {
return MiniMessage.get().parse(message, parsingContext.placeholders());
}
}
@@ -0,0 +1,36 @@
package net.draycia.carbon.common.messages;
import java.lang.reflect.Method;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import net.kyori.adventure.audience.Audience;
import net.kyori.adventure.text.Component;
import net.kyori.adventure.text.minimessage.MiniMessage;
import net.kyori.adventure.text.minimessage.Template;
import net.kyori.moonshine.message.IMessageRenderer;
import org.checkerframework.checker.nullness.qual.NonNull;
import org.checkerframework.framework.qual.DefaultQualifier;
@DefaultQualifier(NonNull.class)
public class CarbonMessageRenderer implements IMessageRenderer<Audience, String, Component, Component> {
@Override
public Component render(
final Audience receiver,
final String intermediateMessage,
final Map<String, ? extends Component> resolvedPlaceholders,
final Method method,
final Type owner
) {
final List<Template> templates = new ArrayList<>();
for (final var entry : resolvedPlaceholders.entrySet()) {
templates.add(Template.of(entry.getKey(), entry.getValue()));
}
return MiniMessage.get().parse(intermediateMessage, templates);
}
}
@@ -1,14 +1,17 @@
package net.draycia.carbon.common.messages; package net.draycia.carbon.common.messages;
import com.proximyst.moonshine.message.IMessageSender;
import net.kyori.adventure.audience.Audience; import net.kyori.adventure.audience.Audience;
import net.kyori.adventure.text.Component; import net.kyori.adventure.text.Component;
import net.kyori.moonshine.message.IMessageSender;
import org.checkerframework.checker.nullness.qual.NonNull;
import org.checkerframework.framework.qual.DefaultQualifier;
@DefaultQualifier(NonNull.class)
public class CarbonMessageSender implements IMessageSender<Audience, Component> { public class CarbonMessageSender implements IMessageSender<Audience, Component> {
@Override @Override
public void sendMessage(final Audience receiver, final Component message) { public void send(final Audience receiver, final Component renderedMessage) {
receiver.sendMessage(message); receiver.sendMessage(renderedMessage);
} }
} }
@@ -1,32 +1,31 @@
package net.draycia.carbon.common.messages; package net.draycia.carbon.common.messages;
import com.proximyst.moonshine.annotation.Message;
import com.proximyst.moonshine.annotation.Placeholder;
import com.proximyst.moonshine.annotation.Receiver;
import java.util.UUID; import java.util.UUID;
import net.kyori.adventure.audience.Audience; import net.kyori.adventure.audience.Audience;
import net.kyori.adventure.text.Component; import net.kyori.adventure.text.Component;
import net.kyori.moonshine.annotation.Message;
import net.kyori.moonshine.annotation.Placeholder;
public interface CarbonMessageService { public interface CarbonMessageService {
@Message("example.command.hello") @Message("example.command.hello")
void exampleCommandFeedback( void exampleCommandFeedback(
@Receiver final Audience audience, final Audience audience,
@Placeholder final Component plugin @Placeholder final Component plugin
); );
@Message("unsupported.legacy") @Message("unsupported.legacy")
void unsupportedLegacyChar( void unsupportedLegacyChar(
@Receiver final Audience audience, final Audience audience,
@Placeholder final String message @Placeholder final String message
); );
@Message("test.phrase") @Message("test.phrase")
void localeTestMessage(@Receiver final Audience audience); void localeTestMessage(final Audience audience);
@Message("channel.format.basic") @Message("channel.format.basic")
Component basicChatFormat( Component basicChatFormat(
@Receiver final Audience audience, final Audience audience,
@Placeholder UUID uuid, @Placeholder UUID uuid,
@Placeholder Component displayname, @Placeholder Component displayname,
@Placeholder String username, @Placeholder String username,
@@ -34,9 +33,6 @@ public interface CarbonMessageService {
); );
@Message("mute.spy.prefix") @Message("mute.spy.prefix")
Component muteSpyPrefix(); Component muteSpyPrefix(final Audience audience);
@Message("placeholders.plugin")
Component pluginName();
} }
@@ -2,7 +2,6 @@ package net.draycia.carbon.common.messages;
import com.google.inject.Inject; import com.google.inject.Inject;
import com.google.inject.Singleton; import com.google.inject.Singleton;
import com.proximyst.moonshine.message.IMessageSource;
import java.io.IOException; import java.io.IOException;
import java.io.InputStream; import java.io.InputStream;
import java.io.InputStreamReader; import java.io.InputStreamReader;
@@ -28,6 +27,7 @@ import net.draycia.carbon.common.ForCarbon;
import net.draycia.carbon.common.config.PrimaryConfig; import net.draycia.carbon.common.config.PrimaryConfig;
import net.kyori.adventure.audience.Audience; import net.kyori.adventure.audience.Audience;
import net.kyori.adventure.translation.Translator; import net.kyori.adventure.translation.Translator;
import net.kyori.moonshine.message.IMessageSource;
import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.Logger;
import org.checkerframework.checker.nullness.qual.NonNull; import org.checkerframework.checker.nullness.qual.NonNull;
import org.checkerframework.checker.nullness.qual.Nullable; import org.checkerframework.checker.nullness.qual.Nullable;
@@ -35,7 +35,7 @@ import org.checkerframework.framework.qual.DefaultQualifier;
@Singleton @Singleton
@DefaultQualifier(NonNull.class) @DefaultQualifier(NonNull.class)
public final class CarbonMessageSource implements IMessageSource<String, Audience> { public final class CarbonMessageSource implements IMessageSource<Audience, String> {
private final Locale defaultLocale; private final Locale defaultLocale;
private final Map<Locale, Properties> locales = new HashMap<>(); private final Map<Locale, Properties> locales = new HashMap<>();
@@ -109,11 +109,11 @@ public final class CarbonMessageSource implements IMessageSource<String, Audienc
} }
@Override @Override
public String message(final String key, final Audience receiver) { public String messageOf(final Audience receiver, final String messageKey) {
if (receiver instanceof CarbonPlayer player) { if (receiver instanceof CarbonPlayer player) {
return this.forPlayer(key, player); return this.forPlayer(messageKey, player);
} else { } else {
return this.forAudience(key, receiver); return this.forAudience(messageKey, receiver);
} }
} }
@@ -1,25 +1,31 @@
package net.draycia.carbon.common.messages; package net.draycia.carbon.common.messages;
import com.google.common.collect.Multimap; import java.lang.reflect.Method;
import com.proximyst.moonshine.component.placeholder.IPlaceholderResolver; import java.lang.reflect.Type;
import com.proximyst.moonshine.component.placeholder.PlaceholderContext; import java.util.Map;
import com.proximyst.moonshine.component.placeholder.ResolveResult;
import net.kyori.adventure.text.Component; import net.kyori.adventure.text.Component;
import net.kyori.adventure.text.minimessage.MiniMessage; import net.kyori.moonshine.placeholder.ConclusionValue;
import net.kyori.moonshine.placeholder.ContinuanceValue;
import net.kyori.moonshine.placeholder.IPlaceholderResolver;
import net.kyori.moonshine.util.Either;
import org.checkerframework.checker.nullness.qual.NonNull; import org.checkerframework.checker.nullness.qual.NonNull;
import org.checkerframework.checker.nullness.qual.Nullable; import org.checkerframework.checker.nullness.qual.Nullable;
import org.checkerframework.framework.qual.DefaultQualifier; import org.checkerframework.framework.qual.DefaultQualifier;
@DefaultQualifier(NonNull.class) @DefaultQualifier(NonNull.class)
public class ComponentPlaceholderResolver<R> implements IPlaceholderResolver<R, Component> { public class ComponentPlaceholderResolver<R> implements IPlaceholderResolver<R, Component, Component> {
public ResolveResult resolve( @Override
public @Nullable Map<String, Either<ConclusionValue<? extends Component>, ContinuanceValue<?>>>
resolve(
final String placeholderName, final String placeholderName,
final Component value, final Component value,
final PlaceholderContext<R> ctx, final R receiver,
final Multimap<String, @Nullable Object> flags final Type owner,
final Method method,
final @Nullable Object[] parameters
) { ) {
return ResolveResult.ok(placeholderName, MiniMessage.get().serialize(value)); return Map.of(placeholderName, Either.left(ConclusionValue.conclusionValue(value)));
} }
} }
@@ -0,0 +1,55 @@
//
// ban - A punishment suite for Velocity.
// Copyright (C) 2021 Mariell Hoversholm
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero 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 Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.
//
// Modified to better fit in Carbon
//
package net.draycia.carbon.common.messages;
import java.lang.reflect.Method;
import java.lang.reflect.Type;
import javax.inject.Singleton;
import net.kyori.adventure.audience.Audience;
import net.kyori.moonshine.receiver.IReceiverLocator;
import net.kyori.moonshine.receiver.IReceiverLocatorResolver;
import org.checkerframework.checker.nullness.qual.NonNull;
import org.checkerframework.checker.nullness.qual.Nullable;
import org.checkerframework.framework.qual.DefaultQualifier;
@Singleton
@DefaultQualifier(NonNull.class)
public final class ReceiverResolver implements IReceiverLocatorResolver<Audience> {
@Override
public IReceiverLocator<Audience> resolve(final Method method, final Type proxy) {
return new Resolver();
}
private static final class Resolver implements IReceiverLocator<Audience> {
@Override
public Audience locate(final Method method, final Object proxy, final @Nullable Object[] parameters) {
for (final Object parameter : parameters) {
if (parameter instanceof Audience audience) {
return audience;
}
}
return Audience.empty();
}
}
}
@@ -1,30 +0,0 @@
//
// ban - A punishment suite for Velocity.
// Copyright (C) 2021 Mariell Hoversholm
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero 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 Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.
//
package net.draycia.carbon.common.messages;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface ServerReceiver {
String permission() default "";
}
@@ -1,81 +0,0 @@
//
// ban - A punishment suite for Velocity.
// Copyright (C) 2021 Mariell Hoversholm
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero 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 Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.
//
// Modified to better fit in Carbon
//
package net.draycia.carbon.common.messages;
import com.google.common.collect.Streams;
import com.proximyst.moonshine.component.receiver.IReceiver;
import com.proximyst.moonshine.component.receiver.IReceiverResolver;
import com.proximyst.moonshine.component.receiver.ReceiverContext;
import java.lang.reflect.Method;
import java.util.Optional;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import javax.inject.Inject;
import javax.inject.Singleton;
import net.draycia.carbon.api.CarbonServer;
import net.kyori.adventure.audience.Audience;
import org.checkerframework.checker.nullness.qual.NonNull;
import org.checkerframework.checker.nullness.qual.Nullable;
@Singleton
public final class ServerReceiverResolver implements IReceiverResolver<Audience> {
private final @NonNull CarbonServer carbonServer;
@Inject
public ServerReceiverResolver(final CarbonServer carbonServer) {
this.carbonServer = carbonServer;
}
@Override
public Optional<IReceiver<Audience>> resolve(final Method method) {
final ServerReceiver annotation = method.getAnnotation(ServerReceiver.class);
if (annotation == null) {
return Optional.empty();
}
return Optional.of(new Resolver(this.carbonServer, annotation.permission()));
}
private static final class Resolver implements IReceiver<Audience> {
private final @NonNull CarbonServer carbonServer;
private final @Nullable String permission;
private Resolver(final @NonNull CarbonServer carbonServer,
final @Nullable String permission) {
this.carbonServer = carbonServer;
this.permission = permission;
}
@Override
public Audience find(final ReceiverContext ctx) {
if (this.permission == null) {
return this.carbonServer;
}
return Audience.audience(Stream.concat(Stream.of(this.carbonServer.console()),
Streams.stream(this.carbonServer.players())
.filter(player -> player.hasPermission(this.permission)))
.collect(Collectors.toList()));
}
}
}
@@ -0,0 +1,28 @@
package net.draycia.carbon.common.messages;
import java.lang.reflect.Method;
import java.lang.reflect.Type;
import java.util.Map;
import net.kyori.adventure.text.Component;
import net.kyori.moonshine.placeholder.ConclusionValue;
import net.kyori.moonshine.placeholder.ContinuanceValue;
import net.kyori.moonshine.placeholder.IPlaceholderResolver;
import net.kyori.moonshine.util.Either;
import org.checkerframework.checker.nullness.qual.Nullable;
public class StringPlaceholderResolver<R> implements IPlaceholderResolver<R, String, Component> {
@Override
public @Nullable Map<String, Either<ConclusionValue<? extends Component>, ContinuanceValue<?>>>
resolve(
final String placeholderName,
final String value,
final R receiver,
final Type owner,
final Method method,
final @Nullable Object[] parameters
) {
return Map.of(placeholderName, Either.left(ConclusionValue.conclusionValue(Component.text(value))));
}
}
@@ -1,21 +1,32 @@
package net.draycia.carbon.common.messages; package net.draycia.carbon.common.messages;
import com.google.common.collect.Multimap; import java.lang.reflect.Method;
import com.proximyst.moonshine.component.placeholder.IPlaceholderResolver; import java.lang.reflect.Type;
import com.proximyst.moonshine.component.placeholder.PlaceholderContext; import java.util.Map;
import com.proximyst.moonshine.component.placeholder.ResolveResult;
import java.util.UUID; import java.util.UUID;
import net.kyori.adventure.text.Component;
import net.kyori.moonshine.placeholder.ConclusionValue;
import net.kyori.moonshine.placeholder.ContinuanceValue;
import net.kyori.moonshine.placeholder.IPlaceholderResolver;
import net.kyori.moonshine.util.Either;
import org.checkerframework.checker.nullness.qual.NonNull;
import org.checkerframework.checker.nullness.qual.Nullable; import org.checkerframework.checker.nullness.qual.Nullable;
import org.checkerframework.framework.qual.DefaultQualifier;
public class UUIDPlaceholderResolver<R> implements IPlaceholderResolver<R, UUID> { @DefaultQualifier(NonNull.class)
public class UUIDPlaceholderResolver<R> implements IPlaceholderResolver<R, UUID, Component> {
public ResolveResult resolve( @Override
public @Nullable Map<String, Either<ConclusionValue<? extends Component>, ContinuanceValue<?>>>
resolve(
final String placeholderName, final String placeholderName,
final UUID value, final UUID value,
final PlaceholderContext<R> ctx, final R receiver,
final Multimap<String, @Nullable Object> flags final Type owner,
final Method method,
final @Nullable Object[] parameters
) { ) {
return ResolveResult.ok(placeholderName, value.toString()); return Map.of(placeholderName, Either.left(ConclusionValue.conclusionValue(Component.text(value.toString()))));
} }
} }
@@ -13,7 +13,10 @@ import net.draycia.carbon.api.channels.ChatChannel;
import net.draycia.carbon.api.users.CarbonPlayer; import net.draycia.carbon.api.users.CarbonPlayer;
import net.draycia.carbon.common.users.CarbonPlayerCommon; import net.draycia.carbon.common.users.CarbonPlayerCommon;
import net.kyori.adventure.text.Component; import net.kyori.adventure.text.Component;
import org.checkerframework.checker.nullness.qual.NonNull;
import org.checkerframework.framework.qual.DefaultQualifier;
@DefaultQualifier(NonNull.class)
public class CarbonPlayerSerializerGson implements JsonSerializer<CarbonPlayerCommon>, JsonDeserializer<CarbonPlayer> { public class CarbonPlayerSerializerGson implements JsonSerializer<CarbonPlayerCommon>, JsonDeserializer<CarbonPlayer> {
@Override @Override
@@ -10,6 +10,7 @@ import net.draycia.carbon.api.channels.ChatChannel;
import org.checkerframework.checker.nullness.qual.NonNull; import org.checkerframework.checker.nullness.qual.NonNull;
import org.checkerframework.checker.nullness.qual.Nullable; import org.checkerframework.checker.nullness.qual.Nullable;
import org.checkerframework.framework.qual.DefaultQualifier; import org.checkerframework.framework.qual.DefaultQualifier;
import org.intellij.lang.annotations.Subst;
import static net.kyori.adventure.key.Key.key; import static net.kyori.adventure.key.Key.key;
@@ -29,9 +30,8 @@ public class ChatChannelSerializerGson extends TypeAdapter<ChatChannel> {
} }
@Override @Override
@SuppressWarnings("PatternValidation") // the input is variable
public @Nullable ChatChannel read(final JsonReader in) throws IOException { public @Nullable ChatChannel read(final JsonReader in) throws IOException {
final @Nullable String channelName = in.nextString(); @Subst("namespace:value") final @Nullable String channelName = in.nextString();
if (channelName != null) { if (channelName != null) {
return this.registry.get(key(channelName)); return this.registry.get(key(channelName));
@@ -1,29 +1,48 @@
package net.draycia.carbon.common.serialisation.gson; package net.draycia.carbon.common.serialisation.gson;
import com.google.inject.Inject;
import java.lang.reflect.Type; import java.lang.reflect.Type;
import java.util.Locale; import java.util.Locale;
import net.kyori.adventure.translation.Translator; import net.kyori.adventure.translation.Translator;
import org.apache.logging.log4j.Logger;
import org.checkerframework.checker.nullness.qual.NonNull;
import org.checkerframework.checker.nullness.qual.Nullable; import org.checkerframework.checker.nullness.qual.Nullable;
import org.checkerframework.framework.qual.DefaultQualifier;
import org.spongepowered.configurate.ConfigurationNode; import org.spongepowered.configurate.ConfigurationNode;
import org.spongepowered.configurate.serialize.SerializationException; import org.spongepowered.configurate.serialize.SerializationException;
import org.spongepowered.configurate.serialize.TypeSerializer; import org.spongepowered.configurate.serialize.TypeSerializer;
import static java.util.Objects.requireNonNull;
@DefaultQualifier(NonNull.class)
public class LocaleSerializerConfigurate implements TypeSerializer<Locale> { public class LocaleSerializerConfigurate implements TypeSerializer<Locale> {
private final Logger logger;
@Inject
public LocaleSerializerConfigurate(final Logger logger) {
this.logger = logger;
}
@Override @Override
public Locale deserialize(final Type type, final ConfigurationNode node) throws SerializationException { public Locale deserialize(final Type type, final ConfigurationNode node) {
final String value = node.getString(); final @Nullable String value = node.getString();
if (value == null) { if (value == null) {
throw new SerializationException("value cannot be null!"); this.logger.warn("value null for locale! defaulting to en_US");
return Locale.ENGLISH;
} }
return Translator.parseLocale(value); return requireNonNull(Translator.parseLocale(value), "value locale cannot be null!");
} }
@Override @Override
public void serialize(final Type type, @Nullable final Locale obj, final ConfigurationNode node) throws SerializationException { public void serialize(final Type type, @Nullable final Locale obj, final ConfigurationNode node) throws SerializationException {
node.set(obj.toLanguageTag()); if (obj == null) {
node.set(null);
} else {
node.set(obj.toLanguageTag());
}
} }
} }
@@ -9,12 +9,11 @@ import net.kyori.adventure.audience.Audience;
import net.kyori.adventure.audience.ForwardingAudience; import net.kyori.adventure.audience.ForwardingAudience;
import net.kyori.adventure.identity.Identity; import net.kyori.adventure.identity.Identity;
import net.kyori.adventure.text.Component; import net.kyori.adventure.text.Component;
import org.checkerframework.checker.nullness.qual.MonotonicNonNull;
import org.checkerframework.checker.nullness.qual.NonNull; import org.checkerframework.checker.nullness.qual.NonNull;
import org.checkerframework.checker.nullness.qual.Nullable; import org.checkerframework.checker.nullness.qual.Nullable;
import org.checkerframework.framework.qual.DefaultQualifier; import org.checkerframework.framework.qual.DefaultQualifier;
import org.jetbrains.annotations.NotNull;
import static java.util.Objects.requireNonNullElseGet;
import static net.kyori.adventure.text.Component.text;
@DefaultQualifier(NonNull.class) @DefaultQualifier(NonNull.class)
public class CarbonPlayerCommon implements CarbonPlayer, ForwardingAudience.Single { public class CarbonPlayerCommon implements CarbonPlayer, ForwardingAudience.Single {
@@ -24,8 +23,8 @@ public class CarbonPlayerCommon implements CarbonPlayer, ForwardingAudience.Sing
protected boolean muted = false; protected boolean muted = false;
protected @Nullable ChatChannel selectedChannel; protected @Nullable ChatChannel selectedChannel;
protected boolean spying = false; protected boolean spying = false;
protected String username; protected @MonotonicNonNull String username;
protected UUID uuid; protected @MonotonicNonNull UUID uuid;
public CarbonPlayerCommon( public CarbonPlayerCommon(
final @Nullable Component displayName, final @Nullable Component displayName,
@@ -44,7 +43,7 @@ public class CarbonPlayerCommon implements CarbonPlayer, ForwardingAudience.Sing
} }
@Override @Override
public @NonNull Audience audience() { public @NotNull Audience audience() {
return Audience.empty(); return Audience.empty();
} }
@@ -58,13 +57,13 @@ public class CarbonPlayerCommon implements CarbonPlayer, ForwardingAudience.Sing
} }
@Override @Override
public Component displayName() { public @Nullable Component displayName() {
return requireNonNullElseGet(this.displayName, () -> text(this.username)); return this.displayName;
} }
@Override @Override
public void displayName(final @Nullable Component displayName) { public void displayName(final @Nullable Component displayName) {
this.displayName = requireNonNullElseGet(displayName, () -> text(this.username)); this.displayName = displayName;
} }
@Override @Override
@@ -9,9 +9,11 @@ import java.nio.file.Files;
import java.nio.file.Path; import java.nio.file.Path;
import java.nio.file.StandardOpenOption; import java.nio.file.StandardOpenOption;
import java.util.Map; import java.util.Map;
import java.util.Objects;
import java.util.UUID; import java.util.UUID;
import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentHashMap;
import net.draycia.carbon.api.CarbonChat;
import net.draycia.carbon.api.channels.ChatChannel; import net.draycia.carbon.api.channels.ChatChannel;
import net.draycia.carbon.api.users.CarbonPlayer; import net.draycia.carbon.api.users.CarbonPlayer;
import net.draycia.carbon.api.users.ComponentPlayerResult; import net.draycia.carbon.api.users.ComponentPlayerResult;
@@ -32,11 +34,10 @@ import static net.kyori.adventure.text.Component.text;
@DefaultQualifier(NonNull.class) @DefaultQualifier(NonNull.class)
public class JSONUserManager implements UserManager { public class JSONUserManager implements UserManager {
private final Path dataDirectory;
private final Injector injector;
private final Logger logger; private final Logger logger;
private final Gson serializer; private final Gson serializer;
private final Path userDirectory; private final Path userDirectory;
private final CarbonChat carbonChat;
private final Map<UUID, CarbonPlayerCommon> userCache = new ConcurrentHashMap<>(); private final Map<UUID, CarbonPlayerCommon> userCache = new ConcurrentHashMap<>();
@@ -44,20 +45,20 @@ public class JSONUserManager implements UserManager {
public JSONUserManager( public JSONUserManager(
final @ForCarbon Path dataDirectory, final @ForCarbon Path dataDirectory,
final Injector injector, final Injector injector,
final Logger logger final Logger logger,
) throws IOException { final CarbonChat carbonChat
this.dataDirectory = dataDirectory; ) throws IOException {
this.injector = injector;
this.logger = logger; this.logger = logger;
this.userDirectory = this.dataDirectory.resolve("users"); this.userDirectory = dataDirectory.resolve("users");
this.carbonChat = carbonChat;
Files.createDirectories(this.userDirectory); Files.createDirectories(this.userDirectory);
this.serializer = GsonComponentSerializer.gson().populator() this.serializer = GsonComponentSerializer.gson().populator()
.apply(new GsonBuilder()) .apply(new GsonBuilder())
.registerTypeAdapter(CarbonPlayerCommon.class, this.injector.getInstance(CarbonPlayerSerializerGson.class)) .registerTypeAdapter(CarbonPlayerCommon.class, injector.getInstance(CarbonPlayerSerializerGson.class))
.registerTypeAdapter(ChatChannel.class, this.injector.getInstance(ChatChannelSerializerGson.class)) .registerTypeAdapter(ChatChannel.class, injector.getInstance(ChatChannelSerializerGson.class))
.registerTypeAdapter(UUID.class, this.injector.getInstance(UUIDSerializerGson.class)) .registerTypeAdapter(UUID.class, injector.getInstance(UUIDSerializerGson.class))
.create(); .create();
} }
@@ -86,7 +87,15 @@ public class JSONUserManager implements UserManager {
} }
} }
return new ComponentPlayerResult(null, text("No save file found for player.")); final String name = Objects.requireNonNull(
this.carbonChat.server().resolveName(uuid).join());
final CarbonPlayerCommon player = new CarbonPlayerCommon(null,
null, name, uuid);
this.userCache.put(uuid, player);
return new ComponentPlayerResult(player, empty());
}); });
} }
@@ -1,7 +1,6 @@
channel.format.basic=<displayname>\: <message> channel.format.basic=<displayname>\: <message>
example.command.hello=<green>Hello from </green><plugin><green>!</green> example.command.hello=<green>Hello from </green><plugin><green>!</green>
placeholders.plugin=<#1DA3A6><bold>Carbon</bold></#1DA3A6> mute.spy.prefix=<red><hover:show_text:<red>Muted</red>M</hover></red>
spy.mute.prefix=<red><hover:show_text:<red>Muted</red>M</hover></red>
test.phrase=English: Has anyone really been far even as decided to use even go want to do look more like? test.phrase=English: Has anyone really been far even as decided to use even go want to do look more like?
unsupported.legacy=<red>Legacy color codes have been detected in a message. This is not supported behavior. Message: '<message>' unsupported.legacy=<red>Legacy color codes have been detected in a message. This is not supported behavior. Message: '<message>'
@@ -1,5 +1,4 @@
channel.format.basic=\ue238<displayname>\: <message> channel.format.basic=\ue238<displayname>\: <message>
example.command.hello=<green>Hello from </green><plugin><green>\!</green> example.command.hello=<green>Hello from </green><plugin><green>\!</green>
placeholders.plugin=<\#1DA3A6><bold>Carbon</bold></\#1DA3A6>
test.phrase=bokmål: I noen tilfeller skulle man gjerne sett for seg at kongen bryr seg om sitt folk. Etter festen i '97, har dette blitt klart at er helt rett: han brakte med seg flere soldater og sammen giljotinerte de alle deltakere under atten år. test.phrase=bokmål: I noen tilfeller skulle man gjerne sett for seg at kongen bryr seg om sitt folk. Etter festen i '97, har dette blitt klart at er helt rett: han brakte med seg flere soldater og sammen giljotinerte de alle deltakere under atten år.
unsupported.legacy=<red>Legacy color codes have been detected in a message. This is not supported behavior. Message\: '<message>' unsupported.legacy=<red>Legacy color codes have been detected in a message. This is not supported behavior. Message\: '<message>'
@@ -1,5 +1,4 @@
channel.format.basic=\ue238<displayname>\: <message> channel.format.basic=\ue238<displayname>\: <message>
example.command.hello=<green>Hello from </green><plugin><green>\!</green> example.command.hello=<green>Hello from </green><plugin><green>\!</green>
placeholders.plugin=<\#1DA3A6><bold>Carbon</bold></\#1DA3A6>
test.phrase=Nynorsk: Alle menneske er fødde til fridom og med same menneskeverd og menneskerettar. Dei har fått fornuft og samvit og skal leve med kvarandre som brør. test.phrase=Nynorsk: Alle menneske er fødde til fridom og med same menneskeverd og menneskerettar. Dei har fått fornuft og samvit og skal leve med kvarandre som brør.
unsupported.legacy=<red>Legacy color codes have been detected in a message. This is not supported behavior. Message\: '<message>' unsupported.legacy=<red>Legacy color codes have been detected in a message. This is not supported behavior. Message\: '<message>'
-1
View File
@@ -1,6 +1,5 @@
# Project Properties # Project Properties
projectVersion=2.0.0-SNAPSHOT projectVersion=2.0.0-SNAPSHOT
# Gradle Properties # Gradle Properties
org.gradle.configureondemand=true org.gradle.configureondemand=true
org.gradle.caching=true org.gradle.caching=true
+13 -6
View File
@@ -27,8 +27,8 @@ versions:
paperLib: 1.0.6 paperLib: 1.0.6
kyoriEventApi: 5.0.0-SNAPSHOT kyoriEventApi: 5.0.0-SNAPSHOT
kyoriRegistry: 1.0.0-SNAPSHOT kyoriRegistry: 1.0.0-SNAPSHOT
kyoriMoonshine: 2.0.0-SNAPSHOT
log4j: 2.11.2 log4j: 2.11.2
moonshine: 0.2.4-SNAPSHOT
guice: 5.0.1 guice: 5.0.1
velocityApi: 3.0.0-SNAPSHOT velocityApi: 3.0.0-SNAPSHOT
@@ -66,11 +66,6 @@ dependencies:
group: org.apache.logging.log4j group: org.apache.logging.log4j
name: log4j-api name: log4j-api
moonshine:
group: com.proximyst.moonshine
name: core
version: { ref: moonshine }
kyoriEventApi: kyoriEventApi:
group: net.kyori group: net.kyori
name: event-api name: event-api
@@ -79,6 +74,18 @@ dependencies:
group: net.kyori group: net.kyori
name: registry name: registry
version: { ref: kyoriRegistry } version: { ref: kyoriRegistry }
kyoriMoonshine:
group: net.kyori.moonshine
name: moonshine
version: { ref: kyoriMoonshine }
kyoriMoonshineCore:
group: net.kyori.moonshine
name: moonshine-core
version: { ref: kyoriMoonshine }
kyoriMoonshineStandard:
group: net.kyori.moonshine
name: moonshine-standard
version: { ref: kyoriMoonshine }
cloudCore: cloudCore:
group: cloud.commandframework group: cloud.commandframework
+3 -4
View File
@@ -3,6 +3,9 @@ enableFeaturePreview("TYPESAFE_PROJECT_ACCESSORS")
dependencyResolutionManagement { dependencyResolutionManagement {
repositories { repositories {
mavenLocal {
content { includeGroup("net.kyori.moonshine") }
}
mavenCentral() mavenCentral()
maven("https://oss.sonatype.org/content/repositories/snapshots/") maven("https://oss.sonatype.org/content/repositories/snapshots/")
// Paper API // Paper API
@@ -19,10 +22,6 @@ dependencyResolutionManagement {
metadataSources { artifact() } metadataSources { artifact() }
content { includeModule("com.velocitypowered", "velocity-proxy") } content { includeModule("com.velocitypowered", "velocity-proxy") }
} }
// Moonshine
maven("https://nexus.proximyst.com/repository/maven-public/") {
content { includeGroup("com.proximyst.moonshine") }
}
// cloud snapshots repo // cloud snapshots repo
//maven("https://repo.incendo.org/content/repositories/snapshots") { //maven("https://repo.incendo.org/content/repositories/snapshots") {
// content { includeGroup("cloud.commandframework") } // content { includeGroup("cloud.commandframework") }
+1 -1
View File
@@ -1,6 +1,6 @@
import org.spongepowered.gradle.plugin.config.PluginLoaders import org.spongepowered.gradle.plugin.config.PluginLoaders
import org.spongepowered.plugin.metadata.PluginDependency import org.spongepowered.plugin.metadata.PluginDependency
import java.util.Locale import java.util.*
plugins { plugins {
id("carbon.shadow-platform") id("carbon.shadow-platform")
@@ -39,12 +39,12 @@ public final class CarbonChatSponge extends CarbonChatCommon {
private final CarbonMessageService messageService; private final CarbonMessageService messageService;
private final CarbonServerSponge carbonServerSponge; private final CarbonServerSponge carbonServerSponge;
private final ChannelRegistry channelRegistry; private final ChannelRegistry channelRegistry;
private final Game game;
private final Injector injector; private final Injector injector;
private final Logger logger; private final Logger logger;
private final Path dataDirectory; private final Path dataDirectory;
private final PluginContainer pluginContainer; private final PluginContainer pluginContainer;
private final UserManager userManager; private final UserManager userManager;
private final CarbonEventHandler eventHandler = new CarbonEventHandler();
@Inject @Inject
public CarbonChatSponge( public CarbonChatSponge(
@@ -57,7 +57,6 @@ public final class CarbonChatSponge extends CarbonChatCommon {
) { ) {
CarbonChatProvider.register(this); CarbonChatProvider.register(this);
this.game = game;
this.pluginContainer = pluginContainer; this.pluginContainer = pluginContainer;
this.injector = injector.createChildInjector(new CarbonChatSpongeModule( this.injector = injector.createChildInjector(new CarbonChatSpongeModule(
@@ -71,7 +70,7 @@ public final class CarbonChatSponge extends CarbonChatCommon {
this.dataDirectory = dataDirectory; this.dataDirectory = dataDirectory;
for (final Class<?> clazz : LISTENER_CLASSES) { for (final Class<?> clazz : LISTENER_CLASSES) {
this.game.eventManager().registerListeners(this.pluginContainer, this.injector.getInstance(clazz)); game.eventManager().registerListeners(this.pluginContainer, this.injector.getInstance(clazz));
} }
//metricsFactory.make(BSTATS_PLUGIN_ID); //metricsFactory.make(BSTATS_PLUGIN_ID);
@@ -132,8 +131,6 @@ public final class CarbonChatSponge extends CarbonChatCommon {
return this.messageService; return this.messageService;
} }
private final CarbonEventHandler eventHandler = new CarbonEventHandler();
@Override @Override
public final @NonNull CarbonEventHandler eventHandler() { public final @NonNull CarbonEventHandler eventHandler() {
return this.eventHandler; return this.eventHandler;
@@ -16,6 +16,7 @@ import net.kyori.adventure.text.Component;
import org.checkerframework.checker.nullness.qual.NonNull; import org.checkerframework.checker.nullness.qual.NonNull;
import org.checkerframework.checker.nullness.qual.Nullable; import org.checkerframework.checker.nullness.qual.Nullable;
import org.checkerframework.framework.qual.DefaultQualifier; import org.checkerframework.framework.qual.DefaultQualifier;
import org.jetbrains.annotations.NotNull;
import org.spongepowered.api.Game; import org.spongepowered.api.Game;
import org.spongepowered.api.Sponge; import org.spongepowered.api.Sponge;
import org.spongepowered.api.entity.living.player.server.ServerPlayer; import org.spongepowered.api.entity.living.player.server.ServerPlayer;
@@ -36,7 +37,7 @@ public final class CarbonServerSponge implements CarbonServer, ForwardingAudienc
} }
@Override @Override
public Audience audience() { public @NotNull Audience audience() {
return this.game.server(); return this.game.server();
} }
@@ -114,7 +115,7 @@ public final class CarbonServerSponge implements CarbonServer, ForwardingAudienc
@Override @Override
public CompletableFuture<@Nullable String> resolveName(final UUID uuid) { public CompletableFuture<@Nullable String> resolveName(final UUID uuid) {
return CompletableFuture.supplyAsync(() -> return CompletableFuture.supplyAsync(() ->
Sponge.server().gameProfileManager().basicProfile(uuid).join().name().get() Sponge.server().gameProfileManager().basicProfile(uuid).join().name().orElse(null)
); );
} }
@@ -4,31 +4,23 @@ import net.draycia.carbon.common.command.Commander;
import net.kyori.adventure.audience.Audience; import net.kyori.adventure.audience.Audience;
import net.kyori.adventure.audience.ForwardingAudience; import net.kyori.adventure.audience.ForwardingAudience;
import org.checkerframework.checker.nullness.qual.NonNull; import org.checkerframework.checker.nullness.qual.NonNull;
import org.checkerframework.framework.qual.DefaultQualifier;
import org.jetbrains.annotations.NotNull;
import org.spongepowered.api.command.CommandCause; import org.spongepowered.api.command.CommandCause;
@DefaultQualifier(NonNull.class)
public interface SpongeCommander extends Commander, ForwardingAudience.Single { public interface SpongeCommander extends Commander, ForwardingAudience.Single {
@NonNull CommandCause commandCause(); static SpongeCommander from(final CommandCause commandCause) {
static @NonNull SpongeCommander from(final @NonNull CommandCause commandCause) {
return new SpongeCommanderImpl(commandCause); return new SpongeCommanderImpl(commandCause);
} }
final class SpongeCommanderImpl implements SpongeCommander { @NonNull CommandCause commandCause();
private final CommandCause commandCause; record SpongeCommanderImpl(CommandCause commandCause) implements SpongeCommander {
private SpongeCommanderImpl(final @NonNull CommandCause commandCause) {
this.commandCause = commandCause;
}
@Override @Override
public @NonNull CommandCause commandCause() { public @NotNull Audience audience() {
return this.commandCause;
}
@Override
public @NonNull Audience audience() {
return this.commandCause.audience(); return this.commandCause.audience();
} }
@@ -5,24 +5,27 @@ import net.draycia.carbon.api.users.CarbonPlayer;
import net.draycia.carbon.common.command.PlayerCommander; import net.draycia.carbon.common.command.PlayerCommander;
import net.kyori.adventure.audience.Audience; import net.kyori.adventure.audience.Audience;
import org.checkerframework.checker.nullness.qual.NonNull; import org.checkerframework.checker.nullness.qual.NonNull;
import org.checkerframework.framework.qual.DefaultQualifier;
import org.jetbrains.annotations.NotNull;
import org.spongepowered.api.command.CommandCause; import org.spongepowered.api.command.CommandCause;
import org.spongepowered.api.entity.living.player.server.ServerPlayer; import org.spongepowered.api.entity.living.player.server.ServerPlayer;
import static java.util.Objects.requireNonNull; import static java.util.Objects.requireNonNull;
@DefaultQualifier(NonNull.class)
public record SpongePlayerCommander( public record SpongePlayerCommander(
@NonNull CarbonChat carbon, CarbonChat carbon,
@NonNull ServerPlayer player, ServerPlayer player,
@NonNull CommandCause commandCause CommandCause commandCause
) implements PlayerCommander, SpongeCommander { ) implements PlayerCommander, SpongeCommander {
@Override @Override
public @NonNull CarbonPlayer carbonPlayer() { public CarbonPlayer carbonPlayer() {
return requireNonNull(this.carbon.server().player(this.player.uniqueId()).join().player(), "No CarbonPlayer for logged in Player!"); return requireNonNull(this.carbon.server().player(this.player.uniqueId()).join().player(), "No CarbonPlayer for logged in Player!");
} }
@Override @Override
public @NonNull Audience audience() { public @NotNull Audience audience() {
return this.commandCause.audience(); return this.commandCause.audience();
} }
@@ -12,6 +12,7 @@ import net.draycia.carbon.sponge.CarbonChatSponge;
import net.kyori.adventure.audience.Audience; import net.kyori.adventure.audience.Audience;
import net.kyori.adventure.text.Component; import net.kyori.adventure.text.Component;
import org.checkerframework.checker.nullness.qual.NonNull; import org.checkerframework.checker.nullness.qual.NonNull;
import org.checkerframework.framework.qual.DefaultQualifier;
import org.spongepowered.api.entity.living.player.Player; import org.spongepowered.api.entity.living.player.Player;
import org.spongepowered.api.entity.living.player.server.ServerPlayer; import org.spongepowered.api.entity.living.player.server.ServerPlayer;
import org.spongepowered.api.event.Listener; import org.spongepowered.api.event.Listener;
@@ -23,6 +24,7 @@ import static net.draycia.carbon.api.util.KeyedRenderer.keyedRenderer;
import static net.kyori.adventure.key.Key.key; import static net.kyori.adventure.key.Key.key;
import static net.kyori.adventure.text.Component.empty; import static net.kyori.adventure.text.Component.empty;
@DefaultQualifier(NonNull.class)
public final class SpongeChatListener { public final class SpongeChatListener {
private final CarbonChatSponge carbonChat; private final CarbonChatSponge carbonChat;
@@ -38,7 +40,7 @@ public final class SpongeChatListener {
} }
@Listener @Listener
public void onPlayerChat(final @NonNull PlayerChatEvent event, final @First Player source) { public void onPlayerChat(final PlayerChatEvent event, final @First Player source) {
final var playerResult = this.carbonChat.server().player(source.uniqueId()).join(); final var playerResult = this.carbonChat.server().player(source.uniqueId()).join();
if (playerResult.player() == null) { if (playerResult.player() == null) {
@@ -13,6 +13,7 @@ import net.kyori.adventure.text.Component;
import org.checkerframework.checker.nullness.qual.NonNull; import org.checkerframework.checker.nullness.qual.NonNull;
import org.checkerframework.checker.nullness.qual.Nullable; import org.checkerframework.checker.nullness.qual.Nullable;
import org.checkerframework.framework.qual.DefaultQualifier; import org.checkerframework.framework.qual.DefaultQualifier;
import org.jetbrains.annotations.NotNull;
import org.spongepowered.api.Sponge; import org.spongepowered.api.Sponge;
import org.spongepowered.api.data.Keys; import org.spongepowered.api.data.Keys;
import org.spongepowered.api.entity.living.player.server.ServerPlayer; import org.spongepowered.api.entity.living.player.server.ServerPlayer;
@@ -37,7 +38,7 @@ public final class CarbonPlayerSponge implements CarbonPlayer, ForwardingAudienc
} }
@Override @Override
public @NonNull Audience audience() { public @NotNull Audience audience() {
return this.player() return this.player()
.map(player -> (Audience) player) .map(player -> (Audience) player)
.orElseGet(Audience::empty); .orElseGet(Audience::empty);
@@ -71,12 +72,12 @@ public final class CarbonPlayerSponge implements CarbonPlayer, ForwardingAudienc
return this.carbonPlayer.uuid(); return this.carbonPlayer.uuid();
} }
private @NonNull Optional<ServerPlayer> player() { private Optional<ServerPlayer> player() {
return Sponge.server().player(this.carbonPlayer.uuid()); return Sponge.server().player(this.carbonPlayer.uuid());
} }
@Override @Override
public @NonNull Component createItemHoverComponent() { public Component createItemHoverComponent() {
final @Nullable ServerPlayer player = this.player().orElse(null); final @Nullable ServerPlayer player = this.player().orElse(null);
if (player == null) { if (player == null) {
return Component.empty(); return Component.empty();
@@ -93,7 +94,7 @@ public final class CarbonPlayerSponge implements CarbonPlayer, ForwardingAudienc
return this.fromStack(itemStack); return this.fromStack(itemStack);
} }
private @NonNull Component fromStack(final @NonNull ItemStack stack) { private Component fromStack(final ItemStack stack) {
return stack.get(Keys.DISPLAY_NAME) return stack.get(Keys.DISPLAY_NAME)
// This is here as a fallback, but really, every ItemStack should // This is here as a fallback, but really, every ItemStack should
@@ -175,7 +176,7 @@ public final class CarbonPlayerSponge implements CarbonPlayer, ForwardingAudienc
} }
@Override @Override
public @NonNull Identity identity() { public @NotNull Identity identity() {
return this.carbonPlayer.identity(); return this.carbonPlayer.identity();
} }
+1 -1
View File
@@ -1,4 +1,4 @@
import java.util.Locale import java.util.*
plugins { plugins {
id("carbon.shadow-platform") id("carbon.shadow-platform")
@@ -8,7 +8,6 @@ import com.velocitypowered.api.plugin.Plugin;
import com.velocitypowered.api.plugin.PluginContainer; import com.velocitypowered.api.plugin.PluginContainer;
import com.velocitypowered.api.plugin.annotation.DataDirectory; import com.velocitypowered.api.plugin.annotation.DataDirectory;
import com.velocitypowered.api.proxy.ProxyServer; import com.velocitypowered.api.proxy.ProxyServer;
import java.net.URISyntaxException;
import java.nio.file.Path; import java.nio.file.Path;
import java.util.Set; import java.util.Set;
import net.draycia.carbon.api.CarbonChatProvider; import net.draycia.carbon.api.CarbonChatProvider;
@@ -40,13 +39,13 @@ public class CarbonChatVelocity extends CarbonChatCommon {
private final Path dataDirectory; private final Path dataDirectory;
private final ProxyServer proxyServer; private final ProxyServer proxyServer;
private final PluginContainer pluginContainer;
private final Logger logger; private final Logger logger;
private final Injector injector; private final Injector injector;
private final CarbonMessageService messageService; private final CarbonMessageService messageService;
private final ChannelRegistry channelRegistry; private final ChannelRegistry channelRegistry;
private final CarbonServerVelocity carbonServer; private final CarbonServerVelocity carbonServer;
private final CarbonEventHandler eventHandler = new CarbonEventHandler();
@Inject @Inject
public CarbonChatVelocity( public CarbonChatVelocity(
@@ -59,17 +58,12 @@ public class CarbonChatVelocity extends CarbonChatCommon {
this.dataDirectory = dataDirectory; this.dataDirectory = dataDirectory;
this.proxyServer = proxyServer; this.proxyServer = proxyServer;
this.pluginContainer = pluginContainer; this.logger = LogManager.getLogger(pluginContainer.getDescription().getId());
this.logger = LogManager.getLogger(this.pluginContainer.getDescription().getId());
final CarbonChatVelocityModule carbonVelocityModule; final CarbonChatVelocityModule carbonVelocityModule;
try { carbonVelocityModule = new CarbonChatVelocityModule(
carbonVelocityModule = new CarbonChatVelocityModule( this.logger, this.dataDirectory, pluginContainer, this.proxyServer, this);
this.logger, this.dataDirectory, this.pluginContainer, this.proxyServer, this);
} catch (final URISyntaxException ex) {
throw new RuntimeException(ex);
}
this.injector = injector.createChildInjector(carbonVelocityModule); this.injector = injector.createChildInjector(carbonVelocityModule);
@@ -113,8 +107,6 @@ public class CarbonChatVelocity extends CarbonChatCommon {
return this.messageService; return this.messageService;
} }
private final CarbonEventHandler eventHandler = new CarbonEventHandler();
@Override @Override
public final @NonNull CarbonEventHandler eventHandler() { public final @NonNull CarbonEventHandler eventHandler() {
return this.eventHandler; return this.eventHandler;
@@ -9,7 +9,6 @@ import com.google.inject.Singleton;
import com.velocitypowered.api.plugin.PluginContainer; import com.velocitypowered.api.plugin.PluginContainer;
import com.velocitypowered.api.proxy.Player; import com.velocitypowered.api.proxy.Player;
import com.velocitypowered.api.proxy.ProxyServer; import com.velocitypowered.api.proxy.ProxyServer;
import java.net.URISyntaxException;
import java.nio.file.Path; import java.nio.file.Path;
import net.draycia.carbon.api.CarbonChat; import net.draycia.carbon.api.CarbonChat;
import net.draycia.carbon.api.CarbonServer; import net.draycia.carbon.api.CarbonServer;
@@ -37,7 +36,7 @@ public final class CarbonChatVelocityModule extends AbstractModule {
final PluginContainer pluginContainer, final PluginContainer pluginContainer,
final ProxyServer proxyServer, final ProxyServer proxyServer,
final CarbonChatVelocity carbonChatVelocity final CarbonChatVelocity carbonChatVelocity
) throws URISyntaxException { ) {
this.logger = logger; this.logger = logger;
this.dataDirectory = dataDirectory; this.dataDirectory = dataDirectory;
this.pluginContainer = pluginContainer; this.pluginContainer = pluginContainer;
@@ -47,7 +46,7 @@ public final class CarbonChatVelocityModule extends AbstractModule {
@Provides @Provides
@Singleton @Singleton
protected @NonNull CommandManager<Commander> createCommandManager() { protected CommandManager<Commander> createCommandManager() {
final VelocityCommandManager<Commander> commandManager = new VelocityCommandManager<>( final VelocityCommandManager<Commander> commandManager = new VelocityCommandManager<>(
this.pluginContainer, this.pluginContainer,
this.proxyServer, this.proxyServer,
@@ -28,6 +28,7 @@ import net.kyori.adventure.text.Component;
import org.checkerframework.checker.nullness.qual.NonNull; import org.checkerframework.checker.nullness.qual.NonNull;
import org.checkerframework.checker.nullness.qual.Nullable; import org.checkerframework.checker.nullness.qual.Nullable;
import org.checkerframework.framework.qual.DefaultQualifier; import org.checkerframework.framework.qual.DefaultQualifier;
import org.jetbrains.annotations.NotNull;
import static net.kyori.adventure.text.Component.text; import static net.kyori.adventure.text.Component.text;
@@ -47,7 +48,7 @@ public final class CarbonServerVelocity implements CarbonServer, ForwardingAudie
} }
@Override @Override
public Audience audience() { public @NotNull Audience audience() {
return Audience.audience(this.console(), Audience.audience(this.players())); return Audience.audience(this.console(), Audience.audience(this.players()));
} }
@@ -123,12 +124,7 @@ public final class CarbonServerVelocity implements CarbonServer, ForwardingAudie
.GET() .GET()
.build(); .build();
final HttpResponse<String> response = final JsonObject json = this.queryMojang(request);
this.client.send(request, HttpResponse.BodyHandlers.ofString());
final String mojangResponse = response.body();
final JsonArray jsonArray = this.gson.fromJson(mojangResponse, JsonObject.class).getAsJsonArray();
final JsonObject json = (JsonObject) jsonArray.get(1);
return UuidUtils.fromUndashed(json.get("uuid").getAsString()); return UuidUtils.fromUndashed(json.get("uuid").getAsString());
} catch (final URISyntaxException | IOException | InterruptedException e) { } catch (final URISyntaxException | IOException | InterruptedException e) {
@@ -148,12 +144,7 @@ public final class CarbonServerVelocity implements CarbonServer, ForwardingAudie
.GET() .GET()
.build(); .build();
final HttpResponse<String> response = final JsonObject json = this.queryMojang(request);
this.client.send(request, HttpResponse.BodyHandlers.ofString());
final String mojangResponse = response.body();
final JsonArray jsonArray = this.gson.fromJson(mojangResponse, JsonObject.class).getAsJsonArray();
final JsonObject json = (JsonObject) jsonArray.get(1);
return json.get("name").getAsString(); return json.get("name").getAsString();
} catch (final URISyntaxException | IOException | InterruptedException e) { } catch (final URISyntaxException | IOException | InterruptedException e) {
@@ -164,4 +155,13 @@ public final class CarbonServerVelocity implements CarbonServer, ForwardingAudie
}); });
} }
private JsonObject queryMojang(final HttpRequest request) throws IOException, InterruptedException {
final HttpResponse<String> response =
this.client.send(request, HttpResponse.BodyHandlers.ofString());
final String mojangResponse = response.body();
final JsonArray jsonArray = this.gson.fromJson(mojangResponse, JsonObject.class).getAsJsonArray();
return (JsonObject) jsonArray.get(1);
}
} }
@@ -6,31 +6,21 @@ import net.kyori.adventure.audience.Audience;
import net.kyori.adventure.audience.ForwardingAudience; import net.kyori.adventure.audience.ForwardingAudience;
import org.checkerframework.checker.nullness.qual.NonNull; import org.checkerframework.checker.nullness.qual.NonNull;
import org.checkerframework.framework.qual.DefaultQualifier; import org.checkerframework.framework.qual.DefaultQualifier;
import org.jetbrains.annotations.NotNull;
@DefaultQualifier(NonNull.class) @DefaultQualifier(NonNull.class)
public interface VelocityCommander extends Commander, ForwardingAudience.Single { public interface VelocityCommander extends Commander, ForwardingAudience.Single {
CommandSource commandSource();
static VelocityCommander from(final CommandSource source) { static VelocityCommander from(final CommandSource source) {
return new VelocityCommanderImpl(source); return new VelocityCommanderImpl(source);
} }
final class VelocityCommanderImpl implements VelocityCommander { CommandSource commandSource();
private final CommandSource commandSource; record VelocityCommanderImpl(CommandSource commandSource) implements VelocityCommander {
private VelocityCommanderImpl(final CommandSource commandSource) {
this.commandSource = commandSource;
}
@Override @Override
public CommandSource commandSource() { public @NotNull Audience audience() {
return this.commandSource;
}
@Override
public Audience audience() {
return this.commandSource; return this.commandSource;
} }
@@ -8,6 +8,7 @@ import net.draycia.carbon.common.command.PlayerCommander;
import net.kyori.adventure.audience.Audience; import net.kyori.adventure.audience.Audience;
import org.checkerframework.checker.nullness.qual.NonNull; import org.checkerframework.checker.nullness.qual.NonNull;
import org.checkerframework.framework.qual.DefaultQualifier; import org.checkerframework.framework.qual.DefaultQualifier;
import org.jetbrains.annotations.NotNull;
import static java.util.Objects.requireNonNull; import static java.util.Objects.requireNonNull;
@@ -23,7 +24,7 @@ public record VelocityPlayerCommander(
} }
@Override @Override
public Audience audience() { public @NotNull Audience audience() {
return this.player; return this.player;
} }
@@ -11,7 +11,9 @@ import net.draycia.carbon.api.events.CarbonChatEvent;
import net.draycia.carbon.api.users.ComponentPlayerResult; import net.draycia.carbon.api.users.ComponentPlayerResult;
import net.draycia.carbon.api.util.KeyedRenderer; import net.draycia.carbon.api.util.KeyedRenderer;
import net.draycia.carbon.velocity.CarbonChatVelocity; import net.draycia.carbon.velocity.CarbonChatVelocity;
import net.kyori.adventure.text.Component;
import org.checkerframework.checker.nullness.qual.NonNull; import org.checkerframework.checker.nullness.qual.NonNull;
import org.checkerframework.framework.qual.DefaultQualifier;
import static java.util.Objects.requireNonNullElse; import static java.util.Objects.requireNonNullElse;
import static net.draycia.carbon.api.util.KeyedRenderer.keyedRenderer; import static net.draycia.carbon.api.util.KeyedRenderer.keyedRenderer;
@@ -19,6 +21,7 @@ import static net.kyori.adventure.key.Key.key;
import static net.kyori.adventure.text.Component.empty; import static net.kyori.adventure.text.Component.empty;
import static net.kyori.adventure.text.Component.text; import static net.kyori.adventure.text.Component.text;
@DefaultQualifier(NonNull.class)
public final class VelocityChatListener { public final class VelocityChatListener {
private final CarbonChatVelocity carbonChat; private final CarbonChatVelocity carbonChat;
@@ -31,7 +34,7 @@ public final class VelocityChatListener {
} }
@Subscribe @Subscribe
public void onPlayerChat(final @NonNull PlayerChatEvent event) { public void onPlayerChat(final PlayerChatEvent event) {
final var playerResult = this.carbonChat.server().player(event.getPlayer().getUniqueId()).join(); final var playerResult = this.carbonChat.server().player(event.getPlayer().getUniqueId()).join();
if (playerResult.player() == null) { if (playerResult.player() == null) {
@@ -67,7 +70,7 @@ public final class VelocityChatListener {
} }
} }
if (component != null) { if (component != Component.empty()) {
recipient.sendMessage(component); recipient.sendMessage(component);
} }
} }
@@ -14,6 +14,7 @@ import net.kyori.adventure.text.Component;
import org.checkerframework.checker.nullness.qual.NonNull; import org.checkerframework.checker.nullness.qual.NonNull;
import org.checkerframework.checker.nullness.qual.Nullable; import org.checkerframework.checker.nullness.qual.Nullable;
import org.checkerframework.framework.qual.DefaultQualifier; import org.checkerframework.framework.qual.DefaultQualifier;
import org.jetbrains.annotations.NotNull;
@DefaultQualifier(NonNull.class) @DefaultQualifier(NonNull.class)
public final class CarbonPlayerVelocity extends CarbonPlayerCommon { public final class CarbonPlayerVelocity extends CarbonPlayerCommon {
@@ -42,7 +43,7 @@ public final class CarbonPlayerVelocity extends CarbonPlayerCommon {
} }
@Override @Override
public Audience audience() { public @NotNull Audience audience() {
final @Nullable Player player = this.player(); final @Nullable Player player = this.player();
if (player == null) { if (player == null) {
@@ -103,7 +104,7 @@ public final class CarbonPlayerVelocity extends CarbonPlayerCommon {
} }
@Override @Override
public @NonNull Identity identity() { public @NotNull Identity identity() {
return this.carbonPlayer.identity(); return this.carbonPlayer.identity();
} }