1
0
mirror of https://github.com/SquidDev-CC/CC-Tweaked synced 2024-12-04 23:40:00 +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
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]
trim_trailing_whitespace = false

View File

@ -4,7 +4,6 @@ import org.codehaus.groovy.runtime.ProcessGroovyMethods
import java.io.BufferedReader
import java.io.IOException
import java.io.InputStreamReader
import java.util.stream.Collectors
internal object ProcessHelpers {
fun startProcess(vararg command: String): Process {
@ -26,7 +25,7 @@ internal object ProcessHelpers {
fun captureLines(process: Process): List<String> {
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)
if (process.waitFor() != 0) throw IOException("Command exited with a non-0 status")

View File

@ -26,17 +26,11 @@
<module name="EmptyCatchBlock">
<property name="exceptionVariableName" value="ignored" />
</module>
<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="LeftCurly" />
<module name="NeedBraces">
<property name="allowSingleLineStatement" value="true"/>
</module>
<module name="RightCurly">
<property name="option" value="alone" />
</module>
<module name="RightCurly" />
<!-- Class design. As if we've ever followed good practice here. -->
<module name="FinalClass" />
@ -131,18 +125,11 @@
<module name="MethodParamPad" />
<module name="NoLineWrap" />
<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 name="NoWhitespaceBefore" />
<!-- TODO: Decide on an OperatorWrap style. -->
<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="ParenPad" />
<module name="SeparatorWrap">
<property name="option" value="eol" />
<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.concurrent.TimeUnit;
@Mod( ComputerCraft.MOD_ID )
public final class ComputerCraft
{
@Mod(ComputerCraft.MOD_ID)
public final class ComputerCraft {
public static final String MOD_ID = "computercraft";
public static int computerSpaceLimit = 1000 * 1000;
@ -32,14 +31,14 @@ public final class ComputerCraft
public static boolean commandRequireCreative = true;
public static int computerThreads = 1;
public static long maxMainGlobalTime = TimeUnit.MILLISECONDS.toNanos( 10 );
public static long maxMainComputerTime = TimeUnit.MILLISECONDS.toNanos( 5 );
public static long maxMainGlobalTime = TimeUnit.MILLISECONDS.toNanos(10);
public static long maxMainComputerTime = TimeUnit.MILLISECONDS.toNanos(5);
public static boolean httpEnabled = true;
public static boolean httpWebsocketEnabled = true;
public static List<AddressRule> httpRules = List.of(
AddressRule.parse( "$private", OptionalInt.empty(), Action.DENY.toPartial() ),
AddressRule.parse( "*", OptionalInt.empty(), Action.ALLOW.toPartial() )
AddressRule.parse("$private", OptionalInt.empty(), Action.DENY.toPartial()),
AddressRule.parse("*", OptionalInt.empty(), Action.ALLOW.toPartial())
);
public static int httpMaxRequests = 16;
@ -77,10 +76,9 @@ public final class ComputerCraft
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();
Registry.setup();
}

View File

@ -41,11 +41,9 @@ import net.minecraft.core.BlockPos;
import net.minecraft.core.Direction;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.server.MinecraftServer;
import net.minecraft.server.packs.resources.ResourceManager;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.level.BlockGetter;
import net.minecraft.world.level.Level;
import net.minecraft.world.level.block.entity.BlockEntity;
import net.minecraftforge.common.capabilities.Capability;
import net.minecraftforge.common.util.LazyOptional;
import net.minecraftforge.fluids.FluidStack;
@ -59,175 +57,141 @@ import java.io.InputStream;
import static dan200.computercraft.shared.Capabilities.CAPABILITY_WIRED_ELEMENT;
@AutoService( ComputerCraftAPIService.class )
public final class ComputerCraftAPIImpl implements ComputerCraftAPIService
{
private final DetailRegistry<ItemStack> itemStackDetails = new DetailRegistryImpl<>( ItemData::fillBasic );
private final DetailRegistry<BlockReference> blockDetails = new DetailRegistryImpl<>( BlockData::fillBasic );
private final DetailRegistry<FluidStack> fluidStackDetails = new DetailRegistryImpl<>( FluidData::fillBasic );
@AutoService(ComputerCraftAPIService.class)
public final class ComputerCraftAPIImpl implements ComputerCraftAPIService {
private final DetailRegistry<ItemStack> itemStackDetails = new DetailRegistryImpl<>(ItemData::fillBasic);
private final DetailRegistry<BlockReference> blockDetails = new DetailRegistryImpl<>(BlockData::fillBasic);
private final DetailRegistry<FluidStack> fluidStackDetails = new DetailRegistryImpl<>(FluidData::fillBasic);
private String version;
public static InputStream getResourceFile( MinecraftServer server, String domain, String subPath )
{
ResourceManager manager = server.getResourceManager();
var resource = manager.getResource( new ResourceLocation( domain, subPath ) ).orElse( null );
if( resource == null ) return null;
try
{
public static InputStream getResourceFile(MinecraftServer server, String domain, String subPath) {
var manager = server.getResourceManager();
var resource = manager.getResource(new ResourceLocation(domain, subPath)).orElse(null);
if (resource == null) return null;
try {
return resource.open();
}
catch( IOException ignored )
{
} catch (IOException ignored) {
return null;
}
}
@Nonnull
@Override
public String getInstalledVersion()
{
if( version != null ) return version;
return version = ModList.get().getModContainerById( ComputerCraft.MOD_ID )
.map( x -> x.getModInfo().getVersion().toString() )
.orElse( "unknown" );
public String getInstalledVersion() {
if (version != null) return version;
return version = ModList.get().getModContainerById(ComputerCraft.MOD_ID)
.map(x -> x.getModInfo().getVersion().toString())
.orElse("unknown");
}
@Override
public int createUniqueNumberedSaveDir( @Nonnull Level world, @Nonnull String parentSubPath )
{
return ServerContext.get( world.getServer() ).getNextId( parentSubPath );
public int createUniqueNumberedSaveDir(@Nonnull Level world, @Nonnull String parentSubPath) {
return ServerContext.get(world.getServer()).getNextId(parentSubPath);
}
@Override
public IWritableMount createSaveDirMount( @Nonnull Level world, @Nonnull String subPath, long capacity )
{
try
{
return new FileMount( new File( ServerContext.get( world.getServer() ).storageDir().toFile(), subPath ), capacity );
}
catch( Exception e )
{
public IWritableMount createSaveDirMount(@Nonnull Level world, @Nonnull String subPath, long capacity) {
try {
return new FileMount(new File(ServerContext.get(world.getServer()).storageDir().toFile(), subPath), capacity);
} catch (Exception e) {
return null;
}
}
@Override
public IMount createResourceMount( @Nonnull String domain, @Nonnull String subPath )
{
ResourceManager manager = ServerLifecycleHooks.getCurrentServer().getResourceManager();
ResourceMount mount = ResourceMount.get( domain, subPath, manager );
return mount.exists( "" ) ? mount : null;
public IMount createResourceMount(@Nonnull String domain, @Nonnull String subPath) {
var manager = ServerLifecycleHooks.getCurrentServer().getResourceManager();
var mount = ResourceMount.get(domain, subPath, manager);
return mount.exists("") ? mount : null;
}
@Override
public void registerPeripheralProvider( @Nonnull IPeripheralProvider provider )
{
Peripherals.register( provider );
public void registerPeripheralProvider(@Nonnull IPeripheralProvider provider) {
Peripherals.register(provider);
}
@Override
public void registerGenericSource( @Nonnull GenericSource source )
{
GenericMethod.register( source );
public void registerGenericSource(@Nonnull GenericSource source) {
GenericMethod.register(source);
}
@Override
public void registerGenericCapability( @Nonnull Capability<?> capability )
{
GenericPeripheralProvider.addCapability( capability );
public void registerGenericCapability(@Nonnull Capability<?> capability) {
GenericPeripheralProvider.addCapability(capability);
}
@Override
public void registerBundledRedstoneProvider( @Nonnull IBundledRedstoneProvider provider )
{
BundledRedstone.register( provider );
public void registerBundledRedstoneProvider(@Nonnull IBundledRedstoneProvider provider) {
BundledRedstone.register(provider);
}
@Override
public int getBundledRedstoneOutput( @Nonnull Level world, @Nonnull BlockPos pos, @Nonnull Direction side )
{
return BundledRedstone.getDefaultOutput( world, pos, side );
public int getBundledRedstoneOutput(@Nonnull Level world, @Nonnull BlockPos pos, @Nonnull Direction side) {
return BundledRedstone.getDefaultOutput(world, pos, side);
}
@Override
public void registerMediaProvider( @Nonnull IMediaProvider provider )
{
MediaProviders.register( provider );
public void registerMediaProvider(@Nonnull IMediaProvider provider) {
MediaProviders.register(provider);
}
@Nonnull
@Override
public IPacketNetwork getWirelessNetwork()
{
public IPacketNetwork getWirelessNetwork() {
return WirelessNetwork.getUniversal();
}
@Override
public void registerAPIFactory( @Nonnull ILuaAPIFactory factory )
{
ApiFactories.register( factory );
public void registerAPIFactory(@Nonnull ILuaAPIFactory factory) {
ApiFactories.register(factory);
}
@Override
@Deprecated
@SuppressWarnings( "unchecked" )
public <T> void registerDetailProvider( @Nonnull Class<T> type, @Nonnull IDetailProvider<T> provider )
{
if( type == ItemStack.class )
{
itemStackDetails.addProvider( (IDetailProvider<ItemStack>) provider );
}
else if( type == BlockReference.class )
{
blockDetails.addProvider( (IDetailProvider<BlockReference>) provider );
}
else if( type == FluidStack.class )
{
itemStackDetails.addProvider( (IDetailProvider<ItemStack>) provider );
}
else
{
throw new IllegalArgumentException( "Unknown detail provider " + type );
@SuppressWarnings("unchecked")
public <T> void registerDetailProvider(@Nonnull Class<T> type, @Nonnull IDetailProvider<T> provider) {
if (type == ItemStack.class) {
itemStackDetails.addProvider((IDetailProvider<ItemStack>) provider);
} else if (type == BlockReference.class) {
blockDetails.addProvider((IDetailProvider<BlockReference>) provider);
} else if (type == FluidStack.class) {
itemStackDetails.addProvider((IDetailProvider<ItemStack>) provider);
} else {
throw new IllegalArgumentException("Unknown detail provider " + type);
}
}
@Nonnull
@Override
public IWiredNode createWiredNodeForElement( @Nonnull IWiredElement element )
{
return new WiredNode( element );
public IWiredNode createWiredNodeForElement(@Nonnull IWiredElement element) {
return new WiredNode(element);
}
@Nonnull
@Override
public LazyOptional<IWiredElement> getWiredElementAt( @Nonnull BlockGetter world, @Nonnull BlockPos pos, @Nonnull Direction side )
{
BlockEntity tile = world.getBlockEntity( pos );
return tile == null ? LazyOptional.empty() : tile.getCapability( CAPABILITY_WIRED_ELEMENT, side );
public LazyOptional<IWiredElement> getWiredElementAt(@Nonnull BlockGetter world, @Nonnull BlockPos pos, @Nonnull Direction side) {
var tile = world.getBlockEntity(pos);
return tile == null ? LazyOptional.empty() : tile.getCapability(CAPABILITY_WIRED_ELEMENT, side);
}
@Override
public void registerRefuelHandler( @Nonnull TurtleRefuelHandler handler )
{
TurtleRefuelHandlers.register( handler );
public void registerRefuelHandler(@Nonnull TurtleRefuelHandler handler) {
TurtleRefuelHandlers.register(handler);
}
@Override
public DetailRegistry<ItemStack> getItemStackDetailRegistry()
{
public DetailRegistry<ItemStack> getItemStackDetailRegistry() {
return itemStackDetails;
}
@Override
public DetailRegistry<BlockReference> getBlockInWorldDetailRegistry()
{
public DetailRegistry<BlockReference> getBlockInWorldDetailRegistry() {
return blockDetails;
}
@Override
public DetailRegistry<FluidStack> getFluidStackDetailRegistry()
{
public DetailRegistry<FluidStack> getFluidStackDetailRegistry() {
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
* fully loaded.
*/
public final class ComputerCraftAPI
{
public final class ComputerCraftAPI {
public static final String MOD_ID = "computercraft";
@Nonnull
public static String getInstalledVersion()
{
public static String getInstalledVersion() {
return getInstance().getInstalledVersion();
}
@ -64,9 +62,8 @@ public final class ComputerCraftAPI
* available for writing.
* @see #createSaveDirMount(Level, String, long)
*/
public static int createUniqueNumberedSaveDir( @Nonnull Level world, @Nonnull String parentSubPath )
{
return getInstance().createUniqueNumberedSaveDir( world, parentSubPath );
public static int createUniqueNumberedSaveDir(@Nonnull Level world, @Nonnull String parentSubPath) {
return getInstance().createUniqueNumberedSaveDir(world, parentSubPath);
}
/**
@ -88,9 +85,8 @@ public final class ComputerCraftAPI
* @see IWritableMount
*/
@Nullable
public static IWritableMount createSaveDirMount( @Nonnull Level world, @Nonnull String subPath, long capacity )
{
return getInstance().createSaveDirMount( world, subPath, capacity );
public static IWritableMount createSaveDirMount(@Nonnull Level world, @Nonnull String subPath, long capacity) {
return getInstance().createSaveDirMount(world, subPath, capacity);
}
/**
@ -112,9 +108,8 @@ public final class ComputerCraftAPI
* @see IMount
*/
@Nullable
public static IMount createResourceMount( @Nonnull String domain, @Nonnull String subPath )
{
return getInstance().createResourceMount( domain, subPath );
public static IMount createResourceMount(@Nonnull String domain, @Nonnull String subPath) {
return getInstance().createResourceMount(domain, subPath);
}
/**
@ -125,10 +120,9 @@ public final class ComputerCraftAPI
* @see IPeripheralProvider
* @deprecated Use {@link ForgeComputerCraftAPI#registerPeripheralProvider(IPeripheralProvider)} instead.
*/
@Deprecated( forRemoval = true )
public static void registerPeripheralProvider( @Nonnull IPeripheralProvider provider )
{
getInstance().registerPeripheralProvider( provider );
@Deprecated(forRemoval = true)
public static void registerPeripheralProvider(@Nonnull IPeripheralProvider provider) {
getInstance().registerPeripheralProvider(provider);
}
/**
@ -137,9 +131,8 @@ public final class ComputerCraftAPI
* @param source The method source to register.
* @see GenericSource
*/
public static void registerGenericSource( @Nonnull GenericSource source )
{
getInstance().registerGenericSource( source );
public static void registerGenericSource(@Nonnull GenericSource source) {
getInstance().registerGenericSource(source);
}
/**
@ -149,10 +142,9 @@ public final class ComputerCraftAPI
* @see GenericSource
* @deprecated Use {@link ForgeComputerCraftAPI} instead.
*/
@Deprecated( forRemoval = true )
public static void registerGenericCapability( @Nonnull Capability<?> capability )
{
getInstance().registerGenericCapability( capability );
@Deprecated(forRemoval = true)
public static void registerGenericCapability(@Nonnull Capability<?> capability) {
getInstance().registerGenericCapability(capability);
}
/**
@ -161,9 +153,8 @@ public final class ComputerCraftAPI
* @param provider The bundled redstone provider to register.
* @see IBundledRedstoneProvider
*/
public static void registerBundledRedstoneProvider( @Nonnull IBundledRedstoneProvider provider )
{
getInstance().registerBundledRedstoneProvider( provider );
public static void registerBundledRedstoneProvider(@Nonnull IBundledRedstoneProvider 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.
* @see IBundledRedstoneProvider
*/
public static int getBundledRedstoneOutput( @Nonnull Level world, @Nonnull BlockPos pos, @Nonnull Direction side )
{
return getInstance().getBundledRedstoneOutput( world, pos, side );
public static int getBundledRedstoneOutput(@Nonnull Level world, @Nonnull BlockPos pos, @Nonnull Direction side) {
return getInstance().getBundledRedstoneOutput(world, pos, side);
}
/**
@ -187,9 +177,8 @@ public final class ComputerCraftAPI
* @param provider The media provider to register.
* @see IMediaProvider
*/
public static void registerMediaProvider( @Nonnull IMediaProvider provider )
{
getInstance().registerMediaProvider( provider );
public static void registerMediaProvider(@Nonnull IMediaProvider 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.
*/
public static IPacketNetwork getWirelessNetwork()
{
public static IPacketNetwork getWirelessNetwork() {
return getInstance().getWirelessNetwork();
}
public static void registerAPIFactory( @Nonnull ILuaAPIFactory factory )
{
getInstance().registerAPIFactory( factory );
public static void registerAPIFactory(@Nonnull ILuaAPIFactory 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.
* @deprecated Use {@link DetailRegistry#addProvider(IDetailProvider)} to register your provider.
*/
@Deprecated( forRemoval = true )
public static <T> void registerDetailProvider( @Nonnull Class<T> type, @Nonnull IDetailProvider<T> provider )
{
getInstance().registerDetailProvider( type, provider );
@Deprecated(forRemoval = true)
public static <T> void registerDetailProvider(@Nonnull Class<T> type, @Nonnull IDetailProvider<T> provider) {
getInstance().registerDetailProvider(type, provider);
}
/**
@ -231,9 +217,8 @@ public final class ComputerCraftAPI
* @see IWiredElement#getNode()
*/
@Nonnull
public static IWiredNode createWiredNodeForElement( @Nonnull IWiredElement element )
{
return getInstance().createWiredNodeForElement( element );
public static IWiredNode createWiredNodeForElement(@Nonnull IWiredElement element) {
return getInstance().createWiredNodeForElement(element);
}
/**
@ -247,20 +232,17 @@ public final class ComputerCraftAPI
* @deprecated Use {@link ForgeComputerCraftAPI#getWiredElementAt(BlockGetter, BlockPos, Direction)}
*/
@Nonnull
@Deprecated( forRemoval = true )
public static LazyOptional<IWiredElement> getWiredElementAt( @Nonnull BlockGetter world, @Nonnull BlockPos pos, @Nonnull Direction side )
{
return getInstance().getWiredElementAt( world, pos, side );
@Deprecated(forRemoval = true)
public static LazyOptional<IWiredElement> getWiredElementAt(@Nonnull BlockGetter world, @Nonnull BlockPos pos, @Nonnull Direction side) {
return getInstance().getWiredElementAt(world, pos, side);
}
public static void registerRefuelHandler( @Nonnull TurtleRefuelHandler handler )
{
getInstance().registerRefuelHandler( handler );
public static void registerRefuelHandler(@Nonnull TurtleRefuelHandler handler) {
getInstance().registerRefuelHandler(handler);
}
@Nonnull
private static ComputerCraftAPIService getInstance()
{
private static ComputerCraftAPIService getInstance() {
return ComputerCraftAPIService.get();
}
}

View File

@ -16,51 +16,46 @@ import net.minecraft.world.level.block.Block;
/**
* Tags provided by ComputerCraft.
*/
public class ComputerCraftTags
{
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> WIRED_MODEM = make( "wired_modem" );
public static final TagKey<Item> MONITOR = make( "monitor" );
public class ComputerCraftTags {
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> WIRED_MODEM = make("wired_modem");
public static final TagKey<Item> MONITOR = make("monitor");
private static TagKey<Item> make( String name )
{
return ItemTags.create( new ResourceLocation( ComputerCraft.MOD_ID, name ) );
private static TagKey<Item> make(String name) {
return ItemTags.create(new ResourceLocation(ComputerCraft.MOD_ID, name));
}
}
public static class Blocks
{
public static final TagKey<Block> COMPUTER = make( "computer" );
public static final TagKey<Block> TURTLE = make( "turtle" );
public static final TagKey<Block> WIRED_MODEM = make( "wired_modem" );
public static final TagKey<Block> MONITOR = make( "monitor" );
public static class Blocks {
public static final TagKey<Block> COMPUTER = make("computer");
public static final TagKey<Block> TURTLE = make("turtle");
public static final TagKey<Block> WIRED_MODEM = make("wired_modem");
public static final TagKey<Block> MONITOR = make("monitor");
/**
* 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.
*/
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.
*/
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.
*/
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 )
{
return BlockTags.create( new ResourceLocation( ComputerCraft.MOD_ID, name ) );
private static TagKey<Block> make(String 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.
*/
public final class ForgeComputerCraftAPI
{
private ForgeComputerCraftAPI()
{
public final class ForgeComputerCraftAPI {
private ForgeComputerCraftAPI() {
}
/**
@ -34,9 +32,8 @@ public final class ForgeComputerCraftAPI
* @see IPeripheral
* @see IPeripheralProvider
*/
public static void registerPeripheralProvider( @Nonnull IPeripheralProvider provider )
{
getInstance().registerPeripheralProvider( provider );
public static void registerPeripheralProvider(@Nonnull IPeripheralProvider provider) {
getInstance().registerPeripheralProvider(provider);
}
/**
@ -45,9 +42,8 @@ public final class ForgeComputerCraftAPI
* @param capability The capability to register.
* @see GenericSource
*/
public static void registerGenericCapability( @Nonnull Capability<?> capability )
{
getInstance().registerGenericCapability( capability );
public static void registerGenericCapability(@Nonnull Capability<?> capability) {
getInstance().registerGenericCapability(capability);
}
/**
@ -60,14 +56,12 @@ public final class ForgeComputerCraftAPI
* @see IWiredElement#getNode()
*/
@Nonnull
public static LazyOptional<IWiredElement> getWiredElementAt( @Nonnull BlockGetter world, @Nonnull BlockPos pos, @Nonnull Direction side )
{
return getInstance().getWiredElementAt( world, pos, side );
public static LazyOptional<IWiredElement> getWiredElementAt(@Nonnull BlockGetter world, @Nonnull BlockPos pos, @Nonnull Direction side) {
return getInstance().getWiredElementAt(world, pos, side);
}
@Nonnull
private static ComputerCraftAPIService getInstance()
{
private static ComputerCraftAPIService getInstance() {
return ComputerCraftAPIService.get();
}
}

View File

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

View File

@ -8,7 +8,6 @@ package dan200.computercraft.api.client;
import com.mojang.math.Transformation;
import net.minecraft.client.Minecraft;
import net.minecraft.client.resources.model.BakedModel;
import net.minecraft.client.resources.model.ModelManager;
import net.minecraft.client.resources.model.ModelResourceLocation;
import net.minecraft.resources.ResourceLocation;
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.
*/
public final class TransformedModel
{
public final class TransformedModel {
private final BakedModel model;
private final Transformation matrix;
public TransformedModel( @Nonnull BakedModel model, @Nonnull Transformation matrix )
{
this.model = Objects.requireNonNull( model );
this.matrix = Objects.requireNonNull( matrix );
public TransformedModel(@Nonnull BakedModel model, @Nonnull Transformation matrix) {
this.model = Objects.requireNonNull(model);
this.matrix = Objects.requireNonNull(matrix);
}
public TransformedModel( @Nonnull BakedModel model )
{
this.model = Objects.requireNonNull( model );
public TransformedModel(@Nonnull BakedModel model) {
this.model = Objects.requireNonNull(model);
matrix = Transformation.identity();
}
public static TransformedModel of( @Nonnull ModelResourceLocation location )
{
ModelManager modelManager = Minecraft.getInstance().getModelManager();
return new TransformedModel( modelManager.getModel( location ) );
public static TransformedModel of(@Nonnull ModelResourceLocation location) {
var modelManager = Minecraft.getInstance().getModelManager();
return new TransformedModel(modelManager.getModel(location));
}
public static TransformedModel of( @Nonnull ResourceLocation location )
{
ModelManager modelManager = Minecraft.getInstance().getModelManager();
return new TransformedModel( modelManager.getModel( location ) );
public static TransformedModel of(@Nonnull ResourceLocation location) {
var modelManager = Minecraft.getInstance().getModelManager();
return new TransformedModel(modelManager.getModel(location));
}
public static TransformedModel of( @Nonnull ItemStack item, @Nonnull Transformation transform )
{
BakedModel model = Minecraft.getInstance().getItemRenderer().getItemModelShaper().getItemModel( item );
return new TransformedModel( model, transform );
public static TransformedModel of(@Nonnull ItemStack item, @Nonnull Transformation transform) {
var model = Minecraft.getInstance().getItemRenderer().getItemModelShaper().getItemModel(item);
return new TransformedModel(model, transform);
}
@Nonnull
public BakedModel getModel()
{
public BakedModel getModel() {
return model;
}
@Nonnull
public Transformation getMatrix()
{
public Transformation getMatrix() {
return matrix;
}
}

View File

@ -23,8 +23,7 @@ import javax.annotation.Nullable;
* @param <T> The type of turtle upgrade this modeller applies to.
* @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.
* <p>
@ -36,7 +35,7 @@ public interface TurtleUpgradeModeller<T extends ITurtleUpgrade>
* @return The model that you wish to be used to render your upgrade.
*/
@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()
@ -48,9 +47,8 @@ public interface TurtleUpgradeModeller<T extends ITurtleUpgrade>
* @param <T> The type of the turtle upgrade.
* @return The constructed modeller.
*/
@SuppressWarnings( "unchecked" )
static <T extends ITurtleUpgrade> TurtleUpgradeModeller<T> flatItem()
{
@SuppressWarnings("unchecked")
static <T extends ITurtleUpgrade> TurtleUpgradeModeller<T> flatItem() {
return (TurtleUpgradeModeller<T>) TurtleUpgradeModellers.FLAT_ITEM;
}
@ -62,9 +60,8 @@ public interface TurtleUpgradeModeller<T extends ITurtleUpgrade>
* @param <T> The type of the turtle upgrade.
* @return The constructed modeller.
*/
static <T extends ITurtleUpgrade> TurtleUpgradeModeller<T> sided( ModelResourceLocation left, ModelResourceLocation right )
{
return ( upgrade, turtle, side ) -> TransformedModel.of( side == TurtleSide.LEFT ? left : right );
static <T extends ITurtleUpgrade> TurtleUpgradeModeller<T> sided(ModelResourceLocation left, ModelResourceLocation 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.
* @return The constructed modeller.
*/
static <T extends ITurtleUpgrade> TurtleUpgradeModeller<T> sided( ResourceLocation left, ResourceLocation right )
{
return ( upgrade, turtle, side ) -> TransformedModel.of( side == TurtleSide.LEFT ? left : right );
static <T extends ITurtleUpgrade> TurtleUpgradeModeller<T> sided(ResourceLocation left, ResourceLocation 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.TurtleSide;
class TurtleUpgradeModellers
{
private static final Transformation leftTransform = getMatrixFor( -0.40625f );
private static final Transformation rightTransform = getMatrixFor( 0.40625f );
class TurtleUpgradeModellers {
private static final Transformation leftTransform = getMatrixFor(-0.40625f);
private static final Transformation rightTransform = getMatrixFor(0.40625f);
private static Transformation getMatrixFor( float offset )
{
return new Transformation( new Matrix4f( new float[] {
private static Transformation getMatrixFor(float offset) {
return new Transformation(new Matrix4f(new float[]{
0.0f, 0.0f, -1.0f, 1.0f + offset,
1.0f, 0.0f, 0.0f, 0.0f,
0.0f, -1.0f, 0.0f, 1.0f,
0.0f, 0.0f, 0.0f, 1.0f,
} ) );
}));
}
static final TurtleUpgradeModeller<ITurtleUpgrade> FLAT_ITEM = ( upgrade, turtle, side ) ->
TransformedModel.of( upgrade.getCraftingItem(), side == TurtleSide.LEFT ? leftTransform : rightTransform );
static final TurtleUpgradeModeller<ITurtleUpgrade> FLAT_ITEM = (upgrade, turtle, side) ->
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.
*/
public abstract class BasicItemDetailProvider<T> implements IDetailProvider<ItemStack>
{
public abstract class BasicItemDetailProvider<T> implements IDetailProvider<ItemStack> {
private final Class<T> itemType;
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 namespace The namespace to use for this provider.
*/
public BasicItemDetailProvider( String namespace, @Nonnull Class<T> itemType )
{
Objects.requireNonNull( itemType );
public BasicItemDetailProvider(String namespace, @Nonnull Class<T> itemType) {
Objects.requireNonNull(itemType);
this.itemType = itemType;
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.
*/
public BasicItemDetailProvider( @Nonnull Class<T> itemType )
{
this( null, itemType );
public BasicItemDetailProvider(@Nonnull Class<T> 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 item The item to provide details for.
*/
public abstract void provideDetails( @Nonnull Map<? super String, Object> data, @Nonnull ItemStack stack,
@Nonnull T item );
public abstract void provideDetails(@Nonnull Map<? super String, Object> data, @Nonnull ItemStack stack,
@Nonnull T item);
@Override
public void provideDetails( @Nonnull Map<? super String, Object> data, @Nonnull ItemStack stack )
{
Item item = stack.getItem();
if( !itemType.isInstance( item ) ) return;
public void provideDetails(@Nonnull Map<? super String, Object> data, @Nonnull ItemStack stack) {
var item = stack.getItem();
if (!itemType.isInstance(item)) return;
// 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<>();
provideDetails( child, stack, itemType.cast( item ) );
provideDetails(child, stack, itemType.cast(item));
if( namespace != null )
{
data.put( namespace, child );
if (namespace != null) {
data.put(namespace, child);
}
}
}

View File

@ -26,10 +26,8 @@ public record BlockReference(
@Nonnull BlockPos pos,
@Nonnull BlockState state,
@Nullable BlockEntity blockEntity
)
{
public BlockReference( Level level, BlockPos pos )
{
this( level, pos, level.getBlockState( pos ), level.getBlockEntity( pos ) );
) {
public BlockReference(Level level, BlockPos 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.
*/
@ApiStatus.NonExtendable
public interface DetailRegistry<T>
{
public interface DetailRegistry<T> {
/**
* Registers a detail provider.
*
* @param provider The detail provider to register.
* @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
@ -37,7 +36,7 @@ public interface DetailRegistry<T>
* @param object The object to get details for.
* @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.
@ -45,5 +44,5 @@ public interface DetailRegistry<T>
* @param object The object to get details for.
* @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.
*/
public class ForgeDetailRegistries
{
public class ForgeDetailRegistries {
/**
* Provides details for {@link FluidStack}.
*/

View File

@ -18,8 +18,7 @@ import java.util.Map;
* @see DetailRegistry
*/
@FunctionalInterface
public interface IDetailProvider<T>
{
public interface IDetailProvider<T> {
/**
* 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
@ -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 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.
*/
public class VanillaDetailRegistries
{
public class VanillaDetailRegistries {
/**
* 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 size The size of the file.
*/
record FileAttributes(boolean isDirectory, long size) implements BasicFileAttributes
{
private static final FileTime EPOCH = FileTime.from( Instant.EPOCH );
record FileAttributes(boolean isDirectory, long size) implements BasicFileAttributes {
private static final FileTime EPOCH = FileTime.from(Instant.EPOCH);
@Override
public FileTime lastModifiedTime()
{
public FileTime lastModifiedTime() {
return EPOCH;
}
@Override
public FileTime lastAccessTime()
{
public FileTime lastAccessTime() {
return EPOCH;
}
@Override
public FileTime creationTime()
{
public FileTime creationTime() {
return EPOCH;
}
@Override
public boolean isRegularFile()
{
public boolean isRegularFile() {
return !isDirectory;
}
@Override
public boolean isSymbolicLink()
{
public boolean isSymbolicLink() {
return false;
}
@Override
public boolean isOther()
{
public boolean isOther() {
return false;
}
@Override
public Object fileKey()
{
public Object fileKey() {
return null;
}
}

View File

@ -15,27 +15,23 @@ import java.util.Objects;
* <p>
* 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 final String filename;
public FileOperationException( @Nullable String filename, @Nonnull String message )
{
super( Objects.requireNonNull( message, "message cannot be null" ) );
public FileOperationException(@Nullable String filename, @Nonnull String message) {
super(Objects.requireNonNull(message, "message cannot be null"));
this.filename = filename;
}
public FileOperationException( @Nonnull String message )
{
super( Objects.requireNonNull( message, "message cannot be null" ) );
public FileOperationException(@Nonnull String message) {
super(Objects.requireNonNull(message, "message cannot be null"));
filename = null;
}
@Nullable
public String getFilename()
{
public String getFilename() {
return filename;
}
}

View File

@ -12,8 +12,7 @@ import java.io.IOException;
* <p>
* 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.
*
@ -21,7 +20,7 @@ public interface IFileSystem extends IWritableMount
* @param child The path to append.
* @return The combined, normalised path.
*/
String combine( String path, String child );
String combine(String path, String child);
/**
* 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.
* @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.
@ -39,5 +38,5 @@ public interface IFileSystem extends IWritableMount
* @param to The location to move to. This should not exist.
* @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 IWritableMount
*/
public interface IMount
{
public interface IMount {
/**
* Returns whether a file with a given path exists or not.
*
@ -37,7 +36,7 @@ public interface IMount
* @return If the file exists.
* @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.
@ -46,7 +45,7 @@ public interface IMount
* @return If the file exists and 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.
@ -55,7 +54,7 @@ public interface IMount
* @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.
*/
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.
@ -64,7 +63,7 @@ public interface IMount
* @return The size of the file, in bytes.
* @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.
@ -76,7 +75,7 @@ public interface IMount
* @throws IOException If the file does not exist, or could not be opened.
*/
@Nonnull
ReadableByteChannel openForRead( @Nonnull String path ) throws IOException;
ReadableByteChannel openForRead(@Nonnull String path) throws IOException;
/**
* 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.
*/
@Nonnull
default BasicFileAttributes getAttributes( @Nonnull String path ) throws IOException
{
if( !exists( path ) ) throw new FileOperationException( path, "No such file" );
return new FileAttributes( isDirectory( path ), getSize( path ) );
default BasicFileAttributes getAttributes(@Nonnull String path) throws IOException {
if (!exists(path)) throw new FileOperationException(path, "No such file");
return new FileAttributes(isDirectory(path), getSize(path));
}
}

View File

@ -27,15 +27,14 @@ import java.util.OptionalLong;
* @see IComputerAccess#mountWritable(String, IWritableMount)
* @see IMount
*/
public interface IWritableMount extends IMount
{
public interface IWritableMount extends IMount {
/**
* 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".
* @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.
@ -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".
* @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.
@ -54,7 +53,7 @@ public interface IWritableMount extends IMount
* @throws IOException If the file could not be opened for writing.
*/
@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.
@ -65,7 +64,7 @@ public interface IWritableMount extends IMount
* @throws IOException If the file could not be opened for writing.
*/
@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
@ -83,8 +82,7 @@ public interface IWritableMount extends IMount
* @return The capacity of this mount, in bytes.
*/
@Nonnull
default OptionalLong getCapacity()
{
default OptionalLong getCapacity() {
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
* 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.
* <p>

View File

@ -16,8 +16,7 @@ import static dan200.computercraft.api.lua.LuaValues.checkFinite;
/**
* The arguments passed to a function.
*/
public interface IArguments
{
public interface IArguments {
/**
* 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.
*/
@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},
@ -49,12 +48,11 @@ public interface IArguments
* @param count The number of arguments to drop.
* @return The new {@link IArguments} instance.
*/
IArguments drop( int count );
IArguments drop(int count);
default Object[] getAll()
{
Object[] result = new Object[count()];
for( int i = 0; i < result.length; i++ ) result[i] = get( i );
default Object[] getAll() {
var result = new Object[count()];
for (var i = 0; i < result.length; i++) result[i] = get(i);
return result;
}
@ -66,10 +64,9 @@ public interface IArguments
* @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).
*/
default double getDouble( int index ) throws LuaException
{
Object value = get( index );
if( !(value instanceof Number number) ) throw LuaValues.badArgumentOf( index, "number", value );
default double getDouble(int index) throws LuaException {
var value = get(index);
if (!(value instanceof Number number)) throw LuaValues.badArgumentOf(index, "number", value);
return number.doubleValue();
}
@ -80,9 +77,8 @@ public interface IArguments
* @return The argument's value.
* @throws LuaException If the value is not an integer.
*/
default int getInt( int index ) throws LuaException
{
return (int) getLong( index );
default int getInt(int index) throws LuaException {
return (int) getLong(index);
}
/**
@ -92,11 +88,10 @@ public interface IArguments
* @return The argument's value.
* @throws LuaException If the value is not a long.
*/
default long getLong( int index ) throws LuaException
{
Object value = get( index );
if( !(value instanceof Number number) ) throw LuaValues.badArgumentOf( index, "number", value );
return LuaValues.checkFiniteNum( index, number ).longValue();
default long getLong(int index) throws LuaException {
var value = get(index);
if (!(value instanceof Number number)) throw LuaValues.badArgumentOf(index, "number", value);
return LuaValues.checkFiniteNum(index, number).longValue();
}
/**
@ -106,9 +101,8 @@ public interface IArguments
* @return The argument's value.
* @throws LuaException If the value is not finite.
*/
default double getFiniteDouble( int index ) throws LuaException
{
return checkFinite( index, getDouble( index ) );
default double getFiniteDouble(int index) throws LuaException {
return checkFinite(index, getDouble(index));
}
/**
@ -118,10 +112,9 @@ public interface IArguments
* @return The argument's value.
* @throws LuaException If the value is not a boolean.
*/
default boolean getBoolean( int index ) throws LuaException
{
Object value = get( index );
if( !(value instanceof Boolean bool) ) throw LuaValues.badArgumentOf( index, "boolean", value );
default boolean getBoolean(int index) throws LuaException {
var value = get(index);
if (!(value instanceof Boolean bool)) throw LuaValues.badArgumentOf(index, "boolean", value);
return bool;
}
@ -133,10 +126,9 @@ public interface IArguments
* @throws LuaException If the value is not a string.
*/
@Nonnull
default String getString( int index ) throws LuaException
{
Object value = get( index );
if( !(value instanceof String string) ) throw LuaValues.badArgumentOf( index, "string", value );
default String getString(int index) throws LuaException {
var value = get(index);
if (!(value instanceof String string)) throw LuaValues.badArgumentOf(index, "string", value);
return string;
}
@ -148,9 +140,8 @@ public interface IArguments
* @throws LuaException If the value is not a string.
*/
@Nonnull
default ByteBuffer getBytes( int index ) throws LuaException
{
return LuaValues.encode( getString( index ) );
default ByteBuffer getBytes(int index) throws LuaException {
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.
*/
@Nonnull
default <T extends Enum<T>> T getEnum( int index, Class<T> klass ) throws LuaException
{
return LuaValues.checkEnum( index, klass, getString( index ) );
default <T extends Enum<T>> T getEnum(int index, Class<T> klass) throws LuaException {
return LuaValues.checkEnum(index, klass, getString(index));
}
/**
@ -176,10 +166,9 @@ public interface IArguments
* @throws LuaException If the value is not a table.
*/
@Nonnull
default Map<?, ?> getTable( int index ) throws LuaException
{
Object value = get( index );
if( !(value instanceof Map) ) throw LuaValues.badArgumentOf( index, "table", value );
default Map<?, ?> getTable(int index) throws LuaException {
var value = get(index);
if (!(value instanceof Map)) throw LuaValues.badArgumentOf(index, "table", value);
return (Map<?, ?>) value;
}
@ -196,9 +185,8 @@ public interface IArguments
* @throws LuaException If the value is not a table.
*/
@Nonnull
default LuaTable<?, ?> getTableUnsafe( int index ) throws LuaException
{
return new ObjectLuaTable( getTable( index ) );
default LuaTable<?, ?> getTableUnsafe(int index) throws LuaException {
return new ObjectLuaTable(getTable(index));
}
/**
@ -209,12 +197,11 @@ public interface IArguments
* @throws LuaException If the value is not a number.
*/
@Nonnull
default Optional<Double> optDouble( int index ) throws LuaException
{
Object value = get( index );
if( value == null ) return Optional.empty();
if( !(value instanceof Number number) ) throw LuaValues.badArgumentOf( index, "number", value );
return Optional.of( number.doubleValue() );
default Optional<Double> optDouble(int index) throws LuaException {
var value = get(index);
if (value == null) return Optional.empty();
if (!(value instanceof Number number)) throw LuaValues.badArgumentOf(index, "number", value);
return Optional.of(number.doubleValue());
}
/**
@ -225,9 +212,8 @@ public interface IArguments
* @throws LuaException If the value is not a number.
*/
@Nonnull
default Optional<Integer> optInt( int index ) throws LuaException
{
return optLong( index ).map( Long::intValue );
default Optional<Integer> optInt(int index) throws LuaException {
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.
* @throws LuaException If the value is not a number.
*/
default Optional<Long> optLong( int index ) throws LuaException
{
Object value = get( index );
if( value == null ) return Optional.empty();
if( !(value instanceof Number number) ) throw LuaValues.badArgumentOf( index, "number", value );
return Optional.of( LuaValues.checkFiniteNum( index, number ).longValue() );
default Optional<Long> optLong(int index) throws LuaException {
var value = get(index);
if (value == null) return Optional.empty();
if (!(value instanceof Number number)) throw LuaValues.badArgumentOf(index, "number", value);
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.
* @throws LuaException If the value is not finite.
*/
default Optional<Double> optFiniteDouble( int index ) throws LuaException
{
Optional<Double> value = optDouble( index );
if( value.isPresent() ) LuaValues.checkFiniteNum( index, value.get() );
default Optional<Double> optFiniteDouble(int index) throws LuaException {
var value = optDouble(index);
if (value.isPresent()) LuaValues.checkFiniteNum(index, value.get());
return value;
}
@ -266,12 +250,11 @@ public interface IArguments
* @return The argument's value, or {@link Optional#empty()} if not present.
* @throws LuaException If the value is not a boolean.
*/
default Optional<Boolean> optBoolean( int index ) throws LuaException
{
Object value = get( index );
if( value == null ) return Optional.empty();
if( !(value instanceof Boolean bool) ) throw LuaValues.badArgumentOf( index, "boolean", value );
return Optional.of( bool );
default Optional<Boolean> optBoolean(int index) throws LuaException {
var value = get(index);
if (value == null) return Optional.empty();
if (!(value instanceof Boolean bool)) throw LuaValues.badArgumentOf(index, "boolean", value);
return Optional.of(bool);
}
/**
@ -281,12 +264,11 @@ public interface IArguments
* @return The argument's value, or {@link Optional#empty()} if not present.
* @throws LuaException If the value is not a string.
*/
default Optional<String> optString( int index ) throws LuaException
{
Object value = get( index );
if( value == null ) return Optional.empty();
if( !(value instanceof String string) ) throw LuaValues.badArgumentOf( index, "string", value );
return Optional.of( string );
default Optional<String> optString(int index) throws LuaException {
var value = get(index);
if (value == null) return Optional.empty();
if (!(value instanceof String string)) throw LuaValues.badArgumentOf(index, "string", value);
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.
* @throws LuaException If the value is not a string.
*/
default Optional<ByteBuffer> optBytes( int index ) throws LuaException
{
return optString( index ).map( LuaValues::encode );
default Optional<ByteBuffer> optBytes(int index) throws LuaException {
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.
*/
@Nonnull
default <T extends Enum<T>> Optional<T> optEnum( int index, Class<T> klass ) throws LuaException
{
Optional<String> str = optString( index );
return str.isPresent() ? Optional.of( LuaValues.checkEnum( index, klass, str.get() ) ) : Optional.empty();
default <T extends Enum<T>> Optional<T> optEnum(int index, Class<T> klass) throws LuaException {
var str = optString(index);
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.
* @throws LuaException If the value is not a table.
*/
default Optional<Map<?, ?>> optTable( int index ) throws LuaException
{
Object value = get( index );
if( value == null ) return Optional.empty();
if( !(value instanceof Map) ) throw LuaValues.badArgumentOf( index, "map", value );
return Optional.of( (Map<?, ?>) value );
default Optional<Map<?, ?>> optTable(int index) throws LuaException {
var value = get(index);
if (value == null) return Optional.empty();
if (!(value instanceof Map)) throw LuaValues.badArgumentOf(index, "map", value);
return Optional.of((Map<?, ?>) value);
}
/**
@ -345,12 +324,11 @@ public interface IArguments
* @throws LuaException If the value is not a table.
*/
@Nonnull
default Optional<LuaTable<?, ?>> optTableUnsafe( int index ) throws LuaException
{
Object value = get( index );
if( value == null ) return Optional.empty();
if( !(value instanceof Map) ) throw LuaValues.badArgumentOf( index, "map", value );
return Optional.of( new ObjectLuaTable( (Map<?, ?>) value ) );
default Optional<LuaTable<?, ?>> optTableUnsafe(int index) throws LuaException {
var value = get(index);
if (value == null) return Optional.empty();
if (!(value instanceof Map)) throw LuaValues.badArgumentOf(index, "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.
* @throws LuaException If the value is not a number.
*/
default double optDouble( int index, double def ) throws LuaException
{
return optDouble( index ).orElse( def );
default double optDouble(int index, double def) throws LuaException {
return optDouble(index).orElse(def);
}
/**
@ -374,9 +351,8 @@ public interface IArguments
* @return The argument's value, or {@code def} if none was provided.
* @throws LuaException If the value is not a number.
*/
default int optInt( int index, int def ) throws LuaException
{
return optInt( index ).orElse( def );
default int optInt(int index, int def) throws LuaException {
return optInt(index).orElse(def);
}
/**
@ -387,9 +363,8 @@ public interface IArguments
* @return The argument's value, or {@code def} if none was provided.
* @throws LuaException If the value is not a number.
*/
default long optLong( int index, long def ) throws LuaException
{
return optLong( index ).orElse( def );
default long optLong(int index, long def) throws LuaException {
return optLong(index).orElse(def);
}
/**
@ -400,9 +375,8 @@ public interface IArguments
* @return The argument's value, or {@code def} if none was provided.
* @throws LuaException If the value is not finite.
*/
default double optFiniteDouble( int index, double def ) throws LuaException
{
return optFiniteDouble( index ).orElse( def );
default double optFiniteDouble(int index, double def) throws LuaException {
return optFiniteDouble(index).orElse(def);
}
/**
@ -413,9 +387,8 @@ public interface IArguments
* @return The argument's value, or {@code def} if none was provided.
* @throws LuaException If the value is not a boolean.
*/
default boolean optBoolean( int index, boolean def ) throws LuaException
{
return optBoolean( index ).orElse( def );
default boolean optBoolean(int index, boolean def) throws LuaException {
return optBoolean(index).orElse(def);
}
/**
@ -426,9 +399,8 @@ public interface IArguments
* @return The argument's value, or {@code def} if none was provided.
* @throws LuaException If the value is not a string.
*/
default String optString( int index, String def ) throws LuaException
{
return optString( index ).orElse( def );
default String optString(int index, String def) throws LuaException {
return optString(index).orElse(def);
}
/**
@ -439,8 +411,7 @@ public interface IArguments
* @return The argument's value, or {@code def} if none was provided.
* @throws LuaException If the value is not a table.
*/
default Map<?, ?> optTable( int index, Map<Object, Object> def ) throws LuaException
{
return optTable( index ).orElse( def );
default Map<?, ?> optTable(int index, Map<Object, Object> def) throws LuaException {
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
* about a computer.
*/
public interface IComputerSystem extends IComputerAccess
{
public interface IComputerSystem extends IComputerAccess {
/**
* 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
* 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
* lifetime.
@ -41,5 +40,5 @@ public interface IDynamicLuaObject
* @throws LuaException If the function threw an exception.
*/
@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 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
*
@ -31,15 +30,13 @@ public interface ILuaAPI
* <p>
* 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.
*/
default void update()
{
default void update() {
}
/**
@ -47,7 +44,6 @@ public interface ILuaAPI
* <p>
* 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)
*/
@FunctionalInterface
public interface ILuaAPIFactory
{
public interface ILuaAPIFactory {
/**
* 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.
*/
@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)
*/
public interface ILuaCallback
{
public interface ILuaCallback {
/**
* Resume this coroutine.
*
@ -23,5 +22,5 @@ public interface ILuaCallback
* @throws LuaException On an error.
*/
@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
* 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
* 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.
* @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.
@ -40,8 +39,7 @@ public interface ILuaContext
* @throws LuaException If the task could not be queued, or if the task threw an exception.
*/
@Nonnull
default MethodResult executeMainThreadTask( @Nonnull ILuaTask task ) throws LuaException
{
return TaskCallback.make( this, task );
default MethodResult executeMainThreadTask(@Nonnull ILuaTask task) throws LuaException {
return TaskCallback.make(this, task);
}
}

View File

@ -14,8 +14,7 @@ import javax.annotation.Nonnull;
* @see MethodResult#of(Object)
*/
@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,
* and so its implementation must be thread-safe.
@ -25,5 +24,5 @@ public interface ILuaFunction
* @throws LuaException Upon Lua errors.
*/
@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)
*/
@FunctionalInterface
public interface ILuaTask
{
public interface ILuaTask {
/**
* 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.
*/
public class LuaException extends Exception
{
public class LuaException extends Exception {
private static final long serialVersionUID = -6136063076818512651L;
private final boolean hasLevel;
private final int level;
public LuaException( @Nullable String message )
{
super( message );
public LuaException(@Nullable String message) {
super(message);
hasLevel = false;
level = 1;
}
public LuaException( @Nullable String message, int level )
{
super( message );
public LuaException(@Nullable String message, int level) {
super(message);
hasLevel = true;
this.level = level;
}
@ -35,8 +32,7 @@ public class LuaException extends Exception
*
* @return Whether this has an explicit level.
*/
public boolean hasLevel()
{
public boolean hasLevel() {
return hasLevel;
}
@ -46,8 +42,7 @@ public class LuaException extends Exception
*
* @return The level to raise the error at.
*/
public int getLevel()
{
public int getLevel() {
return level;
}
}

View File

@ -36,10 +36,9 @@ import java.util.Optional;
* {@link MethodResult#of(Object...)}.
*/
@Documented
@Retention( RetentionPolicy.RUNTIME )
@Target( ElementType.METHOD )
public @interface LuaFunction
{
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface LuaFunction {
/**
* 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.*;
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.
*
* @return This table's length.
*/
default int length()
{
int size = 0;
while( containsKey( (double) (size + 1) ) ) size++;
default int length() {
var size = 0;
while (containsKey((double) (size + 1))) size++;
return size;
}
@ -32,13 +30,12 @@ public interface LuaTable<K, V> extends Map<K, V>
* @return The table's value.
* @throws LuaException If the value is not an integer.
*/
default long getLong( int index ) throws LuaException
{
Object value = get( (double) index );
if( !(value instanceof Number number) ) throw badTableItem( index, "number", getType( value ) );
default long getLong(int index) throws LuaException {
Object value = get((double) index);
if (!(value instanceof Number number)) throw badTableItem(index, "number", getType(value));
double asDouble = number.doubleValue();
if( !Double.isFinite( asDouble ) ) throw badTableItem( index, "number", getNumericType( asDouble ) );
var asDouble = number.doubleValue();
if (!Double.isFinite(asDouble)) throw badTableItem(index, "number", getNumericType(asDouble));
return number.longValue();
}
@ -49,13 +46,12 @@ public interface LuaTable<K, V> extends Map<K, V>
* @return The table's value.
* @throws LuaException If the value is not an integer.
*/
default long getLong( String key ) throws LuaException
{
Object value = get( key );
if( !(value instanceof Number number) ) throw badField( key, "number", getType( value ) );
default long getLong(String key) throws LuaException {
Object value = get(key);
if (!(value instanceof Number number)) throw badField(key, "number", getType(value));
double asDouble = number.doubleValue();
if( !Double.isFinite( asDouble ) ) throw badField( key, "number", getNumericType( asDouble ) );
var asDouble = number.doubleValue();
if (!Double.isFinite(asDouble)) throw badField(key, "number", getNumericType(asDouble));
return number.longValue();
}
@ -66,9 +62,8 @@ public interface LuaTable<K, V> extends Map<K, V>
* @return The table's value.
* @throws LuaException If the value is not an integer.
*/
default int getInt( int index ) throws LuaException
{
return (int) getLong( index );
default int getInt(int index) throws LuaException {
return (int) getLong(index);
}
/**
@ -78,34 +73,29 @@ public interface LuaTable<K, V> extends Map<K, V>
* @return The table's value.
* @throws LuaException If the value is not an integer.
*/
default int getInt( String key ) throws LuaException
{
return (int) getLong( key );
default int getInt(String key) throws LuaException {
return (int) getLong(key);
}
@Nullable
@Override
default V put( K o, V o2 )
{
throw new UnsupportedOperationException( "Cannot modify LuaTable" );
default V put(K o, V o2) {
throw new UnsupportedOperationException("Cannot modify LuaTable");
}
@Override
default V remove( Object o )
{
throw new UnsupportedOperationException( "Cannot modify LuaTable" );
default V remove(Object o) {
throw new UnsupportedOperationException("Cannot modify LuaTable");
}
@Override
default void putAll( @Nonnull Map<? extends K, ? extends V> map )
{
throw new UnsupportedOperationException( "Cannot modify LuaTable" );
default void putAll(@Nonnull Map<? extends K, ? extends V> map) {
throw new UnsupportedOperationException("Cannot modify LuaTable");
}
@Override
default void clear()
{
throw new UnsupportedOperationException( "Cannot modify LuaTable" );
default void clear() {
throw new UnsupportedOperationException("Cannot modify LuaTable");
}
}

View File

@ -15,10 +15,8 @@ import java.util.Map;
*
* @see IArguments
*/
public final class LuaValues
{
private LuaValues()
{
public final class LuaValues {
private LuaValues() {
}
/**
@ -28,16 +26,14 @@ public final class LuaValues
* @return The encoded string.
*/
@Nonnull
public static ByteBuffer encode( @Nonnull String string )
{
byte[] chars = new byte[string.length()];
for( int i = 0; i < chars.length; i++ )
{
char c = string.charAt( i );
public static ByteBuffer encode(@Nonnull String string) {
var chars = new byte[string.length()];
for (var i = 0; i < chars.length; i++) {
var c = string.charAt(i);
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.
*/
@Nonnull
public static String getNumericType( double value )
{
if( Double.isNaN( value ) ) return "nan";
if( value == Double.POSITIVE_INFINITY ) return "inf";
if( value == Double.NEGATIVE_INFINITY ) return "-inf";
public static String getNumericType(double value) {
if (Double.isNaN(value)) return "nan";
if (value == Double.POSITIVE_INFINITY) return "inf";
if (value == Double.NEGATIVE_INFINITY) return "-inf";
return "number";
}
@ -64,13 +59,12 @@ public final class LuaValues
* {@code type} function.
*/
@Nonnull
public static String getType( @Nullable Object value )
{
if( value == null ) return "nil";
if( value instanceof String ) return "string";
if( value instanceof Boolean ) return "boolean";
if( value instanceof Number ) return "number";
if( value instanceof Map ) return "table";
public static String getType(@Nullable Object value) {
if (value == null) return "nil";
if (value instanceof String) return "string";
if (value instanceof Boolean) return "boolean";
if (value instanceof Number) return "number";
if (value instanceof Map) return "table";
return "userdata";
}
@ -83,9 +77,8 @@ public final class LuaValues
* @return The constructed exception, which should be thrown immediately.
*/
@Nonnull
public static LuaException badArgumentOf( int index, @Nonnull String expected, @Nullable Object actual )
{
return badArgument( index, expected, getType( actual ) );
public static LuaException badArgumentOf(int index, @Nonnull String expected, @Nullable Object actual) {
return badArgument(index, expected, getType(actual));
}
/**
@ -97,9 +90,8 @@ public final class LuaValues
* @return The constructed exception, which should be thrown immediately.
*/
@Nonnull
public static LuaException badArgument( int index, @Nonnull String expected, @Nonnull String actual )
{
return new LuaException( "bad argument #" + (index + 1) + " (" + expected + " expected, got " + actual + ")" );
public static LuaException badArgument(int index, @Nonnull String expected, @Nonnull String 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.
*/
@Nonnull
public static LuaException badTableItem( int index, @Nonnull String expected, @Nonnull String actual )
{
return new LuaException( "table item #" + index + " is not " + expected + " (got " + actual + ")" );
public static LuaException badTableItem(int index, @Nonnull String expected, @Nonnull String 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.
*/
@Nonnull
public static LuaException badField( String key, @Nonnull String expected, @Nonnull String actual )
{
return new LuaException( "field " + key + " is not " + expected + " (got " + actual + ")" );
public static LuaException badField(String key, @Nonnull String expected, @Nonnull String actual) {
return new LuaException("field " + key + " is not " + expected + " (got " + actual + ")");
}
/**
@ -138,9 +128,8 @@ public final class LuaValues
* @return The input {@code value}.
* @throws LuaException If this is not a finite number.
*/
public static Number checkFiniteNum( int index, Number value ) throws LuaException
{
checkFinite( index, value.doubleValue() );
public static Number checkFiniteNum(int index, Number value) throws LuaException {
checkFinite(index, value.doubleValue());
return value;
}
@ -152,9 +141,8 @@ public final class LuaValues
* @return The input {@code value}.
* @throws LuaException If this is not a finite number.
*/
public static double checkFinite( int index, double value ) throws LuaException
{
if( !Double.isFinite( value ) ) throw badArgument( index, "number", getNumericType( value ) );
public static double checkFinite(int index, double value) throws LuaException {
if (!Double.isFinite(value)) throw badArgument(index, "number", getNumericType(value));
return value;
}
@ -168,13 +156,11 @@ public final class LuaValues
* @return The parsed 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
{
for( T possibility : klass.getEnumConstants() )
{
if( possibility.name().equalsIgnoreCase( value ) ) return possibility;
public static <T extends Enum<T>> T checkEnum(int index, Class<T> klass, String value) throws LuaException {
for (var possibility : klass.getEnumConstants()) {
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.
* When the current coroutine is resumed, we invoke the provided {@link ILuaCallback#resume(Object[])} callback.
*/
public final class MethodResult
{
private static final MethodResult empty = new MethodResult( null, null );
public final class MethodResult {
private static final MethodResult empty = new MethodResult(null, null);
private final Object[] result;
private final ILuaCallback callback;
private final int adjust;
private MethodResult( Object[] arguments, ILuaCallback callback )
{
private MethodResult(Object[] arguments, ILuaCallback callback) {
result = arguments;
this.callback = callback;
adjust = 0;
}
private MethodResult( Object[] arguments, ILuaCallback callback, int adjust )
{
private MethodResult(Object[] arguments, ILuaCallback callback, int adjust) {
result = arguments;
this.callback = callback;
this.adjust = adjust;
@ -48,8 +45,7 @@ public final class MethodResult
* @return A method result which returns immediately with no values.
*/
@Nonnull
public static MethodResult of()
{
public static MethodResult of() {
return empty;
}
@ -67,9 +63,8 @@ public final class MethodResult
* @return A method result which returns immediately with the given value.
*/
@Nonnull
public static MethodResult of( @Nullable Object value )
{
return new MethodResult( new Object[] { value }, null );
public static MethodResult of(@Nullable Object value) {
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.
*/
@Nonnull
public static MethodResult of( @Nullable Object... values )
{
return values == null || values.length == 0 ? empty : new MethodResult( values, null );
public static MethodResult of(@Nullable Object... values) {
return values == null || values.length == 0 ? empty : new MethodResult(values, null);
}
/**
@ -94,16 +88,14 @@ public final class MethodResult
* @see IComputerAccess#queueEvent(String, Object[])
*/
@Nonnull
public static MethodResult pullEvent( @Nullable String filter, @Nonnull ILuaCallback callback )
{
Objects.requireNonNull( callback, "callback cannot be null" );
return new MethodResult( new Object[] { filter }, results -> {
if( results.length >= 1 && Objects.equals( results[0], "terminate" ) )
{
throw new LuaException( "Terminated", 0 );
public static MethodResult pullEvent(@Nullable String filter, @Nonnull ILuaCallback callback) {
Objects.requireNonNull(callback, "callback cannot be null");
return new MethodResult(new Object[]{ filter }, results -> {
if (results.length >= 1 && Objects.equals(results[0], "terminate")) {
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)
*/
@Nonnull
public static MethodResult pullEventRaw( @Nullable String filter, @Nonnull ILuaCallback callback )
{
Objects.requireNonNull( callback, "callback cannot be null" );
return new MethodResult( new Object[] { filter }, callback );
public static MethodResult pullEventRaw(@Nullable String filter, @Nonnull ILuaCallback callback) {
Objects.requireNonNull(callback, "callback cannot be null");
return new MethodResult(new Object[]{ filter }, callback);
}
/**
@ -133,26 +124,22 @@ public final class MethodResult
* @see #pullEvent(String, ILuaCallback)
*/
@Nonnull
public static MethodResult yield( @Nullable Object[] arguments, @Nonnull ILuaCallback callback )
{
Objects.requireNonNull( callback, "callback cannot be null" );
return new MethodResult( arguments, callback );
public static MethodResult yield(@Nullable Object[] arguments, @Nonnull ILuaCallback callback) {
Objects.requireNonNull(callback, "callback cannot be null");
return new MethodResult(arguments, callback);
}
@Nullable
public Object[] getResult()
{
public Object[] getResult() {
return result;
}
@Nullable
public ILuaCallback getCallback()
{
public ILuaCallback getCallback() {
return callback;
}
public int getErrorAdjust()
{
public int getErrorAdjust() {
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.
*/
@Nonnull
public MethodResult adjustError( int adjust )
{
if( adjust < 0 ) throw new IllegalArgumentException( "cannot adjust by a negative amount" );
if( adjust == 0 || callback == null ) return this;
return new MethodResult( result, callback, this.adjust + adjust );
public MethodResult adjustError(int adjust) {
if (adjust < 0) throw new IllegalArgumentException("cannot adjust by a negative amount");
if (adjust == 0 || callback == null) return this;
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}.
*/
public final class ObjectArguments implements IArguments
{
public final class ObjectArguments implements IArguments {
private static final IArguments EMPTY = new ObjectArguments();
private final List<Object> args;
@Deprecated
@SuppressWarnings( "unused" )
public ObjectArguments( IArguments arguments )
{
@SuppressWarnings("unused")
public ObjectArguments(IArguments arguments) {
throw new IllegalStateException();
}
public ObjectArguments( Object... args )
{
this.args = Arrays.asList( args );
public ObjectArguments(Object... args) {
this.args = Arrays.asList(args);
}
public ObjectArguments( List<Object> args )
{
this.args = Objects.requireNonNull( args );
public ObjectArguments(List<Object> args) {
this.args = Objects.requireNonNull(args);
}
@Override
public int count()
{
public int count() {
return args.size();
}
@Override
public IArguments drop( int count )
{
if( count < 0 ) throw new IllegalStateException( "count cannot be negative" );
if( count == 0 ) return this;
if( count >= args.size() ) return EMPTY;
public IArguments drop(int count) {
if (count < 0) throw new IllegalStateException("count cannot be negative");
if (count == 0) return this;
if (count >= args.size()) return EMPTY;
return new ObjectArguments( args.subList( count, args.size() ) );
return new ObjectArguments(args.subList(count, args.size()));
}
@Nullable
@Override
public Object get( int index )
{
return index >= args.size() ? null : args.get( index );
public Object get(int index) {
return index >= args.size() ? null : args.get(index);
}
@Override
public Object[] getAll()
{
public Object[] getAll() {
return args.toArray();
}
}

View File

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

View File

@ -8,46 +8,36 @@ package dan200.computercraft.api.lua;
import javax.annotation.Nonnull;
import java.util.Arrays;
final class TaskCallback implements ILuaCallback
{
private final MethodResult pull = MethodResult.pullEvent( "task_complete", this );
final class TaskCallback implements ILuaCallback {
private final MethodResult pull = MethodResult.pullEvent("task_complete", this);
private final long task;
private TaskCallback( long task )
{
private TaskCallback(long task) {
this.task = task;
}
@Nonnull
@Override
public MethodResult resume( Object[] response ) throws LuaException
{
if( response.length < 3 || !(response[1] instanceof Number) || !(response[2] instanceof Boolean) )
{
public MethodResult resume(Object[] response) throws LuaException {
if (response.length < 3 || !(response[1] instanceof Number) || !(response[2] instanceof Boolean)) {
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
return MethodResult.of( Arrays.copyOfRange( response, 3, response.length ) );
}
else if( response.length >= 4 && response[3] instanceof String )
{
return MethodResult.of(Arrays.copyOfRange(response, 3, response.length));
} else if (response.length >= 4 && response[3] instanceof String) {
// Extract the error message from the event and raise it
throw new LuaException( (String) response[3] );
}
else
{
throw new LuaException( "error" );
throw new LuaException((String) response[3]);
} else {
throw new LuaException("error");
}
}
static MethodResult make( ILuaContext context, ILuaTask func ) throws LuaException
{
long task = context.issueMainThreadTask( func );
return new TaskCallback( task ).pull;
static MethodResult make(ILuaContext context, ILuaTask func) throws LuaException {
var task = context.issueMainThreadTask(func);
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
* 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.
*
@ -29,7 +28,7 @@ public interface IMedia
* @return The label. ie: "Dan's Programs".
*/
@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.
@ -38,8 +37,7 @@ public interface IMedia
* @param label The string to set the label to.
* @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;
}
@ -51,8 +49,7 @@ public interface IMedia
* @return The name, or null if this item does not represent an item with audio.
*/
@Nullable
default String getAudioTitle( @Nonnull ItemStack stack )
{
default String getAudioTitle(@Nonnull ItemStack stack) {
return null;
}
@ -63,8 +60,7 @@ public interface IMedia
* @return The name, or null if this item does not represent an item with audio.
*/
@Nullable
default SoundEvent getAudio( @Nonnull ItemStack stack )
{
default SoundEvent getAudio(@Nonnull ItemStack stack) {
return null;
}
@ -82,8 +78,7 @@ public interface IMedia
* @see dan200.computercraft.api.ComputerCraftAPI#createResourceMount(String, String)
*/
@Nullable
default IMount createDataMount( @Nonnull ItemStack stack, @Nonnull Level world )
{
default IMount createDataMount(@Nonnull ItemStack stack, @Nonnull Level world) {
return null;
}
}

View File

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

View File

@ -13,21 +13,20 @@ import javax.annotation.Nonnull;
* @see Packet
* @see IPacketReceiver
*/
public interface IPacketNetwork
{
public interface IPacketNetwork {
/**
* Add a receiver 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.
*
* @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.
@ -45,7 +44,7 @@ public interface IPacketNetwork
* @see #transmitInterdimensional(Packet)
* @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
@ -55,5 +54,5 @@ public interface IPacketNetwork
* @see #transmitSameDimension(Packet, double)
* @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.
*/
public interface IPacketReceiver
{
public interface IPacketReceiver {
/**
* Get the world in which this packet receiver exists.
*
@ -68,7 +67,7 @@ public interface IPacketReceiver
* @see IPacketNetwork#transmitSameDimension(Packet, double)
* @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.
@ -80,5 +79,5 @@ public interface IPacketReceiver
* @see IPacketNetwork#transmitSameDimension(Packet, double)
* @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.
*/
public interface IPacketSender
{
public interface IPacketSender {
/**
* Get the world in which this packet sender exists.
*

View File

@ -25,6 +25,5 @@ public record Packet(
int replyChannel,
Object payload,
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
* {@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
* peripherals change.
@ -28,7 +27,6 @@ public interface IWiredElement extends IWiredSender
* @param change The change which occurred.
* @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()
*/
public interface IWiredNetwork
{
public interface IWiredNetwork {
/**
* Create a connection between two nodes.
* <p>
@ -39,7 +38,7 @@ public interface IWiredNetwork
* @see IWiredNode#connectTo(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.
@ -54,7 +53,7 @@ public interface IWiredNetwork
* @see IWiredNode#disconnectFrom(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.
@ -68,7 +67,7 @@ public interface IWiredNetwork
* @throws IllegalArgumentException If the node is not in the network.
* @see IWiredNode#remove()
*/
boolean remove( @Nonnull IWiredNode node );
boolean remove(@Nonnull IWiredNode node);
/**
* Update the peripherals a node provides.
@ -81,5 +80,5 @@ public interface IWiredNetwork
* @throws IllegalArgumentException If the node is not in the network.
* @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)
*/
public interface IWiredNetworkChange
{
public interface IWiredNetworkChange {
/**
* 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.

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
* be used on the main server thread.
*/
public interface IWiredNode extends IPacketNetwork
{
public interface IWiredNode extends IPacketNetwork {
/**
* The associated element for this network node.
*
@ -55,9 +54,8 @@ public interface IWiredNode extends IPacketNetwork
* @see IWiredNetwork#connect(IWiredNode, IWiredNode)
* @see IWiredNode#disconnectFrom(IWiredNode)
*/
default boolean connectTo( @Nonnull IWiredNode node )
{
return getNetwork().connect( this, node );
default boolean connectTo(@Nonnull IWiredNode node) {
return getNetwork().connect(this, node);
}
/**
@ -71,9 +69,8 @@ public interface IWiredNode extends IPacketNetwork
* @see IWiredNetwork#disconnect(IWiredNode, IWiredNode)
* @see IWiredNode#connectTo(IWiredNode)
*/
default boolean disconnectFrom( @Nonnull IWiredNode node )
{
return getNetwork().disconnect( this, node );
default boolean disconnectFrom(@Nonnull IWiredNode 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.
* @see IWiredNetwork#remove(IWiredNode)
*/
default boolean remove()
{
return getNetwork().remove( this );
default boolean remove() {
return getNetwork().remove(this);
}
/**
@ -101,8 +97,7 @@ public interface IWiredNode extends IPacketNetwork
* @param peripherals The new peripherals for this node.
* @see IWiredNetwork#updatePeripherals(IWiredNode, Map)
*/
default void updatePeripherals( @Nonnull Map<String, IPeripheral> peripherals )
{
getNetwork().updatePeripherals( this, peripherals );
default void updatePeripherals(@Nonnull Map<String, IPeripheral> 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
* to send the packet from.
*/
public interface IWiredSender extends IPacketSender
{
public interface IWiredSender extends IPacketSender {
/**
* The node in the network representing this object.
* <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
* {@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.
* <p>
@ -38,8 +37,7 @@ public interface GenericPeripheral extends GenericSource
* @see IPeripheral#getType()
*/
@Nonnull
default PeripheralType getType()
{
default PeripheralType getType() {
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
* 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.
*
@ -41,9 +40,8 @@ public interface IComputerAccess
* @see IMount
*/
@Nullable
default String mount( @Nonnull String desiredLocation, @Nonnull IMount mount )
{
return mount( desiredLocation, mount, getAttachmentName() );
default String mount(@Nonnull String desiredLocation, @Nonnull IMount mount) {
return mount(desiredLocation, mount, getAttachmentName());
}
/**
@ -63,7 +61,7 @@ public interface IComputerAccess
* @see IMount
*/
@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.
@ -80,9 +78,8 @@ public interface IComputerAccess
* @see IMount
*/
@Nullable
default String mountWritable( @Nonnull String desiredLocation, @Nonnull IWritableMount mount )
{
return mountWritable( desiredLocation, mount, getAttachmentName() );
default String mountWritable(@Nonnull String desiredLocation, @Nonnull IWritableMount mount) {
return mountWritable(desiredLocation, mount, getAttachmentName());
}
/**
@ -100,7 +97,7 @@ public interface IComputerAccess
* @see #unmount(String)
* @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)}
@ -120,7 +117,7 @@ public interface IComputerAccess
* @see #mount(String, IMount)
* @see #mountWritable(String, IWritableMount)
*/
void unmount( @Nullable String location );
void unmount(@Nullable String location);
/**
* Returns the numerical ID of this computer.
@ -150,7 +147,7 @@ public interface IComputerAccess
* @throws NotAttachedException If the peripheral has been detached.
* @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.
@ -187,7 +184,7 @@ public interface IComputerAccess
* @see #getAvailablePeripherals()
*/
@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.

View File

@ -15,8 +15,7 @@ import javax.annotation.Nonnull;
* This behaves similarly to {@link IDynamicLuaObject}, though also accepting the current {@link IComputerAccess}.
* 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
* called once before each attachment, and should not change when called multiple times.
@ -49,5 +48,5 @@ public interface IDynamicPeripheral extends IPeripheral
* @see #getMethodNames()
*/
@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
* {@link IDynamicPeripheral}.
*/
public interface IPeripheral
{
public interface IPeripheral {
/**
* Should return a string that uniquely identifies this type of peripheral.
* This can be queried from lua by calling {@code peripheral.getType()}
@ -40,8 +39,7 @@ public interface IPeripheral
* @see PeripheralType#getAdditionalTypes()
*/
@Nonnull
default Set<String> getAdditionalTypes()
{
default Set<String> getAdditionalTypes() {
return Collections.emptySet();
}
@ -63,8 +61,7 @@ public interface IPeripheral
* attached to a peripheral at once.
* @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.
* @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
*/
@Nullable
default Object getTarget()
{
default Object getTarget() {
return null;
}
@ -109,5 +104,5 @@ public interface IPeripheral
* @param other The peripheral to compare against. This may be {@code null}.
* @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)
*/
@FunctionalInterface
public interface IPeripheralProvider
{
public interface IPeripheralProvider {
/**
* Produce an peripheral implementation from a block location.
*
@ -35,5 +34,5 @@ public interface IPeripheralProvider
* @see ForgeComputerCraftAPI#registerPeripheralProvider(IPeripheralProvider)
*/
@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()
*/
public interface IWorkMonitor
{
public interface IWorkMonitor {
/**
* 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 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.
@ -57,19 +56,15 @@ public interface IWorkMonitor
* @param runnable The task to run.
* @return If the task was actually run (namely, {@link #canWork()} returned {@code true}).
*/
default boolean runWork( @Nonnull Runnable runnable )
{
Objects.requireNonNull( runnable, "runnable should not be null" );
if( !canWork() ) return false;
default boolean runWork(@Nonnull Runnable runnable) {
Objects.requireNonNull(runnable, "runnable should not be null");
if (!canWork()) return false;
long start = System.nanoTime();
try
{
var start = System.nanoTime();
try {
runnable.run();
}
finally
{
trackWork( System.nanoTime() - start, TimeUnit.NANOSECONDS );
} finally {
trackWork(System.nanoTime() - start, TimeUnit.NANOSECONDS);
}
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
* the computer.
*/
public class NotAttachedException extends IllegalStateException
{
public class NotAttachedException extends IllegalStateException {
private static final long serialVersionUID = 1221244785535553536L;
public NotAttachedException()
{
super( "You are not attached to this computer" );
public NotAttachedException() {
super("You are not attached to this computer");
}
public NotAttachedException( String s )
{
super( s );
public NotAttachedException(String 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
* lexicographically smallest non-empty name being chosen.
*/
public final class PeripheralType
{
private static final PeripheralType UNTYPED = new PeripheralType( null, Collections.emptySet() );
public final class PeripheralType {
private static final PeripheralType UNTYPED = new PeripheralType(null, Collections.emptySet());
private final String type;
private final Set<String> additionalTypes;
public PeripheralType( String type, Set<String> additionalTypes )
{
public PeripheralType(String type, Set<String> additionalTypes) {
this.type = type;
this.additionalTypes = additionalTypes;
if( additionalTypes.contains( null ) )
{
throw new IllegalArgumentException( "All additional types must be non-null" );
if (additionalTypes.contains(null)) {
throw new IllegalArgumentException("All additional types must be non-null");
}
}
@ -42,8 +39,7 @@ public final class PeripheralType
*
* @return The empty peripheral type.
*/
public static PeripheralType untyped()
{
public static PeripheralType untyped() {
return UNTYPED;
}
@ -53,10 +49,9 @@ public final class PeripheralType
* @param type The name of the type.
* @return The constructed peripheral type.
*/
public static PeripheralType ofType( @Nonnull String type )
{
if( Strings.isNullOrEmpty( type ) ) throw new IllegalArgumentException( "type cannot be null or empty" );
return new PeripheralType( type, Collections.emptySet() );
public static PeripheralType ofType(@Nonnull String type) {
if (Strings.isNullOrEmpty(type)) throw new IllegalArgumentException("type cannot be null or empty");
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"}.
* @return The constructed peripheral type.
*/
public static PeripheralType ofType( @Nonnull String type, Collection<String> additionalTypes )
{
if( Strings.isNullOrEmpty( type ) ) throw new IllegalArgumentException( "type cannot be null or empty" );
return new PeripheralType( type, ImmutableSet.copyOf( additionalTypes ) );
public static PeripheralType ofType(@Nonnull String type, Collection<String> additionalTypes) {
if (Strings.isNullOrEmpty(type)) throw new IllegalArgumentException("type cannot be null or empty");
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"}.
* @return The constructed peripheral type.
*/
public static PeripheralType ofType( @Nonnull String type, @Nonnull String... additionalTypes )
{
if( Strings.isNullOrEmpty( type ) ) throw new IllegalArgumentException( "type cannot be null or empty" );
return new PeripheralType( type, ImmutableSet.copyOf( additionalTypes ) );
public static PeripheralType ofType(@Nonnull String type, @Nonnull String... additionalTypes) {
if (Strings.isNullOrEmpty(type)) throw new IllegalArgumentException("type cannot be null or empty");
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"}.
* @return The constructed peripheral type.
*/
public static PeripheralType ofAdditional( Collection<String> additionalTypes )
{
return new PeripheralType( null, ImmutableSet.copyOf( additionalTypes ) );
public static PeripheralType ofAdditional(Collection<String> 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"}.
* @return The constructed peripheral type.
*/
public static PeripheralType ofAdditional( @Nonnull String... additionalTypes )
{
return new PeripheralType( null, ImmutableSet.copyOf( additionalTypes ) );
public static PeripheralType ofAdditional(@Nonnull String... additionalTypes) {
return new PeripheralType(null, ImmutableSet.copyOf(additionalTypes));
}
/**
@ -113,8 +104,7 @@ public final class PeripheralType
* @return The type of this peripheral.
*/
@Nullable
public String getPrimaryType()
{
public String getPrimaryType() {
return type;
}
@ -124,8 +114,7 @@ public final class PeripheralType
*
* @return All additional types.
*/
public Set<String> getAdditionalTypes()
{
public Set<String> getAdditionalTypes() {
return additionalTypes;
}
}

View File

@ -16,42 +16,36 @@ import javax.annotation.Nonnull;
* <p>
* 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 String adjective;
private final ItemStack stack;
protected AbstractPocketUpgrade( ResourceLocation id, String adjective, ItemStack stack )
{
protected AbstractPocketUpgrade(ResourceLocation id, String adjective, ItemStack stack) {
this.id = id;
this.adjective = adjective;
this.stack = stack;
}
protected AbstractPocketUpgrade( ResourceLocation id, ItemStack stack )
{
this( id, IUpgradeBase.getDefaultAdjective( id ), stack );
protected AbstractPocketUpgrade(ResourceLocation id, ItemStack stack) {
this(id, IUpgradeBase.getDefaultAdjective(id), stack);
}
@Nonnull
@Override
public final ResourceLocation getUpgradeID()
{
public final ResourceLocation getUpgradeID() {
return id;
}
@Nonnull
@Override
public final String getUnlocalisedAdjective()
{
public final String getUnlocalisedAdjective() {
return adjective;
}
@Nonnull
@Override
public final ItemStack getCraftingItem()
{
public final ItemStack getCraftingItem() {
return stack;
}
}

View File

@ -17,8 +17,7 @@ import java.util.Map;
/**
* Wrapper class for pocket computers.
*/
public interface IPocketAccess
{
public interface IPocketAccess {
/**
* Gets the entity holding this item.
* <p>
@ -45,7 +44,7 @@ public interface IPocketAccess
* {@code 0x000000} and {@code 0xFFFFFF} or -1 to reset to the default colour.
* @see #getColour()
*/
void setColour( int colour );
void setColour(int colour);
/**
* 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.
* @see #getLight()
*/
void setLight( int colour );
void setLight(int colour);
/**
* 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.
*/
public interface IPocketUpgrade extends IUpgradeBase
{
public interface IPocketUpgrade extends IUpgradeBase {
/**
* Creates a peripheral for the pocket computer.
* <p>
@ -38,7 +37,7 @@ public interface IPocketUpgrade extends IUpgradeBase
* @see #update(IPocketAccess, IPeripheral)
*/
@Nullable
IPeripheral createPeripheral( @Nonnull IPocketAccess access );
IPeripheral createPeripheral(@Nonnull IPocketAccess access);
/**
* Called when the pocket computer item stack updates.
@ -47,8 +46,7 @@ public interface IPocketUpgrade extends IUpgradeBase
* @param peripheral The peripheral for this upgrade.
* @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.
* @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;
}
}

View File

@ -21,10 +21,8 @@ import java.util.function.Consumer;
* @see GatherDataEvent To register your data provider
* @see PocketUpgradeSerialiser
*/
public abstract class PocketUpgradeDataProvider extends UpgradeDataProvider<IPocketUpgrade, PocketUpgradeSerialiser<?>>
{
public PocketUpgradeDataProvider( @Nonnull DataGenerator generator )
{
super( generator, "Pocket Computer Upgrades", "computercraft/pocket_upgrades", PocketUpgradeSerialiser.REGISTRY_ID );
public abstract class PocketUpgradeDataProvider extends UpgradeDataProvider<IPocketUpgrade, PocketUpgradeSerialiser<?>> {
public PocketUpgradeDataProvider(@Nonnull DataGenerator generator) {
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 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.
* <p>
* This is largely intended for use with Forge Registry methods/classes, such as {@link DeferredRegister} and
* {@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.
@ -50,10 +49,9 @@ public interface PocketUpgradeSerialiser<T extends IPocketUpgrade> extends Upgra
* @see #REGISTRY_ID
* @deprecated Use {@link #REGISTRY_ID} directly.
*/
@Deprecated( forRemoval = true )
static IForgeRegistry<PocketUpgradeSerialiser<?>> registry()
{
return RegistryManager.ACTIVE.getRegistry( REGISTRY_ID );
@Deprecated(forRemoval = true)
static IForgeRegistry<PocketUpgradeSerialiser<?>> registry() {
return RegistryManager.ACTIVE.getRegistry(REGISTRY_ID);
}
/**
@ -67,17 +65,14 @@ public interface PocketUpgradeSerialiser<T extends IPocketUpgrade> extends Upgra
* @return The serialiser for this upgrade
*/
@Nonnull
static <T extends IPocketUpgrade> PocketUpgradeSerialiser<T> simple( @Nonnull Function<ResourceLocation, T> factory )
{
final class Impl extends SimpleSerialiser<T> implements PocketUpgradeSerialiser<T>
{
private Impl( Function<ResourceLocation, T> constructor )
{
super( constructor );
static <T extends IPocketUpgrade> PocketUpgradeSerialiser<T> simple(@Nonnull Function<ResourceLocation, T> factory) {
final class Impl extends SimpleSerialiser<T> implements PocketUpgradeSerialiser<T> {
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.
*/
@Nonnull
static <T extends IPocketUpgrade> PocketUpgradeSerialiser<T> simpleWithCustomItem( @Nonnull BiFunction<ResourceLocation, ItemStack, T> factory )
{
final class Impl extends SerialiserWithCraftingItem<T> implements PocketUpgradeSerialiser<T>
{
private Impl( BiFunction<ResourceLocation, ItemStack, T> factory )
{
super( factory );
static <T extends IPocketUpgrade> PocketUpgradeSerialiser<T> simpleWithCustomItem(@Nonnull BiFunction<ResourceLocation, ItemStack, T> factory) {
final class Impl extends SerialiserWithCraftingItem<T> implements PocketUpgradeSerialiser<T> {
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)
*/
@FunctionalInterface
public interface IBundledRedstoneProvider
{
public interface IBundledRedstoneProvider {
/**
* Produce an bundled redstone output from a block location.
*
@ -29,5 +28,5 @@ public interface IBundledRedstoneProvider
* handle this block.
* @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>
* 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 TurtleUpgradeType type;
private final String adjective;
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.type = type;
this.adjective = adjective;
this.stack = stack;
}
protected AbstractTurtleUpgrade( ResourceLocation id, TurtleUpgradeType type, ItemStack stack )
{
this( id, type, IUpgradeBase.getDefaultAdjective( id ), stack );
protected AbstractTurtleUpgrade(ResourceLocation id, TurtleUpgradeType type, ItemStack stack) {
this(id, type, IUpgradeBase.getDefaultAdjective(id), stack);
}
@Nonnull
@Override
public final ResourceLocation getUpgradeID()
{
public final ResourceLocation getUpgradeID() {
return id;
}
@Nonnull
@Override
public final String getUnlocalisedAdjective()
{
public final String getUnlocalisedAdjective() {
return adjective;
}
@Nonnull
@Override
public final TurtleUpgradeType getType()
{
public final TurtleUpgradeType getType() {
return type;
}
@Nonnull
@Override
public final ItemStack getCraftingItem()
{
public final ItemStack getCraftingItem() {
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
* {@link ITurtleUpgrade}.
*/
public interface ITurtleAccess
{
public interface ITurtleAccess {
/**
* Returns the world in which the turtle resides.
*
@ -70,7 +69,7 @@ public interface ITurtleAccess
* was cancelled.
* @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.
@ -81,7 +80,7 @@ public interface ITurtleAccess
* @see #getVisualYaw(float)
*/
@Nonnull
Vec3 getVisualPosition( float f );
Vec3 getVisualPosition(float f);
/**
* 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.
* @see #getVisualPosition(float)
*/
float getVisualYaw( float f );
float getVisualYaw(float f);
/**
* 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).
* @see #getDirection()
*/
void setDirection( @Nonnull Direction dir );
void setDirection(@Nonnull Direction dir);
/**
* Get the currently selected slot in the turtle's inventory.
@ -128,7 +127,7 @@ public interface ITurtleAccess
* @see #getInventory()
* @see #getSelectedSlot()
*/
void setSelectedSlot( int slot );
void setSelectedSlot(int slot);
/**
* 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.
* @see #getColour()
*/
void setColour( int colour );
void setColour(int colour);
/**
* Get the colour of this turtle as a RGB number.
@ -178,7 +177,7 @@ public interface ITurtleAccess
* @deprecated Use {@link #getInventory()} directly.
*/
@Nonnull
@Deprecated( forRemoval = true )
@Deprecated(forRemoval = true)
IItemHandlerModifiable getItemHandler();
/**
@ -209,7 +208,7 @@ public interface ITurtleAccess
* @see #addFuel(int)
* @see #consumeFuel(int)
*/
void setFuelLevel( int fuel );
void setFuelLevel(int fuel);
/**
* 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.
* @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.
@ -234,7 +233,7 @@ public interface ITurtleAccess
* @param fuel The amount to refuel with.
* @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
@ -251,7 +250,7 @@ public interface ITurtleAccess
* @see MethodResult#pullEvent(String, ILuaCallback)
*/
@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
@ -261,7 +260,7 @@ public interface ITurtleAccess
* @throws UnsupportedOperationException When attempting to execute play an animation on the client side.
* @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.
@ -271,7 +270,7 @@ public interface ITurtleAccess
* @see #setUpgrade(TurtleSide, ITurtleUpgrade)
*/
@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.
@ -280,7 +279,7 @@ public interface ITurtleAccess
* @param upgrade The upgrade to set, may be {@code null} to clear.
* @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.
@ -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.
*/
@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.
@ -302,7 +301,7 @@ public interface ITurtleAccess
* @see #updateUpgradeNBTData(TurtleSide)
*/
@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
@ -311,5 +310,5 @@ public interface ITurtleAccess
* @param side The side to mark dirty.
* @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)
*/
@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.
* <p>
@ -29,5 +28,5 @@ public interface ITurtleCommand
* @see TurtleCommandResult
*/
@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.
*/
public interface ITurtleUpgrade extends IUpgradeBase
{
public interface ITurtleUpgrade extends IUpgradeBase {
/**
* 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.
*/
@Nullable
default IPeripheral createPeripheral( @Nonnull ITurtleAccess turtle, @Nonnull TurtleSide side )
{
default IPeripheral createPeripheral(@Nonnull ITurtleAccess turtle, @Nonnull TurtleSide side) {
return null;
}
@ -75,8 +73,7 @@ public interface ITurtleUpgrade extends IUpgradeBase
* to be called.
*/
@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();
}
@ -86,7 +83,6 @@ public interface ITurtleUpgrade extends IUpgradeBase
* @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.
*/
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)
*/
public enum TurtleAnimation
{
public enum TurtleAnimation {
/**
* 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 ITurtleUpgrade#useTool(ITurtleAccess, TurtleSide, TurtleVerb, Direction)
*/
public final class TurtleCommandResult
{
private static final TurtleCommandResult EMPTY_SUCCESS = new TurtleCommandResult( true, null, null );
private static final TurtleCommandResult EMPTY_FAILURE = new TurtleCommandResult( false, null, null );
public final class TurtleCommandResult {
private static final TurtleCommandResult EMPTY_SUCCESS = new TurtleCommandResult(true, null, null);
private static final TurtleCommandResult EMPTY_FAILURE = new TurtleCommandResult(false, null, null);
/**
* Create a successful command result with no result.
@ -27,8 +26,7 @@ public final class TurtleCommandResult
* @return A successful command result with no values.
*/
@Nonnull
public static TurtleCommandResult success()
{
public static TurtleCommandResult success() {
return EMPTY_SUCCESS;
}
@ -39,10 +37,9 @@ public final class TurtleCommandResult
* @return A successful command result with the given values.
*/
@Nonnull
public static TurtleCommandResult success( @Nullable Object[] results )
{
if( results == null || results.length == 0 ) return EMPTY_SUCCESS;
return new TurtleCommandResult( true, null, results );
public static TurtleCommandResult success(@Nullable Object[] results) {
if (results == null || results.length == 0) return EMPTY_SUCCESS;
return new TurtleCommandResult(true, null, results);
}
/**
@ -51,8 +48,7 @@ public final class TurtleCommandResult
* @return A failed command result with no message.
*/
@Nonnull
public static TurtleCommandResult failure()
{
public static TurtleCommandResult failure() {
return EMPTY_FAILURE;
}
@ -63,18 +59,16 @@ public final class TurtleCommandResult
* @return A failed command result with a message.
*/
@Nonnull
public static TurtleCommandResult failure( @Nullable String errorMessage )
{
if( errorMessage == null ) return EMPTY_FAILURE;
return new TurtleCommandResult( false, errorMessage, null );
public static TurtleCommandResult failure(@Nullable String errorMessage) {
if (errorMessage == null) return EMPTY_FAILURE;
return new TurtleCommandResult(false, errorMessage, null);
}
private final boolean success;
private final String errorMessage;
private final Object[] results;
private TurtleCommandResult( boolean success, String errorMessage, Object[] results )
{
private TurtleCommandResult(boolean success, String errorMessage, Object[] results) {
this.success = success;
this.errorMessage = errorMessage;
this.results = results;
@ -85,8 +79,7 @@ public final class TurtleCommandResult
*
* @return If the command was successful.
*/
public boolean isSuccess()
{
public boolean isSuccess() {
return success;
}
@ -96,8 +89,7 @@ public final class TurtleCommandResult
* @return The command's error message, or {@code null} if it was a success.
*/
@Nullable
public String getErrorMessage()
{
public String getErrorMessage() {
return errorMessage;
}
@ -107,8 +99,7 @@ public final class TurtleCommandResult
* @return The command's result, or {@code null} if it was a failure.
*/
@Nullable
public Object[] getResults()
{
public Object[] getResults() {
return results;
}
}

View File

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

View File

@ -71,15 +71,14 @@ import java.util.function.Function;
* @see TurtleUpgradeDataProvider
* @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.
* <p>
* This is largely intended for use with Forge Registry methods/classes, such as {@link DeferredRegister} and
* {@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.
@ -88,10 +87,9 @@ public interface TurtleUpgradeSerialiser<T extends ITurtleUpgrade> extends Upgra
* @see #REGISTRY_ID
* @deprecated Use {@link #REGISTRY_ID} directly.
*/
@Deprecated( forRemoval = true )
static IForgeRegistry<TurtleUpgradeSerialiser<?>> registry()
{
return RegistryManager.ACTIVE.getRegistry( REGISTRY_ID );
@Deprecated(forRemoval = true)
static IForgeRegistry<TurtleUpgradeSerialiser<?>> registry() {
return RegistryManager.ACTIVE.getRegistry(REGISTRY_ID);
}
/**
@ -105,17 +103,14 @@ public interface TurtleUpgradeSerialiser<T extends ITurtleUpgrade> extends Upgra
* @return The serialiser for this upgrade
*/
@Nonnull
static <T extends ITurtleUpgrade> TurtleUpgradeSerialiser<T> simple( @Nonnull Function<ResourceLocation, T> factory )
{
final class Impl extends SimpleSerialiser<T> implements TurtleUpgradeSerialiser<T>
{
private Impl( Function<ResourceLocation, T> constructor )
{
super( constructor );
static <T extends ITurtleUpgrade> TurtleUpgradeSerialiser<T> simple(@Nonnull Function<ResourceLocation, T> factory) {
final class Impl extends SimpleSerialiser<T> implements TurtleUpgradeSerialiser<T> {
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.
*/
@Nonnull
static <T extends ITurtleUpgrade> TurtleUpgradeSerialiser<T> simpleWithCustomItem( @Nonnull BiFunction<ResourceLocation, ItemStack, T> factory )
{
final class Impl extends SerialiserWithCraftingItem<T> implements TurtleUpgradeSerialiser<T>
{
private Impl( BiFunction<ResourceLocation, ItemStack, T> factory )
{
super( factory );
static <T extends ITurtleUpgrade> TurtleUpgradeSerialiser<T> simpleWithCustomItem(@Nonnull BiFunction<ResourceLocation, ItemStack, T> factory) {
final class Impl extends SerialiserWithCraftingItem<T> implements TurtleUpgradeSerialiser<T> {
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()
*/
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()}
* and {@code turtle.attack()} methods (Such as pickaxe or sword on Mining and Melee turtles).
@ -31,13 +30,11 @@ public enum TurtleUpgradeType
*/
BOTH;
public boolean isTool()
{
public boolean isTool() {
return this == TOOL || this == BOTH;
}
public boolean isPeripheral()
{
public boolean isPeripheral() {
return this == PERIPHERAL || this == BOTH;
}
}

View File

@ -14,8 +14,7 @@ import net.minecraft.core.Direction;
* @see ITurtleUpgrade#getType()
* @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()}.
*/

View File

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

View File

@ -20,17 +20,15 @@ import java.util.Objects;
*
* @deprecated Use {@link TurtleRefuelHandler} instead.
*/
@Deprecated( forRemoval = true )
public class TurtleRefuelEvent extends TurtleEvent
{
@Deprecated(forRemoval = true)
public class TurtleRefuelEvent extends TurtleEvent {
private final ItemStack stack;
private Handler handler;
public TurtleRefuelEvent( @Nonnull ITurtleAccess turtle, @Nonnull ItemStack stack )
{
super( turtle );
public TurtleRefuelEvent(@Nonnull ITurtleAccess turtle, @Nonnull ItemStack stack) {
super(turtle);
Objects.requireNonNull( turtle, "turtle cannot be null" );
Objects.requireNonNull(turtle, "turtle cannot be null");
this.stack = stack;
}
@ -41,8 +39,7 @@ public class TurtleRefuelEvent extends TurtleEvent
*
* @return The stack to refuel from.
*/
public ItemStack getStack()
{
public ItemStack getStack() {
return stack;
}
@ -53,8 +50,7 @@ public class TurtleRefuelEvent extends TurtleEvent
* @see #setHandler(Handler)
*/
@Nullable
public Handler getHandler()
{
public Handler getHandler() {
return handler;
}
@ -67,8 +63,7 @@ public class TurtleRefuelEvent extends TurtleEvent
* @param handler The new refuel handler.
* @see #getHandler()
*/
public void setHandler( @Nullable Handler handler )
{
public void setHandler(@Nullable Handler handler) {
this.handler = handler;
}
@ -76,8 +71,7 @@ public class TurtleRefuelEvent extends TurtleEvent
* Handles refuelling a turtle from a specific item.
*/
@FunctionalInterface
public interface Handler
{
public interface Handler {
/**
* Refuel a turtle using an item.
*
@ -88,6 +82,6 @@ public class TurtleRefuelEvent extends TurtleEvent
* items to consume.
* @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.turtle.ITurtleUpgrade;
import net.minecraft.Util;
import net.minecraft.nbt.CompoundTag;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.world.item.ItemStack;
@ -17,8 +16,7 @@ import javax.annotation.Nonnull;
/**
* 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"
* 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
* check.
*/
default boolean isItemSuitable( @Nonnull ItemStack stack )
{
ItemStack crafting = getCraftingItem();
default boolean isItemSuitable(@Nonnull ItemStack stack) {
var crafting = getCraftingItem();
// A more expanded form of ItemStack.areShareTagsEqual, but allowing an empty tag to be equal to a
// null one.
CompoundTag shareTag = stack.getItem().getShareTag( stack );
CompoundTag craftingShareTag = crafting.getItem().getShareTag( crafting );
if( shareTag == craftingShareTag ) return true;
if( shareTag == null ) return craftingShareTag.isEmpty();
if( craftingShareTag == null ) return shareTag.isEmpty();
return shareTag.equals( craftingShareTag );
var shareTag = stack.getItem().getShareTag(stack);
var craftingShareTag = crafting.getItem().getShareTag(crafting);
if (shareTag == craftingShareTag) return true;
if (shareTag == null) return craftingShareTag.isEmpty();
if (craftingShareTag == null) return shareTag.isEmpty();
return shareTag.equals(craftingShareTag);
}
/**
@ -94,8 +91,7 @@ public interface IUpgradeBase
* @see #getUnlocalisedAdjective()
*/
@Nonnull
static String getDefaultAdjective( @Nonnull ResourceLocation id )
{
return Util.makeDescriptionId( "upgrade", id ) + ".adjective";
static String getDefaultAdjective(@Nonnull ResourceLocation id) {
return Util.makeDescriptionId("upgrade", id) + ".adjective";
}
}

View File

@ -24,7 +24,6 @@ import org.apache.logging.log4j.Logger;
import javax.annotation.Nonnull;
import java.io.IOException;
import java.nio.file.Path;
import java.util.*;
import java.util.function.Consumer;
import java.util.function.Function;
@ -36,8 +35,7 @@ import java.util.function.Function;
* @param <T> The base class of upgrades.
* @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 final DataGenerator generator;
@ -47,8 +45,7 @@ public abstract class UpgradeDataProvider<T extends IUpgradeBase, R extends Upgr
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.name = name;
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.
*/
@Nonnull
public final Upgrade<R> simple( @Nonnull ResourceLocation id, @Nonnull R serialiser )
{
if( !(serialiser instanceof SimpleSerialiser) )
{
throw new IllegalStateException( serialiser + " must be a simple() seriaiser." );
public final Upgrade<R> simple(@Nonnull ResourceLocation id, @Nonnull R serialiser) {
if (!(serialiser instanceof SimpleSerialiser)) {
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.
*/
@Nonnull
public final Upgrade<R> simpleWithCustomItem( @Nonnull ResourceLocation id, @Nonnull R serialiser, @Nonnull Item item )
{
if( !(serialiser instanceof SerialiserWithCraftingItem) )
{
throw new IllegalStateException( serialiser + " must be a simpleWithCustomItem() serialiser." );
public final Upgrade<R> simpleWithCustomItem(@Nonnull ResourceLocation id, @Nonnull R serialiser, @Nonnull Item item) {
if (!(serialiser instanceof SerialiserWithCraftingItem)) {
throw new IllegalStateException(serialiser + " must be a simpleWithCustomItem() serialiser.");
}
return new Upgrade<>( id, serialiser, s ->
s.addProperty( "item", Objects.requireNonNull( ForgeRegistries.ITEMS.getKey( item ), "Item is not registered" ).toString() )
return new Upgrade<>(id, serialiser, s ->
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.
*/
protected abstract void addUpgrades( @Nonnull Consumer<Upgrade<R>> addUpgrade );
protected abstract void addUpgrades(@Nonnull Consumer<Upgrade<R>> addUpgrade);
@Override
public final void run( @Nonnull CachedOutput cache ) throws IOException
{
var registry = RegistryManager.ACTIVE.getRegistry( this.registry );
Path base = generator.getOutputFolder().resolve( "data" );
public final void run(@Nonnull CachedOutput cache) throws IOException {
var registry = RegistryManager.ACTIVE.getRegistry(this.registry);
var base = generator.getOutputFolder().resolve("data");
Set<ResourceLocation> seen = new HashSet<>();
List<T> upgrades = new ArrayList<>();
addUpgrades( upgrade -> {
if( !seen.add( upgrade.id() ) ) throw new IllegalStateException( "Duplicate upgrade " + upgrade.id() );
addUpgrades(upgrade -> {
if (!seen.add(upgrade.id())) throw new IllegalStateException("Duplicate upgrade " + upgrade.id());
var json = new JsonObject();
json.addProperty( "type", Objects.requireNonNull( registry.getKey( upgrade.serialiser() ), "Serialiser has not been registered" ).toString() );
upgrade.serialise().accept( json );
json.addProperty("type", Objects.requireNonNull(registry.getKey(upgrade.serialiser()), "Serialiser has not been registered").toString());
upgrade.serialise().accept(json);
try
{
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 );
try {
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);
}
try
{
var result = upgrade.serialiser().fromJson( upgrade.id(), json );
upgrades.add( result );
try {
var result = upgrade.serialiser().fromJson(upgrade.id(), json);
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;
}
@Nonnull
@Override
public final String getName()
{
public final String getName() {
return name;
}
@Nonnull
public final R existingSerialiser( @Nonnull ResourceLocation id )
{
var result = RegistryManager.ACTIVE.getRegistry( registry ).getValue( id );
if( result == null ) throw new IllegalArgumentException( "No such serialiser " + registry );
public final R existingSerialiser(@Nonnull ResourceLocation id) {
var result = RegistryManager.ACTIVE.getRegistry(registry).getValue(id);
if (result == null) throw new IllegalArgumentException("No such serialiser " + registry);
return result;
}
@Nonnull
public List<T> getGeneratedUpgrades()
{
if( upgrades == null ) throw new IllegalStateException( "Upgrades have not beeen generated yet" );
public List<T> getGeneratedUpgrades() {
if (upgrades == null) throw new IllegalStateException("Upgrades have not beeen generated yet");
return upgrades;
}
@ -178,16 +162,14 @@ public abstract class UpgradeDataProvider<T extends IUpgradeBase, R extends Upgr
*/
public record Upgrade<R extends UpgradeSerialiser<?>>(
ResourceLocation id, R serialiser, Consumer<JsonObject> serialise
)
{
) {
/**
* Convenience method for registering an upgrade.
*
* @param add The callback given to {@link #addUpgrades(Consumer)}
*/
public void add( @Nonnull Consumer<Upgrade<R>> add )
{
add.accept( this );
public void add(@Nonnull Consumer<Upgrade<R>> add) {
add.accept(this);
}
}
}

View File

@ -23,8 +23,7 @@ import javax.annotation.Nonnull;
* @see TurtleUpgradeSerialiser
* @see PocketUpgradeSerialiser
*/
public interface UpgradeSerialiser<T extends IUpgradeBase>
{
public interface UpgradeSerialiser<T extends IUpgradeBase> {
/**
* 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.
*/
@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.
@ -44,7 +43,7 @@ public interface UpgradeSerialiser<T extends IUpgradeBase>
* @return The constructed upgrade, with a {@link IUpgradeBase#getUpgradeID()} equal to {@code id}.
*/
@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.
@ -52,6 +51,6 @@ public interface UpgradeSerialiser<T extends IUpgradeBase>
* @param buffer The buffer object to write this upgrade to
* @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.fml.common.Mod;
@Mod.EventBusSubscriber( modid = ComputerCraft.MOD_ID, value = Dist.CLIENT )
public class ClientHooks
{
@Mod.EventBusSubscriber(modid = ComputerCraft.MOD_ID, value = Dist.CLIENT)
public class ClientHooks {
@SubscribeEvent
public static void onWorldUnload( LevelEvent.Unload event )
{
if( event.getLevel().isClientSide() )
{
public static void onWorldUnload(LevelEvent.Unload event) {
if (event.getLevel().isClientSide()) {
ClientMonitor.destroyAll();
SpeakerManager.reset();
}
}
@SubscribeEvent
public static void onLogIn( ClientPlayerNetworkEvent.LoggingIn event )
{
public static void onLogIn(ClientPlayerNetworkEvent.LoggingIn event) {
ClientPocketComputers.reset();
}
@SubscribeEvent
public static void onLogOut( ClientPlayerNetworkEvent.LoggingOut event )
{
public static void onLogOut(ClientPlayerNetworkEvent.LoggingOut event) {
ClientPocketComputers.reset();
}
}

View File

@ -39,10 +39,9 @@ import java.util.function.Supplier;
/**
* Registers textures and models for items.
*/
@Mod.EventBusSubscriber( modid = ComputerCraft.MOD_ID, value = Dist.CLIENT, bus = Mod.EventBusSubscriber.Bus.MOD )
public final class ClientRegistry
{
private static final String[] EXTRA_MODELS = new String[] {
@Mod.EventBusSubscriber(modid = ComputerCraft.MOD_ID, value = Dist.CLIENT, bus = Mod.EventBusSubscriber.Bus.MOD)
public final class ClientRegistry {
private static final String[] EXTRA_MODELS = new String[]{
// Turtle upgrades
"block/turtle_modem_normal_off_left",
"block/turtle_modem_normal_on_left",
@ -65,124 +64,114 @@ public final class ClientRegistry
"block/turtle_elf_overlay",
};
private ClientRegistry() {}
@SubscribeEvent
public static void registerModelLoaders( ModelEvent.RegisterGeometryLoaders event )
{
event.register( "turtle", TurtleModelLoader.INSTANCE );
private ClientRegistry() {
}
@SubscribeEvent
public static void registerModels( ModelEvent.RegisterAdditional event )
{
for( String model : EXTRA_MODELS )
{
event.register( new ResourceLocation( ComputerCraft.MOD_ID, model ) );
public static void registerModelLoaders(ModelEvent.RegisterGeometryLoaders event) {
event.register("turtle", TurtleModelLoader.INSTANCE);
}
@SubscribeEvent
public static void registerModels(ModelEvent.RegisterAdditional event) {
for (var model : EXTRA_MODELS) {
event.register(new ResourceLocation(ComputerCraft.MOD_ID, model));
}
}
@SubscribeEvent
public static void onItemColours( RegisterColorHandlersEvent.Item event )
{
if( Registry.ModItems.DISK == null || Registry.ModBlocks.TURTLE_NORMAL == null )
{
ComputerCraft.log.warn( "Block/item registration has failed. Skipping registration of item colours." );
public static void onItemColours(RegisterColorHandlersEvent.Item event) {
if (Registry.ModItems.DISK == null || Registry.ModBlocks.TURTLE_NORMAL == null) {
ComputerCraft.log.warn("Block/item registration has failed. Skipping registration of item colours.");
return;
}
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()
);
event.register(
( stack, layer ) -> layer == 1 ? ItemTreasureDisk.getColour( stack ) : 0xFFFFFF,
(stack, layer) -> layer == 1 ? ItemTreasureDisk.getColour(stack) : 0xFFFFFF,
Registry.ModItems.TREASURE_DISK.get()
);
event.register( ( stack, layer ) -> {
switch( layer )
{
event.register((stack, layer) -> {
switch (layer) {
case 0:
default:
return 0xFFFFFF;
case 1: // Frame colour
return IColouredItem.getColourBasic( stack );
case 2: // Light colour
{
int light = ClientPocketComputers.get( stack ).getLightState();
return IColouredItem.getColourBasic(stack);
case 2: { // Light colour
var light = ClientPocketComputers.get(stack).getLightState();
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
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()
);
}
@SubscribeEvent
public static void setupClient( FMLClientSetupEvent event )
{
public static void setupClient(FMLClientSetupEvent event) {
// Setup TESRs
BlockEntityRenderers.register( Registry.ModBlockEntities.MONITOR_NORMAL.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_ADVANCED.get(), TileEntityTurtleRenderer::new );
BlockEntityRenderers.register(Registry.ModBlockEntities.MONITOR_NORMAL.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_ADVANCED.get(), TileEntityTurtleRenderer::new);
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_right" )
) );
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_right" )
) );
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.TOOL.get(), TurtleUpgradeModeller.flatItem() );
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_right")
));
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_right")
));
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.TOOL.get(), TurtleUpgradeModeller.flatItem());
event.enqueueWork( () -> {
event.enqueueWork(() -> {
registerContainers();
registerItemProperty( "state",
( stack, world, player, random ) -> ClientPocketComputers.get( stack ).getState().ordinal(),
registerItemProperty("state",
(stack, world, player, random) -> ClientPocketComputers.get(stack).getState().ordinal(),
Registry.ModItems.POCKET_COMPUTER_NORMAL, Registry.ModItems.POCKET_COMPUTER_ADVANCED
);
registerItemProperty( "coloured",
( stack, world, player, random ) -> IColouredItem.getColourBasic( stack ) != -1 ? 1 : 0,
registerItemProperty("coloured",
(stack, world, player, random) -> IColouredItem.getColourBasic(stack) != -1 ? 1 : 0,
Registry.ModItems.POCKET_COMPUTER_NORMAL, Registry.ModItems.POCKET_COMPUTER_ADVANCED
);
} );
});
}
@SafeVarargs
private static void registerItemProperty( String name, ItemPropertyFunction getter, Supplier<? extends Item>... items )
{
ResourceLocation id = new ResourceLocation( ComputerCraft.MOD_ID, name );
for( Supplier<? extends Item> item : items )
{
ItemProperties.register( item.get(), id, getter );
private static void registerItemProperty(String name, ItemPropertyFunction getter, Supplier<? extends Item>... items) {
var id = new ResourceLocation(ComputerCraft.MOD_ID, name);
for (var item : items) {
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.
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, NoTermComputerScreen<ContainerComputerBase>>register( Registry.ModContainers.POCKET_COMPUTER_NO_TERM.get(), NoTermComputerScreen::new );
MenuScreens.register( Registry.ModContainers.TURTLE.get(), GuiTurtle::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, NoTermComputerScreen<ContainerComputerBase>>register(Registry.ModContainers.POCKET_COMPUTER_NO_TERM.get(), NoTermComputerScreen::new);
MenuScreens.register(Registry.ModContainers.TURTLE.get(), GuiTurtle::new);
MenuScreens.register( Registry.ModContainers.PRINTER.get(), GuiPrinter::new );
MenuScreens.register( Registry.ModContainers.DISK_DRIVE.get(), GuiDiskDrive::new );
MenuScreens.register( Registry.ModContainers.PRINTOUT.get(), GuiPrintout::new );
MenuScreens.register(Registry.ModContainers.PRINTER.get(), GuiPrinter::new);
MenuScreens.register(Registry.ModContainers.DISK_DRIVE.get(), GuiDiskDrive::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.Minecraft;
import net.minecraft.client.gui.Font;
import net.minecraft.client.gui.components.ChatComponent;
import net.minecraft.network.chat.Component;
import net.minecraft.util.Mth;
import org.apache.commons.lang3.StringUtils;
@ -20,72 +19,63 @@ import org.apache.commons.lang3.StringUtils;
import javax.annotation.Nullable;
import java.util.Objects;
public class ClientTableFormatter implements TableFormatter
{
public class ClientTableFormatter implements TableFormatter {
public static final ClientTableFormatter INSTANCE = new ClientTableFormatter();
private static Font renderer()
{
private static Font renderer() {
return Minecraft.getInstance().font;
}
@Override
@Nullable
public Component getPadding( Component component, int width )
{
int extraWidth = width - getWidth( component );
if( extraWidth <= 0 ) return null;
public Component getPadding(Component component, int width) {
var extraWidth = width - getWidth(component);
if (extraWidth <= 0) return null;
Font renderer = renderer();
var renderer = renderer();
float spaceWidth = renderer.width( " " );
int spaces = Mth.floor( extraWidth / spaceWidth );
int extra = extraWidth - (int) (spaces * spaceWidth);
float spaceWidth = renderer.width(" ");
var spaces = Mth.floor(extraWidth / 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
public int getColumnPadding()
{
public int getColumnPadding() {
return 3;
}
@Override
public int getWidth( Component component )
{
return renderer().width( component );
public int getWidth(Component component) {
return renderer().width(component);
}
@Override
public void writeLine( String label, Component component )
{
Minecraft mc = Minecraft.getInstance();
ChatComponent chat = mc.gui.getChat();
public void writeLine(String label, Component component) {
var mc = Minecraft.getInstance();
var chat = mc.gui.getChat();
// TODO: Trim the text if it goes over the allowed length
// int maxWidth = MathHelper.floor( chat.getChatWidth() / chat.getScale() );
// List<ITextProperties> list = RenderComponentsUtil.wrapComponents( component, maxWidth, mc.fontRenderer );
// if( !list.isEmpty() ) chat.printChatMessageWithOptionalDeletion( list.get( 0 ), id );
chat.addMessage( component, null, createTag( label ) );
chat.addMessage(component, null, createTag(label));
}
@Override
public void display( TableBuilder table )
{
ChatComponent chat = Minecraft.getInstance().gui.getChat();
public void display(TableBuilder table) {
var chat = Minecraft.getInstance().gui.getChat();
var tag = createTag( table.getId() );
if( chat.allMessages.removeIf( guiMessage -> guiMessage.tag() != null && Objects.equals( guiMessage.tag().logTag(), tag.logTag() ) ) )
{
var tag = createTag(table.getId());
if (chat.allMessages.removeIf(guiMessage -> guiMessage.tag() != null && Objects.equals(guiMessage.tag().logTag(), tag.logTag()))) {
chat.refreshTrimmedMessage();
}
TableFormatter.super.display( table );
TableFormatter.super.display(table);
}
private static GuiMessageTag createTag( String id )
{
return new GuiMessageTag( 0xa0a0a0, null, null, "ComputerCraft/" + id );
private static GuiMessageTag createTag(String 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;
@AutoService( ComputerCraftAPIClientService.class )
public final class ComputerCraftAPIClientImpl implements ComputerCraftAPIClientService
{
@AutoService(ComputerCraftAPIClientService.class)
public final class ComputerCraftAPIClientImpl implements ComputerCraftAPIClientService {
@Override
public <T extends ITurtleUpgrade> void registerTurtleUpgradeModeller( @Nonnull TurtleUpgradeSerialiser<T> serialiser, @Nonnull TurtleUpgradeModeller<T> modeller )
{
TurtleUpgradeModellers.register( serialiser, modeller );
public <T extends ITurtleUpgrade> void registerTurtleUpgradeModeller(@Nonnull TurtleUpgradeSerialiser<T> serialiser, @Nonnull TurtleUpgradeModeller<T> 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.fml.common.Mod;
@Mod.EventBusSubscriber( modid = ComputerCraft.MOD_ID, value = Dist.CLIENT )
public final class FrameInfo
{
@Mod.EventBusSubscriber(modid = ComputerCraft.MOD_ID, value = Dist.CLIENT)
public final class FrameInfo {
private static int tick;
private static long renderFrame;
private FrameInfo()
{
private FrameInfo() {
}
public static boolean getGlobalCursorBlink()
{
public static boolean getGlobalCursorBlink() {
return (tick / 8) % 2 == 0;
}
public static long getRenderFrame()
{
public static long getRenderFrame() {
return renderFrame;
}
@SubscribeEvent
public static void onTick( TickEvent.ClientTickEvent event )
{
if( event.phase == TickEvent.Phase.START ) tick++;
public static void onTick(TickEvent.ClientTickEvent event) {
if (event.phase == TickEvent.Phase.START) tick++;
}
@SubscribeEvent
public static void onRenderTick( TickEvent.RenderTickEvent event )
{
if( event.phase == TickEvent.Phase.START ) renderFrame++;
public static void onRenderTick(TickEvent.RenderTickEvent event) {
if (event.phase == TickEvent.Phase.START) renderFrame++;
}
}

View File

@ -21,72 +21,60 @@ import javax.annotation.Nullable;
* <p>
* 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;
public ClientInputHandler( AbstractContainerMenu menu )
{
public ClientInputHandler(AbstractContainerMenu menu) {
this.menu = menu;
}
@Override
public void turnOn()
{
NetworkHandler.sendToServer( new ComputerActionServerMessage( menu, ComputerActionServerMessage.Action.TURN_ON ) );
public void turnOn() {
NetworkHandler.sendToServer(new ComputerActionServerMessage(menu, ComputerActionServerMessage.Action.TURN_ON));
}
@Override
public void shutdown()
{
NetworkHandler.sendToServer( new ComputerActionServerMessage( menu, ComputerActionServerMessage.Action.SHUTDOWN ) );
public void shutdown() {
NetworkHandler.sendToServer(new ComputerActionServerMessage(menu, ComputerActionServerMessage.Action.SHUTDOWN));
}
@Override
public void reboot()
{
NetworkHandler.sendToServer( new ComputerActionServerMessage( menu, ComputerActionServerMessage.Action.REBOOT ) );
public void reboot() {
NetworkHandler.sendToServer(new ComputerActionServerMessage(menu, ComputerActionServerMessage.Action.REBOOT));
}
@Override
public void queueEvent( String event, @Nullable Object[] arguments )
{
NetworkHandler.sendToServer( new QueueEventServerMessage( menu, event, arguments ) );
public void queueEvent(String event, @Nullable Object[] arguments) {
NetworkHandler.sendToServer(new QueueEventServerMessage(menu, event, arguments));
}
@Override
public void keyDown( int key, boolean repeat )
{
NetworkHandler.sendToServer( new KeyEventServerMessage( menu, repeat ? KeyEventServerMessage.TYPE_REPEAT : KeyEventServerMessage.TYPE_DOWN, key ) );
public void keyDown(int key, boolean repeat) {
NetworkHandler.sendToServer(new KeyEventServerMessage(menu, repeat ? KeyEventServerMessage.TYPE_REPEAT : KeyEventServerMessage.TYPE_DOWN, key));
}
@Override
public void keyUp( int key )
{
NetworkHandler.sendToServer( new KeyEventServerMessage( menu, KeyEventServerMessage.TYPE_UP, key ) );
public void keyUp(int key) {
NetworkHandler.sendToServer(new KeyEventServerMessage(menu, KeyEventServerMessage.TYPE_UP, key));
}
@Override
public void mouseClick( int button, int x, int y )
{
NetworkHandler.sendToServer( new MouseEventServerMessage( menu, MouseEventServerMessage.TYPE_CLICK, button, x, y ) );
public void mouseClick(int button, int x, int y) {
NetworkHandler.sendToServer(new MouseEventServerMessage(menu, MouseEventServerMessage.TYPE_CLICK, button, x, y));
}
@Override
public void mouseUp( int button, int x, int y )
{
NetworkHandler.sendToServer( new MouseEventServerMessage( menu, MouseEventServerMessage.TYPE_UP, button, x, y ) );
public void mouseUp(int button, int x, int y) {
NetworkHandler.sendToServer(new MouseEventServerMessage(menu, MouseEventServerMessage.TYPE_UP, button, x, y));
}
@Override
public void mouseDrag( int button, int x, int y )
{
NetworkHandler.sendToServer( new MouseEventServerMessage( menu, MouseEventServerMessage.TYPE_DRAG, button, x, y ) );
public void mouseDrag(int button, int x, int y) {
NetworkHandler.sendToServer(new MouseEventServerMessage(menu, MouseEventServerMessage.TYPE_DRAG, button, x, y));
}
@Override
public void mouseScroll( int direction, int x, int y )
{
NetworkHandler.sendToServer( new MouseEventServerMessage( menu, MouseEventServerMessage.TYPE_SCROLL, direction, x, y ) );
public void mouseScroll(int direction, int x, int 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 java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.SeekableByteChannel;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
@ -38,12 +37,11 @@ import java.util.Collections;
import java.util.List;
import java.util.concurrent.TimeUnit;
public abstract class ComputerScreenBase<T extends ContainerComputerBase> extends AbstractContainerScreen<T>
{
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_MSG = Component.translatable( "gui.computercraft.upload.no_response.msg",
Component.literal( "import" ).withStyle( ChatFormatting.DARK_GRAY ) );
public abstract class ComputerScreenBase<T extends ContainerComputerBase> extends AbstractContainerScreen<T> {
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_MSG = Component.translatable("gui.computercraft.upload.no_response.msg",
Component.literal("import").withStyle(ChatFormatting.DARK_GRAY));
protected WidgetTerminal terminal;
protected Terminal terminalData;
@ -55,187 +53,154 @@ public abstract class ComputerScreenBase<T extends ContainerComputerBase> extend
private long uploadNagDeadline = Long.MAX_VALUE;
private final ItemStack displayStack;
public ComputerScreenBase( T container, Inventory player, Component title, int sidebarYOffset )
{
super( container, player, title );
public ComputerScreenBase(T container, Inventory player, Component title, int sidebarYOffset) {
super(container, player, title);
terminalData = container.getTerminal();
family = container.getFamily();
displayStack = container.getDisplayStack();
input = new ClientInputHandler( menu );
input = new ClientInputHandler(menu);
this.sidebarYOffset = sidebarYOffset;
}
protected abstract WidgetTerminal createTerminal();
@Override
protected void init()
{
protected void init() {
super.init();
minecraft.keyboardHandler.setSendRepeatsToGui( true );
minecraft.keyboardHandler.setSendRepeatsToGui(true);
terminal = addRenderableWidget( createTerminal() );
ComputerSidebar.addButtons( this, menu::isOn, input, this::addRenderableWidget, leftPos, topPos + sidebarYOffset );
setFocused( terminal );
terminal = addRenderableWidget(createTerminal());
ComputerSidebar.addButtons(this, menu::isOn, input, this::addRenderableWidget, leftPos, topPos + sidebarYOffset);
setFocused(terminal);
}
@Override
public void removed()
{
public void removed() {
super.removed();
minecraft.keyboardHandler.setSendRepeatsToGui( false );
minecraft.keyboardHandler.setSendRepeatsToGui(false);
}
@Override
public void containerTick()
{
public void containerTick() {
super.containerTick();
terminal.update();
if( uploadNagDeadline != Long.MAX_VALUE && Util.getNanos() >= uploadNagDeadline )
{
new ItemToast( minecraft, displayStack, NO_RESPONSE_TITLE, NO_RESPONSE_MSG, ItemToast.TRANSFER_NO_RESPONSE_TOKEN )
.showOrReplace( minecraft.getToasts() );
if (uploadNagDeadline != Long.MAX_VALUE && Util.getNanos() >= uploadNagDeadline) {
new ItemToast(minecraft, displayStack, NO_RESPONSE_TITLE, NO_RESPONSE_MSG, ItemToast.TRANSFER_NO_RESPONSE_TOKEN)
.showOrReplace(minecraft.getToasts());
uploadNagDeadline = Long.MAX_VALUE;
}
}
@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.
if( key == GLFW.GLFW_KEY_TAB && getFocused() != null && getFocused() == terminal )
{
return getFocused().keyPressed( key, scancode, modifiers );
if (key == GLFW.GLFW_KEY_TAB && getFocused() != null && getFocused() == terminal) {
return getFocused().keyPressed(key, scancode, modifiers);
}
return super.keyPressed( key, scancode, modifiers );
return super.keyPressed(key, scancode, modifiers);
}
@Override
public void render( @Nonnull PoseStack stack, int mouseX, int mouseY, float partialTicks )
{
renderBackground( stack );
super.render( stack, mouseX, mouseY, partialTicks );
renderTooltip( stack, mouseX, mouseY );
public void render(@Nonnull PoseStack stack, int mouseX, int mouseY, float partialTicks) {
renderBackground(stack);
super.render(stack, mouseX, mouseY, partialTicks);
renderTooltip(stack, mouseX, mouseY);
}
@Override
public boolean mouseClicked( double x, double y, int button )
{
boolean changed = super.mouseClicked( x, y, button );
public boolean mouseClicked(double x, double y, int button) {
var changed = super.mouseClicked(x, y, 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.
if( getFocused() instanceof DynamicImageButton ) setFocused( terminal );
if (getFocused() instanceof DynamicImageButton) setFocused(terminal);
return changed;
}
@Override
public boolean mouseDragged( double x, double y, int button, double deltaX, double deltaY )
{
return (getFocused() != null && getFocused().mouseDragged( x, y, button, deltaX, deltaY ))
|| super.mouseDragged( x, y, button, deltaX, deltaY );
public boolean mouseDragged(double x, double y, int button, double deltaX, double deltaY) {
return (getFocused() != null && getFocused().mouseDragged(x, y, button, deltaX, deltaY))
|| super.mouseDragged(x, y, button, deltaX, deltaY);
}
@Override
protected void renderLabels( @Nonnull PoseStack transform, int mouseX, int mouseY )
{
protected void renderLabels(@Nonnull PoseStack transform, int mouseX, int mouseY) {
// Skip rendering labels.
}
@Override
public void onFilesDrop( @Nonnull List<Path> files )
{
if( files.isEmpty() ) return;
public void onFilesDrop(@Nonnull List<Path> files) {
if (files.isEmpty()) return;
if( !menu.isOn() )
{
alert( UploadResult.FAILED_TITLE, UploadResult.COMPUTER_OFF_MSG );
if (!menu.isOn()) {
alert(UploadResult.FAILED_TITLE, UploadResult.COMPUTER_OFF_MSG);
return;
}
long size = 0;
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.
if( !Files.isRegularFile( file ) ) continue;
if (!Files.isRegularFile(file)) continue;
try( SeekableByteChannel sbc = Files.newByteChannel( file ) )
{
long fileSize = sbc.size();
if( fileSize > UploadFileMessage.MAX_SIZE || (size += fileSize) >= UploadFileMessage.MAX_SIZE )
{
alert( UploadResult.FAILED_TITLE, UploadResult.TOO_MUCH_MSG );
try (var sbc = Files.newByteChannel(file)) {
var fileSize = sbc.size();
if (fileSize > UploadFileMessage.MAX_SIZE || (size += fileSize) >= UploadFileMessage.MAX_SIZE) {
alert(UploadResult.FAILED_TITLE, UploadResult.TOO_MUCH_MSG);
return;
}
String name = file.getFileName().toString();
if( name.length() > UploadFileMessage.MAX_FILE_NAME )
{
alert( UploadResult.FAILED_TITLE, Component.translatable( "gui.computercraft.upload.failed.name_too_long" ) );
var name = file.getFileName().toString();
if (name.length() > UploadFileMessage.MAX_FILE_NAME) {
alert(UploadResult.FAILED_TITLE, Component.translatable("gui.computercraft.upload.failed.name_too_long"));
return;
}
ByteBuffer buffer = ByteBuffer.allocateDirect( (int) fileSize );
sbc.read( buffer );
var buffer = ByteBuffer.allocateDirect((int) fileSize);
sbc.read(buffer);
buffer.flip();
byte[] digest = FileUpload.getDigest( buffer );
if( digest == null )
{
alert( UploadResult.FAILED_TITLE, Component.translatable( "gui.computercraft.upload.failed.corrupted" ) );
var digest = FileUpload.getDigest(buffer);
if (digest == null) {
alert(UploadResult.FAILED_TITLE, Component.translatable("gui.computercraft.upload.failed.corrupted"));
return;
}
toUpload.add( new FileUpload( name, buffer, digest ) );
}
catch( IOException e )
{
ComputerCraft.log.error( "Failed uploading files", e );
alert( UploadResult.FAILED_TITLE, Component.translatable( "gui.computercraft.upload.failed.generic", "Cannot compute checksum" ) );
toUpload.add(new FileUpload(name, buffer, digest));
} catch (IOException e) {
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 )
{
alert( UploadResult.FAILED_TITLE, Component.translatable( "gui.computercraft.upload.failed.too_many_files" ) );
if (toUpload.size() > UploadFileMessage.MAX_FILES) {
alert(UploadResult.FAILED_TITLE, Component.translatable("gui.computercraft.upload.failed.too_many_files"));
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 )
{
switch( result )
{
case QUEUED:
{
if( ComputerCraft.uploadNagDelay > 0 )
{
uploadNagDeadline = Util.getNanos() + TimeUnit.SECONDS.toNanos( ComputerCraft.uploadNagDelay );
public void uploadResult(UploadResult result, @Nullable Component message) {
switch (result) {
case QUEUED -> {
if (ComputerCraft.uploadNagDelay > 0) {
uploadNagDeadline = Util.getNanos() + TimeUnit.SECONDS.toNanos(ComputerCraft.uploadNagDelay);
}
break;
}
case CONSUMED:
{
uploadNagDeadline = Long.MAX_VALUE;
break;
}
case ERROR:
alert( UploadResult.FAILED_TITLE, message );
break;
case CONSUMED -> uploadNagDeadline = Long.MAX_VALUE;
case ERROR -> alert(UploadResult.FAILED_TITLE, message);
}
}
private void alert( Component title, Component message )
{
OptionScreen.show( minecraft, title, message,
Collections.singletonList( OptionScreen.newButton( OK, b -> minecraft.setScreen( this ) ) ),
() -> minecraft.setScreen( this )
private void alert(Component title, Component message) {
OptionScreen.show(minecraft, title, message,
Collections.singletonList(OptionScreen.newButton(OK, b -> 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.RenderTypes.FULL_BRIGHT_LIGHTMAP;
public final class GuiComputer<T extends ContainerComputerBase> extends ComputerScreenBase<T>
{
public GuiComputer( T container, Inventory player, Component title )
{
super( container, player, title, BORDER );
public final class GuiComputer<T extends ContainerComputerBase> extends ComputerScreenBase<T> {
public GuiComputer(T container, Inventory player, Component title) {
super(container, player, title, BORDER);
imageWidth = WidgetTerminal.getWidth( terminalData.getWidth() ) + BORDER * 2 + ComputerSidebar.WIDTH;
imageHeight = WidgetTerminal.getHeight( terminalData.getHeight() ) + BORDER * 2;
imageWidth = WidgetTerminal.getWidth(terminalData.getWidth()) + BORDER * 2 + ComputerSidebar.WIDTH;
imageHeight = WidgetTerminal.getHeight(terminalData.getHeight()) + BORDER * 2;
}
@Override
protected WidgetTerminal createTerminal()
{
return new WidgetTerminal( terminalData, input, leftPos + ComputerSidebar.WIDTH + BORDER, topPos + BORDER );
protected WidgetTerminal createTerminal() {
return new WidgetTerminal(terminalData, input, leftPos + ComputerSidebar.WIDTH + BORDER, topPos + BORDER);
}
@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
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()
);
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;
public class GuiDiskDrive extends AbstractContainerScreen<ContainerDiskDrive>
{
private static final ResourceLocation BACKGROUND = new ResourceLocation( "computercraft", "textures/gui/disk_drive.png" );
public class GuiDiskDrive extends AbstractContainerScreen<ContainerDiskDrive> {
private static final ResourceLocation BACKGROUND = new ResourceLocation("computercraft", "textures/gui/disk_drive.png");
public GuiDiskDrive( ContainerDiskDrive container, Inventory player, Component title )
{
super( container, player, title );
public GuiDiskDrive(ContainerDiskDrive container, Inventory player, Component title) {
super(container, player, title);
}
@Override
protected void renderBg( @Nonnull PoseStack transform, float partialTicks, int mouseX, int mouseY )
{
RenderSystem.setShaderColor( 1.0F, 1.0F, 1.0F, 1.0F );
RenderSystem.setShaderTexture( 0, BACKGROUND );
blit( transform, leftPos, topPos, 0, 0, imageWidth, imageHeight );
protected void renderBg(@Nonnull PoseStack transform, float partialTicks, int mouseX, int mouseY) {
RenderSystem.setShaderColor(1.0F, 1.0F, 1.0F, 1.0F);
RenderSystem.setShaderTexture(0, BACKGROUND);
blit(transform, leftPos, topPos, 0, 0, imageWidth, imageHeight);
}
@Override
public void render( @Nonnull PoseStack transform, int mouseX, int mouseY, float partialTicks )
{
renderBackground( transform );
super.render( transform, mouseX, mouseY, partialTicks );
renderTooltip( transform, mouseX, mouseY );
public void render(@Nonnull PoseStack transform, int mouseX, int mouseY, float partialTicks) {
renderBackground(transform);
super.render(transform, mouseX, mouseY, partialTicks);
renderTooltip(transform, mouseX, mouseY);
}
}

View File

@ -15,30 +15,26 @@ import net.minecraft.world.entity.player.Inventory;
import javax.annotation.Nonnull;
public class GuiPrinter extends AbstractContainerScreen<ContainerPrinter>
{
private static final ResourceLocation BACKGROUND = new ResourceLocation( "computercraft", "textures/gui/printer.png" );
public class GuiPrinter extends AbstractContainerScreen<ContainerPrinter> {
private static final ResourceLocation BACKGROUND = new ResourceLocation("computercraft", "textures/gui/printer.png");
public GuiPrinter( ContainerPrinter container, Inventory player, Component title )
{
super( container, player, title );
public GuiPrinter(ContainerPrinter container, Inventory player, Component title) {
super(container, player, title);
}
@Override
protected void renderBg( @Nonnull PoseStack transform, float partialTicks, int mouseX, int mouseY )
{
RenderSystem.setShaderColor( 1.0F, 1.0F, 1.0F, 1.0F );
RenderSystem.setShaderTexture( 0, BACKGROUND );
blit( transform, leftPos, topPos, 0, 0, imageWidth, imageHeight );
protected void renderBg(@Nonnull PoseStack transform, float partialTicks, int mouseX, int mouseY) {
RenderSystem.setShaderColor(1.0F, 1.0F, 1.0F, 1.0F);
RenderSystem.setShaderTexture(0, BACKGROUND);
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
public void render( @Nonnull PoseStack stack, int mouseX, int mouseY, float partialTicks )
{
renderBackground( stack );
super.render( stack, mouseX, mouseY, partialTicks );
renderTooltip( stack, mouseX, mouseY );
public void render(@Nonnull PoseStack stack, int mouseX, int mouseY, float partialTicks) {
renderBackground(stack);
super.render(stack, mouseX, mouseY, partialTicks);
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.RenderTypes.FULL_BRIGHT_LIGHTMAP;
public class GuiPrintout extends AbstractContainerScreen<ContainerHeldItem>
{
public class GuiPrintout extends AbstractContainerScreen<ContainerHeldItem> {
private final boolean book;
private final int pages;
private final TextBuffer[] text;
private final TextBuffer[] colours;
private int page;
public GuiPrintout( ContainerHeldItem container, Inventory player, Component title )
{
super( container, player, title );
public GuiPrintout(ContainerHeldItem container, Inventory player, Component title) {
super(container, player, title);
imageHeight = Y_SIZE;
String[] text = ItemPrintout.getText( container.getStack() );
var text = ItemPrintout.getText(container.getStack());
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];
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;
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;
}
@Override
public boolean keyPressed( int key, int scancode, int modifiers )
{
if( super.keyPressed( key, scancode, modifiers ) ) return true;
public boolean keyPressed(int key, int scancode, int modifiers) {
if (super.keyPressed(key, scancode, modifiers)) return true;
if( key == GLFW.GLFW_KEY_RIGHT )
{
if( page < pages - 1 ) page++;
if (key == GLFW.GLFW_KEY_RIGHT) {
if (page < pages - 1) page++;
return true;
}
if( key == GLFW.GLFW_KEY_LEFT )
{
if( page > 0 ) page--;
if (key == GLFW.GLFW_KEY_LEFT) {
if (page > 0) page--;
return true;
}
@ -70,20 +65,17 @@ public class GuiPrintout extends AbstractContainerScreen<ContainerHeldItem>
}
@Override
public boolean mouseScrolled( double x, double y, double delta )
{
if( super.mouseScrolled( x, y, delta ) ) return true;
if( delta < 0 )
{
public boolean mouseScrolled(double x, double y, double delta) {
if (super.mouseScrolled(x, y, delta)) return true;
if (delta < 0) {
// Scroll up goes to the next page
if( page < pages - 1 ) page++;
if (page < pages - 1) page++;
return true;
}
if( delta > 0 )
{
if (delta > 0) {
// Scroll down goes to the previous page
if( page > 0 ) page--;
if (page > 0) page--;
return true;
}
@ -91,32 +83,29 @@ public class GuiPrintout extends AbstractContainerScreen<ContainerHeldItem>
}
@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
RenderSystem.setShaderColor( 1.0f, 1.0f, 1.0f, 1.0f );
RenderSystem.setShaderColor(1.0f, 1.0f, 1.0f, 1.0f);
RenderSystem.enableDepthTest();
MultiBufferSource.BufferSource renderer = MultiBufferSource.immediate( Tesselator.getInstance().getBuilder() );
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 );
var renderer = MultiBufferSource.immediate(Tesselator.getInstance().getBuilder());
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);
renderer.endBatch();
}
@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.
setBlitOffset( getBlitOffset() - 1 );
renderBackground( stack );
setBlitOffset( getBlitOffset() + 1 );
setBlitOffset(getBlitOffset() - 1);
renderBackground(stack);
setBlitOffset(getBlitOffset() + 1);
super.render( stack, mouseX, mouseY, partialTicks );
super.render(stack, mouseX, mouseY, partialTicks);
}
@Override
protected void renderLabels( @Nonnull PoseStack transform, int mouseX, int mouseY )
{
protected void renderLabels(@Nonnull PoseStack transform, int mouseX, int mouseY) {
// Skip rendering labels.
}
}

View File

@ -21,19 +21,17 @@ import javax.annotation.Nonnull;
import static dan200.computercraft.shared.turtle.inventory.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_ADVANCED = new ResourceLocation( ComputerCraft.MOD_ID, "textures/gui/turtle_advanced.png" );
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_ADVANCED = new ResourceLocation(ComputerCraft.MOD_ID, "textures/gui/turtle_advanced.png");
private static final int TEX_WIDTH = 254;
private static final int TEX_HEIGHT = 217;
private final ComputerFamily family;
public GuiTurtle( ContainerTurtle container, Inventory player, Component title )
{
super( container, player, title, BORDER );
public GuiTurtle(ContainerTurtle container, Inventory player, Component title) {
super(container, player, title, BORDER);
family = container.getFamily();
imageWidth = TEX_WIDTH + ComputerSidebar.WIDTH;
@ -41,31 +39,28 @@ public class GuiTurtle extends ComputerScreenBase<ContainerTurtle>
}
@Override
protected WidgetTerminal createTerminal()
{
return new WidgetTerminal( terminalData, input, leftPos + BORDER + ComputerSidebar.WIDTH, topPos + BORDER );
protected WidgetTerminal createTerminal() {
return new WidgetTerminal(terminalData, input, leftPos + BORDER + ComputerSidebar.WIDTH, topPos + BORDER);
}
@Override
protected void renderBg( @Nonnull PoseStack transform, float partialTicks, int mouseX, int mouseY )
{
boolean advanced = family == ComputerFamily.ADVANCED;
RenderSystem.setShaderTexture( 0, advanced ? BACKGROUND_ADVANCED : BACKGROUND_NORMAL );
blit( transform, leftPos + ComputerSidebar.WIDTH, topPos, 0, 0, TEX_WIDTH, TEX_HEIGHT );
protected void renderBg(@Nonnull PoseStack transform, float partialTicks, int mouseX, int mouseY) {
var advanced = family == ComputerFamily.ADVANCED;
RenderSystem.setShaderTexture(0, advanced ? BACKGROUND_ADVANCED : BACKGROUND_NORMAL);
blit(transform, leftPos + ComputerSidebar.WIDTH, topPos, 0, 0, TEX_WIDTH, TEX_HEIGHT);
int slot = getMenu().getSelectedSlot();
if( slot >= 0 )
{
RenderSystem.setShaderColor( 1.0F, 1.0F, 1.0F, 1.0F );
int slotX = slot % 4;
int slotY = slot / 4;
blit( transform,
var slot = getMenu().getSelectedSlot();
if (slot >= 0) {
RenderSystem.setShaderColor(1.0F, 1.0F, 1.0F, 1.0F);
var slotX = slot % 4;
var slotY = slot / 4;
blit(transform,
leftPos + TURTLE_START_X - 2 + slotX * 18, topPos + PLAYER_START_Y - 2 + slotY * 18,
0, 217, 24, 24
);
}
RenderSystem.setShaderTexture( 0, advanced ? ComputerBorderRenderer.BACKGROUND_ADVANCED : ComputerBorderRenderer.BACKGROUND_NORMAL );
ComputerSidebar.renderBackground( transform, leftPos, topPos + sidebarYOffset );
RenderSystem.setShaderTexture(0, advanced ? ComputerBorderRenderer.BACKGROUND_ADVANCED : ComputerBorderRenderer.BACKGROUND_NORMAL);
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.vertex.PoseStack;
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.ToastComponent;
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}.
*/
public class ItemToast implements Toast
{
public class ItemToast implements Toast {
public static final Object TRANSFER_NO_RESPONSE_TOKEN = new Object();
private static final long DISPLAY_TIME = 7000L;
@ -41,110 +39,92 @@ public class ItemToast implements Toast
private boolean isNew = true;
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.title = title;
this.token = token;
Font font = minecraft.font;
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;
var font = minecraft.font;
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;
}
public void showOrReplace( ToastComponent toasts )
{
ItemToast existing = toasts.getToast( ItemToast.class, getToken() );
if( existing != null )
{
public void showOrReplace(ToastComponent toasts) {
var existing = toasts.getToast(ItemToast.class, getToken());
if (existing != null) {
existing.isNew = true;
}
else
{
toasts.addToast( this );
} else {
toasts.addToast(this);
}
}
@Override
public int width()
{
public int width() {
return width;
}
@Override
public int height()
{
public int height() {
return MARGIN * 2 + LINE_SPACING + message.size() * LINE_SPACING;
}
@Nonnull
@Override
public Object getToken()
{
public Object getToken() {
return token;
}
@Nonnull
@Override
public Visibility render( @Nonnull PoseStack transform, @Nonnull ToastComponent component, long time )
{
if( isNew )
{
public Visibility render(@Nonnull PoseStack transform, @Nonnull ToastComponent component, long time) {
if (isNew) {
firstDisplay = time;
isNew = false;
}
RenderSystem.setShaderTexture( 0, TEXTURE );
RenderSystem.setShaderColor( 1.0F, 1.0F, 1.0F, 1.0F );
RenderSystem.setShaderTexture(0, TEXTURE);
RenderSystem.setShaderColor(1.0F, 1.0F, 1.0F, 1.0F);
if( width == 160 && message.size() <= 1 )
{
component.blit( transform, 0, 0, 0, 64, width, height() );
}
else
{
if (width == 160 && message.size() <= 1) {
component.blit(transform, 0, 0, 0, 64, width, height());
} else {
int height = height();
var height = height();
int bottom = Math.min( 4, height - 28 );
renderBackgroundRow( transform, component, width, 0, 0, 28 );
var bottom = Math.min(4, height - 28);
renderBackgroundRow(transform, component, width, 0, 0, 28);
for( int i = 28; i < height - bottom; i += 10 )
{
renderBackgroundRow( transform, component, width, 16, i, Math.min( 16, height - i - bottom ) );
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, 32 - bottom, height - bottom, bottom );
renderBackgroundRow(transform, component, width, 32 - bottom, height - bottom, bottom);
}
int textX = MARGIN;
if( !stack.isEmpty() )
{
var textX = MARGIN;
if (!stack.isEmpty()) {
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 );
for( int 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, title, textX, MARGIN, 0xff500050);
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);
}
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 )
{
int leftOffset = 5;
int rightOffset = Math.min( 60, x - leftOffset );
private static void renderBackgroundRow(PoseStack transform, ToastComponent component, int x, int u, int y, int height) {
var leftOffset = 5;
var rightOffset = Math.min(60, x - leftOffset);
component.blit( transform, 0, y, 0, 32 + u, leftOffset, height );
for( int 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, 0, y, 0, 32 + u, leftOffset, height);
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, 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.shared.computer.inventory.ContainerComputerBase;
import net.minecraft.client.KeyMapping;
import net.minecraft.client.gui.Font;
import net.minecraft.client.gui.screens.Screen;
import net.minecraft.client.gui.screens.inventory.MenuAccess;
import net.minecraft.network.chat.Component;
import net.minecraft.util.FormattedCharSequence;
import net.minecraft.world.entity.player.Inventory;
import org.lwjgl.glfw.GLFW;
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 Terminal terminalData;
private WidgetTerminal terminal;
public NoTermComputerScreen( T menu, Inventory player, Component title )
{
super( title );
public NoTermComputerScreen(T menu, Inventory player, Component title) {
super(title);
this.menu = menu;
terminalData = menu.getTerminal();
}
@Nonnull
@Override
public T getMenu()
{
public T getMenu() {
return menu;
}
@Override
protected void init()
{
protected void init() {
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
// grabbing unsets.
@ -52,71 +45,62 @@ public class NoTermComputerScreen<T extends ContainerComputerBase> extends Scree
KeyMapping.releaseAll();
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.active = false;
setFocused( terminal );
setFocused(terminal);
}
@Override
public final void removed()
{
public final void removed() {
super.removed();
minecraft.keyboardHandler.setSendRepeatsToGui( false );
minecraft.keyboardHandler.setSendRepeatsToGui(false);
}
@Override
public final void tick()
{
public final void tick() {
super.tick();
terminal.update();
}
@Override
public boolean mouseScrolled( double pMouseX, double pMouseY, double pDelta )
{
minecraft.player.getInventory().swapPaint( pDelta );
return super.mouseScrolled( pMouseX, pMouseY, pDelta );
public boolean mouseScrolled(double pMouseX, double pMouseY, double pDelta) {
minecraft.player.getInventory().swapPaint(pDelta);
return super.mouseScrolled(pMouseX, pMouseY, pDelta);
}
@Override
public void onClose()
{
public void onClose() {
minecraft.player.closeContainer();
super.onClose();
}
@Override
public boolean isPauseScreen()
{
public boolean isPauseScreen() {
return false;
}
@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.
if( key == GLFW.GLFW_KEY_TAB && getFocused() != null && getFocused() == terminal )
{
return getFocused().keyPressed( key, scancode, modifiers );
if (key == GLFW.GLFW_KEY_TAB && getFocused() != null && getFocused() == terminal) {
return getFocused().keyPressed(key, scancode, modifiers);
}
return super.keyPressed( key, scancode, modifiers );
return super.keyPressed(key, scancode, modifiers);
}
@Override
public void render( @Nonnull PoseStack transform, int mouseX, int mouseY, float partialTicks )
{
super.render( transform, mouseX, mouseY, partialTicks );
public void render(@Nonnull PoseStack transform, int mouseX, int mouseY, float partialTicks) {
super.render(transform, mouseX, mouseY, partialTicks);
Font font = minecraft.font;
List<FormattedCharSequence> lines = font.split( Component.translatable( "gui.computercraft.pocket_computer_overlay" ), (int) (width * 0.8) );
float y = 10.0f;
for( FormattedCharSequence line : lines )
{
font.drawShadow( transform, line, (float) ((width / 2) - (minecraft.font.width( line ) / 2)), y, 0xFFFFFF );
var font = minecraft.font;
var lines = font.split(Component.translatable("gui.computercraft.pocket_computer_overlay"), (int) (width * 0.8));
var y = 10.0f;
for (var line : lines) {
font.drawShadow(transform, line, (float) ((width / 2) - (minecraft.font.width(line) / 2)), y, 0xFFFFFF);
y += 9.0f;
}
}

View File

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

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