1
0
mirror of https://github.com/SquidDev-CC/CC-Tweaked synced 2025-07-04 02:52:56 +00:00

Reformat everything

- Switch to a fairly standard code format. This is largely based on
   IntelliJ defaults, with some minor tweaks applied via editor config.
   Should mean people don't need to import a config!

 - Use "var" everywhere instead of explicit types. Type inference is a
   joy, and I intend to use it to its fullest.

 - Start using switch expressions: we couldn't use them before because
   IntelliJ does silly things with our previous brace style, but now we
   have the luxury of them!
This commit is contained in:
Jonathan Coates 2022-11-03 23:43:14 +00:00
parent 7df0412c2d
commit f478c4ffc4
No known key found for this signature in database
GPG Key ID: B9E431FF07C98D06
557 changed files with 17468 additions and 27721 deletions

View File

@ -8,6 +8,17 @@ charset = utf-8
trim_trailing_whitespace = true trim_trailing_whitespace = true
insert_final_newline = true insert_final_newline = true
ij_continuation_indent_size = 4
ij_any_do_while_brace_force = if_multiline
ij_any_if_brace_force = if_multiline
ij_any_for_brace_force = if_multiline
ij_any_spaces_within_array_initializer_braces = true
ij_kotlin_allow_trailing_comma = true
ij_kotlin_allow_trailing_comma_on_call_site = true
ij_kotlin_method_parameters_wrap = off
ij_kotlin_call_parameters_wrap = off
[*.md] [*.md]
trim_trailing_whitespace = false trim_trailing_whitespace = false

View File

@ -4,7 +4,6 @@ import org.codehaus.groovy.runtime.ProcessGroovyMethods
import java.io.BufferedReader import java.io.BufferedReader
import java.io.IOException import java.io.IOException
import java.io.InputStreamReader import java.io.InputStreamReader
import java.util.stream.Collectors
internal object ProcessHelpers { internal object ProcessHelpers {
fun startProcess(vararg command: String): Process { fun startProcess(vararg command: String): Process {
@ -26,7 +25,7 @@ internal object ProcessHelpers {
fun captureLines(process: Process): List<String> { fun captureLines(process: Process): List<String> {
val out = BufferedReader(InputStreamReader(process.inputStream)).use { reader -> val out = BufferedReader(InputStreamReader(process.inputStream)).use { reader ->
reader.lines().filter { it.isNotEmpty() }.collect(Collectors.toList()) reader.lines().filter { it.isNotEmpty() }.toList()
} }
ProcessGroovyMethods.closeStreams(process) ProcessGroovyMethods.closeStreams(process)
if (process.waitFor() != 0) throw IOException("Command exited with a non-0 status") if (process.waitFor() != 0) throw IOException("Command exited with a non-0 status")

View File

@ -26,17 +26,11 @@
<module name="EmptyCatchBlock"> <module name="EmptyCatchBlock">
<property name="exceptionVariableName" value="ignored" /> <property name="exceptionVariableName" value="ignored" />
</module> </module>
<module name="LeftCurly"> <module name="LeftCurly" />
<property name="option" value="nl" />
<!-- The defaults, minus lambdas. -->
<property name="tokens" value="ANNOTATION_DEF,CLASS_DEF,CTOR_DEF,ENUM_CONSTANT_DEF,ENUM_DEF,INTERFACE_DEF,LITERAL_CASE,LITERAL_CATCH,LITERAL_DEFAULT,LITERAL_DO,LITERAL_ELSE,LITERAL_FINALLY,LITERAL_FOR,LITERAL_IF,LITERAL_SWITCH,LITERAL_SYNCHRONIZED,LITERAL_TRY,LITERAL_WHILE,METHOD_DEF,OBJBLOCK,STATIC_INIT" />
</module>
<module name="NeedBraces"> <module name="NeedBraces">
<property name="allowSingleLineStatement" value="true"/> <property name="allowSingleLineStatement" value="true"/>
</module> </module>
<module name="RightCurly"> <module name="RightCurly" />
<property name="option" value="alone" />
</module>
<!-- Class design. As if we've ever followed good practice here. --> <!-- Class design. As if we've ever followed good practice here. -->
<module name="FinalClass" /> <module name="FinalClass" />
@ -131,18 +125,11 @@
<module name="MethodParamPad" /> <module name="MethodParamPad" />
<module name="NoLineWrap" /> <module name="NoLineWrap" />
<module name="NoWhitespaceAfter"> <module name="NoWhitespaceAfter">
<property name="tokens" value="AT,INC,DEC,UNARY_MINUS,UNARY_PLUS,BNOT,LNOT,DOT,ARRAY_DECLARATOR,INDEX_OP" /> <property name="tokens" value="AT,INC,DEC,UNARY_MINUS,UNARY_PLUS,BNOT,LNOT,DOT,ARRAY_DECLARATOR,INDEX_OP,METHOD_REF" />
</module> </module>
<module name="NoWhitespaceBefore" /> <module name="NoWhitespaceBefore" />
<!-- TODO: Decide on an OperatorWrap style. --> <!-- TODO: Decide on an OperatorWrap style. -->
<module name="ParenPad"> <module name="ParenPad" />
<property name="option" value="space" />
<property name="tokens" value="ANNOTATION,ANNOTATION_FIELD_DEF,CTOR_CALL,CTOR_DEF,ENUM_CONSTANT_DEF,LITERAL_CATCH,LITERAL_DO,LITERAL_FOR,LITERAL_IF,LITERAL_NEW,LITERAL_SWITCH,LITERAL_SYNCHRONIZED,LITERAL_WHILE,METHOD_CALL,METHOD_DEF,RESOURCE_SPECIFICATION,SUPER_CTOR_CALL,LAMBDA" />
</module>
<module name="ParenPad">
<property name="option" value="nospace" />
<property name="tokens" value="DOT,EXPR,QUESTION" />
</module>
<module name="SeparatorWrap"> <module name="SeparatorWrap">
<property name="option" value="eol" /> <property name="option" value="eol" />
<property name="tokens" value="COMMA,SEMI,ELLIPSIS,ARRAY_DECLARATOR,RBRACK,METHOD_REF" /> <property name="tokens" value="COMMA,SEMI,ELLIPSIS,ARRAY_DECLARATOR,RBRACK,METHOD_REF" />

File diff suppressed because it is too large Load Diff

View File

@ -1,61 +0,0 @@
<code_scheme name="Project" version="173">
<JSON>
<option name="OBJECT_WRAPPING" value="1" />
<option name="ARRAY_WRAPPING" value="1" />
</JSON>
<JavaCodeStyleSettings>
<option name="PACKAGES_TO_USE_IMPORT_ON_DEMAND">
<value />
</option>
<option name="JD_P_AT_EMPTY_LINES" value="false" />
<option name="JD_PRESERVE_LINE_FEEDS" value="true" />
</JavaCodeStyleSettings>
<codeStyleSettings language="JAVA">
<option name="KEEP_FIRST_COLUMN_COMMENT" value="false" />
<option name="BRACE_STYLE" value="2" />
<option name="CLASS_BRACE_STYLE" value="2" />
<option name="METHOD_BRACE_STYLE" value="2" />
<option name="LAMBDA_BRACE_STYLE" value="5" />
<option name="ELSE_ON_NEW_LINE" value="true" />
<option name="CATCH_ON_NEW_LINE" value="true" />
<option name="FINALLY_ON_NEW_LINE" value="true" />
<option name="SPACE_WITHIN_METHOD_CALL_PARENTHESES" value="true" />
<option name="SPACE_WITHIN_METHOD_PARENTHESES" value="true" />
<option name="SPACE_WITHIN_IF_PARENTHESES" value="true" />
<option name="SPACE_WITHIN_WHILE_PARENTHESES" value="true" />
<option name="SPACE_WITHIN_FOR_PARENTHESES" value="true" />
<option name="SPACE_WITHIN_TRY_PARENTHESES" value="true" />
<option name="SPACE_WITHIN_CATCH_PARENTHESES" value="true" />
<option name="SPACE_WITHIN_SWITCH_PARENTHESES" value="true" />
<option name="SPACE_WITHIN_SYNCHRONIZED_PARENTHESES" value="true" />
<option name="SPACE_WITHIN_ARRAY_INITIALIZER_BRACES" value="true" />
<option name="SPACE_BEFORE_IF_PARENTHESES" value="false" />
<option name="SPACE_BEFORE_WHILE_PARENTHESES" value="false" />
<option name="SPACE_BEFORE_FOR_PARENTHESES" value="false" />
<option name="SPACE_BEFORE_TRY_PARENTHESES" value="false" />
<option name="SPACE_BEFORE_CATCH_PARENTHESES" value="false" />
<option name="SPACE_BEFORE_SWITCH_PARENTHESES" value="false" />
<option name="SPACE_BEFORE_SYNCHRONIZED_PARENTHESES" value="false" />
<option name="SPACE_BEFORE_ARRAY_INITIALIZER_LBRACE" value="true" />
<option name="KEEP_SIMPLE_METHODS_IN_ONE_LINE" value="true" />
<option name="KEEP_SIMPLE_LAMBDAS_IN_ONE_LINE" value="true" />
<option name="KEEP_SIMPLE_CLASSES_IN_ONE_LINE" value="true" />
<option name="IF_BRACE_FORCE" value="1" />
<option name="DOWHILE_BRACE_FORCE" value="1" />
<option name="WHILE_BRACE_FORCE" value="1" />
<option name="FOR_BRACE_FORCE" value="1" />
<option name="SPACE_WITHIN_ANNOTATION_PARENTHESES" value="true" />
<indentOptions>
<option name="CONTINUATION_INDENT_SIZE" value="4" />
</indentOptions>
</codeStyleSettings>
<codeStyleSettings language="JSON">
<option name="KEEP_BLANK_LINES_IN_CODE" value="1" />
<option name="SPACE_WITHIN_BRACKETS" value="true" />
<option name="SPACE_WITHIN_BRACES" value="true" />
<indentOptions>
<option name="INDENT_SIZE" value="4" />
<option name="CONTINUATION_INDENT_SIZE" value="4" />
</indentOptions>
</codeStyleSettings>
</code_scheme>

View File

@ -18,9 +18,8 @@ import java.util.List;
import java.util.OptionalInt; import java.util.OptionalInt;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
@Mod( ComputerCraft.MOD_ID ) @Mod(ComputerCraft.MOD_ID)
public final class ComputerCraft public final class ComputerCraft {
{
public static final String MOD_ID = "computercraft"; public static final String MOD_ID = "computercraft";
public static int computerSpaceLimit = 1000 * 1000; public static int computerSpaceLimit = 1000 * 1000;
@ -32,14 +31,14 @@ public final class ComputerCraft
public static boolean commandRequireCreative = true; public static boolean commandRequireCreative = true;
public static int computerThreads = 1; public static int computerThreads = 1;
public static long maxMainGlobalTime = TimeUnit.MILLISECONDS.toNanos( 10 ); public static long maxMainGlobalTime = TimeUnit.MILLISECONDS.toNanos(10);
public static long maxMainComputerTime = TimeUnit.MILLISECONDS.toNanos( 5 ); public static long maxMainComputerTime = TimeUnit.MILLISECONDS.toNanos(5);
public static boolean httpEnabled = true; public static boolean httpEnabled = true;
public static boolean httpWebsocketEnabled = true; public static boolean httpWebsocketEnabled = true;
public static List<AddressRule> httpRules = List.of( public static List<AddressRule> httpRules = List.of(
AddressRule.parse( "$private", OptionalInt.empty(), Action.DENY.toPartial() ), AddressRule.parse("$private", OptionalInt.empty(), Action.DENY.toPartial()),
AddressRule.parse( "*", OptionalInt.empty(), Action.ALLOW.toPartial() ) AddressRule.parse("*", OptionalInt.empty(), Action.ALLOW.toPartial())
); );
public static int httpMaxRequests = 16; public static int httpMaxRequests = 16;
@ -77,10 +76,9 @@ public final class ComputerCraft
public static int uploadNagDelay = 5; public static int uploadNagDelay = 5;
public static final Logger log = LoggerFactory.getLogger( MOD_ID ); public static final Logger log = LoggerFactory.getLogger(MOD_ID);
public ComputerCraft() public ComputerCraft() {
{
Config.setup(); Config.setup();
Registry.setup(); Registry.setup();
} }

View File

@ -41,11 +41,9 @@ import net.minecraft.core.BlockPos;
import net.minecraft.core.Direction; import net.minecraft.core.Direction;
import net.minecraft.resources.ResourceLocation; import net.minecraft.resources.ResourceLocation;
import net.minecraft.server.MinecraftServer; import net.minecraft.server.MinecraftServer;
import net.minecraft.server.packs.resources.ResourceManager;
import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.ItemStack;
import net.minecraft.world.level.BlockGetter; import net.minecraft.world.level.BlockGetter;
import net.minecraft.world.level.Level; import net.minecraft.world.level.Level;
import net.minecraft.world.level.block.entity.BlockEntity;
import net.minecraftforge.common.capabilities.Capability; import net.minecraftforge.common.capabilities.Capability;
import net.minecraftforge.common.util.LazyOptional; import net.minecraftforge.common.util.LazyOptional;
import net.minecraftforge.fluids.FluidStack; import net.minecraftforge.fluids.FluidStack;
@ -59,175 +57,141 @@ import java.io.InputStream;
import static dan200.computercraft.shared.Capabilities.CAPABILITY_WIRED_ELEMENT; import static dan200.computercraft.shared.Capabilities.CAPABILITY_WIRED_ELEMENT;
@AutoService( ComputerCraftAPIService.class ) @AutoService(ComputerCraftAPIService.class)
public final class ComputerCraftAPIImpl implements ComputerCraftAPIService public final class ComputerCraftAPIImpl implements ComputerCraftAPIService {
{ private final DetailRegistry<ItemStack> itemStackDetails = new DetailRegistryImpl<>(ItemData::fillBasic);
private final DetailRegistry<ItemStack> itemStackDetails = new DetailRegistryImpl<>( ItemData::fillBasic ); private final DetailRegistry<BlockReference> blockDetails = new DetailRegistryImpl<>(BlockData::fillBasic);
private final DetailRegistry<BlockReference> blockDetails = new DetailRegistryImpl<>( BlockData::fillBasic ); private final DetailRegistry<FluidStack> fluidStackDetails = new DetailRegistryImpl<>(FluidData::fillBasic);
private final DetailRegistry<FluidStack> fluidStackDetails = new DetailRegistryImpl<>( FluidData::fillBasic );
private String version; private String version;
public static InputStream getResourceFile( MinecraftServer server, String domain, String subPath ) public static InputStream getResourceFile(MinecraftServer server, String domain, String subPath) {
{ var manager = server.getResourceManager();
ResourceManager manager = server.getResourceManager(); var resource = manager.getResource(new ResourceLocation(domain, subPath)).orElse(null);
var resource = manager.getResource( new ResourceLocation( domain, subPath ) ).orElse( null ); if (resource == null) return null;
if( resource == null ) return null; try {
try
{
return resource.open(); return resource.open();
} } catch (IOException ignored) {
catch( IOException ignored )
{
return null; return null;
} }
} }
@Nonnull @Nonnull
@Override @Override
public String getInstalledVersion() public String getInstalledVersion() {
{ if (version != null) return version;
if( version != null ) return version; return version = ModList.get().getModContainerById(ComputerCraft.MOD_ID)
return version = ModList.get().getModContainerById( ComputerCraft.MOD_ID ) .map(x -> x.getModInfo().getVersion().toString())
.map( x -> x.getModInfo().getVersion().toString() ) .orElse("unknown");
.orElse( "unknown" );
} }
@Override @Override
public int createUniqueNumberedSaveDir( @Nonnull Level world, @Nonnull String parentSubPath ) public int createUniqueNumberedSaveDir(@Nonnull Level world, @Nonnull String parentSubPath) {
{ return ServerContext.get(world.getServer()).getNextId(parentSubPath);
return ServerContext.get( world.getServer() ).getNextId( parentSubPath );
} }
@Override @Override
public IWritableMount createSaveDirMount( @Nonnull Level world, @Nonnull String subPath, long capacity ) public IWritableMount createSaveDirMount(@Nonnull Level world, @Nonnull String subPath, long capacity) {
{ try {
try return new FileMount(new File(ServerContext.get(world.getServer()).storageDir().toFile(), subPath), capacity);
{ } catch (Exception e) {
return new FileMount( new File( ServerContext.get( world.getServer() ).storageDir().toFile(), subPath ), capacity );
}
catch( Exception e )
{
return null; return null;
} }
} }
@Override @Override
public IMount createResourceMount( @Nonnull String domain, @Nonnull String subPath ) public IMount createResourceMount(@Nonnull String domain, @Nonnull String subPath) {
{ var manager = ServerLifecycleHooks.getCurrentServer().getResourceManager();
ResourceManager manager = ServerLifecycleHooks.getCurrentServer().getResourceManager(); var mount = ResourceMount.get(domain, subPath, manager);
ResourceMount mount = ResourceMount.get( domain, subPath, manager ); return mount.exists("") ? mount : null;
return mount.exists( "" ) ? mount : null;
} }
@Override @Override
public void registerPeripheralProvider( @Nonnull IPeripheralProvider provider ) public void registerPeripheralProvider(@Nonnull IPeripheralProvider provider) {
{ Peripherals.register(provider);
Peripherals.register( provider );
} }
@Override @Override
public void registerGenericSource( @Nonnull GenericSource source ) public void registerGenericSource(@Nonnull GenericSource source) {
{ GenericMethod.register(source);
GenericMethod.register( source );
} }
@Override @Override
public void registerGenericCapability( @Nonnull Capability<?> capability ) public void registerGenericCapability(@Nonnull Capability<?> capability) {
{ GenericPeripheralProvider.addCapability(capability);
GenericPeripheralProvider.addCapability( capability );
} }
@Override @Override
public void registerBundledRedstoneProvider( @Nonnull IBundledRedstoneProvider provider ) public void registerBundledRedstoneProvider(@Nonnull IBundledRedstoneProvider provider) {
{ BundledRedstone.register(provider);
BundledRedstone.register( provider );
} }
@Override @Override
public int getBundledRedstoneOutput( @Nonnull Level world, @Nonnull BlockPos pos, @Nonnull Direction side ) public int getBundledRedstoneOutput(@Nonnull Level world, @Nonnull BlockPos pos, @Nonnull Direction side) {
{ return BundledRedstone.getDefaultOutput(world, pos, side);
return BundledRedstone.getDefaultOutput( world, pos, side );
} }
@Override @Override
public void registerMediaProvider( @Nonnull IMediaProvider provider ) public void registerMediaProvider(@Nonnull IMediaProvider provider) {
{ MediaProviders.register(provider);
MediaProviders.register( provider );
} }
@Nonnull @Nonnull
@Override @Override
public IPacketNetwork getWirelessNetwork() public IPacketNetwork getWirelessNetwork() {
{
return WirelessNetwork.getUniversal(); return WirelessNetwork.getUniversal();
} }
@Override @Override
public void registerAPIFactory( @Nonnull ILuaAPIFactory factory ) public void registerAPIFactory(@Nonnull ILuaAPIFactory factory) {
{ ApiFactories.register(factory);
ApiFactories.register( factory );
} }
@Override @Override
@Deprecated @Deprecated
@SuppressWarnings( "unchecked" ) @SuppressWarnings("unchecked")
public <T> void registerDetailProvider( @Nonnull Class<T> type, @Nonnull IDetailProvider<T> provider ) public <T> void registerDetailProvider(@Nonnull Class<T> type, @Nonnull IDetailProvider<T> provider) {
{ if (type == ItemStack.class) {
if( type == ItemStack.class ) itemStackDetails.addProvider((IDetailProvider<ItemStack>) provider);
{ } else if (type == BlockReference.class) {
itemStackDetails.addProvider( (IDetailProvider<ItemStack>) provider ); blockDetails.addProvider((IDetailProvider<BlockReference>) provider);
} } else if (type == FluidStack.class) {
else if( type == BlockReference.class ) itemStackDetails.addProvider((IDetailProvider<ItemStack>) provider);
{ } else {
blockDetails.addProvider( (IDetailProvider<BlockReference>) provider ); throw new IllegalArgumentException("Unknown detail provider " + type);
}
else if( type == FluidStack.class )
{
itemStackDetails.addProvider( (IDetailProvider<ItemStack>) provider );
}
else
{
throw new IllegalArgumentException( "Unknown detail provider " + type );
} }
} }
@Nonnull @Nonnull
@Override @Override
public IWiredNode createWiredNodeForElement( @Nonnull IWiredElement element ) public IWiredNode createWiredNodeForElement(@Nonnull IWiredElement element) {
{ return new WiredNode(element);
return new WiredNode( element );
} }
@Nonnull @Nonnull
@Override @Override
public LazyOptional<IWiredElement> getWiredElementAt( @Nonnull BlockGetter world, @Nonnull BlockPos pos, @Nonnull Direction side ) public LazyOptional<IWiredElement> getWiredElementAt(@Nonnull BlockGetter world, @Nonnull BlockPos pos, @Nonnull Direction side) {
{ var tile = world.getBlockEntity(pos);
BlockEntity tile = world.getBlockEntity( pos ); return tile == null ? LazyOptional.empty() : tile.getCapability(CAPABILITY_WIRED_ELEMENT, side);
return tile == null ? LazyOptional.empty() : tile.getCapability( CAPABILITY_WIRED_ELEMENT, side );
} }
@Override @Override
public void registerRefuelHandler( @Nonnull TurtleRefuelHandler handler ) public void registerRefuelHandler(@Nonnull TurtleRefuelHandler handler) {
{ TurtleRefuelHandlers.register(handler);
TurtleRefuelHandlers.register( handler );
} }
@Override @Override
public DetailRegistry<ItemStack> getItemStackDetailRegistry() public DetailRegistry<ItemStack> getItemStackDetailRegistry() {
{
return itemStackDetails; return itemStackDetails;
} }
@Override @Override
public DetailRegistry<BlockReference> getBlockInWorldDetailRegistry() public DetailRegistry<BlockReference> getBlockInWorldDetailRegistry() {
{
return blockDetails; return blockDetails;
} }
@Override @Override
public DetailRegistry<FluidStack> getFluidStackDetailRegistry() public DetailRegistry<FluidStack> getFluidStackDetailRegistry() {
{
return fluidStackDetails; return fluidStackDetails;
} }
} }

View File

@ -41,13 +41,11 @@ import javax.annotation.Nullable;
* Members in this class must be called after ComputerCraft has been initialised, but may be called before it is * Members in this class must be called after ComputerCraft has been initialised, but may be called before it is
* fully loaded. * fully loaded.
*/ */
public final class ComputerCraftAPI public final class ComputerCraftAPI {
{
public static final String MOD_ID = "computercraft"; public static final String MOD_ID = "computercraft";
@Nonnull @Nonnull
public static String getInstalledVersion() public static String getInstalledVersion() {
{
return getInstance().getInstalledVersion(); return getInstance().getInstalledVersion();
} }
@ -64,9 +62,8 @@ public final class ComputerCraftAPI
* available for writing. * available for writing.
* @see #createSaveDirMount(Level, String, long) * @see #createSaveDirMount(Level, String, long)
*/ */
public static int createUniqueNumberedSaveDir( @Nonnull Level world, @Nonnull String parentSubPath ) public static int createUniqueNumberedSaveDir(@Nonnull Level world, @Nonnull String parentSubPath) {
{ return getInstance().createUniqueNumberedSaveDir(world, parentSubPath);
return getInstance().createUniqueNumberedSaveDir( world, parentSubPath );
} }
/** /**
@ -88,9 +85,8 @@ public final class ComputerCraftAPI
* @see IWritableMount * @see IWritableMount
*/ */
@Nullable @Nullable
public static IWritableMount createSaveDirMount( @Nonnull Level world, @Nonnull String subPath, long capacity ) public static IWritableMount createSaveDirMount(@Nonnull Level world, @Nonnull String subPath, long capacity) {
{ return getInstance().createSaveDirMount(world, subPath, capacity);
return getInstance().createSaveDirMount( world, subPath, capacity );
} }
/** /**
@ -112,9 +108,8 @@ public final class ComputerCraftAPI
* @see IMount * @see IMount
*/ */
@Nullable @Nullable
public static IMount createResourceMount( @Nonnull String domain, @Nonnull String subPath ) public static IMount createResourceMount(@Nonnull String domain, @Nonnull String subPath) {
{ return getInstance().createResourceMount(domain, subPath);
return getInstance().createResourceMount( domain, subPath );
} }
/** /**
@ -125,10 +120,9 @@ public final class ComputerCraftAPI
* @see IPeripheralProvider * @see IPeripheralProvider
* @deprecated Use {@link ForgeComputerCraftAPI#registerPeripheralProvider(IPeripheralProvider)} instead. * @deprecated Use {@link ForgeComputerCraftAPI#registerPeripheralProvider(IPeripheralProvider)} instead.
*/ */
@Deprecated( forRemoval = true ) @Deprecated(forRemoval = true)
public static void registerPeripheralProvider( @Nonnull IPeripheralProvider provider ) public static void registerPeripheralProvider(@Nonnull IPeripheralProvider provider) {
{ getInstance().registerPeripheralProvider(provider);
getInstance().registerPeripheralProvider( provider );
} }
/** /**
@ -137,9 +131,8 @@ public final class ComputerCraftAPI
* @param source The method source to register. * @param source The method source to register.
* @see GenericSource * @see GenericSource
*/ */
public static void registerGenericSource( @Nonnull GenericSource source ) public static void registerGenericSource(@Nonnull GenericSource source) {
{ getInstance().registerGenericSource(source);
getInstance().registerGenericSource( source );
} }
/** /**
@ -149,10 +142,9 @@ public final class ComputerCraftAPI
* @see GenericSource * @see GenericSource
* @deprecated Use {@link ForgeComputerCraftAPI} instead. * @deprecated Use {@link ForgeComputerCraftAPI} instead.
*/ */
@Deprecated( forRemoval = true ) @Deprecated(forRemoval = true)
public static void registerGenericCapability( @Nonnull Capability<?> capability ) public static void registerGenericCapability(@Nonnull Capability<?> capability) {
{ getInstance().registerGenericCapability(capability);
getInstance().registerGenericCapability( capability );
} }
/** /**
@ -161,9 +153,8 @@ public final class ComputerCraftAPI
* @param provider The bundled redstone provider to register. * @param provider The bundled redstone provider to register.
* @see IBundledRedstoneProvider * @see IBundledRedstoneProvider
*/ */
public static void registerBundledRedstoneProvider( @Nonnull IBundledRedstoneProvider provider ) public static void registerBundledRedstoneProvider(@Nonnull IBundledRedstoneProvider provider) {
{ getInstance().registerBundledRedstoneProvider(provider);
getInstance().registerBundledRedstoneProvider( provider );
} }
/** /**
@ -176,9 +167,8 @@ public final class ComputerCraftAPI
* If there is no block capable of emitting bundled redstone at the location, -1 will be returned. * If there is no block capable of emitting bundled redstone at the location, -1 will be returned.
* @see IBundledRedstoneProvider * @see IBundledRedstoneProvider
*/ */
public static int getBundledRedstoneOutput( @Nonnull Level world, @Nonnull BlockPos pos, @Nonnull Direction side ) public static int getBundledRedstoneOutput(@Nonnull Level world, @Nonnull BlockPos pos, @Nonnull Direction side) {
{ return getInstance().getBundledRedstoneOutput(world, pos, side);
return getInstance().getBundledRedstoneOutput( world, pos, side );
} }
/** /**
@ -187,9 +177,8 @@ public final class ComputerCraftAPI
* @param provider The media provider to register. * @param provider The media provider to register.
* @see IMediaProvider * @see IMediaProvider
*/ */
public static void registerMediaProvider( @Nonnull IMediaProvider provider ) public static void registerMediaProvider(@Nonnull IMediaProvider provider) {
{ getInstance().registerMediaProvider(provider);
getInstance().registerMediaProvider( provider );
} }
/** /**
@ -197,14 +186,12 @@ public final class ComputerCraftAPI
* *
* @return The global wireless network, or {@code null} if it could not be fetched. * @return The global wireless network, or {@code null} if it could not be fetched.
*/ */
public static IPacketNetwork getWirelessNetwork() public static IPacketNetwork getWirelessNetwork() {
{
return getInstance().getWirelessNetwork(); return getInstance().getWirelessNetwork();
} }
public static void registerAPIFactory( @Nonnull ILuaAPIFactory factory ) public static void registerAPIFactory(@Nonnull ILuaAPIFactory factory) {
{ getInstance().registerAPIFactory(factory);
getInstance().registerAPIFactory( factory );
} }
/** /**
@ -217,10 +204,9 @@ public final class ComputerCraftAPI
* @param <T> The type of object that this provider can provide details for. * @param <T> The type of object that this provider can provide details for.
* @deprecated Use {@link DetailRegistry#addProvider(IDetailProvider)} to register your provider. * @deprecated Use {@link DetailRegistry#addProvider(IDetailProvider)} to register your provider.
*/ */
@Deprecated( forRemoval = true ) @Deprecated(forRemoval = true)
public static <T> void registerDetailProvider( @Nonnull Class<T> type, @Nonnull IDetailProvider<T> provider ) public static <T> void registerDetailProvider(@Nonnull Class<T> type, @Nonnull IDetailProvider<T> provider) {
{ getInstance().registerDetailProvider(type, provider);
getInstance().registerDetailProvider( type, provider );
} }
/** /**
@ -231,9 +217,8 @@ public final class ComputerCraftAPI
* @see IWiredElement#getNode() * @see IWiredElement#getNode()
*/ */
@Nonnull @Nonnull
public static IWiredNode createWiredNodeForElement( @Nonnull IWiredElement element ) public static IWiredNode createWiredNodeForElement(@Nonnull IWiredElement element) {
{ return getInstance().createWiredNodeForElement(element);
return getInstance().createWiredNodeForElement( element );
} }
/** /**
@ -247,20 +232,17 @@ public final class ComputerCraftAPI
* @deprecated Use {@link ForgeComputerCraftAPI#getWiredElementAt(BlockGetter, BlockPos, Direction)} * @deprecated Use {@link ForgeComputerCraftAPI#getWiredElementAt(BlockGetter, BlockPos, Direction)}
*/ */
@Nonnull @Nonnull
@Deprecated( forRemoval = true ) @Deprecated(forRemoval = true)
public static LazyOptional<IWiredElement> getWiredElementAt( @Nonnull BlockGetter world, @Nonnull BlockPos pos, @Nonnull Direction side ) public static LazyOptional<IWiredElement> getWiredElementAt(@Nonnull BlockGetter world, @Nonnull BlockPos pos, @Nonnull Direction side) {
{ return getInstance().getWiredElementAt(world, pos, side);
return getInstance().getWiredElementAt( world, pos, side );
} }
public static void registerRefuelHandler( @Nonnull TurtleRefuelHandler handler ) public static void registerRefuelHandler(@Nonnull TurtleRefuelHandler handler) {
{ getInstance().registerRefuelHandler(handler);
getInstance().registerRefuelHandler( handler );
} }
@Nonnull @Nonnull
private static ComputerCraftAPIService getInstance() private static ComputerCraftAPIService getInstance() {
{
return ComputerCraftAPIService.get(); return ComputerCraftAPIService.get();
} }
} }

View File

@ -16,51 +16,46 @@ import net.minecraft.world.level.block.Block;
/** /**
* Tags provided by ComputerCraft. * Tags provided by ComputerCraft.
*/ */
public class ComputerCraftTags public class ComputerCraftTags {
{ public static class Items {
public static class Items public static final TagKey<Item> COMPUTER = make("computer");
{ public static final TagKey<Item> TURTLE = make("turtle");
public static final TagKey<Item> COMPUTER = make( "computer" ); public static final TagKey<Item> WIRED_MODEM = make("wired_modem");
public static final TagKey<Item> TURTLE = make( "turtle" ); public static final TagKey<Item> MONITOR = make("monitor");
public static final TagKey<Item> WIRED_MODEM = make( "wired_modem" );
public static final TagKey<Item> MONITOR = make( "monitor" );
private static TagKey<Item> make( String name ) private static TagKey<Item> make(String name) {
{ return ItemTags.create(new ResourceLocation(ComputerCraft.MOD_ID, name));
return ItemTags.create( new ResourceLocation( ComputerCraft.MOD_ID, name ) );
} }
} }
public static class Blocks public static class Blocks {
{ public static final TagKey<Block> COMPUTER = make("computer");
public static final TagKey<Block> COMPUTER = make( "computer" ); public static final TagKey<Block> TURTLE = make("turtle");
public static final TagKey<Block> TURTLE = make( "turtle" ); public static final TagKey<Block> WIRED_MODEM = make("wired_modem");
public static final TagKey<Block> WIRED_MODEM = make( "wired_modem" ); public static final TagKey<Block> MONITOR = make("monitor");
public static final TagKey<Block> MONITOR = make( "monitor" );
/** /**
* Blocks which can be broken by any turtle tool. * Blocks which can be broken by any turtle tool.
*/ */
public static final TagKey<Block> TURTLE_ALWAYS_BREAKABLE = make( "turtle_always_breakable" ); public static final TagKey<Block> TURTLE_ALWAYS_BREAKABLE = make("turtle_always_breakable");
/** /**
* Blocks which can be broken by the default shovel tool. * Blocks which can be broken by the default shovel tool.
*/ */
public static final TagKey<Block> TURTLE_SHOVEL_BREAKABLE = make( "turtle_shovel_harvestable" ); public static final TagKey<Block> TURTLE_SHOVEL_BREAKABLE = make("turtle_shovel_harvestable");
/** /**
* Blocks which can be broken with the default sword tool. * Blocks which can be broken with the default sword tool.
*/ */
public static final TagKey<Block> TURTLE_SWORD_BREAKABLE = make( "turtle_sword_harvestable" ); public static final TagKey<Block> TURTLE_SWORD_BREAKABLE = make("turtle_sword_harvestable");
/** /**
* Blocks which can be broken with the default hoe tool. * Blocks which can be broken with the default hoe tool.
*/ */
public static final TagKey<Block> TURTLE_HOE_BREAKABLE = make( "turtle_hoe_harvestable" ); public static final TagKey<Block> TURTLE_HOE_BREAKABLE = make("turtle_hoe_harvestable");
private static TagKey<Block> make( String name ) private static TagKey<Block> make(String name) {
{ return BlockTags.create(new ResourceLocation(ComputerCraft.MOD_ID, name));
return BlockTags.create( new ResourceLocation( ComputerCraft.MOD_ID, name ) );
} }
} }
} }

View File

@ -21,10 +21,8 @@ import javax.annotation.Nonnull;
/** /**
* The forge-specific entrypoint for ComputerCraft's API. * The forge-specific entrypoint for ComputerCraft's API.
*/ */
public final class ForgeComputerCraftAPI public final class ForgeComputerCraftAPI {
{ private ForgeComputerCraftAPI() {
private ForgeComputerCraftAPI()
{
} }
/** /**
@ -34,9 +32,8 @@ public final class ForgeComputerCraftAPI
* @see IPeripheral * @see IPeripheral
* @see IPeripheralProvider * @see IPeripheralProvider
*/ */
public static void registerPeripheralProvider( @Nonnull IPeripheralProvider provider ) public static void registerPeripheralProvider(@Nonnull IPeripheralProvider provider) {
{ getInstance().registerPeripheralProvider(provider);
getInstance().registerPeripheralProvider( provider );
} }
/** /**
@ -45,9 +42,8 @@ public final class ForgeComputerCraftAPI
* @param capability The capability to register. * @param capability The capability to register.
* @see GenericSource * @see GenericSource
*/ */
public static void registerGenericCapability( @Nonnull Capability<?> capability ) public static void registerGenericCapability(@Nonnull Capability<?> capability) {
{ getInstance().registerGenericCapability(capability);
getInstance().registerGenericCapability( capability );
} }
/** /**
@ -60,14 +56,12 @@ public final class ForgeComputerCraftAPI
* @see IWiredElement#getNode() * @see IWiredElement#getNode()
*/ */
@Nonnull @Nonnull
public static LazyOptional<IWiredElement> getWiredElementAt( @Nonnull BlockGetter world, @Nonnull BlockPos pos, @Nonnull Direction side ) public static LazyOptional<IWiredElement> getWiredElementAt(@Nonnull BlockGetter world, @Nonnull BlockPos pos, @Nonnull Direction side) {
{ return getInstance().getWiredElementAt(world, pos, side);
return getInstance().getWiredElementAt( world, pos, side );
} }
@Nonnull @Nonnull
private static ComputerCraftAPIService getInstance() private static ComputerCraftAPIService getInstance() {
{
return ComputerCraftAPIService.get(); return ComputerCraftAPIService.get();
} }
} }

View File

@ -13,10 +13,8 @@ import net.minecraftforge.fml.event.lifecycle.FMLClientSetupEvent;
import javax.annotation.Nonnull; import javax.annotation.Nonnull;
public final class ComputerCraftAPIClient public final class ComputerCraftAPIClient {
{ private ComputerCraftAPIClient() {
private ComputerCraftAPIClient()
{
} }
/** /**
@ -28,14 +26,12 @@ public final class ComputerCraftAPIClient
* @param modeller The upgrade modeller. * @param modeller The upgrade modeller.
* @param <T> The type of the turtle upgrade. * @param <T> The type of the turtle upgrade.
*/ */
public static <T extends ITurtleUpgrade> void registerTurtleUpgradeModeller( @Nonnull TurtleUpgradeSerialiser<T> serialiser, @Nonnull TurtleUpgradeModeller<T> modeller ) public static <T extends ITurtleUpgrade> void registerTurtleUpgradeModeller(@Nonnull TurtleUpgradeSerialiser<T> serialiser, @Nonnull TurtleUpgradeModeller<T> modeller) {
{ getInstance().registerTurtleUpgradeModeller(serialiser, modeller);
getInstance().registerTurtleUpgradeModeller( serialiser, modeller );
} }
@Nonnull @Nonnull
private static ComputerCraftAPIClientService getInstance() private static ComputerCraftAPIClientService getInstance() {
{
return ComputerCraftAPIClientService.get(); return ComputerCraftAPIClientService.get();
} }
} }

View File

@ -8,7 +8,6 @@ package dan200.computercraft.api.client;
import com.mojang.math.Transformation; import com.mojang.math.Transformation;
import net.minecraft.client.Minecraft; import net.minecraft.client.Minecraft;
import net.minecraft.client.resources.model.BakedModel; import net.minecraft.client.resources.model.BakedModel;
import net.minecraft.client.resources.model.ModelManager;
import net.minecraft.client.resources.model.ModelResourceLocation; import net.minecraft.client.resources.model.ModelResourceLocation;
import net.minecraft.resources.ResourceLocation; import net.minecraft.resources.ResourceLocation;
import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.ItemStack;
@ -19,50 +18,42 @@ import java.util.Objects;
/** /**
* A model to render, combined with a transformation matrix to apply. * A model to render, combined with a transformation matrix to apply.
*/ */
public final class TransformedModel public final class TransformedModel {
{
private final BakedModel model; private final BakedModel model;
private final Transformation matrix; private final Transformation matrix;
public TransformedModel( @Nonnull BakedModel model, @Nonnull Transformation matrix ) public TransformedModel(@Nonnull BakedModel model, @Nonnull Transformation matrix) {
{ this.model = Objects.requireNonNull(model);
this.model = Objects.requireNonNull( model ); this.matrix = Objects.requireNonNull(matrix);
this.matrix = Objects.requireNonNull( matrix );
} }
public TransformedModel( @Nonnull BakedModel model ) public TransformedModel(@Nonnull BakedModel model) {
{ this.model = Objects.requireNonNull(model);
this.model = Objects.requireNonNull( model );
matrix = Transformation.identity(); matrix = Transformation.identity();
} }
public static TransformedModel of( @Nonnull ModelResourceLocation location ) public static TransformedModel of(@Nonnull ModelResourceLocation location) {
{ var modelManager = Minecraft.getInstance().getModelManager();
ModelManager modelManager = Minecraft.getInstance().getModelManager(); return new TransformedModel(modelManager.getModel(location));
return new TransformedModel( modelManager.getModel( location ) );
} }
public static TransformedModel of( @Nonnull ResourceLocation location ) public static TransformedModel of(@Nonnull ResourceLocation location) {
{ var modelManager = Minecraft.getInstance().getModelManager();
ModelManager modelManager = Minecraft.getInstance().getModelManager(); return new TransformedModel(modelManager.getModel(location));
return new TransformedModel( modelManager.getModel( location ) );
} }
public static TransformedModel of( @Nonnull ItemStack item, @Nonnull Transformation transform ) public static TransformedModel of(@Nonnull ItemStack item, @Nonnull Transformation transform) {
{ var model = Minecraft.getInstance().getItemRenderer().getItemModelShaper().getItemModel(item);
BakedModel model = Minecraft.getInstance().getItemRenderer().getItemModelShaper().getItemModel( item ); return new TransformedModel(model, transform);
return new TransformedModel( model, transform );
} }
@Nonnull @Nonnull
public BakedModel getModel() public BakedModel getModel() {
{
return model; return model;
} }
@Nonnull @Nonnull
public Transformation getMatrix() public Transformation getMatrix() {
{
return matrix; return matrix;
} }
} }

View File

@ -23,8 +23,7 @@ import javax.annotation.Nullable;
* @param <T> The type of turtle upgrade this modeller applies to. * @param <T> The type of turtle upgrade this modeller applies to.
* @see ComputerCraftAPIClient#registerTurtleUpgradeModeller(TurtleUpgradeSerialiser, TurtleUpgradeModeller) To register a modeller. * @see ComputerCraftAPIClient#registerTurtleUpgradeModeller(TurtleUpgradeSerialiser, TurtleUpgradeModeller) To register a modeller.
*/ */
public interface TurtleUpgradeModeller<T extends ITurtleUpgrade> public interface TurtleUpgradeModeller<T extends ITurtleUpgrade> {
{
/** /**
* Obtain the model to be used when rendering a turtle peripheral. * Obtain the model to be used when rendering a turtle peripheral.
* <p> * <p>
@ -36,7 +35,7 @@ public interface TurtleUpgradeModeller<T extends ITurtleUpgrade>
* @return The model that you wish to be used to render your upgrade. * @return The model that you wish to be used to render your upgrade.
*/ */
@Nonnull @Nonnull
TransformedModel getModel( @Nonnull T upgrade, @Nullable ITurtleAccess turtle, @Nonnull TurtleSide side ); TransformedModel getModel(@Nonnull T upgrade, @Nullable ITurtleAccess turtle, @Nonnull TurtleSide side);
/** /**
* A basic {@link TurtleUpgradeModeller} which renders using the upgrade's {@linkplain ITurtleUpgrade#getCraftingItem() * A basic {@link TurtleUpgradeModeller} which renders using the upgrade's {@linkplain ITurtleUpgrade#getCraftingItem()
@ -48,9 +47,8 @@ public interface TurtleUpgradeModeller<T extends ITurtleUpgrade>
* @param <T> The type of the turtle upgrade. * @param <T> The type of the turtle upgrade.
* @return The constructed modeller. * @return The constructed modeller.
*/ */
@SuppressWarnings( "unchecked" ) @SuppressWarnings("unchecked")
static <T extends ITurtleUpgrade> TurtleUpgradeModeller<T> flatItem() static <T extends ITurtleUpgrade> TurtleUpgradeModeller<T> flatItem() {
{
return (TurtleUpgradeModeller<T>) TurtleUpgradeModellers.FLAT_ITEM; return (TurtleUpgradeModeller<T>) TurtleUpgradeModellers.FLAT_ITEM;
} }
@ -62,9 +60,8 @@ public interface TurtleUpgradeModeller<T extends ITurtleUpgrade>
* @param <T> The type of the turtle upgrade. * @param <T> The type of the turtle upgrade.
* @return The constructed modeller. * @return The constructed modeller.
*/ */
static <T extends ITurtleUpgrade> TurtleUpgradeModeller<T> sided( ModelResourceLocation left, ModelResourceLocation right ) static <T extends ITurtleUpgrade> TurtleUpgradeModeller<T> sided(ModelResourceLocation left, ModelResourceLocation right) {
{ return (upgrade, turtle, side) -> TransformedModel.of(side == TurtleSide.LEFT ? left : right);
return ( upgrade, turtle, side ) -> TransformedModel.of( side == TurtleSide.LEFT ? left : right );
} }
/** /**
@ -75,8 +72,7 @@ public interface TurtleUpgradeModeller<T extends ITurtleUpgrade>
* @param <T> The type of the turtle upgrade. * @param <T> The type of the turtle upgrade.
* @return The constructed modeller. * @return The constructed modeller.
*/ */
static <T extends ITurtleUpgrade> TurtleUpgradeModeller<T> sided( ResourceLocation left, ResourceLocation right ) static <T extends ITurtleUpgrade> TurtleUpgradeModeller<T> sided(ResourceLocation left, ResourceLocation right) {
{ return (upgrade, turtle, side) -> TransformedModel.of(side == TurtleSide.LEFT ? left : right);
return ( upgrade, turtle, side ) -> TransformedModel.of( side == TurtleSide.LEFT ? left : right );
} }
} }

View File

@ -11,21 +11,19 @@ import dan200.computercraft.api.client.TransformedModel;
import dan200.computercraft.api.turtle.ITurtleUpgrade; import dan200.computercraft.api.turtle.ITurtleUpgrade;
import dan200.computercraft.api.turtle.TurtleSide; import dan200.computercraft.api.turtle.TurtleSide;
class TurtleUpgradeModellers class TurtleUpgradeModellers {
{ private static final Transformation leftTransform = getMatrixFor(-0.40625f);
private static final Transformation leftTransform = getMatrixFor( -0.40625f ); private static final Transformation rightTransform = getMatrixFor(0.40625f);
private static final Transformation rightTransform = getMatrixFor( 0.40625f );
private static Transformation getMatrixFor( float offset ) private static Transformation getMatrixFor(float offset) {
{ return new Transformation(new Matrix4f(new float[]{
return new Transformation( new Matrix4f( new float[] {
0.0f, 0.0f, -1.0f, 1.0f + offset, 0.0f, 0.0f, -1.0f, 1.0f + offset,
1.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f,
0.0f, -1.0f, 0.0f, 1.0f, 0.0f, -1.0f, 0.0f, 1.0f,
0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 1.0f,
} ) ); }));
} }
static final TurtleUpgradeModeller<ITurtleUpgrade> FLAT_ITEM = ( upgrade, turtle, side ) -> static final TurtleUpgradeModeller<ITurtleUpgrade> FLAT_ITEM = (upgrade, turtle, side) ->
TransformedModel.of( upgrade.getCraftingItem(), side == TurtleSide.LEFT ? leftTransform : rightTransform ); TransformedModel.of(upgrade.getCraftingItem(), side == TurtleSide.LEFT ? leftTransform : rightTransform);
} }

View File

@ -18,8 +18,7 @@ import java.util.Objects;
* *
* @param <T> The type the stack's item must have. * @param <T> The type the stack's item must have.
*/ */
public abstract class BasicItemDetailProvider<T> implements IDetailProvider<ItemStack> public abstract class BasicItemDetailProvider<T> implements IDetailProvider<ItemStack> {
{
private final Class<T> itemType; private final Class<T> itemType;
private final String namespace; private final String namespace;
@ -29,9 +28,8 @@ public abstract class BasicItemDetailProvider<T> implements IDetailProvider<Item
* @param itemType The type the stack's item must have. * @param itemType The type the stack's item must have.
* @param namespace The namespace to use for this provider. * @param namespace The namespace to use for this provider.
*/ */
public BasicItemDetailProvider( String namespace, @Nonnull Class<T> itemType ) public BasicItemDetailProvider(String namespace, @Nonnull Class<T> itemType) {
{ Objects.requireNonNull(itemType);
Objects.requireNonNull( itemType );
this.itemType = itemType; this.itemType = itemType;
this.namespace = namespace; this.namespace = namespace;
} }
@ -41,9 +39,8 @@ public abstract class BasicItemDetailProvider<T> implements IDetailProvider<Item
* *
* @param itemType The type the stack's item must have. * @param itemType The type the stack's item must have.
*/ */
public BasicItemDetailProvider( @Nonnull Class<T> itemType ) public BasicItemDetailProvider(@Nonnull Class<T> itemType) {
{ this(null, itemType);
this( null, itemType );
} }
/** /**
@ -57,23 +54,21 @@ public abstract class BasicItemDetailProvider<T> implements IDetailProvider<Item
* @param stack The item stack to provide details for. * @param stack The item stack to provide details for.
* @param item The item to provide details for. * @param item The item to provide details for.
*/ */
public abstract void provideDetails( @Nonnull Map<? super String, Object> data, @Nonnull ItemStack stack, public abstract void provideDetails(@Nonnull Map<? super String, Object> data, @Nonnull ItemStack stack,
@Nonnull T item ); @Nonnull T item);
@Override @Override
public void provideDetails( @Nonnull Map<? super String, Object> data, @Nonnull ItemStack stack ) public void provideDetails(@Nonnull Map<? super String, Object> data, @Nonnull ItemStack stack) {
{ var item = stack.getItem();
Item item = stack.getItem(); if (!itemType.isInstance(item)) return;
if( !itemType.isInstance( item ) ) return;
// If `namespace` is specified, insert into a new data map instead of the existing one. // If `namespace` is specified, insert into a new data map instead of the existing one.
Map<? super String, Object> child = namespace == null ? data : new HashMap<>(); Map<? super String, Object> child = namespace == null ? data : new HashMap<>();
provideDetails( child, stack, itemType.cast( item ) ); provideDetails(child, stack, itemType.cast(item));
if( namespace != null ) if (namespace != null) {
{ data.put(namespace, child);
data.put( namespace, child );
} }
} }
} }

View File

@ -26,10 +26,8 @@ public record BlockReference(
@Nonnull BlockPos pos, @Nonnull BlockPos pos,
@Nonnull BlockState state, @Nonnull BlockState state,
@Nullable BlockEntity blockEntity @Nullable BlockEntity blockEntity
) ) {
{ public BlockReference(Level level, BlockPos pos) {
public BlockReference( Level level, BlockPos pos ) this(level, pos, level.getBlockState(pos), level.getBlockEntity(pos));
{
this( level, pos, level.getBlockState( pos ), level.getBlockEntity( pos ) );
} }
} }

View File

@ -20,15 +20,14 @@ import java.util.Map;
* @param <T> The type of object that this registry provides details for. * @param <T> The type of object that this registry provides details for.
*/ */
@ApiStatus.NonExtendable @ApiStatus.NonExtendable
public interface DetailRegistry<T> public interface DetailRegistry<T> {
{
/** /**
* Registers a detail provider. * Registers a detail provider.
* *
* @param provider The detail provider to register. * @param provider The detail provider to register.
* @see IDetailProvider * @see IDetailProvider
*/ */
void addProvider( IDetailProvider<T> provider ); void addProvider(IDetailProvider<T> provider);
/** /**
* Compute basic details about an object. This is cheaper than computing all details operation, and so is suitable * Compute basic details about an object. This is cheaper than computing all details operation, and so is suitable
@ -37,7 +36,7 @@ public interface DetailRegistry<T>
* @param object The object to get details for. * @param object The object to get details for.
* @return The basic details. * @return The basic details.
*/ */
Map<String, Object> getBasicDetails( T object ); Map<String, Object> getBasicDetails(T object);
/** /**
* Compute all details about an object, using {@link #getBasicDetails(Object)} and any registered providers. * Compute all details about an object, using {@link #getBasicDetails(Object)} and any registered providers.
@ -45,5 +44,5 @@ public interface DetailRegistry<T>
* @param object The object to get details for. * @param object The object to get details for.
* @return The computed details. * @return The computed details.
*/ */
Map<String, Object> getDetails( T object ); Map<String, Object> getDetails(T object);
} }

View File

@ -11,8 +11,7 @@ import net.minecraftforge.fluids.FluidStack;
/** /**
* {@link DetailRegistry}s for Forge-specific types. * {@link DetailRegistry}s for Forge-specific types.
*/ */
public class ForgeDetailRegistries public class ForgeDetailRegistries {
{
/** /**
* Provides details for {@link FluidStack}. * Provides details for {@link FluidStack}.
*/ */

View File

@ -18,8 +18,7 @@ import java.util.Map;
* @see DetailRegistry * @see DetailRegistry
*/ */
@FunctionalInterface @FunctionalInterface
public interface IDetailProvider<T> public interface IDetailProvider<T> {
{
/** /**
* Provide additional details for the given object. This method is called by functions such as * Provide additional details for the given object. This method is called by functions such as
* {@code turtle.getItemDetail()} and {@code turtle.inspect()}. New properties should be added to the given * {@code turtle.getItemDetail()} and {@code turtle.inspect()}. New properties should be added to the given
@ -31,5 +30,5 @@ public interface IDetailProvider<T>
* @param data The full details to be returned. New properties should be added to this map. * @param data The full details to be returned. New properties should be added to this map.
* @param object The object to provide details for. * @param object The object to provide details for.
*/ */
void provideDetails( @Nonnull Map<? super String, Object> data, @Nonnull T object ); void provideDetails(@Nonnull Map<? super String, Object> data, @Nonnull T object);
} }

View File

@ -12,8 +12,7 @@ import net.minecraft.world.level.block.Block;
/** /**
* {@link DetailRegistry}s for built-in Minecraft types. * {@link DetailRegistry}s for built-in Minecraft types.
*/ */
public class VanillaDetailRegistries public class VanillaDetailRegistries {
{
/** /**
* Provides details for {@link ItemStack}s. * Provides details for {@link ItemStack}s.
*/ */

View File

@ -15,49 +15,41 @@ import java.time.Instant;
* @param isDirectory Whether this filesystem entry is a directory. * @param isDirectory Whether this filesystem entry is a directory.
* @param size The size of the file. * @param size The size of the file.
*/ */
record FileAttributes(boolean isDirectory, long size) implements BasicFileAttributes record FileAttributes(boolean isDirectory, long size) implements BasicFileAttributes {
{ private static final FileTime EPOCH = FileTime.from(Instant.EPOCH);
private static final FileTime EPOCH = FileTime.from( Instant.EPOCH );
@Override @Override
public FileTime lastModifiedTime() public FileTime lastModifiedTime() {
{
return EPOCH; return EPOCH;
} }
@Override @Override
public FileTime lastAccessTime() public FileTime lastAccessTime() {
{
return EPOCH; return EPOCH;
} }
@Override @Override
public FileTime creationTime() public FileTime creationTime() {
{
return EPOCH; return EPOCH;
} }
@Override @Override
public boolean isRegularFile() public boolean isRegularFile() {
{
return !isDirectory; return !isDirectory;
} }
@Override @Override
public boolean isSymbolicLink() public boolean isSymbolicLink() {
{
return false; return false;
} }
@Override @Override
public boolean isOther() public boolean isOther() {
{
return false; return false;
} }
@Override @Override
public Object fileKey() public Object fileKey() {
{
return null; return null;
} }
} }

View File

@ -15,27 +15,23 @@ import java.util.Objects;
* <p> * <p>
* This may be thrown from a {@link IMount} or {@link IWritableMount} to give more information about a failure. * This may be thrown from a {@link IMount} or {@link IWritableMount} to give more information about a failure.
*/ */
public class FileOperationException extends IOException public class FileOperationException extends IOException {
{
private static final long serialVersionUID = -8809108200853029849L; private static final long serialVersionUID = -8809108200853029849L;
private final String filename; private final String filename;
public FileOperationException( @Nullable String filename, @Nonnull String message ) public FileOperationException(@Nullable String filename, @Nonnull String message) {
{ super(Objects.requireNonNull(message, "message cannot be null"));
super( Objects.requireNonNull( message, "message cannot be null" ) );
this.filename = filename; this.filename = filename;
} }
public FileOperationException( @Nonnull String message ) public FileOperationException(@Nonnull String message) {
{ super(Objects.requireNonNull(message, "message cannot be null"));
super( Objects.requireNonNull( message, "message cannot be null" ) );
filename = null; filename = null;
} }
@Nullable @Nullable
public String getFilename() public String getFilename() {
{
return filename; return filename;
} }
} }

View File

@ -12,8 +12,7 @@ import java.io.IOException;
* <p> * <p>
* This exists for use by various APIs - one should not attempt to mount it. * This exists for use by various APIs - one should not attempt to mount it.
*/ */
public interface IFileSystem extends IWritableMount public interface IFileSystem extends IWritableMount {
{
/** /**
* Combine two paths together, reducing them into a normalised form. * Combine two paths together, reducing them into a normalised form.
* *
@ -21,7 +20,7 @@ public interface IFileSystem extends IWritableMount
* @param child The path to append. * @param child The path to append.
* @return The combined, normalised path. * @return The combined, normalised path.
*/ */
String combine( String path, String child ); String combine(String path, String child);
/** /**
* Copy files from one location to another. * Copy files from one location to another.
@ -30,7 +29,7 @@ public interface IFileSystem extends IWritableMount
* @param to The location to copy to. This should not exist. * @param to The location to copy to. This should not exist.
* @throws IOException If the copy failed. * @throws IOException If the copy failed.
*/ */
void copy( String from, String to ) throws IOException; void copy(String from, String to) throws IOException;
/** /**
* Move files from one location to another. * Move files from one location to another.
@ -39,5 +38,5 @@ public interface IFileSystem extends IWritableMount
* @param to The location to move to. This should not exist. * @param to The location to move to. This should not exist.
* @throws IOException If the move failed. * @throws IOException If the move failed.
*/ */
void move( String from, String to ) throws IOException; void move(String from, String to) throws IOException;
} }

View File

@ -28,8 +28,7 @@ import java.util.List;
* @see IComputerAccess#mount(String, IMount) * @see IComputerAccess#mount(String, IMount)
* @see IWritableMount * @see IWritableMount
*/ */
public interface IMount public interface IMount {
{
/** /**
* Returns whether a file with a given path exists or not. * Returns whether a file with a given path exists or not.
* *
@ -37,7 +36,7 @@ public interface IMount
* @return If the file exists. * @return If the file exists.
* @throws IOException If an error occurs when checking the existence of the file. * @throws IOException If an error occurs when checking the existence of the file.
*/ */
boolean exists( @Nonnull String path ) throws IOException; boolean exists(@Nonnull String path) throws IOException;
/** /**
* Returns whether a file with a given path is a directory or not. * Returns whether a file with a given path is a directory or not.
@ -46,7 +45,7 @@ public interface IMount
* @return If the file exists and is a directory * @return If the file exists and is a directory
* @throws IOException If an error occurs when checking whether the file is a directory. * @throws IOException If an error occurs when checking whether the file is a directory.
*/ */
boolean isDirectory( @Nonnull String path ) throws IOException; boolean isDirectory(@Nonnull String path) throws IOException;
/** /**
* Returns the file names of all the files in a directory. * Returns the file names of all the files in a directory.
@ -55,7 +54,7 @@ public interface IMount
* @param contents A list of strings. Add all the file names to this list. * @param contents A list of strings. Add all the file names to this list.
* @throws IOException If the file was not a directory, or could not be listed. * @throws IOException If the file was not a directory, or could not be listed.
*/ */
void list( @Nonnull String path, @Nonnull List<String> contents ) throws IOException; void list(@Nonnull String path, @Nonnull List<String> contents) throws IOException;
/** /**
* Returns the size of a file with a given path, in bytes. * Returns the size of a file with a given path, in bytes.
@ -64,7 +63,7 @@ public interface IMount
* @return The size of the file, in bytes. * @return The size of the file, in bytes.
* @throws IOException If the file does not exist, or its size could not be determined. * @throws IOException If the file does not exist, or its size could not be determined.
*/ */
long getSize( @Nonnull String path ) throws IOException; long getSize(@Nonnull String path) throws IOException;
/** /**
* Opens a file with a given path, and returns an {@link ReadableByteChannel} representing its contents. * Opens a file with a given path, and returns an {@link ReadableByteChannel} representing its contents.
@ -76,7 +75,7 @@ public interface IMount
* @throws IOException If the file does not exist, or could not be opened. * @throws IOException If the file does not exist, or could not be opened.
*/ */
@Nonnull @Nonnull
ReadableByteChannel openForRead( @Nonnull String path ) throws IOException; ReadableByteChannel openForRead(@Nonnull String path) throws IOException;
/** /**
* Get attributes about the given file. * Get attributes about the given file.
@ -86,9 +85,8 @@ public interface IMount
* @throws IOException If the file does not exist, or attributes could not be fetched. * @throws IOException If the file does not exist, or attributes could not be fetched.
*/ */
@Nonnull @Nonnull
default BasicFileAttributes getAttributes( @Nonnull String path ) throws IOException default BasicFileAttributes getAttributes(@Nonnull String path) throws IOException {
{ if (!exists(path)) throw new FileOperationException(path, "No such file");
if( !exists( path ) ) throw new FileOperationException( path, "No such file" ); return new FileAttributes(isDirectory(path), getSize(path));
return new FileAttributes( isDirectory( path ), getSize( path ) );
} }
} }

View File

@ -27,15 +27,14 @@ import java.util.OptionalLong;
* @see IComputerAccess#mountWritable(String, IWritableMount) * @see IComputerAccess#mountWritable(String, IWritableMount)
* @see IMount * @see IMount
*/ */
public interface IWritableMount extends IMount public interface IWritableMount extends IMount {
{
/** /**
* Creates a directory at a given path inside the virtual file system. * Creates a directory at a given path inside the virtual file system.
* *
* @param path A file path in normalised format, relative to the mount location. ie: "programs/mynewprograms". * @param path A file path in normalised format, relative to the mount location. ie: "programs/mynewprograms".
* @throws IOException If the directory already exists or could not be created. * @throws IOException If the directory already exists or could not be created.
*/ */
void makeDirectory( @Nonnull String path ) throws IOException; void makeDirectory(@Nonnull String path) throws IOException;
/** /**
* Deletes a directory at a given path inside the virtual file system. * Deletes a directory at a given path inside the virtual file system.
@ -43,7 +42,7 @@ public interface IWritableMount extends IMount
* @param path A file path in normalised format, relative to the mount location. ie: "programs/myoldprograms". * @param path A file path in normalised format, relative to the mount location. ie: "programs/myoldprograms".
* @throws IOException If the file does not exist or could not be deleted. * @throws IOException If the file does not exist or could not be deleted.
*/ */
void delete( @Nonnull String path ) throws IOException; void delete(@Nonnull String path) throws IOException;
/** /**
* Opens a file with a given path, and returns an {@link OutputStream} for writing to it. * Opens a file with a given path, and returns an {@link OutputStream} for writing to it.
@ -54,7 +53,7 @@ public interface IWritableMount extends IMount
* @throws IOException If the file could not be opened for writing. * @throws IOException If the file could not be opened for writing.
*/ */
@Nonnull @Nonnull
WritableByteChannel openForWrite( @Nonnull String path ) throws IOException; WritableByteChannel openForWrite(@Nonnull String path) throws IOException;
/** /**
* Opens a file with a given path, and returns an {@link OutputStream} for appending to it. * Opens a file with a given path, and returns an {@link OutputStream} for appending to it.
@ -65,7 +64,7 @@ public interface IWritableMount extends IMount
* @throws IOException If the file could not be opened for writing. * @throws IOException If the file could not be opened for writing.
*/ */
@Nonnull @Nonnull
WritableByteChannel openForAppend( @Nonnull String path ) throws IOException; WritableByteChannel openForAppend(@Nonnull String path) throws IOException;
/** /**
* Get the amount of free space on the mount, in bytes. You should decrease this value as the user writes to the * Get the amount of free space on the mount, in bytes. You should decrease this value as the user writes to the
@ -83,8 +82,7 @@ public interface IWritableMount extends IMount
* @return The capacity of this mount, in bytes. * @return The capacity of this mount, in bytes.
*/ */
@Nonnull @Nonnull
default OptionalLong getCapacity() default OptionalLong getCapacity() {
{
return OptionalLong.empty(); return OptionalLong.empty();
} }
} }

View File

@ -46,8 +46,7 @@ import javax.annotation.Nonnull;
* @see ForgeComputerCraftAPI#registerGenericCapability(Capability) New capabilities (those not built into Forge) must be * @see ForgeComputerCraftAPI#registerGenericCapability(Capability) New capabilities (those not built into Forge) must be
* explicitly given to the generic peripheral system, as there is no way to enumerate all capabilities. * explicitly given to the generic peripheral system, as there is no way to enumerate all capabilities.
*/ */
public interface GenericSource public interface GenericSource {
{
/** /**
* A unique identifier for this generic source. * A unique identifier for this generic source.
* <p> * <p>

View File

@ -16,8 +16,7 @@ import static dan200.computercraft.api.lua.LuaValues.checkFinite;
/** /**
* The arguments passed to a function. * The arguments passed to a function.
*/ */
public interface IArguments public interface IArguments {
{
/** /**
* Get the number of arguments passed to this function. * Get the number of arguments passed to this function.
* *
@ -40,7 +39,7 @@ public interface IArguments
* @return The argument's value, or {@code null} if not present. * @return The argument's value, or {@code null} if not present.
*/ */
@Nullable @Nullable
Object get( int index ); Object get(int index);
/** /**
* Drop a number of arguments. The returned arguments instance will access arguments at position {@code i + count}, * Drop a number of arguments. The returned arguments instance will access arguments at position {@code i + count},
@ -49,12 +48,11 @@ public interface IArguments
* @param count The number of arguments to drop. * @param count The number of arguments to drop.
* @return The new {@link IArguments} instance. * @return The new {@link IArguments} instance.
*/ */
IArguments drop( int count ); IArguments drop(int count);
default Object[] getAll() default Object[] getAll() {
{ var result = new Object[count()];
Object[] result = new Object[count()]; for (var i = 0; i < result.length; i++) result[i] = get(i);
for( int i = 0; i < result.length; i++ ) result[i] = get( i );
return result; return result;
} }
@ -66,10 +64,9 @@ public interface IArguments
* @throws LuaException If the value is not a number. * @throws LuaException If the value is not a number.
* @see #getFiniteDouble(int) if you require this to be finite (i.e. not infinite or NaN). * @see #getFiniteDouble(int) if you require this to be finite (i.e. not infinite or NaN).
*/ */
default double getDouble( int index ) throws LuaException default double getDouble(int index) throws LuaException {
{ var value = get(index);
Object value = get( index ); if (!(value instanceof Number number)) throw LuaValues.badArgumentOf(index, "number", value);
if( !(value instanceof Number number) ) throw LuaValues.badArgumentOf( index, "number", value );
return number.doubleValue(); return number.doubleValue();
} }
@ -80,9 +77,8 @@ public interface IArguments
* @return The argument's value. * @return The argument's value.
* @throws LuaException If the value is not an integer. * @throws LuaException If the value is not an integer.
*/ */
default int getInt( int index ) throws LuaException default int getInt(int index) throws LuaException {
{ return (int) getLong(index);
return (int) getLong( index );
} }
/** /**
@ -92,11 +88,10 @@ public interface IArguments
* @return The argument's value. * @return The argument's value.
* @throws LuaException If the value is not a long. * @throws LuaException If the value is not a long.
*/ */
default long getLong( int index ) throws LuaException default long getLong(int index) throws LuaException {
{ var value = get(index);
Object value = get( index ); if (!(value instanceof Number number)) throw LuaValues.badArgumentOf(index, "number", value);
if( !(value instanceof Number number) ) throw LuaValues.badArgumentOf( index, "number", value ); return LuaValues.checkFiniteNum(index, number).longValue();
return LuaValues.checkFiniteNum( index, number ).longValue();
} }
/** /**
@ -106,9 +101,8 @@ public interface IArguments
* @return The argument's value. * @return The argument's value.
* @throws LuaException If the value is not finite. * @throws LuaException If the value is not finite.
*/ */
default double getFiniteDouble( int index ) throws LuaException default double getFiniteDouble(int index) throws LuaException {
{ return checkFinite(index, getDouble(index));
return checkFinite( index, getDouble( index ) );
} }
/** /**
@ -118,10 +112,9 @@ public interface IArguments
* @return The argument's value. * @return The argument's value.
* @throws LuaException If the value is not a boolean. * @throws LuaException If the value is not a boolean.
*/ */
default boolean getBoolean( int index ) throws LuaException default boolean getBoolean(int index) throws LuaException {
{ var value = get(index);
Object value = get( index ); if (!(value instanceof Boolean bool)) throw LuaValues.badArgumentOf(index, "boolean", value);
if( !(value instanceof Boolean bool) ) throw LuaValues.badArgumentOf( index, "boolean", value );
return bool; return bool;
} }
@ -133,10 +126,9 @@ public interface IArguments
* @throws LuaException If the value is not a string. * @throws LuaException If the value is not a string.
*/ */
@Nonnull @Nonnull
default String getString( int index ) throws LuaException default String getString(int index) throws LuaException {
{ var value = get(index);
Object value = get( index ); if (!(value instanceof String string)) throw LuaValues.badArgumentOf(index, "string", value);
if( !(value instanceof String string) ) throw LuaValues.badArgumentOf( index, "string", value );
return string; return string;
} }
@ -148,9 +140,8 @@ public interface IArguments
* @throws LuaException If the value is not a string. * @throws LuaException If the value is not a string.
*/ */
@Nonnull @Nonnull
default ByteBuffer getBytes( int index ) throws LuaException default ByteBuffer getBytes(int index) throws LuaException {
{ return LuaValues.encode(getString(index));
return LuaValues.encode( getString( index ) );
} }
/** /**
@ -163,9 +154,8 @@ public interface IArguments
* @throws LuaException If the value is not a string or not a valid option for this enum. * @throws LuaException If the value is not a string or not a valid option for this enum.
*/ */
@Nonnull @Nonnull
default <T extends Enum<T>> T getEnum( int index, Class<T> klass ) throws LuaException default <T extends Enum<T>> T getEnum(int index, Class<T> klass) throws LuaException {
{ return LuaValues.checkEnum(index, klass, getString(index));
return LuaValues.checkEnum( index, klass, getString( index ) );
} }
/** /**
@ -176,10 +166,9 @@ public interface IArguments
* @throws LuaException If the value is not a table. * @throws LuaException If the value is not a table.
*/ */
@Nonnull @Nonnull
default Map<?, ?> getTable( int index ) throws LuaException default Map<?, ?> getTable(int index) throws LuaException {
{ var value = get(index);
Object value = get( index ); if (!(value instanceof Map)) throw LuaValues.badArgumentOf(index, "table", value);
if( !(value instanceof Map) ) throw LuaValues.badArgumentOf( index, "table", value );
return (Map<?, ?>) value; return (Map<?, ?>) value;
} }
@ -196,9 +185,8 @@ public interface IArguments
* @throws LuaException If the value is not a table. * @throws LuaException If the value is not a table.
*/ */
@Nonnull @Nonnull
default LuaTable<?, ?> getTableUnsafe( int index ) throws LuaException default LuaTable<?, ?> getTableUnsafe(int index) throws LuaException {
{ return new ObjectLuaTable(getTable(index));
return new ObjectLuaTable( getTable( index ) );
} }
/** /**
@ -209,12 +197,11 @@ public interface IArguments
* @throws LuaException If the value is not a number. * @throws LuaException If the value is not a number.
*/ */
@Nonnull @Nonnull
default Optional<Double> optDouble( int index ) throws LuaException default Optional<Double> optDouble(int index) throws LuaException {
{ var value = get(index);
Object value = get( index ); if (value == null) return Optional.empty();
if( value == null ) return Optional.empty(); if (!(value instanceof Number number)) throw LuaValues.badArgumentOf(index, "number", value);
if( !(value instanceof Number number) ) throw LuaValues.badArgumentOf( index, "number", value ); return Optional.of(number.doubleValue());
return Optional.of( number.doubleValue() );
} }
/** /**
@ -225,9 +212,8 @@ public interface IArguments
* @throws LuaException If the value is not a number. * @throws LuaException If the value is not a number.
*/ */
@Nonnull @Nonnull
default Optional<Integer> optInt( int index ) throws LuaException default Optional<Integer> optInt(int index) throws LuaException {
{ return optLong(index).map(Long::intValue);
return optLong( index ).map( Long::intValue );
} }
/** /**
@ -237,12 +223,11 @@ public interface IArguments
* @return The argument's value, or {@link Optional#empty()} if not present. * @return The argument's value, or {@link Optional#empty()} if not present.
* @throws LuaException If the value is not a number. * @throws LuaException If the value is not a number.
*/ */
default Optional<Long> optLong( int index ) throws LuaException default Optional<Long> optLong(int index) throws LuaException {
{ var value = get(index);
Object value = get( index ); if (value == null) return Optional.empty();
if( value == null ) return Optional.empty(); if (!(value instanceof Number number)) throw LuaValues.badArgumentOf(index, "number", value);
if( !(value instanceof Number number) ) throw LuaValues.badArgumentOf( index, "number", value ); return Optional.of(LuaValues.checkFiniteNum(index, number).longValue());
return Optional.of( LuaValues.checkFiniteNum( index, number ).longValue() );
} }
/** /**
@ -252,10 +237,9 @@ public interface IArguments
* @return The argument's value, or {@link Optional#empty()} if not present. * @return The argument's value, or {@link Optional#empty()} if not present.
* @throws LuaException If the value is not finite. * @throws LuaException If the value is not finite.
*/ */
default Optional<Double> optFiniteDouble( int index ) throws LuaException default Optional<Double> optFiniteDouble(int index) throws LuaException {
{ var value = optDouble(index);
Optional<Double> value = optDouble( index ); if (value.isPresent()) LuaValues.checkFiniteNum(index, value.get());
if( value.isPresent() ) LuaValues.checkFiniteNum( index, value.get() );
return value; return value;
} }
@ -266,12 +250,11 @@ public interface IArguments
* @return The argument's value, or {@link Optional#empty()} if not present. * @return The argument's value, or {@link Optional#empty()} if not present.
* @throws LuaException If the value is not a boolean. * @throws LuaException If the value is not a boolean.
*/ */
default Optional<Boolean> optBoolean( int index ) throws LuaException default Optional<Boolean> optBoolean(int index) throws LuaException {
{ var value = get(index);
Object value = get( index ); if (value == null) return Optional.empty();
if( value == null ) return Optional.empty(); if (!(value instanceof Boolean bool)) throw LuaValues.badArgumentOf(index, "boolean", value);
if( !(value instanceof Boolean bool) ) throw LuaValues.badArgumentOf( index, "boolean", value ); return Optional.of(bool);
return Optional.of( bool );
} }
/** /**
@ -281,12 +264,11 @@ public interface IArguments
* @return The argument's value, or {@link Optional#empty()} if not present. * @return The argument's value, or {@link Optional#empty()} if not present.
* @throws LuaException If the value is not a string. * @throws LuaException If the value is not a string.
*/ */
default Optional<String> optString( int index ) throws LuaException default Optional<String> optString(int index) throws LuaException {
{ var value = get(index);
Object value = get( index ); if (value == null) return Optional.empty();
if( value == null ) return Optional.empty(); if (!(value instanceof String string)) throw LuaValues.badArgumentOf(index, "string", value);
if( !(value instanceof String string) ) throw LuaValues.badArgumentOf( index, "string", value ); return Optional.of(string);
return Optional.of( string );
} }
/** /**
@ -296,9 +278,8 @@ public interface IArguments
* @return The argument's value, or {@link Optional#empty()} if not present. This is a <em>read only</em> buffer. * @return The argument's value, or {@link Optional#empty()} if not present. This is a <em>read only</em> buffer.
* @throws LuaException If the value is not a string. * @throws LuaException If the value is not a string.
*/ */
default Optional<ByteBuffer> optBytes( int index ) throws LuaException default Optional<ByteBuffer> optBytes(int index) throws LuaException {
{ return optString(index).map(LuaValues::encode);
return optString( index ).map( LuaValues::encode );
} }
/** /**
@ -311,10 +292,9 @@ public interface IArguments
* @throws LuaException If the value is not a string or not a valid option for this enum. * @throws LuaException If the value is not a string or not a valid option for this enum.
*/ */
@Nonnull @Nonnull
default <T extends Enum<T>> Optional<T> optEnum( int index, Class<T> klass ) throws LuaException default <T extends Enum<T>> Optional<T> optEnum(int index, Class<T> klass) throws LuaException {
{ var str = optString(index);
Optional<String> str = optString( index ); return str.isPresent() ? Optional.of(LuaValues.checkEnum(index, klass, str.get())) : Optional.empty();
return str.isPresent() ? Optional.of( LuaValues.checkEnum( index, klass, str.get() ) ) : Optional.empty();
} }
/** /**
@ -324,12 +304,11 @@ public interface IArguments
* @return The argument's value, or {@link Optional#empty()} if not present. * @return The argument's value, or {@link Optional#empty()} if not present.
* @throws LuaException If the value is not a table. * @throws LuaException If the value is not a table.
*/ */
default Optional<Map<?, ?>> optTable( int index ) throws LuaException default Optional<Map<?, ?>> optTable(int index) throws LuaException {
{ var value = get(index);
Object value = get( index ); if (value == null) return Optional.empty();
if( value == null ) return Optional.empty(); if (!(value instanceof Map)) throw LuaValues.badArgumentOf(index, "map", value);
if( !(value instanceof Map) ) throw LuaValues.badArgumentOf( index, "map", value ); return Optional.of((Map<?, ?>) value);
return Optional.of( (Map<?, ?>) value );
} }
/** /**
@ -345,12 +324,11 @@ public interface IArguments
* @throws LuaException If the value is not a table. * @throws LuaException If the value is not a table.
*/ */
@Nonnull @Nonnull
default Optional<LuaTable<?, ?>> optTableUnsafe( int index ) throws LuaException default Optional<LuaTable<?, ?>> optTableUnsafe(int index) throws LuaException {
{ var value = get(index);
Object value = get( index ); if (value == null) return Optional.empty();
if( value == null ) return Optional.empty(); if (!(value instanceof Map)) throw LuaValues.badArgumentOf(index, "map", value);
if( !(value instanceof Map) ) throw LuaValues.badArgumentOf( index, "map", value ); return Optional.of(new ObjectLuaTable((Map<?, ?>) value));
return Optional.of( new ObjectLuaTable( (Map<?, ?>) value ) );
} }
/** /**
@ -361,9 +339,8 @@ public interface IArguments
* @return The argument's value, or {@code def} if none was provided. * @return The argument's value, or {@code def} if none was provided.
* @throws LuaException If the value is not a number. * @throws LuaException If the value is not a number.
*/ */
default double optDouble( int index, double def ) throws LuaException default double optDouble(int index, double def) throws LuaException {
{ return optDouble(index).orElse(def);
return optDouble( index ).orElse( def );
} }
/** /**
@ -374,9 +351,8 @@ public interface IArguments
* @return The argument's value, or {@code def} if none was provided. * @return The argument's value, or {@code def} if none was provided.
* @throws LuaException If the value is not a number. * @throws LuaException If the value is not a number.
*/ */
default int optInt( int index, int def ) throws LuaException default int optInt(int index, int def) throws LuaException {
{ return optInt(index).orElse(def);
return optInt( index ).orElse( def );
} }
/** /**
@ -387,9 +363,8 @@ public interface IArguments
* @return The argument's value, or {@code def} if none was provided. * @return The argument's value, or {@code def} if none was provided.
* @throws LuaException If the value is not a number. * @throws LuaException If the value is not a number.
*/ */
default long optLong( int index, long def ) throws LuaException default long optLong(int index, long def) throws LuaException {
{ return optLong(index).orElse(def);
return optLong( index ).orElse( def );
} }
/** /**
@ -400,9 +375,8 @@ public interface IArguments
* @return The argument's value, or {@code def} if none was provided. * @return The argument's value, or {@code def} if none was provided.
* @throws LuaException If the value is not finite. * @throws LuaException If the value is not finite.
*/ */
default double optFiniteDouble( int index, double def ) throws LuaException default double optFiniteDouble(int index, double def) throws LuaException {
{ return optFiniteDouble(index).orElse(def);
return optFiniteDouble( index ).orElse( def );
} }
/** /**
@ -413,9 +387,8 @@ public interface IArguments
* @return The argument's value, or {@code def} if none was provided. * @return The argument's value, or {@code def} if none was provided.
* @throws LuaException If the value is not a boolean. * @throws LuaException If the value is not a boolean.
*/ */
default boolean optBoolean( int index, boolean def ) throws LuaException default boolean optBoolean(int index, boolean def) throws LuaException {
{ return optBoolean(index).orElse(def);
return optBoolean( index ).orElse( def );
} }
/** /**
@ -426,9 +399,8 @@ public interface IArguments
* @return The argument's value, or {@code def} if none was provided. * @return The argument's value, or {@code def} if none was provided.
* @throws LuaException If the value is not a string. * @throws LuaException If the value is not a string.
*/ */
default String optString( int index, String def ) throws LuaException default String optString(int index, String def) throws LuaException {
{ return optString(index).orElse(def);
return optString( index ).orElse( def );
} }
/** /**
@ -439,8 +411,7 @@ public interface IArguments
* @return The argument's value, or {@code def} if none was provided. * @return The argument's value, or {@code def} if none was provided.
* @throws LuaException If the value is not a table. * @throws LuaException If the value is not a table.
*/ */
default Map<?, ?> optTable( int index, Map<Object, Object> def ) throws LuaException default Map<?, ?> optTable(int index, Map<Object, Object> def) throws LuaException {
{ return optTable(index).orElse(def);
return optTable( index ).orElse( def );
} }
} }

View File

@ -14,8 +14,7 @@ import javax.annotation.Nullable;
* An interface passed to {@link ILuaAPIFactory} in order to provide additional information * An interface passed to {@link ILuaAPIFactory} in order to provide additional information
* about a computer. * about a computer.
*/ */
public interface IComputerSystem extends IComputerAccess public interface IComputerSystem extends IComputerAccess {
{
/** /**
* Get the file system for this computer. * Get the file system for this computer.
* *

View File

@ -16,8 +16,7 @@ import javax.annotation.Nonnull;
* annotated with {@link LuaFunction}. {@link IDynamicLuaObject} is useful when you wish your available methods to * annotated with {@link LuaFunction}. {@link IDynamicLuaObject} is useful when you wish your available methods to
* change at runtime. * change at runtime.
*/ */
public interface IDynamicLuaObject public interface IDynamicLuaObject {
{
/** /**
* Get the names of the methods that this object implements. This should not change over the course of the object's * Get the names of the methods that this object implements. This should not change over the course of the object's
* lifetime. * lifetime.
@ -41,5 +40,5 @@ public interface IDynamicLuaObject
* @throws LuaException If the function threw an exception. * @throws LuaException If the function threw an exception.
*/ */
@Nonnull @Nonnull
MethodResult callMethod( @Nonnull ILuaContext context, int method, @Nonnull IArguments arguments ) throws LuaException; MethodResult callMethod(@Nonnull ILuaContext context, int method, @Nonnull IArguments arguments) throws LuaException;
} }

View File

@ -17,8 +17,7 @@ import dan200.computercraft.api.ComputerCraftAPI;
* @see ILuaAPIFactory * @see ILuaAPIFactory
* @see ComputerCraftAPI#registerAPIFactory(ILuaAPIFactory) * @see ComputerCraftAPI#registerAPIFactory(ILuaAPIFactory)
*/ */
public interface ILuaAPI public interface ILuaAPI {
{
/** /**
* Get the globals this API will be assigned to. This will override any other global, so you should * Get the globals this API will be assigned to. This will override any other global, so you should
* *
@ -31,15 +30,13 @@ public interface ILuaAPI
* <p> * <p>
* One should only interact with the file system. * One should only interact with the file system.
*/ */
default void startup() default void startup() {
{
} }
/** /**
* Called every time the computer is ticked. This can be used to process various. * Called every time the computer is ticked. This can be used to process various.
*/ */
default void update() default void update() {
{
} }
/** /**
@ -47,7 +44,6 @@ public interface ILuaAPI
* <p> * <p>
* This should reset the state of the object, disposing any remaining file handles, or other resources. * This should reset the state of the object, disposing any remaining file handles, or other resources.
*/ */
default void shutdown() default void shutdown() {
{
} }
} }

View File

@ -17,8 +17,7 @@ import javax.annotation.Nullable;
* @see ComputerCraftAPI#registerAPIFactory(ILuaAPIFactory) * @see ComputerCraftAPI#registerAPIFactory(ILuaAPIFactory)
*/ */
@FunctionalInterface @FunctionalInterface
public interface ILuaAPIFactory public interface ILuaAPIFactory {
{
/** /**
* Create a new API instance for a given computer. * Create a new API instance for a given computer.
* *
@ -26,5 +25,5 @@ public interface ILuaAPIFactory
* @return The created API, or {@code null} if one should not be injected. * @return The created API, or {@code null} if one should not be injected.
*/ */
@Nullable @Nullable
ILuaAPI create( @Nonnull IComputerSystem computer ); ILuaAPI create(@Nonnull IComputerSystem computer);
} }

View File

@ -12,8 +12,7 @@ import javax.annotation.Nonnull;
* *
* @see MethodResult#yield(Object[], ILuaCallback) * @see MethodResult#yield(Object[], ILuaCallback)
*/ */
public interface ILuaCallback public interface ILuaCallback {
{
/** /**
* Resume this coroutine. * Resume this coroutine.
* *
@ -23,5 +22,5 @@ public interface ILuaCallback
* @throws LuaException On an error. * @throws LuaException On an error.
*/ */
@Nonnull @Nonnull
MethodResult resume( Object[] args ) throws LuaException; MethodResult resume(Object[] args) throws LuaException;
} }

View File

@ -11,8 +11,7 @@ import javax.annotation.Nonnull;
* An interface passed to peripherals and {@link IDynamicLuaObject}s by computers or turtles, providing methods * An interface passed to peripherals and {@link IDynamicLuaObject}s by computers or turtles, providing methods
* that allow the peripheral call to interface with the computer. * that allow the peripheral call to interface with the computer.
*/ */
public interface ILuaContext public interface ILuaContext {
{
/** /**
* Queue a task to be executed on the main server thread at the beginning of next tick, but do not wait for it to * Queue a task to be executed on the main server thread at the beginning of next tick, but do not wait for it to
* complete. This should be used when you need to interact with the world in a thread-safe manner but do not care * complete. This should be used when you need to interact with the world in a thread-safe manner but do not care
@ -26,7 +25,7 @@ public interface ILuaContext
* @throws LuaException If the task could not be queued. * @throws LuaException If the task could not be queued.
* @see LuaFunction#mainThread() To run functions on the main thread and return their results synchronously. * @see LuaFunction#mainThread() To run functions on the main thread and return their results synchronously.
*/ */
long issueMainThreadTask( @Nonnull ILuaTask task ) throws LuaException; long issueMainThreadTask(@Nonnull ILuaTask task) throws LuaException;
/** /**
* Queue a task to be executed on the main server thread at the beginning of next tick, waiting for it to complete. * Queue a task to be executed on the main server thread at the beginning of next tick, waiting for it to complete.
@ -40,8 +39,7 @@ public interface ILuaContext
* @throws LuaException If the task could not be queued, or if the task threw an exception. * @throws LuaException If the task could not be queued, or if the task threw an exception.
*/ */
@Nonnull @Nonnull
default MethodResult executeMainThreadTask( @Nonnull ILuaTask task ) throws LuaException default MethodResult executeMainThreadTask(@Nonnull ILuaTask task) throws LuaException {
{ return TaskCallback.make(this, task);
return TaskCallback.make( this, task );
} }
} }

View File

@ -14,8 +14,7 @@ import javax.annotation.Nonnull;
* @see MethodResult#of(Object) * @see MethodResult#of(Object)
*/ */
@FunctionalInterface @FunctionalInterface
public interface ILuaFunction public interface ILuaFunction {
{
/** /**
* Call this function with a series of arguments. Note, this will <em>always</em> be called on the computer thread, * Call this function with a series of arguments. Note, this will <em>always</em> be called on the computer thread,
* and so its implementation must be thread-safe. * and so its implementation must be thread-safe.
@ -25,5 +24,5 @@ public interface ILuaFunction
* @throws LuaException Upon Lua errors. * @throws LuaException Upon Lua errors.
*/ */
@Nonnull @Nonnull
MethodResult call( @Nonnull IArguments arguments ) throws LuaException; MethodResult call(@Nonnull IArguments arguments) throws LuaException;
} }

View File

@ -15,8 +15,7 @@ import javax.annotation.Nullable;
* @see ILuaContext#issueMainThreadTask(ILuaTask) * @see ILuaContext#issueMainThreadTask(ILuaTask)
*/ */
@FunctionalInterface @FunctionalInterface
public interface ILuaTask public interface ILuaTask {
{
/** /**
* Execute this task. * Execute this task.
* *

View File

@ -10,22 +10,19 @@ import javax.annotation.Nullable;
/** /**
* An exception representing an error in Lua, like that raised by the {@code error()} function. * An exception representing an error in Lua, like that raised by the {@code error()} function.
*/ */
public class LuaException extends Exception public class LuaException extends Exception {
{
private static final long serialVersionUID = -6136063076818512651L; private static final long serialVersionUID = -6136063076818512651L;
private final boolean hasLevel; private final boolean hasLevel;
private final int level; private final int level;
public LuaException( @Nullable String message ) public LuaException(@Nullable String message) {
{ super(message);
super( message );
hasLevel = false; hasLevel = false;
level = 1; level = 1;
} }
public LuaException( @Nullable String message, int level ) public LuaException(@Nullable String message, int level) {
{ super(message);
super( message );
hasLevel = true; hasLevel = true;
this.level = level; this.level = level;
} }
@ -35,8 +32,7 @@ public class LuaException extends Exception
* *
* @return Whether this has an explicit level. * @return Whether this has an explicit level.
*/ */
public boolean hasLevel() public boolean hasLevel() {
{
return hasLevel; return hasLevel;
} }
@ -46,8 +42,7 @@ public class LuaException extends Exception
* *
* @return The level to raise the error at. * @return The level to raise the error at.
*/ */
public int getLevel() public int getLevel() {
{
return level; return level;
} }
} }

View File

@ -36,10 +36,9 @@ import java.util.Optional;
* {@link MethodResult#of(Object...)}. * {@link MethodResult#of(Object...)}.
*/ */
@Documented @Documented
@Retention( RetentionPolicy.RUNTIME ) @Retention(RetentionPolicy.RUNTIME)
@Target( ElementType.METHOD ) @Target(ElementType.METHOD)
public @interface LuaFunction public @interface LuaFunction {
{
/** /**
* Explicitly specify the method names of this function. If not given, it uses the name of the annotated method. * Explicitly specify the method names of this function. If not given, it uses the name of the annotated method.
* *

View File

@ -11,17 +11,15 @@ import java.util.Map;
import static dan200.computercraft.api.lua.LuaValues.*; import static dan200.computercraft.api.lua.LuaValues.*;
public interface LuaTable<K, V> extends Map<K, V> public interface LuaTable<K, V> extends Map<K, V> {
{
/** /**
* Compute the length of the array part of this table. * Compute the length of the array part of this table.
* *
* @return This table's length. * @return This table's length.
*/ */
default int length() default int length() {
{ var size = 0;
int size = 0; while (containsKey((double) (size + 1))) size++;
while( containsKey( (double) (size + 1) ) ) size++;
return size; return size;
} }
@ -32,13 +30,12 @@ public interface LuaTable<K, V> extends Map<K, V>
* @return The table's value. * @return The table's value.
* @throws LuaException If the value is not an integer. * @throws LuaException If the value is not an integer.
*/ */
default long getLong( int index ) throws LuaException default long getLong(int index) throws LuaException {
{ Object value = get((double) index);
Object value = get( (double) index ); if (!(value instanceof Number number)) throw badTableItem(index, "number", getType(value));
if( !(value instanceof Number number) ) throw badTableItem( index, "number", getType( value ) );
double asDouble = number.doubleValue(); var asDouble = number.doubleValue();
if( !Double.isFinite( asDouble ) ) throw badTableItem( index, "number", getNumericType( asDouble ) ); if (!Double.isFinite(asDouble)) throw badTableItem(index, "number", getNumericType(asDouble));
return number.longValue(); return number.longValue();
} }
@ -49,13 +46,12 @@ public interface LuaTable<K, V> extends Map<K, V>
* @return The table's value. * @return The table's value.
* @throws LuaException If the value is not an integer. * @throws LuaException If the value is not an integer.
*/ */
default long getLong( String key ) throws LuaException default long getLong(String key) throws LuaException {
{ Object value = get(key);
Object value = get( key ); if (!(value instanceof Number number)) throw badField(key, "number", getType(value));
if( !(value instanceof Number number) ) throw badField( key, "number", getType( value ) );
double asDouble = number.doubleValue(); var asDouble = number.doubleValue();
if( !Double.isFinite( asDouble ) ) throw badField( key, "number", getNumericType( asDouble ) ); if (!Double.isFinite(asDouble)) throw badField(key, "number", getNumericType(asDouble));
return number.longValue(); return number.longValue();
} }
@ -66,9 +62,8 @@ public interface LuaTable<K, V> extends Map<K, V>
* @return The table's value. * @return The table's value.
* @throws LuaException If the value is not an integer. * @throws LuaException If the value is not an integer.
*/ */
default int getInt( int index ) throws LuaException default int getInt(int index) throws LuaException {
{ return (int) getLong(index);
return (int) getLong( index );
} }
/** /**
@ -78,34 +73,29 @@ public interface LuaTable<K, V> extends Map<K, V>
* @return The table's value. * @return The table's value.
* @throws LuaException If the value is not an integer. * @throws LuaException If the value is not an integer.
*/ */
default int getInt( String key ) throws LuaException default int getInt(String key) throws LuaException {
{ return (int) getLong(key);
return (int) getLong( key );
} }
@Nullable @Nullable
@Override @Override
default V put( K o, V o2 ) default V put(K o, V o2) {
{ throw new UnsupportedOperationException("Cannot modify LuaTable");
throw new UnsupportedOperationException( "Cannot modify LuaTable" );
} }
@Override @Override
default V remove( Object o ) default V remove(Object o) {
{ throw new UnsupportedOperationException("Cannot modify LuaTable");
throw new UnsupportedOperationException( "Cannot modify LuaTable" );
} }
@Override @Override
default void putAll( @Nonnull Map<? extends K, ? extends V> map ) default void putAll(@Nonnull Map<? extends K, ? extends V> map) {
{ throw new UnsupportedOperationException("Cannot modify LuaTable");
throw new UnsupportedOperationException( "Cannot modify LuaTable" );
} }
@Override @Override
default void clear() default void clear() {
{ throw new UnsupportedOperationException("Cannot modify LuaTable");
throw new UnsupportedOperationException( "Cannot modify LuaTable" );
} }
} }

View File

@ -15,10 +15,8 @@ import java.util.Map;
* *
* @see IArguments * @see IArguments
*/ */
public final class LuaValues public final class LuaValues {
{ private LuaValues() {
private LuaValues()
{
} }
/** /**
@ -28,16 +26,14 @@ public final class LuaValues
* @return The encoded string. * @return The encoded string.
*/ */
@Nonnull @Nonnull
public static ByteBuffer encode( @Nonnull String string ) public static ByteBuffer encode(@Nonnull String string) {
{ var chars = new byte[string.length()];
byte[] chars = new byte[string.length()]; for (var i = 0; i < chars.length; i++) {
for( int i = 0; i < chars.length; i++ ) var c = string.charAt(i);
{
char c = string.charAt( i );
chars[i] = c < 256 ? (byte) c : 63; chars[i] = c < 256 ? (byte) c : 63;
} }
return ByteBuffer.wrap( chars ).asReadOnlyBuffer(); return ByteBuffer.wrap(chars).asReadOnlyBuffer();
} }
/** /**
@ -48,11 +44,10 @@ public final class LuaValues
* @return This value's numeric type. * @return This value's numeric type.
*/ */
@Nonnull @Nonnull
public static String getNumericType( double value ) public static String getNumericType(double value) {
{ if (Double.isNaN(value)) return "nan";
if( Double.isNaN( value ) ) return "nan"; if (value == Double.POSITIVE_INFINITY) return "inf";
if( value == Double.POSITIVE_INFINITY ) return "inf"; if (value == Double.NEGATIVE_INFINITY) return "-inf";
if( value == Double.NEGATIVE_INFINITY ) return "-inf";
return "number"; return "number";
} }
@ -64,13 +59,12 @@ public final class LuaValues
* {@code type} function. * {@code type} function.
*/ */
@Nonnull @Nonnull
public static String getType( @Nullable Object value ) public static String getType(@Nullable Object value) {
{ if (value == null) return "nil";
if( value == null ) return "nil"; if (value instanceof String) return "string";
if( value instanceof String ) return "string"; if (value instanceof Boolean) return "boolean";
if( value instanceof Boolean ) return "boolean"; if (value instanceof Number) return "number";
if( value instanceof Number ) return "number"; if (value instanceof Map) return "table";
if( value instanceof Map ) return "table";
return "userdata"; return "userdata";
} }
@ -83,9 +77,8 @@ public final class LuaValues
* @return The constructed exception, which should be thrown immediately. * @return The constructed exception, which should be thrown immediately.
*/ */
@Nonnull @Nonnull
public static LuaException badArgumentOf( int index, @Nonnull String expected, @Nullable Object actual ) public static LuaException badArgumentOf(int index, @Nonnull String expected, @Nullable Object actual) {
{ return badArgument(index, expected, getType(actual));
return badArgument( index, expected, getType( actual ) );
} }
/** /**
@ -97,9 +90,8 @@ public final class LuaValues
* @return The constructed exception, which should be thrown immediately. * @return The constructed exception, which should be thrown immediately.
*/ */
@Nonnull @Nonnull
public static LuaException badArgument( int index, @Nonnull String expected, @Nonnull String actual ) public static LuaException badArgument(int index, @Nonnull String expected, @Nonnull String actual) {
{ return new LuaException("bad argument #" + (index + 1) + " (" + expected + " expected, got " + actual + ")");
return new LuaException( "bad argument #" + (index + 1) + " (" + expected + " expected, got " + actual + ")" );
} }
/** /**
@ -111,9 +103,8 @@ public final class LuaValues
* @return The constructed exception, which should be thrown immediately. * @return The constructed exception, which should be thrown immediately.
*/ */
@Nonnull @Nonnull
public static LuaException badTableItem( int index, @Nonnull String expected, @Nonnull String actual ) public static LuaException badTableItem(int index, @Nonnull String expected, @Nonnull String actual) {
{ return new LuaException("table item #" + index + " is not " + expected + " (got " + actual + ")");
return new LuaException( "table item #" + index + " is not " + expected + " (got " + actual + ")" );
} }
/** /**
@ -125,9 +116,8 @@ public final class LuaValues
* @return The constructed exception, which should be thrown immediately. * @return The constructed exception, which should be thrown immediately.
*/ */
@Nonnull @Nonnull
public static LuaException badField( String key, @Nonnull String expected, @Nonnull String actual ) public static LuaException badField(String key, @Nonnull String expected, @Nonnull String actual) {
{ return new LuaException("field " + key + " is not " + expected + " (got " + actual + ")");
return new LuaException( "field " + key + " is not " + expected + " (got " + actual + ")" );
} }
/** /**
@ -138,9 +128,8 @@ public final class LuaValues
* @return The input {@code value}. * @return The input {@code value}.
* @throws LuaException If this is not a finite number. * @throws LuaException If this is not a finite number.
*/ */
public static Number checkFiniteNum( int index, Number value ) throws LuaException public static Number checkFiniteNum(int index, Number value) throws LuaException {
{ checkFinite(index, value.doubleValue());
checkFinite( index, value.doubleValue() );
return value; return value;
} }
@ -152,9 +141,8 @@ public final class LuaValues
* @return The input {@code value}. * @return The input {@code value}.
* @throws LuaException If this is not a finite number. * @throws LuaException If this is not a finite number.
*/ */
public static double checkFinite( int index, double value ) throws LuaException public static double checkFinite(int index, double value) throws LuaException {
{ if (!Double.isFinite(value)) throw badArgument(index, "number", getNumericType(value));
if( !Double.isFinite( value ) ) throw badArgument( index, "number", getNumericType( value ) );
return value; return value;
} }
@ -168,13 +156,11 @@ public final class LuaValues
* @return The parsed enum value. * @return The parsed enum value.
* @throws LuaException If this is not a known enum value. * @throws LuaException If this is not a known enum value.
*/ */
public static <T extends Enum<T>> T checkEnum( int index, Class<T> klass, String value ) throws LuaException public static <T extends Enum<T>> T checkEnum(int index, Class<T> klass, String value) throws LuaException {
{ for (var possibility : klass.getEnumConstants()) {
for( T possibility : klass.getEnumConstants() ) if (possibility.name().equalsIgnoreCase(value)) return possibility;
{
if( possibility.name().equalsIgnoreCase( value ) ) return possibility;
} }
throw new LuaException( "bad argument #" + (index + 1) + " (unknown option " + value + ")" ); throw new LuaException("bad argument #" + (index + 1) + " (unknown option " + value + ")");
} }
} }

View File

@ -20,23 +20,20 @@ import java.util.Objects;
* Method results either return a value immediately ({@link #of(Object...)} or yield control to the parent coroutine. * Method results either return a value immediately ({@link #of(Object...)} or yield control to the parent coroutine.
* When the current coroutine is resumed, we invoke the provided {@link ILuaCallback#resume(Object[])} callback. * When the current coroutine is resumed, we invoke the provided {@link ILuaCallback#resume(Object[])} callback.
*/ */
public final class MethodResult public final class MethodResult {
{ private static final MethodResult empty = new MethodResult(null, null);
private static final MethodResult empty = new MethodResult( null, null );
private final Object[] result; private final Object[] result;
private final ILuaCallback callback; private final ILuaCallback callback;
private final int adjust; private final int adjust;
private MethodResult( Object[] arguments, ILuaCallback callback ) private MethodResult(Object[] arguments, ILuaCallback callback) {
{
result = arguments; result = arguments;
this.callback = callback; this.callback = callback;
adjust = 0; adjust = 0;
} }
private MethodResult( Object[] arguments, ILuaCallback callback, int adjust ) private MethodResult(Object[] arguments, ILuaCallback callback, int adjust) {
{
result = arguments; result = arguments;
this.callback = callback; this.callback = callback;
this.adjust = adjust; this.adjust = adjust;
@ -48,8 +45,7 @@ public final class MethodResult
* @return A method result which returns immediately with no values. * @return A method result which returns immediately with no values.
*/ */
@Nonnull @Nonnull
public static MethodResult of() public static MethodResult of() {
{
return empty; return empty;
} }
@ -67,9 +63,8 @@ public final class MethodResult
* @return A method result which returns immediately with the given value. * @return A method result which returns immediately with the given value.
*/ */
@Nonnull @Nonnull
public static MethodResult of( @Nullable Object value ) public static MethodResult of(@Nullable Object value) {
{ return new MethodResult(new Object[]{ value }, null);
return new MethodResult( new Object[] { value }, null );
} }
/** /**
@ -79,9 +74,8 @@ public final class MethodResult
* @return A method result which returns immediately with the given values. * @return A method result which returns immediately with the given values.
*/ */
@Nonnull @Nonnull
public static MethodResult of( @Nullable Object... values ) public static MethodResult of(@Nullable Object... values) {
{ return values == null || values.length == 0 ? empty : new MethodResult(values, null);
return values == null || values.length == 0 ? empty : new MethodResult( values, null );
} }
/** /**
@ -94,16 +88,14 @@ public final class MethodResult
* @see IComputerAccess#queueEvent(String, Object[]) * @see IComputerAccess#queueEvent(String, Object[])
*/ */
@Nonnull @Nonnull
public static MethodResult pullEvent( @Nullable String filter, @Nonnull ILuaCallback callback ) public static MethodResult pullEvent(@Nullable String filter, @Nonnull ILuaCallback callback) {
{ Objects.requireNonNull(callback, "callback cannot be null");
Objects.requireNonNull( callback, "callback cannot be null" ); return new MethodResult(new Object[]{ filter }, results -> {
return new MethodResult( new Object[] { filter }, results -> { if (results.length >= 1 && Objects.equals(results[0], "terminate")) {
if( results.length >= 1 && Objects.equals( results[0], "terminate" ) ) throw new LuaException("Terminated", 0);
{
throw new LuaException( "Terminated", 0 );
} }
return callback.resume( results ); return callback.resume(results);
} ); });
} }
/** /**
@ -117,10 +109,9 @@ public final class MethodResult
* @see #pullEvent(String, ILuaCallback) * @see #pullEvent(String, ILuaCallback)
*/ */
@Nonnull @Nonnull
public static MethodResult pullEventRaw( @Nullable String filter, @Nonnull ILuaCallback callback ) public static MethodResult pullEventRaw(@Nullable String filter, @Nonnull ILuaCallback callback) {
{ Objects.requireNonNull(callback, "callback cannot be null");
Objects.requireNonNull( callback, "callback cannot be null" ); return new MethodResult(new Object[]{ filter }, callback);
return new MethodResult( new Object[] { filter }, callback );
} }
/** /**
@ -133,26 +124,22 @@ public final class MethodResult
* @see #pullEvent(String, ILuaCallback) * @see #pullEvent(String, ILuaCallback)
*/ */
@Nonnull @Nonnull
public static MethodResult yield( @Nullable Object[] arguments, @Nonnull ILuaCallback callback ) public static MethodResult yield(@Nullable Object[] arguments, @Nonnull ILuaCallback callback) {
{ Objects.requireNonNull(callback, "callback cannot be null");
Objects.requireNonNull( callback, "callback cannot be null" ); return new MethodResult(arguments, callback);
return new MethodResult( arguments, callback );
} }
@Nullable @Nullable
public Object[] getResult() public Object[] getResult() {
{
return result; return result;
} }
@Nullable @Nullable
public ILuaCallback getCallback() public ILuaCallback getCallback() {
{
return callback; return callback;
} }
public int getErrorAdjust() public int getErrorAdjust() {
{
return adjust; return adjust;
} }
@ -164,10 +151,9 @@ public final class MethodResult
* @return The new {@link MethodResult} with an adjusted error. This has no effect on immediate results. * @return The new {@link MethodResult} with an adjusted error. This has no effect on immediate results.
*/ */
@Nonnull @Nonnull
public MethodResult adjustError( int adjust ) public MethodResult adjustError(int adjust) {
{ if (adjust < 0) throw new IllegalArgumentException("cannot adjust by a negative amount");
if( adjust < 0 ) throw new IllegalArgumentException( "cannot adjust by a negative amount" ); if (adjust == 0 || callback == null) return this;
if( adjust == 0 || callback == null ) return this; return new MethodResult(result, callback, this.adjust + adjust);
return new MethodResult( result, callback, this.adjust + adjust );
} }
} }

View File

@ -13,55 +13,47 @@ import java.util.Objects;
/** /**
* An implementation of {@link IArguments} which wraps an array of {@link Object}. * An implementation of {@link IArguments} which wraps an array of {@link Object}.
*/ */
public final class ObjectArguments implements IArguments public final class ObjectArguments implements IArguments {
{
private static final IArguments EMPTY = new ObjectArguments(); private static final IArguments EMPTY = new ObjectArguments();
private final List<Object> args; private final List<Object> args;
@Deprecated @Deprecated
@SuppressWarnings( "unused" ) @SuppressWarnings("unused")
public ObjectArguments( IArguments arguments ) public ObjectArguments(IArguments arguments) {
{
throw new IllegalStateException(); throw new IllegalStateException();
} }
public ObjectArguments( Object... args ) public ObjectArguments(Object... args) {
{ this.args = Arrays.asList(args);
this.args = Arrays.asList( args );
} }
public ObjectArguments( List<Object> args ) public ObjectArguments(List<Object> args) {
{ this.args = Objects.requireNonNull(args);
this.args = Objects.requireNonNull( args );
} }
@Override @Override
public int count() public int count() {
{
return args.size(); return args.size();
} }
@Override @Override
public IArguments drop( int count ) public IArguments drop(int count) {
{ if (count < 0) throw new IllegalStateException("count cannot be negative");
if( count < 0 ) throw new IllegalStateException( "count cannot be negative" ); if (count == 0) return this;
if( count == 0 ) return this; if (count >= args.size()) return EMPTY;
if( count >= args.size() ) return EMPTY;
return new ObjectArguments( args.subList( count, args.size() ) ); return new ObjectArguments(args.subList(count, args.size()));
} }
@Nullable @Nullable
@Override @Override
public Object get( int index ) public Object get(int index) {
{ return index >= args.size() ? null : args.get(index);
return index >= args.size() ? null : args.get( index );
} }
@Override @Override
public Object[] getAll() public Object[] getAll() {
{
return args.toArray(); return args.toArray();
} }
} }

View File

@ -11,63 +11,53 @@ import java.util.Collections;
import java.util.Map; import java.util.Map;
import java.util.Set; import java.util.Set;
public class ObjectLuaTable implements LuaTable<Object, Object> public class ObjectLuaTable implements LuaTable<Object, Object> {
{
private final Map<Object, Object> map; private final Map<Object, Object> map;
public ObjectLuaTable( Map<?, ?> map ) public ObjectLuaTable(Map<?, ?> map) {
{ this.map = Collections.unmodifiableMap(map);
this.map = Collections.unmodifiableMap( map );
} }
@Override @Override
public int size() public int size() {
{
return map.size(); return map.size();
} }
@Override @Override
public boolean isEmpty() public boolean isEmpty() {
{
return map.isEmpty(); return map.isEmpty();
} }
@Override @Override
public boolean containsKey( Object o ) public boolean containsKey(Object o) {
{ return map.containsKey(o);
return map.containsKey( o );
} }
@Override @Override
public boolean containsValue( Object o ) public boolean containsValue(Object o) {
{ return map.containsKey(o);
return map.containsKey( o );
} }
@Override @Override
public Object get( Object o ) public Object get(Object o) {
{ return map.get(o);
return map.get( o );
} }
@Nonnull @Nonnull
@Override @Override
public Set<Object> keySet() public Set<Object> keySet() {
{
return map.keySet(); return map.keySet();
} }
@Nonnull @Nonnull
@Override @Override
public Collection<Object> values() public Collection<Object> values() {
{
return map.values(); return map.values();
} }
@Nonnull @Nonnull
@Override @Override
public Set<Entry<Object, Object>> entrySet() public Set<Entry<Object, Object>> entrySet() {
{
return map.entrySet(); return map.entrySet();
} }
} }

View File

@ -8,46 +8,36 @@ package dan200.computercraft.api.lua;
import javax.annotation.Nonnull; import javax.annotation.Nonnull;
import java.util.Arrays; import java.util.Arrays;
final class TaskCallback implements ILuaCallback final class TaskCallback implements ILuaCallback {
{ private final MethodResult pull = MethodResult.pullEvent("task_complete", this);
private final MethodResult pull = MethodResult.pullEvent( "task_complete", this );
private final long task; private final long task;
private TaskCallback( long task ) private TaskCallback(long task) {
{
this.task = task; this.task = task;
} }
@Nonnull @Nonnull
@Override @Override
public MethodResult resume( Object[] response ) throws LuaException public MethodResult resume(Object[] response) throws LuaException {
{ if (response.length < 3 || !(response[1] instanceof Number) || !(response[2] instanceof Boolean)) {
if( response.length < 3 || !(response[1] instanceof Number) || !(response[2] instanceof Boolean) )
{
return pull; return pull;
} }
if( ((Number) response[1]).longValue() != task ) return pull; if (((Number) response[1]).longValue() != task) return pull;
if( (Boolean) response[2] ) if ((Boolean) response[2]) {
{
// Extract the return values from the event and return them // Extract the return values from the event and return them
return MethodResult.of( Arrays.copyOfRange( response, 3, response.length ) ); return MethodResult.of(Arrays.copyOfRange(response, 3, response.length));
} } else if (response.length >= 4 && response[3] instanceof String) {
else if( response.length >= 4 && response[3] instanceof String )
{
// Extract the error message from the event and raise it // Extract the error message from the event and raise it
throw new LuaException( (String) response[3] ); throw new LuaException((String) response[3]);
} } else {
else throw new LuaException("error");
{
throw new LuaException( "error" );
} }
} }
static MethodResult make( ILuaContext context, ILuaTask func ) throws LuaException static MethodResult make(ILuaContext context, ILuaTask func) throws LuaException {
{ var task = context.issueMainThreadTask(func);
long task = context.issueMainThreadTask( func ); return new TaskCallback(task).pull;
return new TaskCallback( task ).pull;
} }
} }

View File

@ -20,8 +20,7 @@ import javax.annotation.Nullable;
* Implement this interface on your {@link Item} class to allow it to be used in the drive. Alternatively, register * Implement this interface on your {@link Item} class to allow it to be used in the drive. Alternatively, register
* a {@link IMediaProvider}. * a {@link IMediaProvider}.
*/ */
public interface IMedia public interface IMedia {
{
/** /**
* Get a string representing the label of this item. Will be called via {@code disk.getLabel()} in lua. * Get a string representing the label of this item. Will be called via {@code disk.getLabel()} in lua.
* *
@ -29,7 +28,7 @@ public interface IMedia
* @return The label. ie: "Dan's Programs". * @return The label. ie: "Dan's Programs".
*/ */
@Nullable @Nullable
String getLabel( @Nonnull ItemStack stack ); String getLabel(@Nonnull ItemStack stack);
/** /**
* Set a string representing the label of this item. Will be called vi {@code disk.setLabel()} in lua. * Set a string representing the label of this item. Will be called vi {@code disk.setLabel()} in lua.
@ -38,8 +37,7 @@ public interface IMedia
* @param label The string to set the label to. * @param label The string to set the label to.
* @return true if the label was updated, false if the label may not be modified. * @return true if the label was updated, false if the label may not be modified.
*/ */
default boolean setLabel( @Nonnull ItemStack stack, @Nullable String label ) default boolean setLabel(@Nonnull ItemStack stack, @Nullable String label) {
{
return false; return false;
} }
@ -51,8 +49,7 @@ public interface IMedia
* @return The name, or null if this item does not represent an item with audio. * @return The name, or null if this item does not represent an item with audio.
*/ */
@Nullable @Nullable
default String getAudioTitle( @Nonnull ItemStack stack ) default String getAudioTitle(@Nonnull ItemStack stack) {
{
return null; return null;
} }
@ -63,8 +60,7 @@ public interface IMedia
* @return The name, or null if this item does not represent an item with audio. * @return The name, or null if this item does not represent an item with audio.
*/ */
@Nullable @Nullable
default SoundEvent getAudio( @Nonnull ItemStack stack ) default SoundEvent getAudio(@Nonnull ItemStack stack) {
{
return null; return null;
} }
@ -82,8 +78,7 @@ public interface IMedia
* @see dan200.computercraft.api.ComputerCraftAPI#createResourceMount(String, String) * @see dan200.computercraft.api.ComputerCraftAPI#createResourceMount(String, String)
*/ */
@Nullable @Nullable
default IMount createDataMount( @Nonnull ItemStack stack, @Nonnull Level world ) default IMount createDataMount(@Nonnull ItemStack stack, @Nonnull Level world) {
{
return null; return null;
} }
} }

View File

@ -16,8 +16,7 @@ import javax.annotation.Nullable;
* @see dan200.computercraft.api.ComputerCraftAPI#registerMediaProvider(IMediaProvider) * @see dan200.computercraft.api.ComputerCraftAPI#registerMediaProvider(IMediaProvider)
*/ */
@FunctionalInterface @FunctionalInterface
public interface IMediaProvider public interface IMediaProvider {
{
/** /**
* Produce an IMedia implementation from an ItemStack. * Produce an IMedia implementation from an ItemStack.
* *
@ -26,5 +25,5 @@ public interface IMediaProvider
* @see dan200.computercraft.api.ComputerCraftAPI#registerMediaProvider(IMediaProvider) * @see dan200.computercraft.api.ComputerCraftAPI#registerMediaProvider(IMediaProvider)
*/ */
@Nullable @Nullable
IMedia getMedia( @Nonnull ItemStack stack ); IMedia getMedia(@Nonnull ItemStack stack);
} }

View File

@ -13,21 +13,20 @@ import javax.annotation.Nonnull;
* @see Packet * @see Packet
* @see IPacketReceiver * @see IPacketReceiver
*/ */
public interface IPacketNetwork public interface IPacketNetwork {
{
/** /**
* Add a receiver to the network. * Add a receiver to the network.
* *
* @param receiver The receiver to register to the network. * @param receiver The receiver to register to the network.
*/ */
void addReceiver( @Nonnull IPacketReceiver receiver ); void addReceiver(@Nonnull IPacketReceiver receiver);
/** /**
* Remove a receiver from the network. * Remove a receiver from the network.
* *
* @param receiver The device to remove from the network. * @param receiver The device to remove from the network.
*/ */
void removeReceiver( @Nonnull IPacketReceiver receiver ); void removeReceiver(@Nonnull IPacketReceiver receiver);
/** /**
* Determine whether this network is wireless. * Determine whether this network is wireless.
@ -45,7 +44,7 @@ public interface IPacketNetwork
* @see #transmitInterdimensional(Packet) * @see #transmitInterdimensional(Packet)
* @see IPacketReceiver#receiveSameDimension(Packet, double) * @see IPacketReceiver#receiveSameDimension(Packet, double)
*/ */
void transmitSameDimension( @Nonnull Packet packet, double range ); void transmitSameDimension(@Nonnull Packet packet, double range);
/** /**
* Submit a packet for transmitting across the network. This will route the packet through the network, sending it * Submit a packet for transmitting across the network. This will route the packet through the network, sending it
@ -55,5 +54,5 @@ public interface IPacketNetwork
* @see #transmitSameDimension(Packet, double) * @see #transmitSameDimension(Packet, double)
* @see IPacketReceiver#receiveDifferentDimension(Packet) * @see IPacketReceiver#receiveDifferentDimension(Packet)
*/ */
void transmitInterdimensional( @Nonnull Packet packet ); void transmitInterdimensional(@Nonnull Packet packet);
} }

View File

@ -13,8 +13,7 @@ import javax.annotation.Nonnull;
/** /**
* An object on an {@link IPacketNetwork}, capable of receiving packets. * An object on an {@link IPacketNetwork}, capable of receiving packets.
*/ */
public interface IPacketReceiver public interface IPacketReceiver {
{
/** /**
* Get the world in which this packet receiver exists. * Get the world in which this packet receiver exists.
* *
@ -68,7 +67,7 @@ public interface IPacketReceiver
* @see IPacketNetwork#transmitSameDimension(Packet, double) * @see IPacketNetwork#transmitSameDimension(Packet, double)
* @see IPacketNetwork#transmitInterdimensional(Packet) * @see IPacketNetwork#transmitInterdimensional(Packet)
*/ */
void receiveSameDimension( @Nonnull Packet packet, double distance ); void receiveSameDimension(@Nonnull Packet packet, double distance);
/** /**
* Receive a network packet from a different dimension. * Receive a network packet from a different dimension.
@ -80,5 +79,5 @@ public interface IPacketReceiver
* @see IPacketNetwork#transmitSameDimension(Packet, double) * @see IPacketNetwork#transmitSameDimension(Packet, double)
* @see #isInterdimensional() * @see #isInterdimensional()
*/ */
void receiveDifferentDimension( @Nonnull Packet packet ); void receiveDifferentDimension(@Nonnull Packet packet);
} }

View File

@ -13,8 +13,7 @@ import javax.annotation.Nonnull;
/** /**
* An object on a {@link IPacketNetwork}, capable of sending packets. * An object on a {@link IPacketNetwork}, capable of sending packets.
*/ */
public interface IPacketSender public interface IPacketSender {
{
/** /**
* Get the world in which this packet sender exists. * Get the world in which this packet sender exists.
* *

View File

@ -25,6 +25,5 @@ public record Packet(
int replyChannel, int replyChannel,
Object payload, Object payload,
IPacketSender sender IPacketSender sender
) ) {
{
} }

View File

@ -19,8 +19,7 @@ import javax.annotation.Nonnull;
* Elements are generally tied to a block or tile entity in world. In such as case, one should provide the * Elements are generally tied to a block or tile entity in world. In such as case, one should provide the
* {@link IWiredElement} capability for the appropriate sides. * {@link IWiredElement} capability for the appropriate sides.
*/ */
public interface IWiredElement extends IWiredSender public interface IWiredElement extends IWiredSender {
{
/** /**
* Called when objects on the network change. This may occur when network nodes are added or removed, or when * Called when objects on the network change. This may occur when network nodes are added or removed, or when
* peripherals change. * peripherals change.
@ -28,7 +27,6 @@ public interface IWiredElement extends IWiredSender
* @param change The change which occurred. * @param change The change which occurred.
* @see IWiredNetworkChange * @see IWiredNetworkChange
*/ */
default void networkChanged( @Nonnull IWiredNetworkChange change ) default void networkChanged(@Nonnull IWiredNetworkChange change) {
{
} }
} }

View File

@ -24,8 +24,7 @@ import java.util.Map;
* *
* @see IWiredNode#getNetwork() * @see IWiredNode#getNetwork()
*/ */
public interface IWiredNetwork public interface IWiredNetwork {
{
/** /**
* Create a connection between two nodes. * Create a connection between two nodes.
* <p> * <p>
@ -39,7 +38,7 @@ public interface IWiredNetwork
* @see IWiredNode#connectTo(IWiredNode) * @see IWiredNode#connectTo(IWiredNode)
* @see IWiredNetwork#connect(IWiredNode, IWiredNode) * @see IWiredNetwork#connect(IWiredNode, IWiredNode)
*/ */
boolean connect( @Nonnull IWiredNode left, @Nonnull IWiredNode right ); boolean connect(@Nonnull IWiredNode left, @Nonnull IWiredNode right);
/** /**
* Destroy a connection between this node and another. * Destroy a connection between this node and another.
@ -54,7 +53,7 @@ public interface IWiredNetwork
* @see IWiredNode#disconnectFrom(IWiredNode) * @see IWiredNode#disconnectFrom(IWiredNode)
* @see IWiredNetwork#connect(IWiredNode, IWiredNode) * @see IWiredNetwork#connect(IWiredNode, IWiredNode)
*/ */
boolean disconnect( @Nonnull IWiredNode left, @Nonnull IWiredNode right ); boolean disconnect(@Nonnull IWiredNode left, @Nonnull IWiredNode right);
/** /**
* Sever all connections this node has, removing it from this network. * Sever all connections this node has, removing it from this network.
@ -68,7 +67,7 @@ public interface IWiredNetwork
* @throws IllegalArgumentException If the node is not in the network. * @throws IllegalArgumentException If the node is not in the network.
* @see IWiredNode#remove() * @see IWiredNode#remove()
*/ */
boolean remove( @Nonnull IWiredNode node ); boolean remove(@Nonnull IWiredNode node);
/** /**
* Update the peripherals a node provides. * Update the peripherals a node provides.
@ -81,5 +80,5 @@ public interface IWiredNetwork
* @throws IllegalArgumentException If the node is not in the network. * @throws IllegalArgumentException If the node is not in the network.
* @see IWiredNode#updatePeripherals(Map) * @see IWiredNode#updatePeripherals(Map)
*/ */
void updatePeripherals( @Nonnull IWiredNode node, @Nonnull Map<String, IPeripheral> peripherals ); void updatePeripherals(@Nonnull IWiredNode node, @Nonnull Map<String, IPeripheral> peripherals);
} }

View File

@ -15,8 +15,7 @@ import java.util.Map;
* *
* @see IWiredElement#networkChanged(IWiredNetworkChange) * @see IWiredElement#networkChanged(IWiredNetworkChange)
*/ */
public interface IWiredNetworkChange public interface IWiredNetworkChange {
{
/** /**
* A set of peripherals which have been removed. Note that there may be entries with the same name * A set of peripherals which have been removed. Note that there may be entries with the same name
* in the added and removed set, but with a different peripheral. * in the added and removed set, but with a different peripheral.

View File

@ -24,8 +24,7 @@ import java.util.Map;
* Wired nodes also provide several convenience methods for interacting with a wired network. These should only ever * Wired nodes also provide several convenience methods for interacting with a wired network. These should only ever
* be used on the main server thread. * be used on the main server thread.
*/ */
public interface IWiredNode extends IPacketNetwork public interface IWiredNode extends IPacketNetwork {
{
/** /**
* The associated element for this network node. * The associated element for this network node.
* *
@ -55,9 +54,8 @@ public interface IWiredNode extends IPacketNetwork
* @see IWiredNetwork#connect(IWiredNode, IWiredNode) * @see IWiredNetwork#connect(IWiredNode, IWiredNode)
* @see IWiredNode#disconnectFrom(IWiredNode) * @see IWiredNode#disconnectFrom(IWiredNode)
*/ */
default boolean connectTo( @Nonnull IWiredNode node ) default boolean connectTo(@Nonnull IWiredNode node) {
{ return getNetwork().connect(this, node);
return getNetwork().connect( this, node );
} }
/** /**
@ -71,9 +69,8 @@ public interface IWiredNode extends IPacketNetwork
* @see IWiredNetwork#disconnect(IWiredNode, IWiredNode) * @see IWiredNetwork#disconnect(IWiredNode, IWiredNode)
* @see IWiredNode#connectTo(IWiredNode) * @see IWiredNode#connectTo(IWiredNode)
*/ */
default boolean disconnectFrom( @Nonnull IWiredNode node ) default boolean disconnectFrom(@Nonnull IWiredNode node) {
{ return getNetwork().disconnect(this, node);
return getNetwork().disconnect( this, node );
} }
/** /**
@ -87,9 +84,8 @@ public interface IWiredNode extends IPacketNetwork
* @throws IllegalArgumentException If the node is not in the network. * @throws IllegalArgumentException If the node is not in the network.
* @see IWiredNetwork#remove(IWiredNode) * @see IWiredNetwork#remove(IWiredNode)
*/ */
default boolean remove() default boolean remove() {
{ return getNetwork().remove(this);
return getNetwork().remove( this );
} }
/** /**
@ -101,8 +97,7 @@ public interface IWiredNode extends IPacketNetwork
* @param peripherals The new peripherals for this node. * @param peripherals The new peripherals for this node.
* @see IWiredNetwork#updatePeripherals(IWiredNode, Map) * @see IWiredNetwork#updatePeripherals(IWiredNode, Map)
*/ */
default void updatePeripherals( @Nonnull Map<String, IPeripheral> peripherals ) default void updatePeripherals(@Nonnull Map<String, IPeripheral> peripherals) {
{ getNetwork().updatePeripherals(this, peripherals);
getNetwork().updatePeripherals( this, peripherals );
} }
} }

View File

@ -15,8 +15,7 @@ import javax.annotation.Nonnull;
* Unlike a regular {@link IPacketSender}, this must be associated with the node you are attempting to * Unlike a regular {@link IPacketSender}, this must be associated with the node you are attempting to
* to send the packet from. * to send the packet from.
*/ */
public interface IWiredSender extends IPacketSender public interface IWiredSender extends IPacketSender {
{
/** /**
* The node in the network representing this object. * The node in the network representing this object.
* <p> * <p>

View File

@ -17,8 +17,7 @@ import javax.annotation.Nonnull;
* Unlike a {@link GenericSource}, all methods <strong>should</strong> target the same type, for instance a * Unlike a {@link GenericSource}, all methods <strong>should</strong> target the same type, for instance a
* {@link BlockEntity} subclass or a capability interface. This is not currently enforced. * {@link BlockEntity} subclass or a capability interface. This is not currently enforced.
*/ */
public interface GenericPeripheral extends GenericSource public interface GenericPeripheral extends GenericSource {
{
/** /**
* Get the type of the exposed peripheral. * Get the type of the exposed peripheral.
* <p> * <p>
@ -38,8 +37,7 @@ public interface GenericPeripheral extends GenericSource
* @see IPeripheral#getType() * @see IPeripheral#getType()
*/ */
@Nonnull @Nonnull
default PeripheralType getType() default PeripheralType getType() {
{
return PeripheralType.untyped(); return PeripheralType.untyped();
} }
} }

View File

@ -23,8 +23,7 @@ import java.util.Map;
* that they can call. This should not be implemented by your classes. Do not interact * that they can call. This should not be implemented by your classes. Do not interact
* with computers except via this interface. * with computers except via this interface.
*/ */
public interface IComputerAccess public interface IComputerAccess {
{
/** /**
* Mount a mount onto the computer's file system in a read only mode. * Mount a mount onto the computer's file system in a read only mode.
* *
@ -41,9 +40,8 @@ public interface IComputerAccess
* @see IMount * @see IMount
*/ */
@Nullable @Nullable
default String mount( @Nonnull String desiredLocation, @Nonnull IMount mount ) default String mount(@Nonnull String desiredLocation, @Nonnull IMount mount) {
{ return mount(desiredLocation, mount, getAttachmentName());
return mount( desiredLocation, mount, getAttachmentName() );
} }
/** /**
@ -63,7 +61,7 @@ public interface IComputerAccess
* @see IMount * @see IMount
*/ */
@Nullable @Nullable
String mount( @Nonnull String desiredLocation, @Nonnull IMount mount, @Nonnull String driveName ); String mount(@Nonnull String desiredLocation, @Nonnull IMount mount, @Nonnull String driveName);
/** /**
* Mount a mount onto the computer's file system in a writable mode. * Mount a mount onto the computer's file system in a writable mode.
@ -80,9 +78,8 @@ public interface IComputerAccess
* @see IMount * @see IMount
*/ */
@Nullable @Nullable
default String mountWritable( @Nonnull String desiredLocation, @Nonnull IWritableMount mount ) default String mountWritable(@Nonnull String desiredLocation, @Nonnull IWritableMount mount) {
{ return mountWritable(desiredLocation, mount, getAttachmentName());
return mountWritable( desiredLocation, mount, getAttachmentName() );
} }
/** /**
@ -100,7 +97,7 @@ public interface IComputerAccess
* @see #unmount(String) * @see #unmount(String)
* @see IMount * @see IMount
*/ */
String mountWritable( @Nonnull String desiredLocation, @Nonnull IWritableMount mount, @Nonnull String driveName ); String mountWritable(@Nonnull String desiredLocation, @Nonnull IWritableMount mount, @Nonnull String driveName);
/** /**
* Unmounts a directory previously mounted onto the computers file system by {@link #mount(String, IMount)} * Unmounts a directory previously mounted onto the computers file system by {@link #mount(String, IMount)}
@ -120,7 +117,7 @@ public interface IComputerAccess
* @see #mount(String, IMount) * @see #mount(String, IMount)
* @see #mountWritable(String, IWritableMount) * @see #mountWritable(String, IWritableMount)
*/ */
void unmount( @Nullable String location ); void unmount(@Nullable String location);
/** /**
* Returns the numerical ID of this computer. * Returns the numerical ID of this computer.
@ -150,7 +147,7 @@ public interface IComputerAccess
* @throws NotAttachedException If the peripheral has been detached. * @throws NotAttachedException If the peripheral has been detached.
* @see MethodResult#pullEvent(String, ILuaCallback) * @see MethodResult#pullEvent(String, ILuaCallback)
*/ */
void queueEvent( @Nonnull String event, @Nullable Object... arguments ); void queueEvent(@Nonnull String event, @Nullable Object... arguments);
/** /**
* Get a string, unique to the computer, by which the computer refers to this peripheral. * Get a string, unique to the computer, by which the computer refers to this peripheral.
@ -187,7 +184,7 @@ public interface IComputerAccess
* @see #getAvailablePeripherals() * @see #getAvailablePeripherals()
*/ */
@Nullable @Nullable
IPeripheral getAvailablePeripheral( @Nonnull String name ); IPeripheral getAvailablePeripheral(@Nonnull String name);
/** /**
* Get a {@link IWorkMonitor} for tasks your peripheral might execute on the main (server) thread. * Get a {@link IWorkMonitor} for tasks your peripheral might execute on the main (server) thread.

View File

@ -15,8 +15,7 @@ import javax.annotation.Nonnull;
* This behaves similarly to {@link IDynamicLuaObject}, though also accepting the current {@link IComputerAccess}. * This behaves similarly to {@link IDynamicLuaObject}, though also accepting the current {@link IComputerAccess}.
* Generally one may use {@link LuaFunction} instead of implementing this interface. * Generally one may use {@link LuaFunction} instead of implementing this interface.
*/ */
public interface IDynamicPeripheral extends IPeripheral public interface IDynamicPeripheral extends IPeripheral {
{
/** /**
* Should return an array of strings that identify the methods that this peripheral exposes to Lua. This will be * Should return an array of strings that identify the methods that this peripheral exposes to Lua. This will be
* called once before each attachment, and should not change when called multiple times. * called once before each attachment, and should not change when called multiple times.
@ -49,5 +48,5 @@ public interface IDynamicPeripheral extends IPeripheral
* @see #getMethodNames() * @see #getMethodNames()
*/ */
@Nonnull @Nonnull
MethodResult callMethod( @Nonnull IComputerAccess computer, @Nonnull ILuaContext context, int method, @Nonnull IArguments arguments ) throws LuaException; MethodResult callMethod(@Nonnull IComputerAccess computer, @Nonnull ILuaContext context, int method, @Nonnull IArguments arguments) throws LuaException;
} }

View File

@ -22,8 +22,7 @@ import java.util.Set;
* Peripherals should provide a series of methods to the user, either using {@link LuaFunction} or by implementing * Peripherals should provide a series of methods to the user, either using {@link LuaFunction} or by implementing
* {@link IDynamicPeripheral}. * {@link IDynamicPeripheral}.
*/ */
public interface IPeripheral public interface IPeripheral {
{
/** /**
* Should return a string that uniquely identifies this type of peripheral. * Should return a string that uniquely identifies this type of peripheral.
* This can be queried from lua by calling {@code peripheral.getType()} * This can be queried from lua by calling {@code peripheral.getType()}
@ -40,8 +39,7 @@ public interface IPeripheral
* @see PeripheralType#getAdditionalTypes() * @see PeripheralType#getAdditionalTypes()
*/ */
@Nonnull @Nonnull
default Set<String> getAdditionalTypes() default Set<String> getAdditionalTypes() {
{
return Collections.emptySet(); return Collections.emptySet();
} }
@ -63,8 +61,7 @@ public interface IPeripheral
* attached to a peripheral at once. * attached to a peripheral at once.
* @see #detach * @see #detach
*/ */
default void attach( @Nonnull IComputerAccess computer ) default void attach(@Nonnull IComputerAccess computer) {
{
} }
/** /**
@ -84,8 +81,7 @@ public interface IPeripheral
* attached to a peripheral at once. * attached to a peripheral at once.
* @see #attach * @see #attach
*/ */
default void detach( @Nonnull IComputerAccess computer ) default void detach(@Nonnull IComputerAccess computer) {
{
} }
/** /**
@ -95,8 +91,7 @@ public interface IPeripheral
* @return The object this peripheral targets * @return The object this peripheral targets
*/ */
@Nullable @Nullable
default Object getTarget() default Object getTarget() {
{
return null; return null;
} }
@ -109,5 +104,5 @@ public interface IPeripheral
* @param other The peripheral to compare against. This may be {@code null}. * @param other The peripheral to compare against. This may be {@code null}.
* @return Whether these peripherals are equivalent. * @return Whether these peripherals are equivalent.
*/ */
boolean equals( @Nullable IPeripheral other ); boolean equals(@Nullable IPeripheral other);
} }

View File

@ -23,8 +23,7 @@ import javax.annotation.Nonnull;
* @see dan200.computercraft.api.ComputerCraftAPI#registerPeripheralProvider(IPeripheralProvider) * @see dan200.computercraft.api.ComputerCraftAPI#registerPeripheralProvider(IPeripheralProvider)
*/ */
@FunctionalInterface @FunctionalInterface
public interface IPeripheralProvider public interface IPeripheralProvider {
{
/** /**
* Produce an peripheral implementation from a block location. * Produce an peripheral implementation from a block location.
* *
@ -35,5 +34,5 @@ public interface IPeripheralProvider
* @see ForgeComputerCraftAPI#registerPeripheralProvider(IPeripheralProvider) * @see ForgeComputerCraftAPI#registerPeripheralProvider(IPeripheralProvider)
*/ */
@Nonnull @Nonnull
LazyOptional<IPeripheral> getPeripheral( @Nonnull Level world, @Nonnull BlockPos pos, @Nonnull Direction side ); LazyOptional<IPeripheral> getPeripheral(@Nonnull Level world, @Nonnull BlockPos pos, @Nonnull Direction side);
} }

View File

@ -24,8 +24,7 @@ import java.util.concurrent.TimeUnit;
* *
* @see IComputerAccess#getMainThreadMonitor() * @see IComputerAccess#getMainThreadMonitor()
*/ */
public interface IWorkMonitor public interface IWorkMonitor {
{
/** /**
* If the owning computer is currently allowed to execute work. * If the owning computer is currently allowed to execute work.
* *
@ -49,7 +48,7 @@ public interface IWorkMonitor
* @param time The time some task took to run * @param time The time some task took to run
* @param unit The unit that {@code time} was measured in. * @param unit The unit that {@code time} was measured in.
*/ */
void trackWork( long time, @Nonnull TimeUnit unit ); void trackWork(long time, @Nonnull TimeUnit unit);
/** /**
* Run a task if possible, and inform the monitor of how long it took. * Run a task if possible, and inform the monitor of how long it took.
@ -57,19 +56,15 @@ public interface IWorkMonitor
* @param runnable The task to run. * @param runnable The task to run.
* @return If the task was actually run (namely, {@link #canWork()} returned {@code true}). * @return If the task was actually run (namely, {@link #canWork()} returned {@code true}).
*/ */
default boolean runWork( @Nonnull Runnable runnable ) default boolean runWork(@Nonnull Runnable runnable) {
{ Objects.requireNonNull(runnable, "runnable should not be null");
Objects.requireNonNull( runnable, "runnable should not be null" ); if (!canWork()) return false;
if( !canWork() ) return false;
long start = System.nanoTime(); var start = System.nanoTime();
try try {
{
runnable.run(); runnable.run();
} } finally {
finally trackWork(System.nanoTime() - start, TimeUnit.NANOSECONDS);
{
trackWork( System.nanoTime() - start, TimeUnit.NANOSECONDS );
} }
return true; return true;

View File

@ -9,17 +9,14 @@ package dan200.computercraft.api.peripheral;
* Thrown when performing operations on {@link IComputerAccess} when the current peripheral is no longer attached to * Thrown when performing operations on {@link IComputerAccess} when the current peripheral is no longer attached to
* the computer. * the computer.
*/ */
public class NotAttachedException extends IllegalStateException public class NotAttachedException extends IllegalStateException {
{
private static final long serialVersionUID = 1221244785535553536L; private static final long serialVersionUID = 1221244785535553536L;
public NotAttachedException() public NotAttachedException() {
{ super("You are not attached to this computer");
super( "You are not attached to this computer" );
} }
public NotAttachedException( String s ) public NotAttachedException(String s) {
{ super(s);
super( s );
} }
} }

View File

@ -20,20 +20,17 @@ import java.util.Set;
* When determining the final type of the resulting peripheral, the union of all types is taken, with the * When determining the final type of the resulting peripheral, the union of all types is taken, with the
* lexicographically smallest non-empty name being chosen. * lexicographically smallest non-empty name being chosen.
*/ */
public final class PeripheralType public final class PeripheralType {
{ private static final PeripheralType UNTYPED = new PeripheralType(null, Collections.emptySet());
private static final PeripheralType UNTYPED = new PeripheralType( null, Collections.emptySet() );
private final String type; private final String type;
private final Set<String> additionalTypes; private final Set<String> additionalTypes;
public PeripheralType( String type, Set<String> additionalTypes ) public PeripheralType(String type, Set<String> additionalTypes) {
{
this.type = type; this.type = type;
this.additionalTypes = additionalTypes; this.additionalTypes = additionalTypes;
if( additionalTypes.contains( null ) ) if (additionalTypes.contains(null)) {
{ throw new IllegalArgumentException("All additional types must be non-null");
throw new IllegalArgumentException( "All additional types must be non-null" );
} }
} }
@ -42,8 +39,7 @@ public final class PeripheralType
* *
* @return The empty peripheral type. * @return The empty peripheral type.
*/ */
public static PeripheralType untyped() public static PeripheralType untyped() {
{
return UNTYPED; return UNTYPED;
} }
@ -53,10 +49,9 @@ public final class PeripheralType
* @param type The name of the type. * @param type The name of the type.
* @return The constructed peripheral type. * @return The constructed peripheral type.
*/ */
public static PeripheralType ofType( @Nonnull String type ) public static PeripheralType ofType(@Nonnull String type) {
{ if (Strings.isNullOrEmpty(type)) throw new IllegalArgumentException("type cannot be null or empty");
if( Strings.isNullOrEmpty( type ) ) throw new IllegalArgumentException( "type cannot be null or empty" ); return new PeripheralType(type, Collections.emptySet());
return new PeripheralType( type, Collections.emptySet() );
} }
/** /**
@ -66,10 +61,9 @@ public final class PeripheralType
* @param additionalTypes Additional types, or "traits" of this peripheral. For instance, {@code "inventory"}. * @param additionalTypes Additional types, or "traits" of this peripheral. For instance, {@code "inventory"}.
* @return The constructed peripheral type. * @return The constructed peripheral type.
*/ */
public static PeripheralType ofType( @Nonnull String type, Collection<String> additionalTypes ) public static PeripheralType ofType(@Nonnull String type, Collection<String> additionalTypes) {
{ if (Strings.isNullOrEmpty(type)) throw new IllegalArgumentException("type cannot be null or empty");
if( Strings.isNullOrEmpty( type ) ) throw new IllegalArgumentException( "type cannot be null or empty" ); return new PeripheralType(type, ImmutableSet.copyOf(additionalTypes));
return new PeripheralType( type, ImmutableSet.copyOf( additionalTypes ) );
} }
/** /**
@ -79,10 +73,9 @@ public final class PeripheralType
* @param additionalTypes Additional types, or "traits" of this peripheral. For instance, {@code "inventory"}. * @param additionalTypes Additional types, or "traits" of this peripheral. For instance, {@code "inventory"}.
* @return The constructed peripheral type. * @return The constructed peripheral type.
*/ */
public static PeripheralType ofType( @Nonnull String type, @Nonnull String... additionalTypes ) public static PeripheralType ofType(@Nonnull String type, @Nonnull String... additionalTypes) {
{ if (Strings.isNullOrEmpty(type)) throw new IllegalArgumentException("type cannot be null or empty");
if( Strings.isNullOrEmpty( type ) ) throw new IllegalArgumentException( "type cannot be null or empty" ); return new PeripheralType(type, ImmutableSet.copyOf(additionalTypes));
return new PeripheralType( type, ImmutableSet.copyOf( additionalTypes ) );
} }
/** /**
@ -91,9 +84,8 @@ public final class PeripheralType
* @param additionalTypes Additional types, or "traits" of this peripheral. For instance, {@code "inventory"}. * @param additionalTypes Additional types, or "traits" of this peripheral. For instance, {@code "inventory"}.
* @return The constructed peripheral type. * @return The constructed peripheral type.
*/ */
public static PeripheralType ofAdditional( Collection<String> additionalTypes ) public static PeripheralType ofAdditional(Collection<String> additionalTypes) {
{ return new PeripheralType(null, ImmutableSet.copyOf(additionalTypes));
return new PeripheralType( null, ImmutableSet.copyOf( additionalTypes ) );
} }
/** /**
@ -102,9 +94,8 @@ public final class PeripheralType
* @param additionalTypes Additional types, or "traits" of this peripheral. For instance, {@code "inventory"}. * @param additionalTypes Additional types, or "traits" of this peripheral. For instance, {@code "inventory"}.
* @return The constructed peripheral type. * @return The constructed peripheral type.
*/ */
public static PeripheralType ofAdditional( @Nonnull String... additionalTypes ) public static PeripheralType ofAdditional(@Nonnull String... additionalTypes) {
{ return new PeripheralType(null, ImmutableSet.copyOf(additionalTypes));
return new PeripheralType( null, ImmutableSet.copyOf( additionalTypes ) );
} }
/** /**
@ -113,8 +104,7 @@ public final class PeripheralType
* @return The type of this peripheral. * @return The type of this peripheral.
*/ */
@Nullable @Nullable
public String getPrimaryType() public String getPrimaryType() {
{
return type; return type;
} }
@ -124,8 +114,7 @@ public final class PeripheralType
* *
* @return All additional types. * @return All additional types.
*/ */
public Set<String> getAdditionalTypes() public Set<String> getAdditionalTypes() {
{
return additionalTypes; return additionalTypes;
} }
} }

View File

@ -16,42 +16,36 @@ import javax.annotation.Nonnull;
* <p> * <p>
* One does not have to use this, but it does provide a convenient template. * One does not have to use this, but it does provide a convenient template.
*/ */
public abstract class AbstractPocketUpgrade implements IPocketUpgrade public abstract class AbstractPocketUpgrade implements IPocketUpgrade {
{
private final ResourceLocation id; private final ResourceLocation id;
private final String adjective; private final String adjective;
private final ItemStack stack; private final ItemStack stack;
protected AbstractPocketUpgrade( ResourceLocation id, String adjective, ItemStack stack ) protected AbstractPocketUpgrade(ResourceLocation id, String adjective, ItemStack stack) {
{
this.id = id; this.id = id;
this.adjective = adjective; this.adjective = adjective;
this.stack = stack; this.stack = stack;
} }
protected AbstractPocketUpgrade( ResourceLocation id, ItemStack stack ) protected AbstractPocketUpgrade(ResourceLocation id, ItemStack stack) {
{ this(id, IUpgradeBase.getDefaultAdjective(id), stack);
this( id, IUpgradeBase.getDefaultAdjective( id ), stack );
} }
@Nonnull @Nonnull
@Override @Override
public final ResourceLocation getUpgradeID() public final ResourceLocation getUpgradeID() {
{
return id; return id;
} }
@Nonnull @Nonnull
@Override @Override
public final String getUnlocalisedAdjective() public final String getUnlocalisedAdjective() {
{
return adjective; return adjective;
} }
@Nonnull @Nonnull
@Override @Override
public final ItemStack getCraftingItem() public final ItemStack getCraftingItem() {
{
return stack; return stack;
} }
} }

View File

@ -17,8 +17,7 @@ import java.util.Map;
/** /**
* Wrapper class for pocket computers. * Wrapper class for pocket computers.
*/ */
public interface IPocketAccess public interface IPocketAccess {
{
/** /**
* Gets the entity holding this item. * Gets the entity holding this item.
* <p> * <p>
@ -45,7 +44,7 @@ public interface IPocketAccess
* {@code 0x000000} and {@code 0xFFFFFF} or -1 to reset to the default colour. * {@code 0x000000} and {@code 0xFFFFFF} or -1 to reset to the default colour.
* @see #getColour() * @see #getColour()
*/ */
void setColour( int colour ); void setColour(int colour);
/** /**
* Get the colour of this pocket computer's light as a RGB number. * Get the colour of this pocket computer's light as a RGB number.
@ -63,7 +62,7 @@ public interface IPocketAccess
* {@code 0x000000} and {@code 0xFFFFFF} or -1 to reset to the default colour. * {@code 0x000000} and {@code 0xFFFFFF} or -1 to reset to the default colour.
* @see #getLight() * @see #getLight()
*/ */
void setLight( int colour ); void setLight(int colour);
/** /**
* Get the upgrade-specific NBT. * Get the upgrade-specific NBT.

View File

@ -24,8 +24,7 @@ import javax.annotation.Nullable;
* *
* @see PocketUpgradeSerialiser For how to register a pocket computer upgrade. * @see PocketUpgradeSerialiser For how to register a pocket computer upgrade.
*/ */
public interface IPocketUpgrade extends IUpgradeBase public interface IPocketUpgrade extends IUpgradeBase {
{
/** /**
* Creates a peripheral for the pocket computer. * Creates a peripheral for the pocket computer.
* <p> * <p>
@ -38,7 +37,7 @@ public interface IPocketUpgrade extends IUpgradeBase
* @see #update(IPocketAccess, IPeripheral) * @see #update(IPocketAccess, IPeripheral)
*/ */
@Nullable @Nullable
IPeripheral createPeripheral( @Nonnull IPocketAccess access ); IPeripheral createPeripheral(@Nonnull IPocketAccess access);
/** /**
* Called when the pocket computer item stack updates. * Called when the pocket computer item stack updates.
@ -47,8 +46,7 @@ public interface IPocketUpgrade extends IUpgradeBase
* @param peripheral The peripheral for this upgrade. * @param peripheral The peripheral for this upgrade.
* @see #createPeripheral(IPocketAccess) * @see #createPeripheral(IPocketAccess)
*/ */
default void update( @Nonnull IPocketAccess access, @Nullable IPeripheral peripheral ) default void update(@Nonnull IPocketAccess access, @Nullable IPeripheral peripheral) {
{
} }
/** /**
@ -62,8 +60,7 @@ public interface IPocketUpgrade extends IUpgradeBase
* access the GUI. * access the GUI.
* @see #createPeripheral(IPocketAccess) * @see #createPeripheral(IPocketAccess)
*/ */
default boolean onRightClick( @Nonnull Level world, @Nonnull IPocketAccess access, @Nullable IPeripheral peripheral ) default boolean onRightClick(@Nonnull Level world, @Nonnull IPocketAccess access, @Nullable IPeripheral peripheral) {
{
return false; return false;
} }
} }

View File

@ -21,10 +21,8 @@ import java.util.function.Consumer;
* @see GatherDataEvent To register your data provider * @see GatherDataEvent To register your data provider
* @see PocketUpgradeSerialiser * @see PocketUpgradeSerialiser
*/ */
public abstract class PocketUpgradeDataProvider extends UpgradeDataProvider<IPocketUpgrade, PocketUpgradeSerialiser<?>> public abstract class PocketUpgradeDataProvider extends UpgradeDataProvider<IPocketUpgrade, PocketUpgradeSerialiser<?>> {
{ public PocketUpgradeDataProvider(@Nonnull DataGenerator generator) {
public PocketUpgradeDataProvider( @Nonnull DataGenerator generator ) super(generator, "Pocket Computer Upgrades", "computercraft/pocket_upgrades", PocketUpgradeSerialiser.REGISTRY_ID);
{
super( generator, "Pocket Computer Upgrades", "computercraft/pocket_upgrades", PocketUpgradeSerialiser.REGISTRY_ID );
} }
} }

View File

@ -33,15 +33,14 @@ import java.util.function.Function;
* @see IPocketUpgrade * @see IPocketUpgrade
* @see PocketUpgradeDataProvider * @see PocketUpgradeDataProvider
*/ */
public interface PocketUpgradeSerialiser<T extends IPocketUpgrade> extends UpgradeSerialiser<T> public interface PocketUpgradeSerialiser<T extends IPocketUpgrade> extends UpgradeSerialiser<T> {
{
/** /**
* The ID for the associated registry. * The ID for the associated registry.
* <p> * <p>
* This is largely intended for use with Forge Registry methods/classes, such as {@link DeferredRegister} and * This is largely intended for use with Forge Registry methods/classes, such as {@link DeferredRegister} and
* {@link RegistryManager#getRegistry(ResourceKey)}. * {@link RegistryManager#getRegistry(ResourceKey)}.
*/ */
ResourceKey<Registry<PocketUpgradeSerialiser<?>>> REGISTRY_ID = ResourceKey.createRegistryKey( new ResourceLocation( ComputerCraft.MOD_ID, "pocket_upgrade_serialiser" ) ); ResourceKey<Registry<PocketUpgradeSerialiser<?>>> REGISTRY_ID = ResourceKey.createRegistryKey(new ResourceLocation(ComputerCraft.MOD_ID, "pocket_upgrade_serialiser"));
/** /**
* The associated registry. * The associated registry.
@ -50,10 +49,9 @@ public interface PocketUpgradeSerialiser<T extends IPocketUpgrade> extends Upgra
* @see #REGISTRY_ID * @see #REGISTRY_ID
* @deprecated Use {@link #REGISTRY_ID} directly. * @deprecated Use {@link #REGISTRY_ID} directly.
*/ */
@Deprecated( forRemoval = true ) @Deprecated(forRemoval = true)
static IForgeRegistry<PocketUpgradeSerialiser<?>> registry() static IForgeRegistry<PocketUpgradeSerialiser<?>> registry() {
{ return RegistryManager.ACTIVE.getRegistry(REGISTRY_ID);
return RegistryManager.ACTIVE.getRegistry( REGISTRY_ID );
} }
/** /**
@ -67,17 +65,14 @@ public interface PocketUpgradeSerialiser<T extends IPocketUpgrade> extends Upgra
* @return The serialiser for this upgrade * @return The serialiser for this upgrade
*/ */
@Nonnull @Nonnull
static <T extends IPocketUpgrade> PocketUpgradeSerialiser<T> simple( @Nonnull Function<ResourceLocation, T> factory ) static <T extends IPocketUpgrade> PocketUpgradeSerialiser<T> simple(@Nonnull Function<ResourceLocation, T> factory) {
{ final class Impl extends SimpleSerialiser<T> implements PocketUpgradeSerialiser<T> {
final class Impl extends SimpleSerialiser<T> implements PocketUpgradeSerialiser<T> private Impl(Function<ResourceLocation, T> constructor) {
{ super(constructor);
private Impl( Function<ResourceLocation, T> constructor )
{
super( constructor );
} }
} }
return new Impl( factory ); return new Impl(factory);
} }
/** /**
@ -90,16 +85,13 @@ public interface PocketUpgradeSerialiser<T extends IPocketUpgrade> extends Upgra
* @see #simple(Function) For upgrades whose crafting stack should not vary. * @see #simple(Function) For upgrades whose crafting stack should not vary.
*/ */
@Nonnull @Nonnull
static <T extends IPocketUpgrade> PocketUpgradeSerialiser<T> simpleWithCustomItem( @Nonnull BiFunction<ResourceLocation, ItemStack, T> factory ) static <T extends IPocketUpgrade> PocketUpgradeSerialiser<T> simpleWithCustomItem(@Nonnull BiFunction<ResourceLocation, ItemStack, T> factory) {
{ final class Impl extends SerialiserWithCraftingItem<T> implements PocketUpgradeSerialiser<T> {
final class Impl extends SerialiserWithCraftingItem<T> implements PocketUpgradeSerialiser<T> private Impl(BiFunction<ResourceLocation, ItemStack, T> factory) {
{ super(factory);
private Impl( BiFunction<ResourceLocation, ItemStack, T> factory )
{
super( factory );
} }
} }
return new Impl( factory ); return new Impl(factory);
} }
} }

View File

@ -17,8 +17,7 @@ import javax.annotation.Nonnull;
* @see dan200.computercraft.api.ComputerCraftAPI#registerBundledRedstoneProvider(IBundledRedstoneProvider) * @see dan200.computercraft.api.ComputerCraftAPI#registerBundledRedstoneProvider(IBundledRedstoneProvider)
*/ */
@FunctionalInterface @FunctionalInterface
public interface IBundledRedstoneProvider public interface IBundledRedstoneProvider {
{
/** /**
* Produce an bundled redstone output from a block location. * Produce an bundled redstone output from a block location.
* *
@ -29,5 +28,5 @@ public interface IBundledRedstoneProvider
* handle this block. * handle this block.
* @see dan200.computercraft.api.ComputerCraftAPI#registerBundledRedstoneProvider(IBundledRedstoneProvider) * @see dan200.computercraft.api.ComputerCraftAPI#registerBundledRedstoneProvider(IBundledRedstoneProvider)
*/ */
int getBundledRedstoneOutput( @Nonnull Level world, @Nonnull BlockPos pos, @Nonnull Direction side ); int getBundledRedstoneOutput(@Nonnull Level world, @Nonnull BlockPos pos, @Nonnull Direction side);
} }

View File

@ -16,51 +16,44 @@ import javax.annotation.Nonnull;
* <p> * <p>
* One does not have to use this, but it does provide a convenient template. * One does not have to use this, but it does provide a convenient template.
*/ */
public abstract class AbstractTurtleUpgrade implements ITurtleUpgrade public abstract class AbstractTurtleUpgrade implements ITurtleUpgrade {
{
private final ResourceLocation id; private final ResourceLocation id;
private final TurtleUpgradeType type; private final TurtleUpgradeType type;
private final String adjective; private final String adjective;
private final ItemStack stack; private final ItemStack stack;
protected AbstractTurtleUpgrade( ResourceLocation id, TurtleUpgradeType type, String adjective, ItemStack stack ) protected AbstractTurtleUpgrade(ResourceLocation id, TurtleUpgradeType type, String adjective, ItemStack stack) {
{
this.id = id; this.id = id;
this.type = type; this.type = type;
this.adjective = adjective; this.adjective = adjective;
this.stack = stack; this.stack = stack;
} }
protected AbstractTurtleUpgrade( ResourceLocation id, TurtleUpgradeType type, ItemStack stack ) protected AbstractTurtleUpgrade(ResourceLocation id, TurtleUpgradeType type, ItemStack stack) {
{ this(id, type, IUpgradeBase.getDefaultAdjective(id), stack);
this( id, type, IUpgradeBase.getDefaultAdjective( id ), stack );
} }
@Nonnull @Nonnull
@Override @Override
public final ResourceLocation getUpgradeID() public final ResourceLocation getUpgradeID() {
{
return id; return id;
} }
@Nonnull @Nonnull
@Override @Override
public final String getUnlocalisedAdjective() public final String getUnlocalisedAdjective() {
{
return adjective; return adjective;
} }
@Nonnull @Nonnull
@Override @Override
public final TurtleUpgradeType getType() public final TurtleUpgradeType getType() {
{
return type; return type;
} }
@Nonnull @Nonnull
@Override @Override
public final ItemStack getCraftingItem() public final ItemStack getCraftingItem() {
{
return stack; return stack;
} }
} }

View File

@ -26,8 +26,7 @@ import javax.annotation.Nullable;
* This should not be implemented by your classes. Do not interact with turtles except via this interface and * This should not be implemented by your classes. Do not interact with turtles except via this interface and
* {@link ITurtleUpgrade}. * {@link ITurtleUpgrade}.
*/ */
public interface ITurtleAccess public interface ITurtleAccess {
{
/** /**
* Returns the world in which the turtle resides. * Returns the world in which the turtle resides.
* *
@ -70,7 +69,7 @@ public interface ITurtleAccess
* was cancelled. * was cancelled.
* @throws UnsupportedOperationException When attempting to teleport on the client side. * @throws UnsupportedOperationException When attempting to teleport on the client side.
*/ */
boolean teleportTo( @Nonnull Level world, @Nonnull BlockPos pos ); boolean teleportTo(@Nonnull Level world, @Nonnull BlockPos pos);
/** /**
* Returns a vector containing the floating point co-ordinates at which the turtle is rendered. * Returns a vector containing the floating point co-ordinates at which the turtle is rendered.
@ -81,7 +80,7 @@ public interface ITurtleAccess
* @see #getVisualYaw(float) * @see #getVisualYaw(float)
*/ */
@Nonnull @Nonnull
Vec3 getVisualPosition( float f ); Vec3 getVisualPosition(float f);
/** /**
* Returns the yaw the turtle is facing when it is rendered. * Returns the yaw the turtle is facing when it is rendered.
@ -90,7 +89,7 @@ public interface ITurtleAccess
* @return The yaw the turtle is facing. * @return The yaw the turtle is facing.
* @see #getVisualPosition(float) * @see #getVisualPosition(float)
*/ */
float getVisualYaw( float f ); float getVisualYaw(float f);
/** /**
* Returns the world direction the turtle is currently facing. * Returns the world direction the turtle is currently facing.
@ -108,7 +107,7 @@ public interface ITurtleAccess
* @param dir The new direction to set. This should be on either the x or z axis (so north, south, east or west). * @param dir The new direction to set. This should be on either the x or z axis (so north, south, east or west).
* @see #getDirection() * @see #getDirection()
*/ */
void setDirection( @Nonnull Direction dir ); void setDirection(@Nonnull Direction dir);
/** /**
* Get the currently selected slot in the turtle's inventory. * Get the currently selected slot in the turtle's inventory.
@ -128,7 +127,7 @@ public interface ITurtleAccess
* @see #getInventory() * @see #getInventory()
* @see #getSelectedSlot() * @see #getSelectedSlot()
*/ */
void setSelectedSlot( int slot ); void setSelectedSlot(int slot);
/** /**
* Set the colour of the turtle to a RGB number. * Set the colour of the turtle to a RGB number.
@ -137,7 +136,7 @@ public interface ITurtleAccess
* and {@code 0xFFFFFF} or -1 to reset to the default colour. * and {@code 0xFFFFFF} or -1 to reset to the default colour.
* @see #getColour() * @see #getColour()
*/ */
void setColour( int colour ); void setColour(int colour);
/** /**
* Get the colour of this turtle as a RGB number. * Get the colour of this turtle as a RGB number.
@ -178,7 +177,7 @@ public interface ITurtleAccess
* @deprecated Use {@link #getInventory()} directly. * @deprecated Use {@link #getInventory()} directly.
*/ */
@Nonnull @Nonnull
@Deprecated( forRemoval = true ) @Deprecated(forRemoval = true)
IItemHandlerModifiable getItemHandler(); IItemHandlerModifiable getItemHandler();
/** /**
@ -209,7 +208,7 @@ public interface ITurtleAccess
* @see #addFuel(int) * @see #addFuel(int)
* @see #consumeFuel(int) * @see #consumeFuel(int)
*/ */
void setFuelLevel( int fuel ); void setFuelLevel(int fuel);
/** /**
* Get the maximum amount of fuel a turtle can hold. * Get the maximum amount of fuel a turtle can hold.
@ -226,7 +225,7 @@ public interface ITurtleAccess
* greater than the current fuel level of the turtle. No fuel will be consumed if {@code false} is returned. * greater than the current fuel level of the turtle. No fuel will be consumed if {@code false} is returned.
* @throws UnsupportedOperationException When attempting to consume fuel on the client side. * @throws UnsupportedOperationException When attempting to consume fuel on the client side.
*/ */
boolean consumeFuel( int fuel ); boolean consumeFuel(int fuel);
/** /**
* Increase the turtle's fuel level by the given amount. * Increase the turtle's fuel level by the given amount.
@ -234,7 +233,7 @@ public interface ITurtleAccess
* @param fuel The amount to refuel with. * @param fuel The amount to refuel with.
* @throws UnsupportedOperationException When attempting to refuel on the client side. * @throws UnsupportedOperationException When attempting to refuel on the client side.
*/ */
void addFuel( int fuel ); void addFuel(int fuel);
/** /**
* Adds a custom command to the turtles command queue. Unlike peripheral methods, these custom commands will be executed * Adds a custom command to the turtles command queue. Unlike peripheral methods, these custom commands will be executed
@ -251,7 +250,7 @@ public interface ITurtleAccess
* @see MethodResult#pullEvent(String, ILuaCallback) * @see MethodResult#pullEvent(String, ILuaCallback)
*/ */
@Nonnull @Nonnull
MethodResult executeCommand( @Nonnull ITurtleCommand command ); MethodResult executeCommand(@Nonnull ITurtleCommand command);
/** /**
* Start playing a specific animation. This will prevent other turtle commands from executing until * Start playing a specific animation. This will prevent other turtle commands from executing until
@ -261,7 +260,7 @@ public interface ITurtleAccess
* @throws UnsupportedOperationException When attempting to execute play an animation on the client side. * @throws UnsupportedOperationException When attempting to execute play an animation on the client side.
* @see TurtleAnimation * @see TurtleAnimation
*/ */
void playAnimation( @Nonnull TurtleAnimation animation ); void playAnimation(@Nonnull TurtleAnimation animation);
/** /**
* Returns the turtle on the specified side of the turtle, if there is one. * Returns the turtle on the specified side of the turtle, if there is one.
@ -271,7 +270,7 @@ public interface ITurtleAccess
* @see #setUpgrade(TurtleSide, ITurtleUpgrade) * @see #setUpgrade(TurtleSide, ITurtleUpgrade)
*/ */
@Nullable @Nullable
ITurtleUpgrade getUpgrade( @Nonnull TurtleSide side ); ITurtleUpgrade getUpgrade(@Nonnull TurtleSide side);
/** /**
* Set the upgrade for a given side, resetting peripherals and clearing upgrade specific data. * Set the upgrade for a given side, resetting peripherals and clearing upgrade specific data.
@ -280,7 +279,7 @@ public interface ITurtleAccess
* @param upgrade The upgrade to set, may be {@code null} to clear. * @param upgrade The upgrade to set, may be {@code null} to clear.
* @see #getUpgrade(TurtleSide) * @see #getUpgrade(TurtleSide)
*/ */
void setUpgrade( @Nonnull TurtleSide side, @Nullable ITurtleUpgrade upgrade ); void setUpgrade(@Nonnull TurtleSide side, @Nullable ITurtleUpgrade upgrade);
/** /**
* Returns the peripheral created by the upgrade on the specified side of the turtle, if there is one. * Returns the peripheral created by the upgrade on the specified side of the turtle, if there is one.
@ -289,7 +288,7 @@ public interface ITurtleAccess
* @return The peripheral created by the upgrade on the specified side of the turtle, {@code null} if none exists. * @return The peripheral created by the upgrade on the specified side of the turtle, {@code null} if none exists.
*/ */
@Nullable @Nullable
IPeripheral getPeripheral( @Nonnull TurtleSide side ); IPeripheral getPeripheral(@Nonnull TurtleSide side);
/** /**
* Get an upgrade-specific NBT compound, which can be used to store arbitrary data. * Get an upgrade-specific NBT compound, which can be used to store arbitrary data.
@ -302,7 +301,7 @@ public interface ITurtleAccess
* @see #updateUpgradeNBTData(TurtleSide) * @see #updateUpgradeNBTData(TurtleSide)
*/ */
@Nonnull @Nonnull
CompoundTag getUpgradeNBTData( @Nullable TurtleSide side ); CompoundTag getUpgradeNBTData(@Nullable TurtleSide side);
/** /**
* Mark the upgrade-specific data as dirty on a specific side. This is required for the data to be synced to the * Mark the upgrade-specific data as dirty on a specific side. This is required for the data to be synced to the
@ -311,5 +310,5 @@ public interface ITurtleAccess
* @param side The side to mark dirty. * @param side The side to mark dirty.
* @see #updateUpgradeNBTData(TurtleSide) * @see #updateUpgradeNBTData(TurtleSide)
*/ */
void updateUpgradeNBTData( @Nonnull TurtleSide side ); void updateUpgradeNBTData(@Nonnull TurtleSide side);
} }

View File

@ -13,8 +13,7 @@ import javax.annotation.Nonnull;
* @see ITurtleAccess#executeCommand(ITurtleCommand) * @see ITurtleAccess#executeCommand(ITurtleCommand)
*/ */
@FunctionalInterface @FunctionalInterface
public interface ITurtleCommand public interface ITurtleCommand {
{
/** /**
* Will be called by the turtle on the main thread when it is time to execute the custom command. * Will be called by the turtle on the main thread when it is time to execute the custom command.
* <p> * <p>
@ -29,5 +28,5 @@ public interface ITurtleCommand
* @see TurtleCommandResult * @see TurtleCommandResult
*/ */
@Nonnull @Nonnull
TurtleCommandResult execute( @Nonnull ITurtleAccess turtle ); TurtleCommandResult execute(@Nonnull ITurtleAccess turtle);
} }

View File

@ -27,8 +27,7 @@ import javax.annotation.Nullable;
* *
* @see TurtleUpgradeSerialiser For how to register a turtle upgrade. * @see TurtleUpgradeSerialiser For how to register a turtle upgrade.
*/ */
public interface ITurtleUpgrade extends IUpgradeBase public interface ITurtleUpgrade extends IUpgradeBase {
{
/** /**
* Return whether this turtle adds a tool or a peripheral to the turtle. * Return whether this turtle adds a tool or a peripheral to the turtle.
* *
@ -51,8 +50,7 @@ public interface ITurtleUpgrade extends IUpgradeBase
* and this method is not expected to be called. * and this method is not expected to be called.
*/ */
@Nullable @Nullable
default IPeripheral createPeripheral( @Nonnull ITurtleAccess turtle, @Nonnull TurtleSide side ) default IPeripheral createPeripheral(@Nonnull ITurtleAccess turtle, @Nonnull TurtleSide side) {
{
return null; return null;
} }
@ -75,8 +73,7 @@ public interface ITurtleUpgrade extends IUpgradeBase
* to be called. * to be called.
*/ */
@Nonnull @Nonnull
default TurtleCommandResult useTool( @Nonnull ITurtleAccess turtle, @Nonnull TurtleSide side, @Nonnull TurtleVerb verb, @Nonnull Direction direction ) default TurtleCommandResult useTool(@Nonnull ITurtleAccess turtle, @Nonnull TurtleSide side, @Nonnull TurtleVerb verb, @Nonnull Direction direction) {
{
return TurtleCommandResult.failure(); return TurtleCommandResult.failure();
} }
@ -86,7 +83,6 @@ public interface ITurtleUpgrade extends IUpgradeBase
* @param turtle Access to the turtle that the upgrade resides on. * @param turtle Access to the turtle that the upgrade resides on.
* @param side Which side of the turtle (left or right) the upgrade resides on. * @param side Which side of the turtle (left or right) the upgrade resides on.
*/ */
default void update( @Nonnull ITurtleAccess turtle, @Nonnull TurtleSide side ) default void update(@Nonnull ITurtleAccess turtle, @Nonnull TurtleSide side) {
{
} }
} }

View File

@ -12,8 +12,7 @@ package dan200.computercraft.api.turtle;
* *
* @see ITurtleAccess#playAnimation(TurtleAnimation) * @see ITurtleAccess#playAnimation(TurtleAnimation)
*/ */
public enum TurtleAnimation public enum TurtleAnimation {
{
/** /**
* An animation which does nothing. This takes no time to complete. * An animation which does nothing. This takes no time to complete.
* *

View File

@ -16,10 +16,9 @@ import javax.annotation.Nullable;
* @see ITurtleCommand#execute(ITurtleAccess) * @see ITurtleCommand#execute(ITurtleAccess)
* @see ITurtleUpgrade#useTool(ITurtleAccess, TurtleSide, TurtleVerb, Direction) * @see ITurtleUpgrade#useTool(ITurtleAccess, TurtleSide, TurtleVerb, Direction)
*/ */
public final class TurtleCommandResult public final class TurtleCommandResult {
{ private static final TurtleCommandResult EMPTY_SUCCESS = new TurtleCommandResult(true, null, null);
private static final TurtleCommandResult EMPTY_SUCCESS = new TurtleCommandResult( true, null, null ); private static final TurtleCommandResult EMPTY_FAILURE = new TurtleCommandResult(false, null, null);
private static final TurtleCommandResult EMPTY_FAILURE = new TurtleCommandResult( false, null, null );
/** /**
* Create a successful command result with no result. * Create a successful command result with no result.
@ -27,8 +26,7 @@ public final class TurtleCommandResult
* @return A successful command result with no values. * @return A successful command result with no values.
*/ */
@Nonnull @Nonnull
public static TurtleCommandResult success() public static TurtleCommandResult success() {
{
return EMPTY_SUCCESS; return EMPTY_SUCCESS;
} }
@ -39,10 +37,9 @@ public final class TurtleCommandResult
* @return A successful command result with the given values. * @return A successful command result with the given values.
*/ */
@Nonnull @Nonnull
public static TurtleCommandResult success( @Nullable Object[] results ) public static TurtleCommandResult success(@Nullable Object[] results) {
{ if (results == null || results.length == 0) return EMPTY_SUCCESS;
if( results == null || results.length == 0 ) return EMPTY_SUCCESS; return new TurtleCommandResult(true, null, results);
return new TurtleCommandResult( true, null, results );
} }
/** /**
@ -51,8 +48,7 @@ public final class TurtleCommandResult
* @return A failed command result with no message. * @return A failed command result with no message.
*/ */
@Nonnull @Nonnull
public static TurtleCommandResult failure() public static TurtleCommandResult failure() {
{
return EMPTY_FAILURE; return EMPTY_FAILURE;
} }
@ -63,18 +59,16 @@ public final class TurtleCommandResult
* @return A failed command result with a message. * @return A failed command result with a message.
*/ */
@Nonnull @Nonnull
public static TurtleCommandResult failure( @Nullable String errorMessage ) public static TurtleCommandResult failure(@Nullable String errorMessage) {
{ if (errorMessage == null) return EMPTY_FAILURE;
if( errorMessage == null ) return EMPTY_FAILURE; return new TurtleCommandResult(false, errorMessage, null);
return new TurtleCommandResult( false, errorMessage, null );
} }
private final boolean success; private final boolean success;
private final String errorMessage; private final String errorMessage;
private final Object[] results; private final Object[] results;
private TurtleCommandResult( boolean success, String errorMessage, Object[] results ) private TurtleCommandResult(boolean success, String errorMessage, Object[] results) {
{
this.success = success; this.success = success;
this.errorMessage = errorMessage; this.errorMessage = errorMessage;
this.results = results; this.results = results;
@ -85,8 +79,7 @@ public final class TurtleCommandResult
* *
* @return If the command was successful. * @return If the command was successful.
*/ */
public boolean isSuccess() public boolean isSuccess() {
{
return success; return success;
} }
@ -96,8 +89,7 @@ public final class TurtleCommandResult
* @return The command's error message, or {@code null} if it was a success. * @return The command's error message, or {@code null} if it was a success.
*/ */
@Nullable @Nullable
public String getErrorMessage() public String getErrorMessage() {
{
return errorMessage; return errorMessage;
} }
@ -107,8 +99,7 @@ public final class TurtleCommandResult
* @return The command's result, or {@code null} if it was a failure. * @return The command's result, or {@code null} if it was a failure.
*/ */
@Nullable @Nullable
public Object[] getResults() public Object[] getResults() {
{
return results; return results;
} }
} }

View File

@ -16,8 +16,7 @@ import java.util.OptionalInt;
* *
* @see ComputerCraftAPI#registerRefuelHandler(TurtleRefuelHandler) * @see ComputerCraftAPI#registerRefuelHandler(TurtleRefuelHandler)
*/ */
public interface TurtleRefuelHandler public interface TurtleRefuelHandler {
{
/** /**
* Refuel a turtle using an item. * Refuel a turtle using an item.
* *
@ -31,5 +30,5 @@ public interface TurtleRefuelHandler
* {@code OptionalInt#of(0)} if so), but should <em>NOT</em> modify the stack or inventory. * {@code OptionalInt#of(0)} if so), but should <em>NOT</em> modify the stack or inventory.
* @return The amount of fuel gained, or {@link OptionalInt#empty()} if this handler does not accept the given item. * @return The amount of fuel gained, or {@link OptionalInt#empty()} if this handler does not accept the given item.
*/ */
OptionalInt refuel( ITurtleAccess turtle, ItemStack stack, int slot, int limit ); OptionalInt refuel(ITurtleAccess turtle, ItemStack stack, int slot, int limit);
} }

View File

@ -8,8 +8,7 @@ package dan200.computercraft.api.turtle;
/** /**
* An enum representing the two sides of the turtle that a turtle turtle might reside. * An enum representing the two sides of the turtle that a turtle turtle might reside.
*/ */
public enum TurtleSide public enum TurtleSide {
{
/** /**
* The turtle's left side (where the pickaxe usually is on a Wireless Mining Turtle). * The turtle's left side (where the pickaxe usually is on a Wireless Mining Turtle).
*/ */

View File

@ -29,13 +29,11 @@ import java.util.function.Consumer;
* @see GatherDataEvent To register your data provider * @see GatherDataEvent To register your data provider
* @see TurtleUpgradeSerialiser * @see TurtleUpgradeSerialiser
*/ */
public abstract class TurtleUpgradeDataProvider extends UpgradeDataProvider<ITurtleUpgrade, TurtleUpgradeSerialiser<?>> public abstract class TurtleUpgradeDataProvider extends UpgradeDataProvider<ITurtleUpgrade, TurtleUpgradeSerialiser<?>> {
{ private static final ResourceLocation TOOL_ID = new ResourceLocation(ComputerCraftAPI.MOD_ID, "tool");
private static final ResourceLocation TOOL_ID = new ResourceLocation( ComputerCraftAPI.MOD_ID, "tool" );
public TurtleUpgradeDataProvider( DataGenerator generator ) public TurtleUpgradeDataProvider(DataGenerator generator) {
{ super(generator, "Turtle Upgrades", "computercraft/turtle_upgrades", TurtleUpgradeSerialiser.REGISTRY_ID);
super( generator, "Turtle Upgrades", "computercraft/turtle_upgrades", TurtleUpgradeSerialiser.REGISTRY_ID );
} }
/** /**
@ -47,9 +45,8 @@ public abstract class TurtleUpgradeDataProvider extends UpgradeDataProvider<ITur
* @return A tool builder, * @return A tool builder,
*/ */
@Nonnull @Nonnull
public final ToolBuilder tool( @Nonnull ResourceLocation id, @Nonnull Item item ) public final ToolBuilder tool(@Nonnull ResourceLocation id, @Nonnull Item item) {
{ return new ToolBuilder(id, existingSerialiser(TOOL_ID), item);
return new ToolBuilder( id, existingSerialiser( TOOL_ID ), item );
} }
/** /**
@ -57,8 +54,7 @@ public abstract class TurtleUpgradeDataProvider extends UpgradeDataProvider<ITur
* *
* @see #tool(ResourceLocation, Item) * @see #tool(ResourceLocation, Item)
*/ */
public static class ToolBuilder public static class ToolBuilder {
{
private final ResourceLocation id; private final ResourceLocation id;
private final TurtleUpgradeSerialiser<?> serialiser; private final TurtleUpgradeSerialiser<?> serialiser;
private final Item toolItem; private final Item toolItem;
@ -67,8 +63,7 @@ public abstract class TurtleUpgradeDataProvider extends UpgradeDataProvider<ITur
private Float damageMultiplier = null; private Float damageMultiplier = null;
private TagKey<Block> breakable; private TagKey<Block> breakable;
ToolBuilder( ResourceLocation id, TurtleUpgradeSerialiser<?> serialiser, Item toolItem ) ToolBuilder(ResourceLocation id, TurtleUpgradeSerialiser<?> serialiser, Item toolItem) {
{
this.id = id; this.id = id;
this.serialiser = serialiser; this.serialiser = serialiser;
this.toolItem = toolItem; this.toolItem = toolItem;
@ -82,8 +77,7 @@ public abstract class TurtleUpgradeDataProvider extends UpgradeDataProvider<ITur
* @return The tool builder, for further use. * @return The tool builder, for further use.
*/ */
@Nonnull @Nonnull
public ToolBuilder adjective( @Nonnull String adjective ) public ToolBuilder adjective(@Nonnull String adjective) {
{
this.adjective = adjective; this.adjective = adjective;
return this; return this;
} }
@ -96,8 +90,7 @@ public abstract class TurtleUpgradeDataProvider extends UpgradeDataProvider<ITur
* @return The tool builder, for further use. * @return The tool builder, for further use.
*/ */
@Nonnull @Nonnull
public ToolBuilder craftingItem( @Nonnull Item craftingItem ) public ToolBuilder craftingItem(@Nonnull Item craftingItem) {
{
this.craftingItem = craftingItem; this.craftingItem = craftingItem;
return this; return this;
} }
@ -109,8 +102,7 @@ public abstract class TurtleUpgradeDataProvider extends UpgradeDataProvider<ITur
* @param damageMultiplier The damage multiplier. * @param damageMultiplier The damage multiplier.
* @return The tool builder, for futher use. * @return The tool builder, for futher use.
*/ */
public ToolBuilder damageMultiplier( float damageMultiplier ) public ToolBuilder damageMultiplier(float damageMultiplier) {
{
this.damageMultiplier = damageMultiplier; this.damageMultiplier = damageMultiplier;
return this; return this;
} }
@ -124,8 +116,7 @@ public abstract class TurtleUpgradeDataProvider extends UpgradeDataProvider<ITur
* @return The tool builder, for further use. * @return The tool builder, for further use.
* @see ComputerCraftTags.Blocks * @see ComputerCraftTags.Blocks
*/ */
public ToolBuilder breakable( @Nonnull TagKey<Block> breakable ) public ToolBuilder breakable(@Nonnull TagKey<Block> breakable) {
{
this.breakable = breakable; this.breakable = breakable;
return this; return this;
} }
@ -135,18 +126,16 @@ public abstract class TurtleUpgradeDataProvider extends UpgradeDataProvider<ITur
* *
* @param add The callback given to {@link #addUpgrades(Consumer)}. * @param add The callback given to {@link #addUpgrades(Consumer)}.
*/ */
public void add( @Nonnull Consumer<Upgrade<TurtleUpgradeSerialiser<?>>> add ) public void add(@Nonnull Consumer<Upgrade<TurtleUpgradeSerialiser<?>>> add) {
{ add.accept(new Upgrade<>(id, serialiser, s -> {
add.accept( new Upgrade<>( id, serialiser, s -> { s.addProperty("item", ForgeRegistries.ITEMS.getKey(toolItem).toString());
s.addProperty( "item", ForgeRegistries.ITEMS.getKey( toolItem ).toString() ); if (adjective != null) s.addProperty("adjective", adjective);
if( adjective != null ) s.addProperty( "adjective", adjective ); if (craftingItem != null) {
if( craftingItem != null ) s.addProperty("craftItem", ForgeRegistries.ITEMS.getKey(craftingItem).toString());
{
s.addProperty( "craftItem", ForgeRegistries.ITEMS.getKey( craftingItem ).toString() );
} }
if( damageMultiplier != null ) s.addProperty( "damageMultiplier", damageMultiplier ); if (damageMultiplier != null) s.addProperty("damageMultiplier", damageMultiplier);
if( breakable != null ) s.addProperty( "breakable", breakable.location().toString() ); if (breakable != null) s.addProperty("breakable", breakable.location().toString());
} ) ); }));
} }
} }
} }

View File

@ -71,15 +71,14 @@ import java.util.function.Function;
* @see TurtleUpgradeDataProvider * @see TurtleUpgradeDataProvider
* @see TurtleUpgradeModeller * @see TurtleUpgradeModeller
*/ */
public interface TurtleUpgradeSerialiser<T extends ITurtleUpgrade> extends UpgradeSerialiser<T> public interface TurtleUpgradeSerialiser<T extends ITurtleUpgrade> extends UpgradeSerialiser<T> {
{
/** /**
* The ID for the associated registry. * The ID for the associated registry.
* <p> * <p>
* This is largely intended for use with Forge Registry methods/classes, such as {@link DeferredRegister} and * This is largely intended for use with Forge Registry methods/classes, such as {@link DeferredRegister} and
* {@link RegistryManager#getRegistry(ResourceKey)}. * {@link RegistryManager#getRegistry(ResourceKey)}.
*/ */
ResourceKey<Registry<TurtleUpgradeSerialiser<?>>> REGISTRY_ID = ResourceKey.createRegistryKey( new ResourceLocation( ComputerCraft.MOD_ID, "turtle_upgrade_serialiser" ) ); ResourceKey<Registry<TurtleUpgradeSerialiser<?>>> REGISTRY_ID = ResourceKey.createRegistryKey(new ResourceLocation(ComputerCraft.MOD_ID, "turtle_upgrade_serialiser"));
/** /**
* The associated registry. * The associated registry.
@ -88,10 +87,9 @@ public interface TurtleUpgradeSerialiser<T extends ITurtleUpgrade> extends Upgra
* @see #REGISTRY_ID * @see #REGISTRY_ID
* @deprecated Use {@link #REGISTRY_ID} directly. * @deprecated Use {@link #REGISTRY_ID} directly.
*/ */
@Deprecated( forRemoval = true ) @Deprecated(forRemoval = true)
static IForgeRegistry<TurtleUpgradeSerialiser<?>> registry() static IForgeRegistry<TurtleUpgradeSerialiser<?>> registry() {
{ return RegistryManager.ACTIVE.getRegistry(REGISTRY_ID);
return RegistryManager.ACTIVE.getRegistry( REGISTRY_ID );
} }
/** /**
@ -105,17 +103,14 @@ public interface TurtleUpgradeSerialiser<T extends ITurtleUpgrade> extends Upgra
* @return The serialiser for this upgrade * @return The serialiser for this upgrade
*/ */
@Nonnull @Nonnull
static <T extends ITurtleUpgrade> TurtleUpgradeSerialiser<T> simple( @Nonnull Function<ResourceLocation, T> factory ) static <T extends ITurtleUpgrade> TurtleUpgradeSerialiser<T> simple(@Nonnull Function<ResourceLocation, T> factory) {
{ final class Impl extends SimpleSerialiser<T> implements TurtleUpgradeSerialiser<T> {
final class Impl extends SimpleSerialiser<T> implements TurtleUpgradeSerialiser<T> private Impl(Function<ResourceLocation, T> constructor) {
{ super(constructor);
private Impl( Function<ResourceLocation, T> constructor )
{
super( constructor );
} }
} }
return new Impl( factory ); return new Impl(factory);
} }
/** /**
@ -128,16 +123,13 @@ public interface TurtleUpgradeSerialiser<T extends ITurtleUpgrade> extends Upgra
* @see #simple(Function) For upgrades whose crafting stack should not vary. * @see #simple(Function) For upgrades whose crafting stack should not vary.
*/ */
@Nonnull @Nonnull
static <T extends ITurtleUpgrade> TurtleUpgradeSerialiser<T> simpleWithCustomItem( @Nonnull BiFunction<ResourceLocation, ItemStack, T> factory ) static <T extends ITurtleUpgrade> TurtleUpgradeSerialiser<T> simpleWithCustomItem(@Nonnull BiFunction<ResourceLocation, ItemStack, T> factory) {
{ final class Impl extends SerialiserWithCraftingItem<T> implements TurtleUpgradeSerialiser<T> {
final class Impl extends SerialiserWithCraftingItem<T> implements TurtleUpgradeSerialiser<T> private Impl(BiFunction<ResourceLocation, ItemStack, T> factory) {
{ super(factory);
private Impl( BiFunction<ResourceLocation, ItemStack, T> factory )
{
super( factory );
} }
} }
return new Impl( factory ); return new Impl(factory);
} }
} }

View File

@ -10,8 +10,7 @@ package dan200.computercraft.api.turtle;
* *
* @see ITurtleUpgrade#getType() * @see ITurtleUpgrade#getType()
*/ */
public enum TurtleUpgradeType public enum TurtleUpgradeType {
{
/** /**
* A tool is rendered as an item on the side of the turtle, and responds to the {@code turtle.dig()} * A tool is rendered as an item on the side of the turtle, and responds to the {@code turtle.dig()}
* and {@code turtle.attack()} methods (Such as pickaxe or sword on Mining and Melee turtles). * and {@code turtle.attack()} methods (Such as pickaxe or sword on Mining and Melee turtles).
@ -31,13 +30,11 @@ public enum TurtleUpgradeType
*/ */
BOTH; BOTH;
public boolean isTool() public boolean isTool() {
{
return this == TOOL || this == BOTH; return this == TOOL || this == BOTH;
} }
public boolean isPeripheral() public boolean isPeripheral() {
{
return this == PERIPHERAL || this == BOTH; return this == PERIPHERAL || this == BOTH;
} }
} }

View File

@ -14,8 +14,7 @@ import net.minecraft.core.Direction;
* @see ITurtleUpgrade#getType() * @see ITurtleUpgrade#getType()
* @see ITurtleUpgrade#useTool(ITurtleAccess, TurtleSide, TurtleVerb, Direction) * @see ITurtleUpgrade#useTool(ITurtleAccess, TurtleSide, TurtleVerb, Direction)
*/ */
public enum TurtleVerb public enum TurtleVerb {
{
/** /**
* The turtle called {@code turtle.dig()}, {@code turtle.digUp()} or {@code turtle.digDown()}. * The turtle called {@code turtle.dig()}, {@code turtle.digUp()} or {@code turtle.digDown()}.
*/ */

View File

@ -19,14 +19,12 @@ import java.util.Objects;
* *
* @deprecated No longer needed, see {@link TurtleRefuelEvent}. * @deprecated No longer needed, see {@link TurtleRefuelEvent}.
*/ */
@Deprecated( forRemoval = true ) @Deprecated(forRemoval = true)
public abstract class TurtleEvent extends Event public abstract class TurtleEvent extends Event {
{
private final ITurtleAccess turtle; private final ITurtleAccess turtle;
protected TurtleEvent( @Nonnull ITurtleAccess turtle ) protected TurtleEvent(@Nonnull ITurtleAccess turtle) {
{ Objects.requireNonNull(turtle, "turtle cannot be null");
Objects.requireNonNull( turtle, "turtle cannot be null" );
this.turtle = turtle; this.turtle = turtle;
} }
@ -36,8 +34,7 @@ public abstract class TurtleEvent extends Event
* @return The access for this turtle. * @return The access for this turtle.
*/ */
@Nonnull @Nonnull
public ITurtleAccess getTurtle() public ITurtleAccess getTurtle() {
{
return turtle; return turtle;
} }
} }

View File

@ -20,17 +20,15 @@ import java.util.Objects;
* *
* @deprecated Use {@link TurtleRefuelHandler} instead. * @deprecated Use {@link TurtleRefuelHandler} instead.
*/ */
@Deprecated( forRemoval = true ) @Deprecated(forRemoval = true)
public class TurtleRefuelEvent extends TurtleEvent public class TurtleRefuelEvent extends TurtleEvent {
{
private final ItemStack stack; private final ItemStack stack;
private Handler handler; private Handler handler;
public TurtleRefuelEvent( @Nonnull ITurtleAccess turtle, @Nonnull ItemStack stack ) public TurtleRefuelEvent(@Nonnull ITurtleAccess turtle, @Nonnull ItemStack stack) {
{ super(turtle);
super( turtle );
Objects.requireNonNull( turtle, "turtle cannot be null" ); Objects.requireNonNull(turtle, "turtle cannot be null");
this.stack = stack; this.stack = stack;
} }
@ -41,8 +39,7 @@ public class TurtleRefuelEvent extends TurtleEvent
* *
* @return The stack to refuel from. * @return The stack to refuel from.
*/ */
public ItemStack getStack() public ItemStack getStack() {
{
return stack; return stack;
} }
@ -53,8 +50,7 @@ public class TurtleRefuelEvent extends TurtleEvent
* @see #setHandler(Handler) * @see #setHandler(Handler)
*/ */
@Nullable @Nullable
public Handler getHandler() public Handler getHandler() {
{
return handler; return handler;
} }
@ -67,8 +63,7 @@ public class TurtleRefuelEvent extends TurtleEvent
* @param handler The new refuel handler. * @param handler The new refuel handler.
* @see #getHandler() * @see #getHandler()
*/ */
public void setHandler( @Nullable Handler handler ) public void setHandler(@Nullable Handler handler) {
{
this.handler = handler; this.handler = handler;
} }
@ -76,8 +71,7 @@ public class TurtleRefuelEvent extends TurtleEvent
* Handles refuelling a turtle from a specific item. * Handles refuelling a turtle from a specific item.
*/ */
@FunctionalInterface @FunctionalInterface
public interface Handler public interface Handler {
{
/** /**
* Refuel a turtle using an item. * Refuel a turtle using an item.
* *
@ -88,6 +82,6 @@ public class TurtleRefuelEvent extends TurtleEvent
* items to consume. * items to consume.
* @return The amount of fuel gained. * @return The amount of fuel gained.
*/ */
int refuel( @Nonnull ITurtleAccess turtle, @Nonnull ItemStack stack, int slot, int limit ); int refuel(@Nonnull ITurtleAccess turtle, @Nonnull ItemStack stack, int slot, int limit);
} }
} }

View File

@ -8,7 +8,6 @@ package dan200.computercraft.api.upgrades;
import dan200.computercraft.api.pocket.IPocketUpgrade; import dan200.computercraft.api.pocket.IPocketUpgrade;
import dan200.computercraft.api.turtle.ITurtleUpgrade; import dan200.computercraft.api.turtle.ITurtleUpgrade;
import net.minecraft.Util; import net.minecraft.Util;
import net.minecraft.nbt.CompoundTag;
import net.minecraft.resources.ResourceLocation; import net.minecraft.resources.ResourceLocation;
import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.ItemStack;
@ -17,8 +16,7 @@ import javax.annotation.Nonnull;
/** /**
* Common functionality between {@link ITurtleUpgrade} and {@link IPocketUpgrade}. * Common functionality between {@link ITurtleUpgrade} and {@link IPocketUpgrade}.
*/ */
public interface IUpgradeBase public interface IUpgradeBase {
{
/** /**
* Gets a unique identifier representing this type of turtle upgrade. eg: "computercraft:wireless_modem" * Gets a unique identifier representing this type of turtle upgrade. eg: "computercraft:wireless_modem"
* or "my_mod:my_upgrade". * or "my_mod:my_upgrade".
@ -71,18 +69,17 @@ public interface IUpgradeBase
* @see net.minecraftforge.common.crafting.StrictNBTIngredient#test(ItemStack) For the implementation of the default * @see net.minecraftforge.common.crafting.StrictNBTIngredient#test(ItemStack) For the implementation of the default
* check. * check.
*/ */
default boolean isItemSuitable( @Nonnull ItemStack stack ) default boolean isItemSuitable(@Nonnull ItemStack stack) {
{ var crafting = getCraftingItem();
ItemStack crafting = getCraftingItem();
// A more expanded form of ItemStack.areShareTagsEqual, but allowing an empty tag to be equal to a // A more expanded form of ItemStack.areShareTagsEqual, but allowing an empty tag to be equal to a
// null one. // null one.
CompoundTag shareTag = stack.getItem().getShareTag( stack ); var shareTag = stack.getItem().getShareTag(stack);
CompoundTag craftingShareTag = crafting.getItem().getShareTag( crafting ); var craftingShareTag = crafting.getItem().getShareTag(crafting);
if( shareTag == craftingShareTag ) return true; if (shareTag == craftingShareTag) return true;
if( shareTag == null ) return craftingShareTag.isEmpty(); if (shareTag == null) return craftingShareTag.isEmpty();
if( craftingShareTag == null ) return shareTag.isEmpty(); if (craftingShareTag == null) return shareTag.isEmpty();
return shareTag.equals( craftingShareTag ); return shareTag.equals(craftingShareTag);
} }
/** /**
@ -94,8 +91,7 @@ public interface IUpgradeBase
* @see #getUnlocalisedAdjective() * @see #getUnlocalisedAdjective()
*/ */
@Nonnull @Nonnull
static String getDefaultAdjective( @Nonnull ResourceLocation id ) static String getDefaultAdjective(@Nonnull ResourceLocation id) {
{ return Util.makeDescriptionId("upgrade", id) + ".adjective";
return Util.makeDescriptionId( "upgrade", id ) + ".adjective";
} }
} }

View File

@ -24,7 +24,6 @@ import org.apache.logging.log4j.Logger;
import javax.annotation.Nonnull; import javax.annotation.Nonnull;
import java.io.IOException; import java.io.IOException;
import java.nio.file.Path;
import java.util.*; import java.util.*;
import java.util.function.Consumer; import java.util.function.Consumer;
import java.util.function.Function; import java.util.function.Function;
@ -36,8 +35,7 @@ import java.util.function.Function;
* @param <T> The base class of upgrades. * @param <T> The base class of upgrades.
* @param <R> The upgrade serialiser to register for. * @param <R> The upgrade serialiser to register for.
*/ */
public abstract class UpgradeDataProvider<T extends IUpgradeBase, R extends UpgradeSerialiser<? extends T>> implements DataProvider public abstract class UpgradeDataProvider<T extends IUpgradeBase, R extends UpgradeSerialiser<? extends T>> implements DataProvider {
{
private static final Logger LOGGER = LogManager.getLogger(); private static final Logger LOGGER = LogManager.getLogger();
private final DataGenerator generator; private final DataGenerator generator;
@ -47,8 +45,7 @@ public abstract class UpgradeDataProvider<T extends IUpgradeBase, R extends Upgr
private List<T> upgrades; private List<T> upgrades;
protected UpgradeDataProvider( @Nonnull DataGenerator generator, @Nonnull String name, @Nonnull String folder, @Nonnull ResourceKey<Registry<R>> registry ) protected UpgradeDataProvider(@Nonnull DataGenerator generator, @Nonnull String name, @Nonnull String folder, @Nonnull ResourceKey<Registry<R>> registry) {
{
this.generator = generator; this.generator = generator;
this.name = name; this.name = name;
this.folder = folder; this.folder = folder;
@ -63,14 +60,13 @@ public abstract class UpgradeDataProvider<T extends IUpgradeBase, R extends Upgr
* @return The constructed upgrade, ready to be passed off to {@link #addUpgrades(Consumer)}'s consumer. * @return The constructed upgrade, ready to be passed off to {@link #addUpgrades(Consumer)}'s consumer.
*/ */
@Nonnull @Nonnull
public final Upgrade<R> simple( @Nonnull ResourceLocation id, @Nonnull R serialiser ) public final Upgrade<R> simple(@Nonnull ResourceLocation id, @Nonnull R serialiser) {
{ if (!(serialiser instanceof SimpleSerialiser)) {
if( !(serialiser instanceof SimpleSerialiser) ) throw new IllegalStateException(serialiser + " must be a simple() seriaiser.");
{
throw new IllegalStateException( serialiser + " must be a simple() seriaiser." );
} }
return new Upgrade<>( id, serialiser, s -> {} ); return new Upgrade<>(id, serialiser, s -> {
});
} }
/** /**
@ -82,15 +78,13 @@ public abstract class UpgradeDataProvider<T extends IUpgradeBase, R extends Upgr
* @return The constructed upgrade, ready to be passed off to {@link #addUpgrades(Consumer)}'s consumer. * @return The constructed upgrade, ready to be passed off to {@link #addUpgrades(Consumer)}'s consumer.
*/ */
@Nonnull @Nonnull
public final Upgrade<R> simpleWithCustomItem( @Nonnull ResourceLocation id, @Nonnull R serialiser, @Nonnull Item item ) public final Upgrade<R> simpleWithCustomItem(@Nonnull ResourceLocation id, @Nonnull R serialiser, @Nonnull Item item) {
{ if (!(serialiser instanceof SerialiserWithCraftingItem)) {
if( !(serialiser instanceof SerialiserWithCraftingItem) ) throw new IllegalStateException(serialiser + " must be a simpleWithCustomItem() serialiser.");
{
throw new IllegalStateException( serialiser + " must be a simpleWithCustomItem() serialiser." );
} }
return new Upgrade<>( id, serialiser, s -> return new Upgrade<>(id, serialiser, s ->
s.addProperty( "item", Objects.requireNonNull( ForgeRegistries.ITEMS.getKey( item ), "Item is not registered" ).toString() ) s.addProperty("item", Objects.requireNonNull(ForgeRegistries.ITEMS.getKey(item), "Item is not registered").toString())
); );
} }
@ -106,65 +100,55 @@ public abstract class UpgradeDataProvider<T extends IUpgradeBase, R extends Upgr
* *
* @param addUpgrade A callback used to register an upgrade. * @param addUpgrade A callback used to register an upgrade.
*/ */
protected abstract void addUpgrades( @Nonnull Consumer<Upgrade<R>> addUpgrade ); protected abstract void addUpgrades(@Nonnull Consumer<Upgrade<R>> addUpgrade);
@Override @Override
public final void run( @Nonnull CachedOutput cache ) throws IOException public final void run(@Nonnull CachedOutput cache) throws IOException {
{ var registry = RegistryManager.ACTIVE.getRegistry(this.registry);
var registry = RegistryManager.ACTIVE.getRegistry( this.registry ); var base = generator.getOutputFolder().resolve("data");
Path base = generator.getOutputFolder().resolve( "data" );
Set<ResourceLocation> seen = new HashSet<>(); Set<ResourceLocation> seen = new HashSet<>();
List<T> upgrades = new ArrayList<>(); List<T> upgrades = new ArrayList<>();
addUpgrades( upgrade -> { addUpgrades(upgrade -> {
if( !seen.add( upgrade.id() ) ) throw new IllegalStateException( "Duplicate upgrade " + upgrade.id() ); if (!seen.add(upgrade.id())) throw new IllegalStateException("Duplicate upgrade " + upgrade.id());
var json = new JsonObject(); var json = new JsonObject();
json.addProperty( "type", Objects.requireNonNull( registry.getKey( upgrade.serialiser() ), "Serialiser has not been registered" ).toString() ); json.addProperty("type", Objects.requireNonNull(registry.getKey(upgrade.serialiser()), "Serialiser has not been registered").toString());
upgrade.serialise().accept( json ); upgrade.serialise().accept(json);
try try {
{ DataProvider.saveStable(cache, json, base.resolve(upgrade.id().getNamespace() + "/" + folder + "/" + upgrade.id().getPath() + ".json"));
DataProvider.saveStable( cache, json, base.resolve( upgrade.id().getNamespace() + "/" + folder + "/" + upgrade.id().getPath() + ".json" ) ); } catch (IOException e) {
} LOGGER.error("Failed to save {} {}", name, upgrade.id(), e);
catch( IOException e )
{
LOGGER.error( "Failed to save {} {}", name, upgrade.id(), e );
} }
try try {
{ var result = upgrade.serialiser().fromJson(upgrade.id(), json);
var result = upgrade.serialiser().fromJson( upgrade.id(), json ); upgrades.add(result);
upgrades.add( result ); } catch (IllegalArgumentException | JsonParseException e) {
LOGGER.error("Failed to parse {} {}", name, upgrade.id(), e);
} }
catch( IllegalArgumentException | JsonParseException e ) });
{
LOGGER.error( "Failed to parse {} {}", name, upgrade.id(), e );
}
} );
this.upgrades = upgrades; this.upgrades = upgrades;
} }
@Nonnull @Nonnull
@Override @Override
public final String getName() public final String getName() {
{
return name; return name;
} }
@Nonnull @Nonnull
public final R existingSerialiser( @Nonnull ResourceLocation id ) public final R existingSerialiser(@Nonnull ResourceLocation id) {
{ var result = RegistryManager.ACTIVE.getRegistry(registry).getValue(id);
var result = RegistryManager.ACTIVE.getRegistry( registry ).getValue( id ); if (result == null) throw new IllegalArgumentException("No such serialiser " + registry);
if( result == null ) throw new IllegalArgumentException( "No such serialiser " + registry );
return result; return result;
} }
@Nonnull @Nonnull
public List<T> getGeneratedUpgrades() public List<T> getGeneratedUpgrades() {
{ if (upgrades == null) throw new IllegalStateException("Upgrades have not beeen generated yet");
if( upgrades == null ) throw new IllegalStateException( "Upgrades have not beeen generated yet" );
return upgrades; return upgrades;
} }
@ -178,16 +162,14 @@ public abstract class UpgradeDataProvider<T extends IUpgradeBase, R extends Upgr
*/ */
public record Upgrade<R extends UpgradeSerialiser<?>>( public record Upgrade<R extends UpgradeSerialiser<?>>(
ResourceLocation id, R serialiser, Consumer<JsonObject> serialise ResourceLocation id, R serialiser, Consumer<JsonObject> serialise
) ) {
{
/** /**
* Convenience method for registering an upgrade. * Convenience method for registering an upgrade.
* *
* @param add The callback given to {@link #addUpgrades(Consumer)} * @param add The callback given to {@link #addUpgrades(Consumer)}
*/ */
public void add( @Nonnull Consumer<Upgrade<R>> add ) public void add(@Nonnull Consumer<Upgrade<R>> add) {
{ add.accept(this);
add.accept( this );
} }
} }
} }

View File

@ -23,8 +23,7 @@ import javax.annotation.Nonnull;
* @see TurtleUpgradeSerialiser * @see TurtleUpgradeSerialiser
* @see PocketUpgradeSerialiser * @see PocketUpgradeSerialiser
*/ */
public interface UpgradeSerialiser<T extends IUpgradeBase> public interface UpgradeSerialiser<T extends IUpgradeBase> {
{
/** /**
* Read this upgrade from a JSON file in a datapack. * Read this upgrade from a JSON file in a datapack.
* *
@ -34,7 +33,7 @@ public interface UpgradeSerialiser<T extends IUpgradeBase>
* @see net.minecraft.util.GsonHelper For additional JSON helper methods. * @see net.minecraft.util.GsonHelper For additional JSON helper methods.
*/ */
@Nonnull @Nonnull
T fromJson( @Nonnull ResourceLocation id, @Nonnull JsonObject object ); T fromJson(@Nonnull ResourceLocation id, @Nonnull JsonObject object);
/** /**
* Read this upgrade from a network packet, sent from the server. * Read this upgrade from a network packet, sent from the server.
@ -44,7 +43,7 @@ public interface UpgradeSerialiser<T extends IUpgradeBase>
* @return The constructed upgrade, with a {@link IUpgradeBase#getUpgradeID()} equal to {@code id}. * @return The constructed upgrade, with a {@link IUpgradeBase#getUpgradeID()} equal to {@code id}.
*/ */
@Nonnull @Nonnull
T fromNetwork( @Nonnull ResourceLocation id, @Nonnull FriendlyByteBuf buffer ); T fromNetwork(@Nonnull ResourceLocation id, @Nonnull FriendlyByteBuf buffer);
/** /**
* Write this upgrade to a network packet, to be sent to the client. * Write this upgrade to a network packet, to be sent to the client.
@ -52,6 +51,6 @@ public interface UpgradeSerialiser<T extends IUpgradeBase>
* @param buffer The buffer object to write this upgrade to * @param buffer The buffer object to write this upgrade to
* @param upgrade The upgrade to write. * @param upgrade The upgrade to write.
*/ */
void toNetwork( @Nonnull FriendlyByteBuf buffer, @Nonnull T upgrade ); void toNetwork(@Nonnull FriendlyByteBuf buffer, @Nonnull T upgrade);
} }

View File

@ -15,28 +15,23 @@ import net.minecraftforge.event.level.LevelEvent;
import net.minecraftforge.eventbus.api.SubscribeEvent; import net.minecraftforge.eventbus.api.SubscribeEvent;
import net.minecraftforge.fml.common.Mod; import net.minecraftforge.fml.common.Mod;
@Mod.EventBusSubscriber( modid = ComputerCraft.MOD_ID, value = Dist.CLIENT ) @Mod.EventBusSubscriber(modid = ComputerCraft.MOD_ID, value = Dist.CLIENT)
public class ClientHooks public class ClientHooks {
{
@SubscribeEvent @SubscribeEvent
public static void onWorldUnload( LevelEvent.Unload event ) public static void onWorldUnload(LevelEvent.Unload event) {
{ if (event.getLevel().isClientSide()) {
if( event.getLevel().isClientSide() )
{
ClientMonitor.destroyAll(); ClientMonitor.destroyAll();
SpeakerManager.reset(); SpeakerManager.reset();
} }
} }
@SubscribeEvent @SubscribeEvent
public static void onLogIn( ClientPlayerNetworkEvent.LoggingIn event ) public static void onLogIn(ClientPlayerNetworkEvent.LoggingIn event) {
{
ClientPocketComputers.reset(); ClientPocketComputers.reset();
} }
@SubscribeEvent @SubscribeEvent
public static void onLogOut( ClientPlayerNetworkEvent.LoggingOut event ) public static void onLogOut(ClientPlayerNetworkEvent.LoggingOut event) {
{
ClientPocketComputers.reset(); ClientPocketComputers.reset();
} }
} }

View File

@ -39,10 +39,9 @@ import java.util.function.Supplier;
/** /**
* Registers textures and models for items. * Registers textures and models for items.
*/ */
@Mod.EventBusSubscriber( modid = ComputerCraft.MOD_ID, value = Dist.CLIENT, bus = Mod.EventBusSubscriber.Bus.MOD ) @Mod.EventBusSubscriber(modid = ComputerCraft.MOD_ID, value = Dist.CLIENT, bus = Mod.EventBusSubscriber.Bus.MOD)
public final class ClientRegistry public final class ClientRegistry {
{ private static final String[] EXTRA_MODELS = new String[]{
private static final String[] EXTRA_MODELS = new String[] {
// Turtle upgrades // Turtle upgrades
"block/turtle_modem_normal_off_left", "block/turtle_modem_normal_off_left",
"block/turtle_modem_normal_on_left", "block/turtle_modem_normal_on_left",
@ -65,124 +64,114 @@ public final class ClientRegistry
"block/turtle_elf_overlay", "block/turtle_elf_overlay",
}; };
private ClientRegistry() {} private ClientRegistry() {
@SubscribeEvent
public static void registerModelLoaders( ModelEvent.RegisterGeometryLoaders event )
{
event.register( "turtle", TurtleModelLoader.INSTANCE );
} }
@SubscribeEvent @SubscribeEvent
public static void registerModels( ModelEvent.RegisterAdditional event ) public static void registerModelLoaders(ModelEvent.RegisterGeometryLoaders event) {
{ event.register("turtle", TurtleModelLoader.INSTANCE);
for( String model : EXTRA_MODELS ) }
{
event.register( new ResourceLocation( ComputerCraft.MOD_ID, model ) ); @SubscribeEvent
public static void registerModels(ModelEvent.RegisterAdditional event) {
for (var model : EXTRA_MODELS) {
event.register(new ResourceLocation(ComputerCraft.MOD_ID, model));
} }
} }
@SubscribeEvent @SubscribeEvent
public static void onItemColours( RegisterColorHandlersEvent.Item event ) public static void onItemColours(RegisterColorHandlersEvent.Item event) {
{ if (Registry.ModItems.DISK == null || Registry.ModBlocks.TURTLE_NORMAL == null) {
if( Registry.ModItems.DISK == null || Registry.ModBlocks.TURTLE_NORMAL == null ) ComputerCraft.log.warn("Block/item registration has failed. Skipping registration of item colours.");
{
ComputerCraft.log.warn( "Block/item registration has failed. Skipping registration of item colours." );
return; return;
} }
event.register( event.register(
( stack, layer ) -> layer == 1 ? ((ItemDisk) stack.getItem()).getColour( stack ) : 0xFFFFFF, (stack, layer) -> layer == 1 ? ((ItemDisk) stack.getItem()).getColour(stack) : 0xFFFFFF,
Registry.ModItems.DISK.get() Registry.ModItems.DISK.get()
); );
event.register( event.register(
( stack, layer ) -> layer == 1 ? ItemTreasureDisk.getColour( stack ) : 0xFFFFFF, (stack, layer) -> layer == 1 ? ItemTreasureDisk.getColour(stack) : 0xFFFFFF,
Registry.ModItems.TREASURE_DISK.get() Registry.ModItems.TREASURE_DISK.get()
); );
event.register( ( stack, layer ) -> { event.register((stack, layer) -> {
switch( layer ) switch (layer) {
{
case 0: case 0:
default: default:
return 0xFFFFFF; return 0xFFFFFF;
case 1: // Frame colour case 1: // Frame colour
return IColouredItem.getColourBasic( stack ); return IColouredItem.getColourBasic(stack);
case 2: // Light colour case 2: { // Light colour
{ var light = ClientPocketComputers.get(stack).getLightState();
int light = ClientPocketComputers.get( stack ).getLightState();
return light == -1 ? Colour.BLACK.getHex() : light; return light == -1 ? Colour.BLACK.getHex() : light;
} }
} }
}, Registry.ModItems.POCKET_COMPUTER_NORMAL.get(), Registry.ModItems.POCKET_COMPUTER_ADVANCED.get() ); }, Registry.ModItems.POCKET_COMPUTER_NORMAL.get(), Registry.ModItems.POCKET_COMPUTER_ADVANCED.get());
// Setup turtle colours // Setup turtle colours
event.register( event.register(
( stack, tintIndex ) -> tintIndex == 0 ? ((IColouredItem) stack.getItem()).getColour( stack ) : 0xFFFFFF, (stack, tintIndex) -> tintIndex == 0 ? ((IColouredItem) stack.getItem()).getColour(stack) : 0xFFFFFF,
Registry.ModBlocks.TURTLE_NORMAL.get(), Registry.ModBlocks.TURTLE_ADVANCED.get() Registry.ModBlocks.TURTLE_NORMAL.get(), Registry.ModBlocks.TURTLE_ADVANCED.get()
); );
} }
@SubscribeEvent @SubscribeEvent
public static void setupClient( FMLClientSetupEvent event ) public static void setupClient(FMLClientSetupEvent event) {
{
// Setup TESRs // Setup TESRs
BlockEntityRenderers.register( Registry.ModBlockEntities.MONITOR_NORMAL.get(), TileEntityMonitorRenderer::new ); BlockEntityRenderers.register(Registry.ModBlockEntities.MONITOR_NORMAL.get(), TileEntityMonitorRenderer::new);
BlockEntityRenderers.register( Registry.ModBlockEntities.MONITOR_ADVANCED.get(), TileEntityMonitorRenderer::new ); BlockEntityRenderers.register(Registry.ModBlockEntities.MONITOR_ADVANCED.get(), TileEntityMonitorRenderer::new);
BlockEntityRenderers.register( Registry.ModBlockEntities.TURTLE_NORMAL.get(), TileEntityTurtleRenderer::new ); BlockEntityRenderers.register(Registry.ModBlockEntities.TURTLE_NORMAL.get(), TileEntityTurtleRenderer::new);
BlockEntityRenderers.register( Registry.ModBlockEntities.TURTLE_ADVANCED.get(), TileEntityTurtleRenderer::new ); BlockEntityRenderers.register(Registry.ModBlockEntities.TURTLE_ADVANCED.get(), TileEntityTurtleRenderer::new);
ComputerCraftAPIClient.registerTurtleUpgradeModeller( Registry.ModTurtleSerialisers.SPEAKER.get(), TurtleUpgradeModeller.sided( ComputerCraftAPIClient.registerTurtleUpgradeModeller(Registry.ModTurtleSerialisers.SPEAKER.get(), TurtleUpgradeModeller.sided(
new ResourceLocation( ComputerCraft.MOD_ID, "block/turtle_speaker_left" ), new ResourceLocation(ComputerCraft.MOD_ID, "block/turtle_speaker_left"),
new ResourceLocation( ComputerCraft.MOD_ID, "block/turtle_speaker_right" ) new ResourceLocation(ComputerCraft.MOD_ID, "block/turtle_speaker_right")
) ); ));
ComputerCraftAPIClient.registerTurtleUpgradeModeller( Registry.ModTurtleSerialisers.WORKBENCH.get(), TurtleUpgradeModeller.sided( ComputerCraftAPIClient.registerTurtleUpgradeModeller(Registry.ModTurtleSerialisers.WORKBENCH.get(), TurtleUpgradeModeller.sided(
new ResourceLocation( ComputerCraft.MOD_ID, "block/turtle_crafting_table_left" ), new ResourceLocation(ComputerCraft.MOD_ID, "block/turtle_crafting_table_left"),
new ResourceLocation( ComputerCraft.MOD_ID, "block/turtle_crafting_table_right" ) new ResourceLocation(ComputerCraft.MOD_ID, "block/turtle_crafting_table_right")
) ); ));
ComputerCraftAPIClient.registerTurtleUpgradeModeller( Registry.ModTurtleSerialisers.WIRELESS_MODEM_NORMAL.get(), new TurtleModemModeller( false ) ); ComputerCraftAPIClient.registerTurtleUpgradeModeller(Registry.ModTurtleSerialisers.WIRELESS_MODEM_NORMAL.get(), new TurtleModemModeller(false));
ComputerCraftAPIClient.registerTurtleUpgradeModeller( Registry.ModTurtleSerialisers.WIRELESS_MODEM_ADVANCED.get(), new TurtleModemModeller( true ) ); ComputerCraftAPIClient.registerTurtleUpgradeModeller(Registry.ModTurtleSerialisers.WIRELESS_MODEM_ADVANCED.get(), new TurtleModemModeller(true));
ComputerCraftAPIClient.registerTurtleUpgradeModeller( Registry.ModTurtleSerialisers.TOOL.get(), TurtleUpgradeModeller.flatItem() ); ComputerCraftAPIClient.registerTurtleUpgradeModeller(Registry.ModTurtleSerialisers.TOOL.get(), TurtleUpgradeModeller.flatItem());
event.enqueueWork( () -> { event.enqueueWork(() -> {
registerContainers(); registerContainers();
registerItemProperty( "state", registerItemProperty("state",
( stack, world, player, random ) -> ClientPocketComputers.get( stack ).getState().ordinal(), (stack, world, player, random) -> ClientPocketComputers.get(stack).getState().ordinal(),
Registry.ModItems.POCKET_COMPUTER_NORMAL, Registry.ModItems.POCKET_COMPUTER_ADVANCED Registry.ModItems.POCKET_COMPUTER_NORMAL, Registry.ModItems.POCKET_COMPUTER_ADVANCED
); );
registerItemProperty( "coloured", registerItemProperty("coloured",
( stack, world, player, random ) -> IColouredItem.getColourBasic( stack ) != -1 ? 1 : 0, (stack, world, player, random) -> IColouredItem.getColourBasic(stack) != -1 ? 1 : 0,
Registry.ModItems.POCKET_COMPUTER_NORMAL, Registry.ModItems.POCKET_COMPUTER_ADVANCED Registry.ModItems.POCKET_COMPUTER_NORMAL, Registry.ModItems.POCKET_COMPUTER_ADVANCED
); );
} ); });
} }
@SafeVarargs @SafeVarargs
private static void registerItemProperty( String name, ItemPropertyFunction getter, Supplier<? extends Item>... items ) private static void registerItemProperty(String name, ItemPropertyFunction getter, Supplier<? extends Item>... items) {
{ var id = new ResourceLocation(ComputerCraft.MOD_ID, name);
ResourceLocation id = new ResourceLocation( ComputerCraft.MOD_ID, name ); for (var item : items) {
for( Supplier<? extends Item> item : items ) ItemProperties.register(item.get(), id, getter);
{
ItemProperties.register( item.get(), id, getter );
} }
} }
private static void registerContainers() private static void registerContainers() {
{
// My IDE doesn't think so, but we do actually need these generics. // My IDE doesn't think so, but we do actually need these generics.
MenuScreens.<ContainerComputerBase, GuiComputer<ContainerComputerBase>>register( Registry.ModContainers.COMPUTER.get(), GuiComputer::new ); MenuScreens.<ContainerComputerBase, GuiComputer<ContainerComputerBase>>register(Registry.ModContainers.COMPUTER.get(), GuiComputer::new);
MenuScreens.<ContainerComputerBase, GuiComputer<ContainerComputerBase>>register( Registry.ModContainers.POCKET_COMPUTER.get(), GuiComputer::new ); MenuScreens.<ContainerComputerBase, GuiComputer<ContainerComputerBase>>register(Registry.ModContainers.POCKET_COMPUTER.get(), GuiComputer::new);
MenuScreens.<ContainerComputerBase, NoTermComputerScreen<ContainerComputerBase>>register( Registry.ModContainers.POCKET_COMPUTER_NO_TERM.get(), NoTermComputerScreen::new ); MenuScreens.<ContainerComputerBase, NoTermComputerScreen<ContainerComputerBase>>register(Registry.ModContainers.POCKET_COMPUTER_NO_TERM.get(), NoTermComputerScreen::new);
MenuScreens.register( Registry.ModContainers.TURTLE.get(), GuiTurtle::new ); MenuScreens.register(Registry.ModContainers.TURTLE.get(), GuiTurtle::new);
MenuScreens.register( Registry.ModContainers.PRINTER.get(), GuiPrinter::new ); MenuScreens.register(Registry.ModContainers.PRINTER.get(), GuiPrinter::new);
MenuScreens.register( Registry.ModContainers.DISK_DRIVE.get(), GuiDiskDrive::new ); MenuScreens.register(Registry.ModContainers.DISK_DRIVE.get(), GuiDiskDrive::new);
MenuScreens.register( Registry.ModContainers.PRINTOUT.get(), GuiPrintout::new ); MenuScreens.register(Registry.ModContainers.PRINTOUT.get(), GuiPrintout::new);
MenuScreens.<ContainerViewComputer, GuiComputer<ContainerViewComputer>>register( Registry.ModContainers.VIEW_COMPUTER.get(), GuiComputer::new ); MenuScreens.<ContainerViewComputer, GuiComputer<ContainerViewComputer>>register(Registry.ModContainers.VIEW_COMPUTER.get(), GuiComputer::new);
} }
} }

View File

@ -12,7 +12,6 @@ import net.minecraft.ChatFormatting;
import net.minecraft.client.GuiMessageTag; import net.minecraft.client.GuiMessageTag;
import net.minecraft.client.Minecraft; import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.Font; import net.minecraft.client.gui.Font;
import net.minecraft.client.gui.components.ChatComponent;
import net.minecraft.network.chat.Component; import net.minecraft.network.chat.Component;
import net.minecraft.util.Mth; import net.minecraft.util.Mth;
import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.StringUtils;
@ -20,72 +19,63 @@ import org.apache.commons.lang3.StringUtils;
import javax.annotation.Nullable; import javax.annotation.Nullable;
import java.util.Objects; import java.util.Objects;
public class ClientTableFormatter implements TableFormatter public class ClientTableFormatter implements TableFormatter {
{
public static final ClientTableFormatter INSTANCE = new ClientTableFormatter(); public static final ClientTableFormatter INSTANCE = new ClientTableFormatter();
private static Font renderer() private static Font renderer() {
{
return Minecraft.getInstance().font; return Minecraft.getInstance().font;
} }
@Override @Override
@Nullable @Nullable
public Component getPadding( Component component, int width ) public Component getPadding(Component component, int width) {
{ var extraWidth = width - getWidth(component);
int extraWidth = width - getWidth( component ); if (extraWidth <= 0) return null;
if( extraWidth <= 0 ) return null;
Font renderer = renderer(); var renderer = renderer();
float spaceWidth = renderer.width( " " ); float spaceWidth = renderer.width(" ");
int spaces = Mth.floor( extraWidth / spaceWidth ); var spaces = Mth.floor(extraWidth / spaceWidth);
int extra = extraWidth - (int) (spaces * spaceWidth); var extra = extraWidth - (int) (spaces * spaceWidth);
return ChatHelpers.coloured( StringUtils.repeat( ' ', spaces ) + StringUtils.repeat( (char) 712, extra ), ChatFormatting.GRAY ); return ChatHelpers.coloured(StringUtils.repeat(' ', spaces) + StringUtils.repeat((char) 712, extra), ChatFormatting.GRAY);
} }
@Override @Override
public int getColumnPadding() public int getColumnPadding() {
{
return 3; return 3;
} }
@Override @Override
public int getWidth( Component component ) public int getWidth(Component component) {
{ return renderer().width(component);
return renderer().width( component );
} }
@Override @Override
public void writeLine( String label, Component component ) public void writeLine(String label, Component component) {
{ var mc = Minecraft.getInstance();
Minecraft mc = Minecraft.getInstance(); var chat = mc.gui.getChat();
ChatComponent chat = mc.gui.getChat();
// TODO: Trim the text if it goes over the allowed length // TODO: Trim the text if it goes over the allowed length
// int maxWidth = MathHelper.floor( chat.getChatWidth() / chat.getScale() ); // int maxWidth = MathHelper.floor( chat.getChatWidth() / chat.getScale() );
// List<ITextProperties> list = RenderComponentsUtil.wrapComponents( component, maxWidth, mc.fontRenderer ); // List<ITextProperties> list = RenderComponentsUtil.wrapComponents( component, maxWidth, mc.fontRenderer );
// if( !list.isEmpty() ) chat.printChatMessageWithOptionalDeletion( list.get( 0 ), id ); // if( !list.isEmpty() ) chat.printChatMessageWithOptionalDeletion( list.get( 0 ), id );
chat.addMessage( component, null, createTag( label ) ); chat.addMessage(component, null, createTag(label));
} }
@Override @Override
public void display( TableBuilder table ) public void display(TableBuilder table) {
{ var chat = Minecraft.getInstance().gui.getChat();
ChatComponent chat = Minecraft.getInstance().gui.getChat();
var tag = createTag( table.getId() ); var tag = createTag(table.getId());
if( chat.allMessages.removeIf( guiMessage -> guiMessage.tag() != null && Objects.equals( guiMessage.tag().logTag(), tag.logTag() ) ) ) if (chat.allMessages.removeIf(guiMessage -> guiMessage.tag() != null && Objects.equals(guiMessage.tag().logTag(), tag.logTag()))) {
{
chat.refreshTrimmedMessage(); chat.refreshTrimmedMessage();
} }
TableFormatter.super.display( table ); TableFormatter.super.display(table);
} }
private static GuiMessageTag createTag( String id ) private static GuiMessageTag createTag(String id) {
{ return new GuiMessageTag(0xa0a0a0, null, null, "ComputerCraft/" + id);
return new GuiMessageTag( 0xa0a0a0, null, null, "ComputerCraft/" + id );
} }
} }

View File

@ -14,12 +14,10 @@ import dan200.computercraft.impl.client.ComputerCraftAPIClientService;
import javax.annotation.Nonnull; import javax.annotation.Nonnull;
@AutoService( ComputerCraftAPIClientService.class ) @AutoService(ComputerCraftAPIClientService.class)
public final class ComputerCraftAPIClientImpl implements ComputerCraftAPIClientService public final class ComputerCraftAPIClientImpl implements ComputerCraftAPIClientService {
{
@Override @Override
public <T extends ITurtleUpgrade> void registerTurtleUpgradeModeller( @Nonnull TurtleUpgradeSerialiser<T> serialiser, @Nonnull TurtleUpgradeModeller<T> modeller ) public <T extends ITurtleUpgrade> void registerTurtleUpgradeModeller(@Nonnull TurtleUpgradeSerialiser<T> serialiser, @Nonnull TurtleUpgradeModeller<T> modeller) {
{ TurtleUpgradeModellers.register(serialiser, modeller);
TurtleUpgradeModellers.register( serialiser, modeller );
} }
} }

View File

@ -11,35 +11,29 @@ import net.minecraftforge.event.TickEvent;
import net.minecraftforge.eventbus.api.SubscribeEvent; import net.minecraftforge.eventbus.api.SubscribeEvent;
import net.minecraftforge.fml.common.Mod; import net.minecraftforge.fml.common.Mod;
@Mod.EventBusSubscriber( modid = ComputerCraft.MOD_ID, value = Dist.CLIENT ) @Mod.EventBusSubscriber(modid = ComputerCraft.MOD_ID, value = Dist.CLIENT)
public final class FrameInfo public final class FrameInfo {
{
private static int tick; private static int tick;
private static long renderFrame; private static long renderFrame;
private FrameInfo() private FrameInfo() {
{
} }
public static boolean getGlobalCursorBlink() public static boolean getGlobalCursorBlink() {
{
return (tick / 8) % 2 == 0; return (tick / 8) % 2 == 0;
} }
public static long getRenderFrame() public static long getRenderFrame() {
{
return renderFrame; return renderFrame;
} }
@SubscribeEvent @SubscribeEvent
public static void onTick( TickEvent.ClientTickEvent event ) public static void onTick(TickEvent.ClientTickEvent event) {
{ if (event.phase == TickEvent.Phase.START) tick++;
if( event.phase == TickEvent.Phase.START ) tick++;
} }
@SubscribeEvent @SubscribeEvent
public static void onRenderTick( TickEvent.RenderTickEvent event ) public static void onRenderTick(TickEvent.RenderTickEvent event) {
{ if (event.phase == TickEvent.Phase.START) renderFrame++;
if( event.phase == TickEvent.Phase.START ) renderFrame++;
} }
} }

View File

@ -21,72 +21,60 @@ import javax.annotation.Nullable;
* <p> * <p>
* This queues events on the remote player's open {@link ComputerMenu} * This queues events on the remote player's open {@link ComputerMenu}
*/ */
public final class ClientInputHandler implements InputHandler public final class ClientInputHandler implements InputHandler {
{
private final AbstractContainerMenu menu; private final AbstractContainerMenu menu;
public ClientInputHandler( AbstractContainerMenu menu ) public ClientInputHandler(AbstractContainerMenu menu) {
{
this.menu = menu; this.menu = menu;
} }
@Override @Override
public void turnOn() public void turnOn() {
{ NetworkHandler.sendToServer(new ComputerActionServerMessage(menu, ComputerActionServerMessage.Action.TURN_ON));
NetworkHandler.sendToServer( new ComputerActionServerMessage( menu, ComputerActionServerMessage.Action.TURN_ON ) );
} }
@Override @Override
public void shutdown() public void shutdown() {
{ NetworkHandler.sendToServer(new ComputerActionServerMessage(menu, ComputerActionServerMessage.Action.SHUTDOWN));
NetworkHandler.sendToServer( new ComputerActionServerMessage( menu, ComputerActionServerMessage.Action.SHUTDOWN ) );
} }
@Override @Override
public void reboot() public void reboot() {
{ NetworkHandler.sendToServer(new ComputerActionServerMessage(menu, ComputerActionServerMessage.Action.REBOOT));
NetworkHandler.sendToServer( new ComputerActionServerMessage( menu, ComputerActionServerMessage.Action.REBOOT ) );
} }
@Override @Override
public void queueEvent( String event, @Nullable Object[] arguments ) public void queueEvent(String event, @Nullable Object[] arguments) {
{ NetworkHandler.sendToServer(new QueueEventServerMessage(menu, event, arguments));
NetworkHandler.sendToServer( new QueueEventServerMessage( menu, event, arguments ) );
} }
@Override @Override
public void keyDown( int key, boolean repeat ) public void keyDown(int key, boolean repeat) {
{ NetworkHandler.sendToServer(new KeyEventServerMessage(menu, repeat ? KeyEventServerMessage.TYPE_REPEAT : KeyEventServerMessage.TYPE_DOWN, key));
NetworkHandler.sendToServer( new KeyEventServerMessage( menu, repeat ? KeyEventServerMessage.TYPE_REPEAT : KeyEventServerMessage.TYPE_DOWN, key ) );
} }
@Override @Override
public void keyUp( int key ) public void keyUp(int key) {
{ NetworkHandler.sendToServer(new KeyEventServerMessage(menu, KeyEventServerMessage.TYPE_UP, key));
NetworkHandler.sendToServer( new KeyEventServerMessage( menu, KeyEventServerMessage.TYPE_UP, key ) );
} }
@Override @Override
public void mouseClick( int button, int x, int y ) public void mouseClick(int button, int x, int y) {
{ NetworkHandler.sendToServer(new MouseEventServerMessage(menu, MouseEventServerMessage.TYPE_CLICK, button, x, y));
NetworkHandler.sendToServer( new MouseEventServerMessage( menu, MouseEventServerMessage.TYPE_CLICK, button, x, y ) );
} }
@Override @Override
public void mouseUp( int button, int x, int y ) public void mouseUp(int button, int x, int y) {
{ NetworkHandler.sendToServer(new MouseEventServerMessage(menu, MouseEventServerMessage.TYPE_UP, button, x, y));
NetworkHandler.sendToServer( new MouseEventServerMessage( menu, MouseEventServerMessage.TYPE_UP, button, x, y ) );
} }
@Override @Override
public void mouseDrag( int button, int x, int y ) public void mouseDrag(int button, int x, int y) {
{ NetworkHandler.sendToServer(new MouseEventServerMessage(menu, MouseEventServerMessage.TYPE_DRAG, button, x, y));
NetworkHandler.sendToServer( new MouseEventServerMessage( menu, MouseEventServerMessage.TYPE_DRAG, button, x, y ) );
} }
@Override @Override
public void mouseScroll( int direction, int x, int y ) public void mouseScroll(int direction, int x, int y) {
{ NetworkHandler.sendToServer(new MouseEventServerMessage(menu, MouseEventServerMessage.TYPE_SCROLL, direction, x, y));
NetworkHandler.sendToServer( new MouseEventServerMessage( menu, MouseEventServerMessage.TYPE_SCROLL, direction, x, y ) );
} }
} }

View File

@ -30,7 +30,6 @@ import javax.annotation.Nonnull;
import javax.annotation.Nullable; import javax.annotation.Nullable;
import java.io.IOException; import java.io.IOException;
import java.nio.ByteBuffer; import java.nio.ByteBuffer;
import java.nio.channels.SeekableByteChannel;
import java.nio.file.Files; import java.nio.file.Files;
import java.nio.file.Path; import java.nio.file.Path;
import java.util.ArrayList; import java.util.ArrayList;
@ -38,12 +37,11 @@ import java.util.Collections;
import java.util.List; import java.util.List;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
public abstract class ComputerScreenBase<T extends ContainerComputerBase> extends AbstractContainerScreen<T> public abstract class ComputerScreenBase<T extends ContainerComputerBase> extends AbstractContainerScreen<T> {
{ private static final Component OK = Component.translatable("gui.ok");
private static final Component OK = Component.translatable( "gui.ok" ); private static final Component NO_RESPONSE_TITLE = Component.translatable("gui.computercraft.upload.no_response");
private static final Component NO_RESPONSE_TITLE = Component.translatable( "gui.computercraft.upload.no_response" ); private static final Component NO_RESPONSE_MSG = Component.translatable("gui.computercraft.upload.no_response.msg",
private static final Component NO_RESPONSE_MSG = Component.translatable( "gui.computercraft.upload.no_response.msg", Component.literal("import").withStyle(ChatFormatting.DARK_GRAY));
Component.literal( "import" ).withStyle( ChatFormatting.DARK_GRAY ) );
protected WidgetTerminal terminal; protected WidgetTerminal terminal;
protected Terminal terminalData; protected Terminal terminalData;
@ -55,187 +53,154 @@ public abstract class ComputerScreenBase<T extends ContainerComputerBase> extend
private long uploadNagDeadline = Long.MAX_VALUE; private long uploadNagDeadline = Long.MAX_VALUE;
private final ItemStack displayStack; private final ItemStack displayStack;
public ComputerScreenBase( T container, Inventory player, Component title, int sidebarYOffset ) public ComputerScreenBase(T container, Inventory player, Component title, int sidebarYOffset) {
{ super(container, player, title);
super( container, player, title );
terminalData = container.getTerminal(); terminalData = container.getTerminal();
family = container.getFamily(); family = container.getFamily();
displayStack = container.getDisplayStack(); displayStack = container.getDisplayStack();
input = new ClientInputHandler( menu ); input = new ClientInputHandler(menu);
this.sidebarYOffset = sidebarYOffset; this.sidebarYOffset = sidebarYOffset;
} }
protected abstract WidgetTerminal createTerminal(); protected abstract WidgetTerminal createTerminal();
@Override @Override
protected void init() protected void init() {
{
super.init(); super.init();
minecraft.keyboardHandler.setSendRepeatsToGui( true ); minecraft.keyboardHandler.setSendRepeatsToGui(true);
terminal = addRenderableWidget( createTerminal() ); terminal = addRenderableWidget(createTerminal());
ComputerSidebar.addButtons( this, menu::isOn, input, this::addRenderableWidget, leftPos, topPos + sidebarYOffset ); ComputerSidebar.addButtons(this, menu::isOn, input, this::addRenderableWidget, leftPos, topPos + sidebarYOffset);
setFocused( terminal ); setFocused(terminal);
} }
@Override @Override
public void removed() public void removed() {
{
super.removed(); super.removed();
minecraft.keyboardHandler.setSendRepeatsToGui( false ); minecraft.keyboardHandler.setSendRepeatsToGui(false);
} }
@Override @Override
public void containerTick() public void containerTick() {
{
super.containerTick(); super.containerTick();
terminal.update(); terminal.update();
if( uploadNagDeadline != Long.MAX_VALUE && Util.getNanos() >= uploadNagDeadline ) if (uploadNagDeadline != Long.MAX_VALUE && Util.getNanos() >= uploadNagDeadline) {
{ new ItemToast(minecraft, displayStack, NO_RESPONSE_TITLE, NO_RESPONSE_MSG, ItemToast.TRANSFER_NO_RESPONSE_TOKEN)
new ItemToast( minecraft, displayStack, NO_RESPONSE_TITLE, NO_RESPONSE_MSG, ItemToast.TRANSFER_NO_RESPONSE_TOKEN ) .showOrReplace(minecraft.getToasts());
.showOrReplace( minecraft.getToasts() );
uploadNagDeadline = Long.MAX_VALUE; uploadNagDeadline = Long.MAX_VALUE;
} }
} }
@Override @Override
public boolean keyPressed( int key, int scancode, int modifiers ) public boolean keyPressed(int key, int scancode, int modifiers) {
{
// Forward the tab key to the terminal, rather than moving between controls. // Forward the tab key to the terminal, rather than moving between controls.
if( key == GLFW.GLFW_KEY_TAB && getFocused() != null && getFocused() == terminal ) if (key == GLFW.GLFW_KEY_TAB && getFocused() != null && getFocused() == terminal) {
{ return getFocused().keyPressed(key, scancode, modifiers);
return getFocused().keyPressed( key, scancode, modifiers );
} }
return super.keyPressed( key, scancode, modifiers ); return super.keyPressed(key, scancode, modifiers);
} }
@Override @Override
public void render( @Nonnull PoseStack stack, int mouseX, int mouseY, float partialTicks ) public void render(@Nonnull PoseStack stack, int mouseX, int mouseY, float partialTicks) {
{ renderBackground(stack);
renderBackground( stack ); super.render(stack, mouseX, mouseY, partialTicks);
super.render( stack, mouseX, mouseY, partialTicks ); renderTooltip(stack, mouseX, mouseY);
renderTooltip( stack, mouseX, mouseY );
} }
@Override @Override
public boolean mouseClicked( double x, double y, int button ) public boolean mouseClicked(double x, double y, int button) {
{ var changed = super.mouseClicked(x, y, button);
boolean changed = super.mouseClicked( x, y, button );
// Clicking the terminate/shutdown button steals focus, which means then pressing "enter" will click the button // Clicking the terminate/shutdown button steals focus, which means then pressing "enter" will click the button
// again. Restore the focus to the terminal in these cases. // again. Restore the focus to the terminal in these cases.
if( getFocused() instanceof DynamicImageButton ) setFocused( terminal ); if (getFocused() instanceof DynamicImageButton) setFocused(terminal);
return changed; return changed;
} }
@Override @Override
public boolean mouseDragged( double x, double y, int button, double deltaX, double deltaY ) public boolean mouseDragged(double x, double y, int button, double deltaX, double deltaY) {
{ return (getFocused() != null && getFocused().mouseDragged(x, y, button, deltaX, deltaY))
return (getFocused() != null && getFocused().mouseDragged( x, y, button, deltaX, deltaY )) || super.mouseDragged(x, y, button, deltaX, deltaY);
|| super.mouseDragged( x, y, button, deltaX, deltaY );
} }
@Override @Override
protected void renderLabels( @Nonnull PoseStack transform, int mouseX, int mouseY ) protected void renderLabels(@Nonnull PoseStack transform, int mouseX, int mouseY) {
{
// Skip rendering labels. // Skip rendering labels.
} }
@Override @Override
public void onFilesDrop( @Nonnull List<Path> files ) public void onFilesDrop(@Nonnull List<Path> files) {
{ if (files.isEmpty()) return;
if( files.isEmpty() ) return;
if( !menu.isOn() ) if (!menu.isOn()) {
{ alert(UploadResult.FAILED_TITLE, UploadResult.COMPUTER_OFF_MSG);
alert( UploadResult.FAILED_TITLE, UploadResult.COMPUTER_OFF_MSG );
return; return;
} }
long size = 0; long size = 0;
List<FileUpload> toUpload = new ArrayList<>(); List<FileUpload> toUpload = new ArrayList<>();
for( Path file : files ) for (var file : files) {
{
// TODO: Recurse directories? If so, we probably want to shunt this off-thread. // TODO: Recurse directories? If so, we probably want to shunt this off-thread.
if( !Files.isRegularFile( file ) ) continue; if (!Files.isRegularFile(file)) continue;
try( SeekableByteChannel sbc = Files.newByteChannel( file ) ) try (var sbc = Files.newByteChannel(file)) {
{ var fileSize = sbc.size();
long fileSize = sbc.size(); if (fileSize > UploadFileMessage.MAX_SIZE || (size += fileSize) >= UploadFileMessage.MAX_SIZE) {
if( fileSize > UploadFileMessage.MAX_SIZE || (size += fileSize) >= UploadFileMessage.MAX_SIZE ) alert(UploadResult.FAILED_TITLE, UploadResult.TOO_MUCH_MSG);
{
alert( UploadResult.FAILED_TITLE, UploadResult.TOO_MUCH_MSG );
return; return;
} }
String name = file.getFileName().toString(); var name = file.getFileName().toString();
if( name.length() > UploadFileMessage.MAX_FILE_NAME ) if (name.length() > UploadFileMessage.MAX_FILE_NAME) {
{ alert(UploadResult.FAILED_TITLE, Component.translatable("gui.computercraft.upload.failed.name_too_long"));
alert( UploadResult.FAILED_TITLE, Component.translatable( "gui.computercraft.upload.failed.name_too_long" ) );
return; return;
} }
ByteBuffer buffer = ByteBuffer.allocateDirect( (int) fileSize ); var buffer = ByteBuffer.allocateDirect((int) fileSize);
sbc.read( buffer ); sbc.read(buffer);
buffer.flip(); buffer.flip();
byte[] digest = FileUpload.getDigest( buffer ); var digest = FileUpload.getDigest(buffer);
if( digest == null ) if (digest == null) {
{ alert(UploadResult.FAILED_TITLE, Component.translatable("gui.computercraft.upload.failed.corrupted"));
alert( UploadResult.FAILED_TITLE, Component.translatable( "gui.computercraft.upload.failed.corrupted" ) );
return; return;
} }
toUpload.add( new FileUpload( name, buffer, digest ) ); toUpload.add(new FileUpload(name, buffer, digest));
} } catch (IOException e) {
catch( IOException e ) ComputerCraft.log.error("Failed uploading files", e);
{ alert(UploadResult.FAILED_TITLE, Component.translatable("gui.computercraft.upload.failed.generic", "Cannot compute checksum"));
ComputerCraft.log.error( "Failed uploading files", e );
alert( UploadResult.FAILED_TITLE, Component.translatable( "gui.computercraft.upload.failed.generic", "Cannot compute checksum" ) );
} }
} }
if( toUpload.size() > UploadFileMessage.MAX_FILES ) if (toUpload.size() > UploadFileMessage.MAX_FILES) {
{ alert(UploadResult.FAILED_TITLE, Component.translatable("gui.computercraft.upload.failed.too_many_files"));
alert( UploadResult.FAILED_TITLE, Component.translatable( "gui.computercraft.upload.failed.too_many_files" ) );
return; return;
} }
if( toUpload.size() > 0 ) UploadFileMessage.send( menu, toUpload, NetworkHandler::sendToServer ); if (toUpload.size() > 0) UploadFileMessage.send(menu, toUpload, NetworkHandler::sendToServer);
} }
public void uploadResult( UploadResult result, @Nullable Component message ) public void uploadResult(UploadResult result, @Nullable Component message) {
{ switch (result) {
switch( result ) case QUEUED -> {
{ if (ComputerCraft.uploadNagDelay > 0) {
case QUEUED: uploadNagDeadline = Util.getNanos() + TimeUnit.SECONDS.toNanos(ComputerCraft.uploadNagDelay);
{
if( ComputerCraft.uploadNagDelay > 0 )
{
uploadNagDeadline = Util.getNanos() + TimeUnit.SECONDS.toNanos( ComputerCraft.uploadNagDelay );
} }
break;
} }
case CONSUMED: case CONSUMED -> uploadNagDeadline = Long.MAX_VALUE;
{ case ERROR -> alert(UploadResult.FAILED_TITLE, message);
uploadNagDeadline = Long.MAX_VALUE;
break;
}
case ERROR:
alert( UploadResult.FAILED_TITLE, message );
break;
} }
} }
private void alert( Component title, Component message ) private void alert(Component title, Component message) {
{ OptionScreen.show(minecraft, title, message,
OptionScreen.show( minecraft, title, message, Collections.singletonList(OptionScreen.newButton(OK, b -> minecraft.setScreen(this))),
Collections.singletonList( OptionScreen.newButton( OK, b -> minecraft.setScreen( this ) ) ), () -> minecraft.setScreen(this)
() -> minecraft.setScreen( this )
); );
} }
} }

View File

@ -18,30 +18,26 @@ import javax.annotation.Nonnull;
import static dan200.computercraft.client.render.ComputerBorderRenderer.BORDER; import static dan200.computercraft.client.render.ComputerBorderRenderer.BORDER;
import static dan200.computercraft.client.render.RenderTypes.FULL_BRIGHT_LIGHTMAP; import static dan200.computercraft.client.render.RenderTypes.FULL_BRIGHT_LIGHTMAP;
public final class GuiComputer<T extends ContainerComputerBase> extends ComputerScreenBase<T> public final class GuiComputer<T extends ContainerComputerBase> extends ComputerScreenBase<T> {
{ public GuiComputer(T container, Inventory player, Component title) {
public GuiComputer( T container, Inventory player, Component title ) super(container, player, title, BORDER);
{
super( container, player, title, BORDER );
imageWidth = WidgetTerminal.getWidth( terminalData.getWidth() ) + BORDER * 2 + ComputerSidebar.WIDTH; imageWidth = WidgetTerminal.getWidth(terminalData.getWidth()) + BORDER * 2 + ComputerSidebar.WIDTH;
imageHeight = WidgetTerminal.getHeight( terminalData.getHeight() ) + BORDER * 2; imageHeight = WidgetTerminal.getHeight(terminalData.getHeight()) + BORDER * 2;
} }
@Override @Override
protected WidgetTerminal createTerminal() protected WidgetTerminal createTerminal() {
{ return new WidgetTerminal(terminalData, input, leftPos + ComputerSidebar.WIDTH + BORDER, topPos + BORDER);
return new WidgetTerminal( terminalData, input, leftPos + ComputerSidebar.WIDTH + BORDER, topPos + BORDER );
} }
@Override @Override
public void renderBg( @Nonnull PoseStack stack, float partialTicks, int mouseX, int mouseY ) public void renderBg(@Nonnull PoseStack stack, float partialTicks, int mouseX, int mouseY) {
{
// Draw a border around the terminal // Draw a border around the terminal
ComputerBorderRenderer.render( ComputerBorderRenderer.render(
stack.last().pose(), ComputerBorderRenderer.getTexture( family ), terminal.x, terminal.y, getBlitOffset(), stack.last().pose(), ComputerBorderRenderer.getTexture(family), terminal.x, terminal.y, getBlitOffset(),
FULL_BRIGHT_LIGHTMAP, terminal.getWidth(), terminal.getHeight() FULL_BRIGHT_LIGHTMAP, terminal.getWidth(), terminal.getHeight()
); );
ComputerSidebar.renderBackground( stack, leftPos, topPos + sidebarYOffset ); ComputerSidebar.renderBackground(stack, leftPos, topPos + sidebarYOffset);
} }
} }

View File

@ -15,28 +15,24 @@ import net.minecraft.world.entity.player.Inventory;
import javax.annotation.Nonnull; import javax.annotation.Nonnull;
public class GuiDiskDrive extends AbstractContainerScreen<ContainerDiskDrive> public class GuiDiskDrive extends AbstractContainerScreen<ContainerDiskDrive> {
{ private static final ResourceLocation BACKGROUND = new ResourceLocation("computercraft", "textures/gui/disk_drive.png");
private static final ResourceLocation BACKGROUND = new ResourceLocation( "computercraft", "textures/gui/disk_drive.png" );
public GuiDiskDrive( ContainerDiskDrive container, Inventory player, Component title ) public GuiDiskDrive(ContainerDiskDrive container, Inventory player, Component title) {
{ super(container, player, title);
super( container, player, title );
} }
@Override @Override
protected void renderBg( @Nonnull PoseStack transform, float partialTicks, int mouseX, int mouseY ) protected void renderBg(@Nonnull PoseStack transform, float partialTicks, int mouseX, int mouseY) {
{ RenderSystem.setShaderColor(1.0F, 1.0F, 1.0F, 1.0F);
RenderSystem.setShaderColor( 1.0F, 1.0F, 1.0F, 1.0F ); RenderSystem.setShaderTexture(0, BACKGROUND);
RenderSystem.setShaderTexture( 0, BACKGROUND ); blit(transform, leftPos, topPos, 0, 0, imageWidth, imageHeight);
blit( transform, leftPos, topPos, 0, 0, imageWidth, imageHeight );
} }
@Override @Override
public void render( @Nonnull PoseStack transform, int mouseX, int mouseY, float partialTicks ) public void render(@Nonnull PoseStack transform, int mouseX, int mouseY, float partialTicks) {
{ renderBackground(transform);
renderBackground( transform ); super.render(transform, mouseX, mouseY, partialTicks);
super.render( transform, mouseX, mouseY, partialTicks ); renderTooltip(transform, mouseX, mouseY);
renderTooltip( transform, mouseX, mouseY );
} }
} }

View File

@ -15,30 +15,26 @@ import net.minecraft.world.entity.player.Inventory;
import javax.annotation.Nonnull; import javax.annotation.Nonnull;
public class GuiPrinter extends AbstractContainerScreen<ContainerPrinter> public class GuiPrinter extends AbstractContainerScreen<ContainerPrinter> {
{ private static final ResourceLocation BACKGROUND = new ResourceLocation("computercraft", "textures/gui/printer.png");
private static final ResourceLocation BACKGROUND = new ResourceLocation( "computercraft", "textures/gui/printer.png" );
public GuiPrinter( ContainerPrinter container, Inventory player, Component title ) public GuiPrinter(ContainerPrinter container, Inventory player, Component title) {
{ super(container, player, title);
super( container, player, title );
} }
@Override @Override
protected void renderBg( @Nonnull PoseStack transform, float partialTicks, int mouseX, int mouseY ) protected void renderBg(@Nonnull PoseStack transform, float partialTicks, int mouseX, int mouseY) {
{ RenderSystem.setShaderColor(1.0F, 1.0F, 1.0F, 1.0F);
RenderSystem.setShaderColor( 1.0F, 1.0F, 1.0F, 1.0F ); RenderSystem.setShaderTexture(0, BACKGROUND);
RenderSystem.setShaderTexture( 0, BACKGROUND ); blit(transform, leftPos, topPos, 0, 0, imageWidth, imageHeight);
blit( transform, leftPos, topPos, 0, 0, imageWidth, imageHeight );
if( getMenu().isPrinting() ) blit( transform, leftPos + 34, topPos + 21, 176, 0, 25, 45 ); if (getMenu().isPrinting()) blit(transform, leftPos + 34, topPos + 21, 176, 0, 25, 45);
} }
@Override @Override
public void render( @Nonnull PoseStack stack, int mouseX, int mouseY, float partialTicks ) public void render(@Nonnull PoseStack stack, int mouseX, int mouseY, float partialTicks) {
{ renderBackground(stack);
renderBackground( stack ); super.render(stack, mouseX, mouseY, partialTicks);
super.render( stack, mouseX, mouseY, partialTicks ); renderTooltip(stack, mouseX, mouseY);
renderTooltip( stack, mouseX, mouseY );
} }
} }

View File

@ -22,47 +22,42 @@ import javax.annotation.Nonnull;
import static dan200.computercraft.client.render.PrintoutRenderer.*; import static dan200.computercraft.client.render.PrintoutRenderer.*;
import static dan200.computercraft.client.render.RenderTypes.FULL_BRIGHT_LIGHTMAP; import static dan200.computercraft.client.render.RenderTypes.FULL_BRIGHT_LIGHTMAP;
public class GuiPrintout extends AbstractContainerScreen<ContainerHeldItem> public class GuiPrintout extends AbstractContainerScreen<ContainerHeldItem> {
{
private final boolean book; private final boolean book;
private final int pages; private final int pages;
private final TextBuffer[] text; private final TextBuffer[] text;
private final TextBuffer[] colours; private final TextBuffer[] colours;
private int page; private int page;
public GuiPrintout( ContainerHeldItem container, Inventory player, Component title ) public GuiPrintout(ContainerHeldItem container, Inventory player, Component title) {
{ super(container, player, title);
super( container, player, title );
imageHeight = Y_SIZE; imageHeight = Y_SIZE;
String[] text = ItemPrintout.getText( container.getStack() ); var text = ItemPrintout.getText(container.getStack());
this.text = new TextBuffer[text.length]; this.text = new TextBuffer[text.length];
for( int i = 0; i < this.text.length; i++ ) this.text[i] = new TextBuffer( text[i] ); for (var i = 0; i < this.text.length; i++) this.text[i] = new TextBuffer(text[i]);
String[] colours = ItemPrintout.getColours( container.getStack() ); var colours = ItemPrintout.getColours(container.getStack());
this.colours = new TextBuffer[colours.length]; this.colours = new TextBuffer[colours.length];
for( int i = 0; i < this.colours.length; i++ ) this.colours[i] = new TextBuffer( colours[i] ); for (var i = 0; i < this.colours.length; i++) this.colours[i] = new TextBuffer(colours[i]);
page = 0; page = 0;
pages = Math.max( this.text.length / ItemPrintout.LINES_PER_PAGE, 1 ); pages = Math.max(this.text.length / ItemPrintout.LINES_PER_PAGE, 1);
book = ((ItemPrintout) container.getStack().getItem()).getType() == ItemPrintout.Type.BOOK; book = ((ItemPrintout) container.getStack().getItem()).getType() == ItemPrintout.Type.BOOK;
} }
@Override @Override
public boolean keyPressed( int key, int scancode, int modifiers ) public boolean keyPressed(int key, int scancode, int modifiers) {
{ if (super.keyPressed(key, scancode, modifiers)) return true;
if( super.keyPressed( key, scancode, modifiers ) ) return true;
if( key == GLFW.GLFW_KEY_RIGHT ) if (key == GLFW.GLFW_KEY_RIGHT) {
{ if (page < pages - 1) page++;
if( page < pages - 1 ) page++;
return true; return true;
} }
if( key == GLFW.GLFW_KEY_LEFT ) if (key == GLFW.GLFW_KEY_LEFT) {
{ if (page > 0) page--;
if( page > 0 ) page--;
return true; return true;
} }
@ -70,20 +65,17 @@ public class GuiPrintout extends AbstractContainerScreen<ContainerHeldItem>
} }
@Override @Override
public boolean mouseScrolled( double x, double y, double delta ) public boolean mouseScrolled(double x, double y, double delta) {
{ if (super.mouseScrolled(x, y, delta)) return true;
if( super.mouseScrolled( x, y, delta ) ) return true; if (delta < 0) {
if( delta < 0 )
{
// Scroll up goes to the next page // Scroll up goes to the next page
if( page < pages - 1 ) page++; if (page < pages - 1) page++;
return true; return true;
} }
if( delta > 0 ) if (delta > 0) {
{
// Scroll down goes to the previous page // Scroll down goes to the previous page
if( page > 0 ) page--; if (page > 0) page--;
return true; return true;
} }
@ -91,32 +83,29 @@ public class GuiPrintout extends AbstractContainerScreen<ContainerHeldItem>
} }
@Override @Override
protected void renderBg( @Nonnull PoseStack transform, float partialTicks, int mouseX, int mouseY ) protected void renderBg(@Nonnull PoseStack transform, float partialTicks, int mouseX, int mouseY) {
{
// Draw the printout // Draw the printout
RenderSystem.setShaderColor( 1.0f, 1.0f, 1.0f, 1.0f ); RenderSystem.setShaderColor(1.0f, 1.0f, 1.0f, 1.0f);
RenderSystem.enableDepthTest(); RenderSystem.enableDepthTest();
MultiBufferSource.BufferSource renderer = MultiBufferSource.immediate( Tesselator.getInstance().getBuilder() ); var renderer = MultiBufferSource.immediate(Tesselator.getInstance().getBuilder());
drawBorder( transform, renderer, leftPos, topPos, getBlitOffset(), page, pages, book, FULL_BRIGHT_LIGHTMAP ); drawBorder(transform, renderer, leftPos, topPos, getBlitOffset(), page, pages, book, FULL_BRIGHT_LIGHTMAP);
drawText( transform, renderer, leftPos + X_TEXT_MARGIN, topPos + Y_TEXT_MARGIN, ItemPrintout.LINES_PER_PAGE * page, FULL_BRIGHT_LIGHTMAP, text, colours ); drawText(transform, renderer, leftPos + X_TEXT_MARGIN, topPos + Y_TEXT_MARGIN, ItemPrintout.LINES_PER_PAGE * page, FULL_BRIGHT_LIGHTMAP, text, colours);
renderer.endBatch(); renderer.endBatch();
} }
@Override @Override
public void render( @Nonnull PoseStack stack, int mouseX, int mouseY, float partialTicks ) public void render(@Nonnull PoseStack stack, int mouseX, int mouseY, float partialTicks) {
{
// We must take the background further back in order to not overlap with our printed pages. // We must take the background further back in order to not overlap with our printed pages.
setBlitOffset( getBlitOffset() - 1 ); setBlitOffset(getBlitOffset() - 1);
renderBackground( stack ); renderBackground(stack);
setBlitOffset( getBlitOffset() + 1 ); setBlitOffset(getBlitOffset() + 1);
super.render( stack, mouseX, mouseY, partialTicks ); super.render(stack, mouseX, mouseY, partialTicks);
} }
@Override @Override
protected void renderLabels( @Nonnull PoseStack transform, int mouseX, int mouseY ) protected void renderLabels(@Nonnull PoseStack transform, int mouseX, int mouseY) {
{
// Skip rendering labels. // Skip rendering labels.
} }
} }

View File

@ -21,19 +21,17 @@ import javax.annotation.Nonnull;
import static dan200.computercraft.shared.turtle.inventory.ContainerTurtle.*; import static dan200.computercraft.shared.turtle.inventory.ContainerTurtle.*;
public class GuiTurtle extends ComputerScreenBase<ContainerTurtle> public class GuiTurtle extends ComputerScreenBase<ContainerTurtle> {
{ private static final ResourceLocation BACKGROUND_NORMAL = new ResourceLocation(ComputerCraft.MOD_ID, "textures/gui/turtle_normal.png");
private static final ResourceLocation BACKGROUND_NORMAL = new ResourceLocation( ComputerCraft.MOD_ID, "textures/gui/turtle_normal.png" ); private static final ResourceLocation BACKGROUND_ADVANCED = new ResourceLocation(ComputerCraft.MOD_ID, "textures/gui/turtle_advanced.png");
private static final ResourceLocation BACKGROUND_ADVANCED = new ResourceLocation( ComputerCraft.MOD_ID, "textures/gui/turtle_advanced.png" );
private static final int TEX_WIDTH = 254; private static final int TEX_WIDTH = 254;
private static final int TEX_HEIGHT = 217; private static final int TEX_HEIGHT = 217;
private final ComputerFamily family; private final ComputerFamily family;
public GuiTurtle( ContainerTurtle container, Inventory player, Component title ) public GuiTurtle(ContainerTurtle container, Inventory player, Component title) {
{ super(container, player, title, BORDER);
super( container, player, title, BORDER );
family = container.getFamily(); family = container.getFamily();
imageWidth = TEX_WIDTH + ComputerSidebar.WIDTH; imageWidth = TEX_WIDTH + ComputerSidebar.WIDTH;
@ -41,31 +39,28 @@ public class GuiTurtle extends ComputerScreenBase<ContainerTurtle>
} }
@Override @Override
protected WidgetTerminal createTerminal() protected WidgetTerminal createTerminal() {
{ return new WidgetTerminal(terminalData, input, leftPos + BORDER + ComputerSidebar.WIDTH, topPos + BORDER);
return new WidgetTerminal( terminalData, input, leftPos + BORDER + ComputerSidebar.WIDTH, topPos + BORDER );
} }
@Override @Override
protected void renderBg( @Nonnull PoseStack transform, float partialTicks, int mouseX, int mouseY ) protected void renderBg(@Nonnull PoseStack transform, float partialTicks, int mouseX, int mouseY) {
{ var advanced = family == ComputerFamily.ADVANCED;
boolean advanced = family == ComputerFamily.ADVANCED; RenderSystem.setShaderTexture(0, advanced ? BACKGROUND_ADVANCED : BACKGROUND_NORMAL);
RenderSystem.setShaderTexture( 0, advanced ? BACKGROUND_ADVANCED : BACKGROUND_NORMAL ); blit(transform, leftPos + ComputerSidebar.WIDTH, topPos, 0, 0, TEX_WIDTH, TEX_HEIGHT);
blit( transform, leftPos + ComputerSidebar.WIDTH, topPos, 0, 0, TEX_WIDTH, TEX_HEIGHT );
int slot = getMenu().getSelectedSlot(); var slot = getMenu().getSelectedSlot();
if( slot >= 0 ) if (slot >= 0) {
{ RenderSystem.setShaderColor(1.0F, 1.0F, 1.0F, 1.0F);
RenderSystem.setShaderColor( 1.0F, 1.0F, 1.0F, 1.0F ); var slotX = slot % 4;
int slotX = slot % 4; var slotY = slot / 4;
int slotY = slot / 4; blit(transform,
blit( transform,
leftPos + TURTLE_START_X - 2 + slotX * 18, topPos + PLAYER_START_Y - 2 + slotY * 18, leftPos + TURTLE_START_X - 2 + slotX * 18, topPos + PLAYER_START_Y - 2 + slotY * 18,
0, 217, 24, 24 0, 217, 24, 24
); );
} }
RenderSystem.setShaderTexture( 0, advanced ? ComputerBorderRenderer.BACKGROUND_ADVANCED : ComputerBorderRenderer.BACKGROUND_NORMAL ); RenderSystem.setShaderTexture(0, advanced ? ComputerBorderRenderer.BACKGROUND_ADVANCED : ComputerBorderRenderer.BACKGROUND_NORMAL);
ComputerSidebar.renderBackground( transform, leftPos, topPos + sidebarYOffset ); ComputerSidebar.renderBackground(transform, leftPos, topPos + sidebarYOffset);
} }
} }

View File

@ -8,7 +8,6 @@ package dan200.computercraft.client.gui;
import com.mojang.blaze3d.systems.RenderSystem; import com.mojang.blaze3d.systems.RenderSystem;
import com.mojang.blaze3d.vertex.PoseStack; import com.mojang.blaze3d.vertex.PoseStack;
import net.minecraft.client.Minecraft; import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.Font;
import net.minecraft.client.gui.components.toasts.Toast; import net.minecraft.client.gui.components.toasts.Toast;
import net.minecraft.client.gui.components.toasts.ToastComponent; import net.minecraft.client.gui.components.toasts.ToastComponent;
import net.minecraft.network.chat.Component; import net.minecraft.network.chat.Component;
@ -21,8 +20,7 @@ import java.util.List;
/** /**
* A {@link Toast} implementation which displays an arbitrary message along with an optional {@link ItemStack}. * A {@link Toast} implementation which displays an arbitrary message along with an optional {@link ItemStack}.
*/ */
public class ItemToast implements Toast public class ItemToast implements Toast {
{
public static final Object TRANSFER_NO_RESPONSE_TOKEN = new Object(); public static final Object TRANSFER_NO_RESPONSE_TOKEN = new Object();
private static final long DISPLAY_TIME = 7000L; private static final long DISPLAY_TIME = 7000L;
@ -41,110 +39,92 @@ public class ItemToast implements Toast
private boolean isNew = true; private boolean isNew = true;
private long firstDisplay; private long firstDisplay;
public ItemToast( Minecraft minecraft, ItemStack stack, Component title, Component message, Object token ) public ItemToast(Minecraft minecraft, ItemStack stack, Component title, Component message, Object token) {
{
this.stack = stack; this.stack = stack;
this.title = title; this.title = title;
this.token = token; this.token = token;
Font font = minecraft.font; var font = minecraft.font;
this.message = font.split( message, MAX_LINE_SIZE ); this.message = font.split(message, MAX_LINE_SIZE);
width = Math.max( MAX_LINE_SIZE, this.message.stream().mapToInt( font::width ).max().orElse( MAX_LINE_SIZE ) ) + MARGIN * 3 + IMAGE_SIZE; width = Math.max(MAX_LINE_SIZE, this.message.stream().mapToInt(font::width).max().orElse(MAX_LINE_SIZE)) + MARGIN * 3 + IMAGE_SIZE;
} }
public void showOrReplace( ToastComponent toasts ) public void showOrReplace(ToastComponent toasts) {
{ var existing = toasts.getToast(ItemToast.class, getToken());
ItemToast existing = toasts.getToast( ItemToast.class, getToken() ); if (existing != null) {
if( existing != null )
{
existing.isNew = true; existing.isNew = true;
} } else {
else toasts.addToast(this);
{
toasts.addToast( this );
} }
} }
@Override @Override
public int width() public int width() {
{
return width; return width;
} }
@Override @Override
public int height() public int height() {
{
return MARGIN * 2 + LINE_SPACING + message.size() * LINE_SPACING; return MARGIN * 2 + LINE_SPACING + message.size() * LINE_SPACING;
} }
@Nonnull @Nonnull
@Override @Override
public Object getToken() public Object getToken() {
{
return token; return token;
} }
@Nonnull @Nonnull
@Override @Override
public Visibility render( @Nonnull PoseStack transform, @Nonnull ToastComponent component, long time ) public Visibility render(@Nonnull PoseStack transform, @Nonnull ToastComponent component, long time) {
{ if (isNew) {
if( isNew )
{
firstDisplay = time; firstDisplay = time;
isNew = false; isNew = false;
} }
RenderSystem.setShaderTexture( 0, TEXTURE ); RenderSystem.setShaderTexture(0, TEXTURE);
RenderSystem.setShaderColor( 1.0F, 1.0F, 1.0F, 1.0F ); RenderSystem.setShaderColor(1.0F, 1.0F, 1.0F, 1.0F);
if( width == 160 && message.size() <= 1 ) if (width == 160 && message.size() <= 1) {
{ component.blit(transform, 0, 0, 0, 64, width, height());
component.blit( transform, 0, 0, 0, 64, width, height() ); } else {
}
else
{
int height = height(); var height = height();
int bottom = Math.min( 4, height - 28 ); var bottom = Math.min(4, height - 28);
renderBackgroundRow( transform, component, width, 0, 0, 28 ); renderBackgroundRow(transform, component, width, 0, 0, 28);
for( int i = 28; i < height - bottom; i += 10 ) for (var i = 28; i < height - bottom; i += 10) {
{ renderBackgroundRow(transform, component, width, 16, i, Math.min(16, height - i - bottom));
renderBackgroundRow( transform, component, width, 16, i, Math.min( 16, height - i - bottom ) );
} }
renderBackgroundRow( transform, component, width, 32 - bottom, height - bottom, bottom ); renderBackgroundRow(transform, component, width, 32 - bottom, height - bottom, bottom);
} }
int textX = MARGIN; var textX = MARGIN;
if( !stack.isEmpty() ) if (!stack.isEmpty()) {
{
textX += MARGIN + IMAGE_SIZE; textX += MARGIN + IMAGE_SIZE;
component.getMinecraft().getItemRenderer().renderAndDecorateFakeItem( stack, MARGIN, MARGIN + height() / 2 - IMAGE_SIZE ); component.getMinecraft().getItemRenderer().renderAndDecorateFakeItem(stack, MARGIN, MARGIN + height() / 2 - IMAGE_SIZE);
} }
component.getMinecraft().font.draw( transform, title, textX, MARGIN, 0xff500050 ); component.getMinecraft().font.draw(transform, title, textX, MARGIN, 0xff500050);
for( int i = 0; i < message.size(); ++i ) for (var i = 0; i < message.size(); ++i) {
{ component.getMinecraft().font.draw(transform, message.get(i), textX, (float) (LINE_SPACING + (i + 1) * LINE_SPACING), 0xff000000);
component.getMinecraft().font.draw( transform, message.get( i ), textX, (float) (LINE_SPACING + (i + 1) * LINE_SPACING), 0xff000000 );
} }
return time - firstDisplay < DISPLAY_TIME ? Visibility.SHOW : Visibility.HIDE; return time - firstDisplay < DISPLAY_TIME ? Visibility.SHOW : Visibility.HIDE;
} }
private static void renderBackgroundRow( PoseStack transform, ToastComponent component, int x, int u, int y, int height ) private static void renderBackgroundRow(PoseStack transform, ToastComponent component, int x, int u, int y, int height) {
{ var leftOffset = 5;
int leftOffset = 5; var rightOffset = Math.min(60, x - leftOffset);
int rightOffset = Math.min( 60, x - leftOffset );
component.blit( transform, 0, y, 0, 32 + u, leftOffset, height ); component.blit(transform, 0, y, 0, 32 + u, leftOffset, height);
for( int k = leftOffset; k < x - rightOffset; k += 64 ) for (var k = leftOffset; k < x - rightOffset; k += 64) {
{ component.blit(transform, k, y, 32, 32 + u, Math.min(64, x - k - rightOffset), height);
component.blit( transform, k, y, 32, 32 + u, Math.min( 64, x - k - rightOffset ), height );
} }
component.blit( transform, x - rightOffset, y, 160 - rightOffset, 32 + u, rightOffset, height ); component.blit(transform, x - rightOffset, y, 160 - rightOffset, 32 + u, rightOffset, height);
} }
} }

View File

@ -10,40 +10,33 @@ import dan200.computercraft.client.gui.widgets.WidgetTerminal;
import dan200.computercraft.core.terminal.Terminal; import dan200.computercraft.core.terminal.Terminal;
import dan200.computercraft.shared.computer.inventory.ContainerComputerBase; import dan200.computercraft.shared.computer.inventory.ContainerComputerBase;
import net.minecraft.client.KeyMapping; import net.minecraft.client.KeyMapping;
import net.minecraft.client.gui.Font;
import net.minecraft.client.gui.screens.Screen; import net.minecraft.client.gui.screens.Screen;
import net.minecraft.client.gui.screens.inventory.MenuAccess; import net.minecraft.client.gui.screens.inventory.MenuAccess;
import net.minecraft.network.chat.Component; import net.minecraft.network.chat.Component;
import net.minecraft.util.FormattedCharSequence;
import net.minecraft.world.entity.player.Inventory; import net.minecraft.world.entity.player.Inventory;
import org.lwjgl.glfw.GLFW; import org.lwjgl.glfw.GLFW;
import javax.annotation.Nonnull; import javax.annotation.Nonnull;
import java.util.List;
public class NoTermComputerScreen<T extends ContainerComputerBase> extends Screen implements MenuAccess<T> public class NoTermComputerScreen<T extends ContainerComputerBase> extends Screen implements MenuAccess<T> {
{
private final T menu; private final T menu;
private final Terminal terminalData; private final Terminal terminalData;
private WidgetTerminal terminal; private WidgetTerminal terminal;
public NoTermComputerScreen( T menu, Inventory player, Component title ) public NoTermComputerScreen(T menu, Inventory player, Component title) {
{ super(title);
super( title );
this.menu = menu; this.menu = menu;
terminalData = menu.getTerminal(); terminalData = menu.getTerminal();
} }
@Nonnull @Nonnull
@Override @Override
public T getMenu() public T getMenu() {
{
return menu; return menu;
} }
@Override @Override
protected void init() protected void init() {
{
passEvents = true; // Pass mouse vents through to the game's mouse handler. passEvents = true; // Pass mouse vents through to the game's mouse handler.
// First ensure we're still grabbing the mouse, so the user can look around. Then reset bits of state that // First ensure we're still grabbing the mouse, so the user can look around. Then reset bits of state that
// grabbing unsets. // grabbing unsets.
@ -52,71 +45,62 @@ public class NoTermComputerScreen<T extends ContainerComputerBase> extends Scree
KeyMapping.releaseAll(); KeyMapping.releaseAll();
super.init(); super.init();
minecraft.keyboardHandler.setSendRepeatsToGui( true ); minecraft.keyboardHandler.setSendRepeatsToGui(true);
terminal = addWidget( new WidgetTerminal( terminalData, new ClientInputHandler( menu ), 0, 0 ) ); terminal = addWidget(new WidgetTerminal(terminalData, new ClientInputHandler(menu), 0, 0));
terminal.visible = false; terminal.visible = false;
terminal.active = false; terminal.active = false;
setFocused( terminal ); setFocused(terminal);
} }
@Override @Override
public final void removed() public final void removed() {
{
super.removed(); super.removed();
minecraft.keyboardHandler.setSendRepeatsToGui( false ); minecraft.keyboardHandler.setSendRepeatsToGui(false);
} }
@Override @Override
public final void tick() public final void tick() {
{
super.tick(); super.tick();
terminal.update(); terminal.update();
} }
@Override @Override
public boolean mouseScrolled( double pMouseX, double pMouseY, double pDelta ) public boolean mouseScrolled(double pMouseX, double pMouseY, double pDelta) {
{ minecraft.player.getInventory().swapPaint(pDelta);
minecraft.player.getInventory().swapPaint( pDelta ); return super.mouseScrolled(pMouseX, pMouseY, pDelta);
return super.mouseScrolled( pMouseX, pMouseY, pDelta );
} }
@Override @Override
public void onClose() public void onClose() {
{
minecraft.player.closeContainer(); minecraft.player.closeContainer();
super.onClose(); super.onClose();
} }
@Override @Override
public boolean isPauseScreen() public boolean isPauseScreen() {
{
return false; return false;
} }
@Override @Override
public final boolean keyPressed( int key, int scancode, int modifiers ) public final boolean keyPressed(int key, int scancode, int modifiers) {
{
// Forward the tab key to the terminal, rather than moving between controls. // Forward the tab key to the terminal, rather than moving between controls.
if( key == GLFW.GLFW_KEY_TAB && getFocused() != null && getFocused() == terminal ) if (key == GLFW.GLFW_KEY_TAB && getFocused() != null && getFocused() == terminal) {
{ return getFocused().keyPressed(key, scancode, modifiers);
return getFocused().keyPressed( key, scancode, modifiers );
} }
return super.keyPressed( key, scancode, modifiers ); return super.keyPressed(key, scancode, modifiers);
} }
@Override @Override
public void render( @Nonnull PoseStack transform, int mouseX, int mouseY, float partialTicks ) public void render(@Nonnull PoseStack transform, int mouseX, int mouseY, float partialTicks) {
{ super.render(transform, mouseX, mouseY, partialTicks);
super.render( transform, mouseX, mouseY, partialTicks );
Font font = minecraft.font; var font = minecraft.font;
List<FormattedCharSequence> lines = font.split( Component.translatable( "gui.computercraft.pocket_computer_overlay" ), (int) (width * 0.8) ); var lines = font.split(Component.translatable("gui.computercraft.pocket_computer_overlay"), (int) (width * 0.8));
float y = 10.0f; var y = 10.0f;
for( FormattedCharSequence line : lines ) for (var line : lines) {
{ font.drawShadow(transform, line, (float) ((width / 2) - (minecraft.font.width(line) / 2)), y, 0xFFFFFF);
font.drawShadow( transform, line, (float) ((width / 2) - (minecraft.font.width( line ) / 2)), y, 0xFFFFFF );
y += 9.0f; y += 9.0f;
} }
} }

View File

@ -18,9 +18,8 @@ import net.minecraft.resources.ResourceLocation;
import javax.annotation.Nonnull; import javax.annotation.Nonnull;
import java.util.List; import java.util.List;
public final class OptionScreen extends Screen public final class OptionScreen extends Screen {
{ private static final ResourceLocation BACKGROUND = new ResourceLocation("computercraft", "textures/gui/blank_screen.png");
private static final ResourceLocation BACKGROUND = new ResourceLocation( "computercraft", "textures/gui/blank_screen.png" );
public static final int BUTTON_WIDTH = 100; public static final int BUTTON_WIDTH = 100;
public static final int BUTTON_HEIGHT = 20; public static final int BUTTON_HEIGHT = 20;
@ -40,89 +39,79 @@ public final class OptionScreen extends Screen
private final Screen originalScreen; private final Screen originalScreen;
private OptionScreen( Component title, Component message, List<AbstractWidget> buttons, Runnable exit, Screen originalScreen ) private OptionScreen(Component title, Component message, List<AbstractWidget> buttons, Runnable exit, Screen originalScreen) {
{ super(title);
super( title );
this.message = message; this.message = message;
this.buttons = buttons; this.buttons = buttons;
this.exit = exit; this.exit = exit;
this.originalScreen = originalScreen; this.originalScreen = originalScreen;
} }
public static void show( Minecraft minecraft, Component title, Component message, List<AbstractWidget> buttons, Runnable exit ) public static void show(Minecraft minecraft, Component title, Component message, List<AbstractWidget> buttons, Runnable exit) {
{ minecraft.setScreen(new OptionScreen(title, message, buttons, exit, unwrap(minecraft.screen)));
minecraft.setScreen( new OptionScreen( title, message, buttons, exit, unwrap( minecraft.screen ) ) );
} }
public static Screen unwrap( Screen screen ) public static Screen unwrap(Screen screen) {
{
return screen instanceof OptionScreen option ? option.getOriginalScreen() : screen; return screen instanceof OptionScreen option ? option.getOriginalScreen() : screen;
} }
@Override @Override
public void init() public void init() {
{
super.init(); super.init();
int buttonWidth = BUTTON_WIDTH * buttons.size() + PADDING * (buttons.size() - 1); var buttonWidth = BUTTON_WIDTH * buttons.size() + PADDING * (buttons.size() - 1);
int innerWidth = this.innerWidth = Math.max( 256, buttonWidth + PADDING * 2 ); var innerWidth = this.innerWidth = Math.max(256, buttonWidth + PADDING * 2);
messageRenderer = MultiLineLabel.create( font, message, innerWidth - PADDING * 2 ); messageRenderer = MultiLineLabel.create(font, message, innerWidth - PADDING * 2);
int textHeight = messageRenderer.getLineCount() * FONT_HEIGHT + PADDING * 2; var textHeight = messageRenderer.getLineCount() * FONT_HEIGHT + PADDING * 2;
innerHeight = textHeight + (buttons.isEmpty() ? 0 : buttons.get( 0 ).getHeight()) + PADDING; innerHeight = textHeight + (buttons.isEmpty() ? 0 : buttons.get(0).getHeight()) + PADDING;
x = (width - innerWidth) / 2; x = (width - innerWidth) / 2;
y = (height - innerHeight) / 2; y = (height - innerHeight) / 2;
int x = (width - buttonWidth) / 2; var x = (width - buttonWidth) / 2;
for( AbstractWidget button : buttons ) for (var button : buttons) {
{
button.x = x; button.x = x;
button.y = y + textHeight; button.y = y + textHeight;
addRenderableWidget( button ); addRenderableWidget(button);
x += BUTTON_WIDTH + PADDING; x += BUTTON_WIDTH + PADDING;
} }
} }
@Override @Override
public void render( @Nonnull PoseStack transform, int mouseX, int mouseY, float partialTicks ) public void render(@Nonnull PoseStack transform, int mouseX, int mouseY, float partialTicks) {
{ renderBackground(transform);
renderBackground( transform );
// Render the actual texture. // Render the actual texture.
RenderSystem.setShaderTexture( 0, BACKGROUND ); RenderSystem.setShaderTexture(0, BACKGROUND);
blit( transform, x, y, 0, 0, innerWidth, PADDING ); blit(transform, x, y, 0, 0, innerWidth, PADDING);
blit( transform, blit(transform,
x, y + PADDING, 0, PADDING, innerWidth, innerHeight - PADDING * 2, x, y + PADDING, 0, PADDING, innerWidth, innerHeight - PADDING * 2,
innerWidth, PADDING innerWidth, PADDING
); );
blit( transform, x, y + innerHeight - PADDING, 0, 256 - PADDING, innerWidth, PADDING ); blit(transform, x, y + innerHeight - PADDING, 0, 256 - PADDING, innerWidth, PADDING);
messageRenderer.renderLeftAlignedNoShadow( transform, x + PADDING, y + PADDING, FONT_HEIGHT, 0x404040 ); messageRenderer.renderLeftAlignedNoShadow(transform, x + PADDING, y + PADDING, FONT_HEIGHT, 0x404040);
super.render( transform, mouseX, mouseY, partialTicks ); super.render(transform, mouseX, mouseY, partialTicks);
} }
@Override @Override
public void onClose() public void onClose() {
{
exit.run(); exit.run();
} }
public static AbstractWidget newButton( Component component, Button.OnPress clicked ) public static AbstractWidget newButton(Component component, Button.OnPress clicked) {
{ return new Button(0, 0, BUTTON_WIDTH, BUTTON_HEIGHT, component, clicked);
return new Button( 0, 0, BUTTON_WIDTH, BUTTON_HEIGHT, component, clicked );
} }
public void disable() public void disable() {
{ for (var widget : buttons) widget.active = false;
for( AbstractWidget widget : buttons ) widget.active = false;
} }
@Nonnull @Nonnull
public Screen getOriginalScreen() public Screen getOriginalScreen() {
{
return originalScreen; return originalScreen;
} }
} }

Some files were not shown because too many files have changed in this diff Show More