1
0
mirror of https://github.com/SquidDev-CC/CC-Tweaked synced 2025-07-04 11:02:54 +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

@ -19,8 +19,7 @@ import java.util.OptionalInt;
import java.util.concurrent.TimeUnit;
@Mod(ComputerCraft.MOD_ID)
public final class ComputerCraft
{
public final class ComputerCraft {
public static final String MOD_ID = "computercraft";
public static int computerSpaceLimit = 1000 * 1000;
@ -79,8 +78,7 @@ public final class ComputerCraft
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;
@ -60,33 +58,27 @@ import java.io.InputStream;
import static dan200.computercraft.shared.Capabilities.CAPABILITY_WIRED_ELEMENT;
@AutoService(ComputerCraftAPIService.class)
public final class ComputerCraftAPIImpl implements ComputerCraftAPIService
{
public final class ComputerCraftAPIImpl implements ComputerCraftAPIService {
private final DetailRegistry<ItemStack> itemStackDetails = new DetailRegistryImpl<>(ItemData::fillBasic);
private final DetailRegistry<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();
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
{
try {
return resource.open();
}
catch( IOException ignored )
{
} catch (IOException ignored) {
return null;
}
}
@Nonnull
@Override
public String getInstalledVersion()
{
public String getInstalledVersion() {
if (version != null) return version;
return version = ModList.get().getModContainerById(ComputerCraft.MOD_ID)
.map(x -> x.getModInfo().getVersion().toString())
@ -94,140 +86,112 @@ public final class ComputerCraftAPIImpl implements ComputerCraftAPIService
}
@Override
public int createUniqueNumberedSaveDir( @Nonnull Level world, @Nonnull String parentSubPath )
{
public int createUniqueNumberedSaveDir(@Nonnull Level world, @Nonnull String parentSubPath) {
return ServerContext.get(world.getServer()).getNextId(parentSubPath);
}
@Override
public IWritableMount createSaveDirMount( @Nonnull Level world, @Nonnull String subPath, long capacity )
{
try
{
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 )
{
} 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 );
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 )
{
public void registerPeripheralProvider(@Nonnull IPeripheralProvider provider) {
Peripherals.register(provider);
}
@Override
public void registerGenericSource( @Nonnull GenericSource source )
{
public void registerGenericSource(@Nonnull GenericSource source) {
GenericMethod.register(source);
}
@Override
public void registerGenericCapability( @Nonnull Capability<?> capability )
{
public void registerGenericCapability(@Nonnull Capability<?> capability) {
GenericPeripheralProvider.addCapability(capability);
}
@Override
public void registerBundledRedstoneProvider( @Nonnull IBundledRedstoneProvider provider )
{
public void registerBundledRedstoneProvider(@Nonnull IBundledRedstoneProvider provider) {
BundledRedstone.register(provider);
}
@Override
public int getBundledRedstoneOutput( @Nonnull Level world, @Nonnull BlockPos pos, @Nonnull Direction side )
{
public int getBundledRedstoneOutput(@Nonnull Level world, @Nonnull BlockPos pos, @Nonnull Direction side) {
return BundledRedstone.getDefaultOutput(world, pos, side);
}
@Override
public void registerMediaProvider( @Nonnull IMediaProvider 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 )
{
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 )
{
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 )
{
} else if (type == BlockReference.class) {
blockDetails.addProvider((IDetailProvider<BlockReference>) provider);
}
else if( type == FluidStack.class )
{
} else if (type == FluidStack.class) {
itemStackDetails.addProvider((IDetailProvider<ItemStack>) provider);
}
else
{
} else {
throw new IllegalArgumentException("Unknown detail provider " + type);
}
}
@Nonnull
@Override
public IWiredNode createWiredNodeForElement( @Nonnull IWiredElement 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 );
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 )
{
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,8 +62,7 @@ public final class ComputerCraftAPI
* available for writing.
* @see #createSaveDirMount(Level, String, long)
*/
public static int createUniqueNumberedSaveDir( @Nonnull Level world, @Nonnull String parentSubPath )
{
public static int createUniqueNumberedSaveDir(@Nonnull Level world, @Nonnull String parentSubPath) {
return getInstance().createUniqueNumberedSaveDir(world, parentSubPath);
}
@ -88,8 +85,7 @@ public final class ComputerCraftAPI
* @see IWritableMount
*/
@Nullable
public static IWritableMount createSaveDirMount( @Nonnull Level world, @Nonnull String subPath, long capacity )
{
public static IWritableMount createSaveDirMount(@Nonnull Level world, @Nonnull String subPath, long capacity) {
return getInstance().createSaveDirMount(world, subPath, capacity);
}
@ -112,8 +108,7 @@ public final class ComputerCraftAPI
* @see IMount
*/
@Nullable
public static IMount createResourceMount( @Nonnull String domain, @Nonnull String subPath )
{
public static IMount createResourceMount(@Nonnull String domain, @Nonnull String subPath) {
return getInstance().createResourceMount(domain, subPath);
}
@ -126,8 +121,7 @@ public final class ComputerCraftAPI
* @deprecated Use {@link ForgeComputerCraftAPI#registerPeripheralProvider(IPeripheralProvider)} instead.
*/
@Deprecated(forRemoval = true)
public static void registerPeripheralProvider( @Nonnull IPeripheralProvider provider )
{
public static void registerPeripheralProvider(@Nonnull IPeripheralProvider provider) {
getInstance().registerPeripheralProvider(provider);
}
@ -137,8 +131,7 @@ public final class ComputerCraftAPI
* @param source The method source to register.
* @see GenericSource
*/
public static void registerGenericSource( @Nonnull GenericSource source )
{
public static void registerGenericSource(@Nonnull GenericSource source) {
getInstance().registerGenericSource(source);
}
@ -150,8 +143,7 @@ public final class ComputerCraftAPI
* @deprecated Use {@link ForgeComputerCraftAPI} instead.
*/
@Deprecated(forRemoval = true)
public static void registerGenericCapability( @Nonnull Capability<?> capability )
{
public static void registerGenericCapability(@Nonnull Capability<?> capability) {
getInstance().registerGenericCapability(capability);
}
@ -161,8 +153,7 @@ public final class ComputerCraftAPI
* @param provider The bundled redstone provider to register.
* @see IBundledRedstoneProvider
*/
public static void registerBundledRedstoneProvider( @Nonnull IBundledRedstoneProvider provider )
{
public static void registerBundledRedstoneProvider(@Nonnull IBundledRedstoneProvider provider) {
getInstance().registerBundledRedstoneProvider(provider);
}
@ -176,8 +167,7 @@ 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 )
{
public static int getBundledRedstoneOutput(@Nonnull Level world, @Nonnull BlockPos pos, @Nonnull Direction side) {
return getInstance().getBundledRedstoneOutput(world, pos, side);
}
@ -187,8 +177,7 @@ public final class ComputerCraftAPI
* @param provider The media provider to register.
* @see IMediaProvider
*/
public static void registerMediaProvider( @Nonnull IMediaProvider provider )
{
public static void registerMediaProvider(@Nonnull IMediaProvider provider) {
getInstance().registerMediaProvider(provider);
}
@ -197,13 +186,11 @@ 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 )
{
public static void registerAPIFactory(@Nonnull ILuaAPIFactory factory) {
getInstance().registerAPIFactory(factory);
}
@ -218,8 +205,7 @@ public final class ComputerCraftAPI
* @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 )
{
public static <T> void registerDetailProvider(@Nonnull Class<T> type, @Nonnull IDetailProvider<T> provider) {
getInstance().registerDetailProvider(type, provider);
}
@ -231,8 +217,7 @@ public final class ComputerCraftAPI
* @see IWiredElement#getNode()
*/
@Nonnull
public static IWiredNode createWiredNodeForElement( @Nonnull IWiredElement element )
{
public static IWiredNode createWiredNodeForElement(@Nonnull IWiredElement element) {
return getInstance().createWiredNodeForElement(element);
}
@ -248,19 +233,16 @@ public final class ComputerCraftAPI
*/
@Nonnull
@Deprecated(forRemoval = true)
public static LazyOptional<IWiredElement> getWiredElementAt( @Nonnull BlockGetter world, @Nonnull BlockPos pos, @Nonnull Direction side )
{
public static LazyOptional<IWiredElement> getWiredElementAt(@Nonnull BlockGetter world, @Nonnull BlockPos pos, @Nonnull Direction side) {
return getInstance().getWiredElementAt(world, pos, side);
}
public static void registerRefuelHandler( @Nonnull TurtleRefuelHandler 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,23 +16,19 @@ import net.minecraft.world.level.block.Block;
/**
* Tags provided by ComputerCraft.
*/
public class ComputerCraftTags
{
public static class Items
{
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 )
{
private static TagKey<Item> make(String name) {
return ItemTags.create(new ResourceLocation(ComputerCraft.MOD_ID, name));
}
}
public static class Blocks
{
public static class Blocks {
public static final TagKey<Block> COMPUTER = make("computer");
public static final TagKey<Block> TURTLE = make("turtle");
public static final TagKey<Block> WIRED_MODEM = make("wired_modem");
@ -58,8 +54,7 @@ public class ComputerCraftTags
*/
public static final TagKey<Block> TURTLE_HOE_BREAKABLE = make("turtle_hoe_harvestable");
private static TagKey<Block> make( String name )
{
private static TagKey<Block> make(String name) {
return BlockTags.create(new ResourceLocation(ComputerCraft.MOD_ID, name));
}
}

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,8 +32,7 @@ public final class ForgeComputerCraftAPI
* @see IPeripheral
* @see IPeripheralProvider
*/
public static void registerPeripheralProvider( @Nonnull IPeripheralProvider provider )
{
public static void registerPeripheralProvider(@Nonnull IPeripheralProvider provider) {
getInstance().registerPeripheralProvider(provider);
}
@ -45,8 +42,7 @@ public final class ForgeComputerCraftAPI
* @param capability The capability to register.
* @see GenericSource
*/
public static void registerGenericCapability( @Nonnull Capability<?> 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 )
{
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 )
{
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 )
{
public TransformedModel(@Nonnull BakedModel model, @Nonnull Transformation matrix) {
this.model = Objects.requireNonNull(model);
this.matrix = Objects.requireNonNull(matrix);
}
public TransformedModel( @Nonnull BakedModel 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();
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();
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 );
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>
@ -49,8 +48,7 @@ public interface TurtleUpgradeModeller<T extends ITurtleUpgrade>
* @return The constructed modeller.
*/
@SuppressWarnings("unchecked")
static <T extends ITurtleUpgrade> TurtleUpgradeModeller<T> flatItem()
{
static <T extends ITurtleUpgrade> TurtleUpgradeModeller<T> flatItem() {
return (TurtleUpgradeModeller<T>) TurtleUpgradeModellers.FLAT_ITEM;
}
@ -62,8 +60,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( ModelResourceLocation left, ModelResourceLocation right )
{
static <T extends ITurtleUpgrade> TurtleUpgradeModeller<T> sided(ModelResourceLocation left, ModelResourceLocation right) {
return (upgrade, turtle, side) -> TransformedModel.of(side == TurtleSide.LEFT ? left : right);
}
@ -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 )
{
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,13 +11,11 @@ import dan200.computercraft.api.client.TransformedModel;
import dan200.computercraft.api.turtle.ITurtleUpgrade;
import dan200.computercraft.api.turtle.TurtleSide;
class TurtleUpgradeModellers
{
class TurtleUpgradeModellers {
private static final Transformation leftTransform = getMatrixFor(-0.40625f);
private static final Transformation rightTransform = getMatrixFor(0.40625f);
private static Transformation getMatrixFor( float offset )
{
private static Transformation getMatrixFor(float offset) {
return new Transformation(new Matrix4f(new float[]{
0.0f, 0.0f, -1.0f, 1.0f + offset,
1.0f, 0.0f, 0.0f, 0.0f,

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,8 +28,7 @@ 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 )
{
public BasicItemDetailProvider(String namespace, @Nonnull Class<T> itemType) {
Objects.requireNonNull(itemType);
this.itemType = itemType;
this.namespace = namespace;
@ -41,8 +39,7 @@ public abstract class BasicItemDetailProvider<T> implements IDetailProvider<Item
*
* @param itemType The type the stack's item must have.
*/
public BasicItemDetailProvider( @Nonnull Class<T> itemType )
{
public BasicItemDetailProvider(@Nonnull Class<T> itemType) {
this(null, itemType);
}
@ -61,9 +58,8 @@ public abstract class BasicItemDetailProvider<T> implements IDetailProvider<Item
@Nonnull T item);
@Override
public void provideDetails( @Nonnull Map<? super String, Object> data, @Nonnull ItemStack stack )
{
Item item = stack.getItem();
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.
@ -71,8 +67,7 @@ public abstract class BasicItemDetailProvider<T> implements IDetailProvider<Item
provideDetails(child, stack, itemType.cast(item));
if( namespace != null )
{
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 )
{
) {
public BlockReference(Level level, BlockPos pos) {
this(level, pos, level.getBlockState(pos), level.getBlockEntity(pos));
}
}

View File

@ -20,8 +20,7 @@ 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.
*

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

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
{
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 )
{
public FileOperationException(@Nullable String filename, @Nonnull String message) {
super(Objects.requireNonNull(message, "message cannot be null"));
this.filename = filename;
}
public FileOperationException( @Nonnull String message )
{
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.
*

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.
*
@ -86,8 +85,7 @@ 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
{
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,8 +27,7 @@ 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.
*
@ -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.
*
@ -51,10 +50,9 @@ public interface IArguments
*/
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,9 +64,8 @@ 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 );
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,8 +77,7 @@ public interface IArguments
* @return The argument's value.
* @throws LuaException If the value is not an integer.
*/
default int getInt( int index ) throws LuaException
{
default int getInt(int index) throws LuaException {
return (int) getLong(index);
}
@ -92,9 +88,8 @@ 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 );
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,8 +101,7 @@ public interface IArguments
* @return The argument's value.
* @throws LuaException If the value is not finite.
*/
default double getFiniteDouble( int index ) throws LuaException
{
default double getFiniteDouble(int index) throws LuaException {
return checkFinite(index, getDouble(index));
}
@ -118,9 +112,8 @@ 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 );
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,9 +126,8 @@ public interface IArguments
* @throws LuaException If the value is not a string.
*/
@Nonnull
default String getString( int index ) throws LuaException
{
Object value = get( index );
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,8 +140,7 @@ public interface IArguments
* @throws LuaException If the value is not a string.
*/
@Nonnull
default ByteBuffer getBytes( int index ) throws LuaException
{
default ByteBuffer getBytes(int index) throws LuaException {
return LuaValues.encode(getString(index));
}
@ -163,8 +154,7 @@ 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
{
default <T extends Enum<T>> T getEnum(int index, Class<T> klass) throws LuaException {
return LuaValues.checkEnum(index, klass, getString(index));
}
@ -176,9 +166,8 @@ public interface IArguments
* @throws LuaException If the value is not a table.
*/
@Nonnull
default Map<?, ?> getTable( int index ) throws LuaException
{
Object value = get( index );
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,8 +185,7 @@ public interface IArguments
* @throws LuaException If the value is not a table.
*/
@Nonnull
default LuaTable<?, ?> getTableUnsafe( int index ) throws LuaException
{
default LuaTable<?, ?> getTableUnsafe(int index) throws LuaException {
return new ObjectLuaTable(getTable(index));
}
@ -209,9 +197,8 @@ 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 );
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,8 +212,7 @@ public interface IArguments
* @throws LuaException If the value is not a number.
*/
@Nonnull
default Optional<Integer> optInt( int index ) throws LuaException
{
default Optional<Integer> optInt(int index) throws LuaException {
return optLong(index).map(Long::intValue);
}
@ -237,9 +223,8 @@ 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 );
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,9 +237,8 @@ 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 );
default Optional<Double> optFiniteDouble(int index) throws LuaException {
var value = optDouble(index);
if (value.isPresent()) LuaValues.checkFiniteNum(index, value.get());
return value;
}
@ -266,9 +250,8 @@ 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 );
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,9 +264,8 @@ 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 );
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,8 +278,7 @@ 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
{
default Optional<ByteBuffer> optBytes(int index) throws LuaException {
return optString(index).map(LuaValues::encode);
}
@ -311,9 +292,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>> Optional<T> optEnum( int index, Class<T> klass ) throws LuaException
{
Optional<String> str = optString( index );
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,9 +304,8 @@ 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 );
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,9 +324,8 @@ 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 );
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,8 +339,7 @@ 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
{
default double optDouble(int index, double def) throws LuaException {
return optDouble(index).orElse(def);
}
@ -374,8 +351,7 @@ 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
{
default int optInt(int index, int def) throws LuaException {
return optInt(index).orElse(def);
}
@ -387,8 +363,7 @@ 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
{
default long optLong(int index, long def) throws LuaException {
return optLong(index).orElse(def);
}
@ -400,8 +375,7 @@ 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
{
default double optFiniteDouble(int index, double def) throws LuaException {
return optFiniteDouble(index).orElse(def);
}
@ -413,8 +387,7 @@ 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
{
default boolean optBoolean(int index, boolean def) throws LuaException {
return optBoolean(index).orElse(def);
}
@ -426,8 +399,7 @@ 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
{
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
{
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.

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.
*

View File

@ -12,8 +12,7 @@ import javax.annotation.Nonnull;
*
* @see MethodResult#yield(Object[], ILuaCallback)
*/
public interface ILuaCallback
{
public interface ILuaCallback {
/**
* Resume this coroutine.
*

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
@ -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
{
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.

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,21 +10,18 @@ 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 )
{
public LuaException(@Nullable String message) {
super(message);
hasLevel = false;
level = 1;
}
public LuaException( @Nullable String message, int level )
{
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

@ -38,8 +38,7 @@ import java.util.Optional;
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface LuaFunction
{
public @interface LuaFunction {
/**
* Explicitly specify the method names of this function. If not given, it uses the name of the annotated method.
*

View File

@ -11,16 +11,14 @@ 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;
default int length() {
var size = 0;
while (containsKey((double) (size + 1))) size++;
return size;
}
@ -32,12 +30,11 @@ 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
{
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();
var asDouble = number.doubleValue();
if (!Double.isFinite(asDouble)) throw badTableItem(index, "number", getNumericType(asDouble));
return number.longValue();
}
@ -49,12 +46,11 @@ 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
{
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();
var asDouble = number.doubleValue();
if (!Double.isFinite(asDouble)) throw badField(key, "number", getNumericType(asDouble));
return number.longValue();
}
@ -66,8 +62,7 @@ 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
{
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
{
default int getInt(String key) throws LuaException {
return (int) getLong(key);
}
@Nullable
@Override
default V put( K o, V o2 )
{
default V put(K o, V o2) {
throw new UnsupportedOperationException("Cannot modify LuaTable");
}
@Override
default V remove( Object o )
{
default V remove(Object o) {
throw new UnsupportedOperationException("Cannot modify LuaTable");
}
@Override
default void putAll( @Nonnull Map<? extends K, ? extends V> map )
{
default void putAll(@Nonnull Map<? extends K, ? extends V> map) {
throw new UnsupportedOperationException("Cannot modify LuaTable");
}
@Override
default void clear()
{
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,12 +26,10 @@ 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;
}
@ -48,8 +44,7 @@ public final class LuaValues
* @return This value's numeric type.
*/
@Nonnull
public static String getNumericType( double value )
{
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";
@ -64,8 +59,7 @@ public final class LuaValues
* {@code type} function.
*/
@Nonnull
public static String getType( @Nullable Object value )
{
public static String getType(@Nullable Object value) {
if (value == null) return "nil";
if (value instanceof String) return "string";
if (value instanceof Boolean) return "boolean";
@ -83,8 +77,7 @@ 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 )
{
public static LuaException badArgumentOf(int index, @Nonnull String expected, @Nullable Object actual) {
return badArgument(index, expected, getType(actual));
}
@ -97,8 +90,7 @@ 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 )
{
public static LuaException badArgument(int index, @Nonnull String expected, @Nonnull String actual) {
return new LuaException("bad argument #" + (index + 1) + " (" + expected + " expected, got " + actual + ")");
}
@ -111,8 +103,7 @@ 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 )
{
public static LuaException badTableItem(int index, @Nonnull String expected, @Nonnull String actual) {
return new LuaException("table item #" + index + " is not " + expected + " (got " + actual + ")");
}
@ -125,8 +116,7 @@ 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 )
{
public static LuaException badField(String key, @Nonnull String expected, @Nonnull String actual) {
return new LuaException("field " + key + " is not " + expected + " (got " + actual + ")");
}
@ -138,8 +128,7 @@ 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
{
public static Number checkFiniteNum(int index, Number value) throws LuaException {
checkFinite(index, value.doubleValue());
return value;
}
@ -152,8 +141,7 @@ 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
{
public static double checkFinite(int index, double value) throws LuaException {
if (!Double.isFinite(value)) throw badArgument(index, "number", getNumericType(value));
return value;
}
@ -168,10 +156,8 @@ 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() )
{
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;
}

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
{
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,8 +63,7 @@ public final class MethodResult
* @return A method result which returns immediately with the given value.
*/
@Nonnull
public static MethodResult of( @Nullable Object value )
{
public static MethodResult of(@Nullable Object value) {
return new MethodResult(new Object[]{ value }, null);
}
@ -79,8 +74,7 @@ public final class MethodResult
* @return A method result which returns immediately with the given values.
*/
@Nonnull
public static MethodResult of( @Nullable Object... values )
{
public static MethodResult of(@Nullable Object... values) {
return values == null || values.length == 0 ? empty : new MethodResult(values, null);
}
@ -94,12 +88,10 @@ public final class MethodResult
* @see IComputerAccess#queueEvent(String, Object[])
*/
@Nonnull
public static MethodResult pullEvent( @Nullable String filter, @Nonnull ILuaCallback callback )
{
public static MethodResult pullEvent(@Nullable String filter, @Nonnull ILuaCallback callback) {
Objects.requireNonNull(callback, "callback cannot be null");
return new MethodResult(new Object[]{ filter }, results -> {
if( results.length >= 1 && Objects.equals( results[0], "terminate" ) )
{
if (results.length >= 1 && Objects.equals(results[0], "terminate")) {
throw new LuaException("Terminated", 0);
}
return callback.resume(results);
@ -117,8 +109,7 @@ public final class MethodResult
* @see #pullEvent(String, ILuaCallback)
*/
@Nonnull
public static MethodResult pullEventRaw( @Nullable String filter, @Nonnull ILuaCallback callback )
{
public static MethodResult pullEventRaw(@Nullable String filter, @Nonnull ILuaCallback callback) {
Objects.requireNonNull(callback, "callback cannot be null");
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 )
{
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,8 +151,7 @@ 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 )
{
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,38 +13,32 @@ 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 )
{
public ObjectArguments(IArguments arguments) {
throw new IllegalStateException();
}
public ObjectArguments( Object... args )
{
public ObjectArguments(Object... args) {
this.args = Arrays.asList(args);
}
public ObjectArguments( List<Object> 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 )
{
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;
@ -54,14 +48,12 @@ public final class ObjectArguments implements IArguments
@Nullable
@Override
public Object get( int 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 )
{
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 )
{
public boolean containsKey(Object o) {
return map.containsKey(o);
}
@Override
public boolean containsValue( Object o )
{
public boolean containsValue(Object o) {
return map.containsKey(o);
}
@Override
public Object get( Object 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
{
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( (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 )
{
} 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
{
} else {
throw new LuaException("error");
}
}
static MethodResult make( ILuaContext context, ILuaTask func ) throws LuaException
{
long task = context.issueMainThreadTask( func );
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.
*
@ -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.
*

View File

@ -13,8 +13,7 @@ import javax.annotation.Nonnull;
* @see Packet
* @see IPacketReceiver
*/
public interface IPacketNetwork
{
public interface IPacketNetwork {
/**
* Add a receiver to the network.
*

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.
*

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>

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,8 +54,7 @@ public interface IWiredNode extends IPacketNetwork
* @see IWiredNetwork#connect(IWiredNode, IWiredNode)
* @see IWiredNode#disconnectFrom(IWiredNode)
*/
default boolean connectTo( @Nonnull IWiredNode node )
{
default boolean connectTo(@Nonnull IWiredNode node) {
return getNetwork().connect(this, node);
}
@ -71,8 +69,7 @@ public interface IWiredNode extends IPacketNetwork
* @see IWiredNetwork#disconnect(IWiredNode, IWiredNode)
* @see IWiredNode#connectTo(IWiredNode)
*/
default boolean disconnectFrom( @Nonnull IWiredNode node )
{
default boolean disconnectFrom(@Nonnull IWiredNode node) {
return getNetwork().disconnect(this, node);
}
@ -87,8 +84,7 @@ public interface IWiredNode extends IPacketNetwork
* @throws IllegalArgumentException If the node is not in the network.
* @see IWiredNetwork#remove(IWiredNode)
*/
default boolean remove()
{
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 )
{
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,8 +40,7 @@ public interface IComputerAccess
* @see IMount
*/
@Nullable
default String mount( @Nonnull String desiredLocation, @Nonnull IMount mount )
{
default String mount(@Nonnull String desiredLocation, @Nonnull IMount mount) {
return mount(desiredLocation, mount, getAttachmentName());
}
@ -80,8 +78,7 @@ public interface IComputerAccess
* @see IMount
*/
@Nullable
default String mountWritable( @Nonnull String desiredLocation, @Nonnull IWritableMount mount )
{
default String mountWritable(@Nonnull String desiredLocation, @Nonnull IWritableMount mount) {
return mountWritable(desiredLocation, mount, getAttachmentName());
}

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.

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;
}

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.
*

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.
*
@ -57,18 +56,14 @@ 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 )
{
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
{
} finally {
trackWork(System.nanoTime() - start, TimeUnit.NANOSECONDS);
}

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()
{
public NotAttachedException() {
super("You are not attached to this computer");
}
public NotAttachedException( String s )
{
public NotAttachedException(String s) {
super(s);
}
}

View File

@ -20,19 +20,16 @@ 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
{
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 ) )
{
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,8 +49,7 @@ public final class PeripheralType
* @param type The name of the type.
* @return The constructed peripheral type.
*/
public static PeripheralType ofType( @Nonnull String type )
{
public static PeripheralType ofType(@Nonnull String type) {
if (Strings.isNullOrEmpty(type)) throw new IllegalArgumentException("type cannot be null or empty");
return new PeripheralType(type, Collections.emptySet());
}
@ -66,8 +61,7 @@ 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 )
{
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,8 +73,7 @@ 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 )
{
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,8 +84,7 @@ 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 )
{
public static PeripheralType ofAdditional(Collection<String> additionalTypes) {
return new PeripheralType(null, ImmutableSet.copyOf(additionalTypes));
}
@ -102,8 +94,7 @@ 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 )
{
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 )
{
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>

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>
@ -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 )
{
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,8 +33,7 @@ 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>
@ -51,8 +50,7 @@ public interface PocketUpgradeSerialiser<T extends IPocketUpgrade> extends Upgra
* @deprecated Use {@link #REGISTRY_ID} directly.
*/
@Deprecated(forRemoval = true)
static IForgeRegistry<PocketUpgradeSerialiser<?>> registry()
{
static IForgeRegistry<PocketUpgradeSerialiser<?>> registry() {
return RegistryManager.ACTIVE.getRegistry(REGISTRY_ID);
}
@ -67,12 +65,9 @@ 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 )
{
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);
}
}
@ -90,12 +85,9 @@ 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 )
{
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);
}
}

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.
*

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 )
{
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.
*

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>

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,8 +16,7 @@ import javax.annotation.Nullable;
* @see ITurtleCommand#execute(ITurtleAccess)
* @see ITurtleUpgrade#useTool(ITurtleAccess, TurtleSide, TurtleVerb, Direction)
*/
public final class TurtleCommandResult
{
public final class TurtleCommandResult {
private static final TurtleCommandResult EMPTY_SUCCESS = new TurtleCommandResult(true, null, null);
private static final TurtleCommandResult EMPTY_FAILURE = new TurtleCommandResult(false, null, null);
@ -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,8 +37,7 @@ public final class TurtleCommandResult
* @return A successful command result with the given values.
*/
@Nonnull
public static TurtleCommandResult success( @Nullable Object[] 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,8 +59,7 @@ public final class TurtleCommandResult
* @return A failed command result with a message.
*/
@Nonnull
public static TurtleCommandResult failure( @Nullable String errorMessage )
{
public static TurtleCommandResult failure(@Nullable String errorMessage) {
if (errorMessage == null) return EMPTY_FAILURE;
return new TurtleCommandResult(false, errorMessage, null);
}
@ -73,8 +68,7 @@ public final class TurtleCommandResult
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.
*

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,12 +29,10 @@ import java.util.function.Consumer;
* @see GatherDataEvent To register your data provider
* @see TurtleUpgradeSerialiser
*/
public abstract class TurtleUpgradeDataProvider extends UpgradeDataProvider<ITurtleUpgrade, TurtleUpgradeSerialiser<?>>
{
public abstract class TurtleUpgradeDataProvider extends UpgradeDataProvider<ITurtleUpgrade, TurtleUpgradeSerialiser<?>> {
private static final ResourceLocation TOOL_ID = new ResourceLocation(ComputerCraftAPI.MOD_ID, "tool");
public TurtleUpgradeDataProvider( DataGenerator generator )
{
public TurtleUpgradeDataProvider(DataGenerator generator) {
super(generator, "Turtle Upgrades", "computercraft/turtle_upgrades", TurtleUpgradeSerialiser.REGISTRY_ID);
}
@ -47,8 +45,7 @@ public abstract class TurtleUpgradeDataProvider extends UpgradeDataProvider<ITur
* @return A tool builder,
*/
@Nonnull
public final ToolBuilder tool( @Nonnull ResourceLocation id, @Nonnull Item item )
{
public final ToolBuilder tool(@Nonnull ResourceLocation id, @Nonnull Item item) {
return new ToolBuilder(id, existingSerialiser(TOOL_ID), item);
}
@ -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,13 +126,11 @@ public abstract class TurtleUpgradeDataProvider extends UpgradeDataProvider<ITur
*
* @param add The callback given to {@link #addUpgrades(Consumer)}.
*/
public void add( @Nonnull Consumer<Upgrade<TurtleUpgradeSerialiser<?>>> add )
{
public void add(@Nonnull Consumer<Upgrade<TurtleUpgradeSerialiser<?>>> add) {
add.accept(new Upgrade<>(id, serialiser, s -> {
s.addProperty("item", ForgeRegistries.ITEMS.getKey(toolItem).toString());
if (adjective != null) s.addProperty("adjective", adjective);
if( craftingItem != null )
{
if (craftingItem != null) {
s.addProperty("craftItem", ForgeRegistries.ITEMS.getKey(craftingItem).toString());
}
if (damageMultiplier != null) s.addProperty("damageMultiplier", damageMultiplier);

View File

@ -71,8 +71,7 @@ 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>
@ -89,8 +88,7 @@ public interface TurtleUpgradeSerialiser<T extends ITurtleUpgrade> extends Upgra
* @deprecated Use {@link #REGISTRY_ID} directly.
*/
@Deprecated(forRemoval = true)
static IForgeRegistry<TurtleUpgradeSerialiser<?>> registry()
{
static IForgeRegistry<TurtleUpgradeSerialiser<?>> registry() {
return RegistryManager.ACTIVE.getRegistry(REGISTRY_ID);
}
@ -105,12 +103,9 @@ 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 )
{
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);
}
}
@ -128,12 +123,9 @@ 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 )
{
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);
}
}

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

@ -20,12 +20,10 @@ import java.util.Objects;
* @deprecated No longer needed, see {@link TurtleRefuelEvent}.
*/
@Deprecated(forRemoval = true)
public abstract class TurtleEvent extends Event
{
public abstract class TurtleEvent extends Event {
private final ITurtleAccess turtle;
protected TurtleEvent( @Nonnull ITurtleAccess turtle )
{
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

@ -21,13 +21,11 @@ import java.util.Objects;
* @deprecated Use {@link TurtleRefuelHandler} instead.
*/
@Deprecated(forRemoval = true)
public class TurtleRefuelEvent extends TurtleEvent
{
public class TurtleRefuelEvent extends TurtleEvent {
private final ItemStack stack;
private Handler handler;
public TurtleRefuelEvent( @Nonnull ITurtleAccess turtle, @Nonnull ItemStack stack )
{
public TurtleRefuelEvent(@Nonnull ITurtleAccess turtle, @Nonnull ItemStack stack) {
super(turtle);
Objects.requireNonNull(turtle, "turtle cannot be null");
@ -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.
*

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,14 +69,13 @@ 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 );
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();
@ -94,8 +91,7 @@ public interface IUpgradeBase
* @see #getUnlocalisedAdjective()
*/
@Nonnull
static String getDefaultAdjective( @Nonnull ResourceLocation id )
{
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) )
{
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,10 +78,8 @@ 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) )
{
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.");
}
@ -109,10 +103,9 @@ public abstract class UpgradeDataProvider<T extends IUpgradeBase, R extends Upgr
protected abstract void addUpgrades(@Nonnull Consumer<Upgrade<R>> addUpgrade);
@Override
public final void run( @Nonnull CachedOutput cache ) throws IOException
{
public final void run(@Nonnull CachedOutput cache) throws IOException {
var registry = RegistryManager.ACTIVE.getRegistry(this.registry);
Path base = generator.getOutputFolder().resolve( "data" );
var base = generator.getOutputFolder().resolve("data");
Set<ResourceLocation> seen = new HashSet<>();
List<T> upgrades = new ArrayList<>();
@ -123,22 +116,16 @@ public abstract class UpgradeDataProvider<T extends IUpgradeBase, R extends Upgr
json.addProperty("type", Objects.requireNonNull(registry.getKey(upgrade.serialiser()), "Serialiser has not been registered").toString());
upgrade.serialise().accept(json);
try
{
try {
DataProvider.saveStable(cache, json, base.resolve(upgrade.id().getNamespace() + "/" + folder + "/" + upgrade.id().getPath() + ".json"));
}
catch( IOException e )
{
} catch (IOException e) {
LOGGER.error("Failed to save {} {}", name, upgrade.id(), e);
}
try
{
try {
var result = upgrade.serialiser().fromJson(upgrade.id(), json);
upgrades.add(result);
}
catch( IllegalArgumentException | JsonParseException e )
{
} catch (IllegalArgumentException | JsonParseException e) {
LOGGER.error("Failed to parse {} {}", name, upgrade.id(), e);
}
});
@ -148,22 +135,19 @@ public abstract class UpgradeDataProvider<T extends IUpgradeBase, R extends Upgr
@Nonnull
@Override
public final String getName()
{
public final String getName() {
return name;
}
@Nonnull
public final R existingSerialiser( @Nonnull ResourceLocation id )
{
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()
{
public List<T> getGeneratedUpgrades() {
if (upgrades == null) throw new IllegalStateException("Upgrades have not beeen generated yet");
return upgrades;
}
@ -178,15 +162,13 @@ 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 )
{
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.
*

View File

@ -16,27 +16,22 @@ import net.minecraftforge.eventbus.api.SubscribeEvent;
import net.minecraftforge.fml.common.Mod;
@Mod.EventBusSubscriber(modid = ComputerCraft.MOD_ID, value = Dist.CLIENT)
public class ClientHooks
{
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

@ -40,8 +40,7 @@ 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
{
public final class ClientRegistry {
private static final String[] EXTRA_MODELS = new String[]{
// Turtle upgrades
"block/turtle_modem_normal_off_left",
@ -65,28 +64,24 @@ public final class ClientRegistry
"block/turtle_elf_overlay",
};
private ClientRegistry() {}
private ClientRegistry() {
}
@SubscribeEvent
public static void registerModelLoaders( ModelEvent.RegisterGeometryLoaders event )
{
public static void registerModelLoaders(ModelEvent.RegisterGeometryLoaders event) {
event.register("turtle", TurtleModelLoader.INSTANCE);
}
@SubscribeEvent
public static void registerModels( ModelEvent.RegisterAdditional event )
{
for( String model : EXTRA_MODELS )
{
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 )
{
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;
}
@ -102,16 +97,14 @@ public final class ClientRegistry
);
event.register((stack, layer) -> {
switch( 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();
case 2: { // Light colour
var light = ClientPocketComputers.get(stack).getLightState();
return light == -1 ? Colour.BLACK.getHex() : light;
}
}
@ -125,8 +118,7 @@ public final class ClientRegistry
}
@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);
@ -160,18 +152,15 @@ public final class ClientRegistry
}
@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 )
{
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);

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,48 +19,42 @@ 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 );
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);
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);
}
@Override
public int getColumnPadding()
{
public int getColumnPadding() {
return 3;
}
@Override
public int getWidth( Component 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() );
@ -71,21 +64,18 @@ public class ClientTableFormatter implements TableFormatter
}
@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() ) ) )
{
if (chat.allMessages.removeIf(guiMessage -> guiMessage.tag() != null && Objects.equals(guiMessage.tag().logTag(), tag.logTag()))) {
chat.refreshTrimmedMessage();
}
TableFormatter.super.display(table);
}
private static GuiMessageTag createTag( String id )
{
private static GuiMessageTag createTag(String id) {
return new GuiMessageTag(0xa0a0a0, null, null, "ComputerCraft/" + id);
}
}

View File

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

View File

@ -12,34 +12,28 @@ 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
{
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 )
{
public static void onTick(TickEvent.ClientTickEvent event) {
if (event.phase == TickEvent.Phase.START) tick++;
}
@SubscribeEvent
public static void onRenderTick( TickEvent.RenderTickEvent event )
{
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()
{
public void turnOn() {
NetworkHandler.sendToServer(new ComputerActionServerMessage(menu, ComputerActionServerMessage.Action.TURN_ON));
}
@Override
public void shutdown()
{
public void shutdown() {
NetworkHandler.sendToServer(new ComputerActionServerMessage(menu, ComputerActionServerMessage.Action.SHUTDOWN));
}
@Override
public void reboot()
{
public void reboot() {
NetworkHandler.sendToServer(new ComputerActionServerMessage(menu, ComputerActionServerMessage.Action.REBOOT));
}
@Override
public void queueEvent( String event, @Nullable Object[] arguments )
{
public void queueEvent(String event, @Nullable Object[] arguments) {
NetworkHandler.sendToServer(new QueueEventServerMessage(menu, event, arguments));
}
@Override
public void keyDown( int key, boolean repeat )
{
public void keyDown(int key, boolean repeat) {
NetworkHandler.sendToServer(new KeyEventServerMessage(menu, repeat ? KeyEventServerMessage.TYPE_REPEAT : KeyEventServerMessage.TYPE_DOWN, key));
}
@Override
public void keyUp( int 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 )
{
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 )
{
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 )
{
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 )
{
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,8 +37,7 @@ import java.util.Collections;
import java.util.List;
import java.util.concurrent.TimeUnit;
public abstract class ComputerScreenBase<T extends ContainerComputerBase> extends AbstractContainerScreen<T>
{
public abstract class ComputerScreenBase<T extends ContainerComputerBase> extends AbstractContainerScreen<T> {
private static final Component OK = Component.translatable("gui.ok");
private static final Component 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",
@ -55,8 +53,7 @@ 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 )
{
public ComputerScreenBase(T container, Inventory player, Component title, int sidebarYOffset) {
super(container, player, title);
terminalData = container.getTerminal();
family = container.getFamily();
@ -68,8 +65,7 @@ public abstract class ComputerScreenBase<T extends ContainerComputerBase> extend
protected abstract WidgetTerminal createTerminal();
@Override
protected void init()
{
protected void init() {
super.init();
minecraft.keyboardHandler.setSendRepeatsToGui(true);
@ -79,20 +75,17 @@ public abstract class ComputerScreenBase<T extends ContainerComputerBase> extend
}
@Override
public void removed()
{
public void removed() {
super.removed();
minecraft.keyboardHandler.setSendRepeatsToGui(false);
}
@Override
public void containerTick()
{
public void containerTick() {
super.containerTick();
terminal.update();
if( uploadNagDeadline != Long.MAX_VALUE && Util.getNanos() >= uploadNagDeadline )
{
if (uploadNagDeadline != Long.MAX_VALUE && Util.getNanos() >= uploadNagDeadline) {
new ItemToast(minecraft, displayStack, NO_RESPONSE_TITLE, NO_RESPONSE_MSG, ItemToast.TRANSFER_NO_RESPONSE_TOKEN)
.showOrReplace(minecraft.getToasts());
uploadNagDeadline = Long.MAX_VALUE;
@ -100,11 +93,9 @@ public abstract class ComputerScreenBase<T extends ContainerComputerBase> extend
}
@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 )
{
if (key == GLFW.GLFW_KEY_TAB && getFocused() != null && getFocused() == terminal) {
return getFocused().keyPressed(key, scancode, modifiers);
}
@ -113,17 +104,15 @@ public abstract class ComputerScreenBase<T extends ContainerComputerBase> extend
@Override
public void render( @Nonnull PoseStack stack, int mouseX, int mouseY, float partialTicks )
{
public void render(@Nonnull PoseStack stack, int mouseX, int mouseY, float partialTicks) {
renderBackground(stack);
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);
@ -131,26 +120,22 @@ public abstract class ComputerScreenBase<T extends ContainerComputerBase> extend
}
@Override
public boolean mouseDragged( double x, double y, int button, double deltaX, double deltaY )
{
public boolean mouseDragged(double x, double y, int button, double deltaX, double deltaY) {
return (getFocused() != null && getFocused().mouseDragged(x, y, button, deltaX, deltaY))
|| 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 )
{
public void onFilesDrop(@Nonnull List<Path> files) {
if (files.isEmpty()) return;
if( !menu.isOn() )
{
if (!menu.isOn()) {
alert(UploadResult.FAILED_TITLE, UploadResult.COMPUTER_OFF_MSG);
return;
}
@ -158,49 +143,41 @@ public abstract class ComputerScreenBase<T extends ContainerComputerBase> extend
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;
try( SeekableByteChannel sbc = Files.newByteChannel( file ) )
{
long fileSize = sbc.size();
if( fileSize > UploadFileMessage.MAX_SIZE || (size += fileSize) >= UploadFileMessage.MAX_SIZE )
{
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 )
{
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 );
var buffer = ByteBuffer.allocateDirect((int) fileSize);
sbc.read(buffer);
buffer.flip();
byte[] digest = FileUpload.getDigest( buffer );
if( digest == null )
{
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 )
{
} 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 )
{
if (toUpload.size() > UploadFileMessage.MAX_FILES) {
alert(UploadResult.FAILED_TITLE, Component.translatable("gui.computercraft.upload.failed.too_many_files"));
return;
}
@ -208,31 +185,19 @@ public abstract class ComputerScreenBase<T extends ContainerComputerBase> extend
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 )
{
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 )
{
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,10 +18,8 @@ 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 )
{
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;
@ -29,14 +27,12 @@ public final class GuiComputer<T extends ContainerComputerBase> extends Computer
}
@Override
protected WidgetTerminal createTerminal()
{
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(),

View File

@ -15,26 +15,22 @@ import net.minecraft.world.entity.player.Inventory;
import javax.annotation.Nonnull;
public class GuiDiskDrive extends AbstractContainerScreen<ContainerDiskDrive>
{
public class GuiDiskDrive extends AbstractContainerScreen<ContainerDiskDrive> {
private static final ResourceLocation BACKGROUND = new ResourceLocation("computercraft", "textures/gui/disk_drive.png");
public GuiDiskDrive( ContainerDiskDrive container, Inventory player, Component 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 )
{
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 )
{
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,18 +15,15 @@ import net.minecraft.world.entity.player.Inventory;
import javax.annotation.Nonnull;
public class GuiPrinter extends AbstractContainerScreen<ContainerPrinter>
{
public class GuiPrinter extends AbstractContainerScreen<ContainerPrinter> {
private static final ResourceLocation BACKGROUND = new ResourceLocation("computercraft", "textures/gui/printer.png");
public GuiPrinter( ContainerPrinter container, Inventory player, Component 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 )
{
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);
@ -35,8 +32,7 @@ public class GuiPrinter extends AbstractContainerScreen<ContainerPrinter>
}
@Override
public void render( @Nonnull PoseStack stack, int mouseX, int mouseY, float partialTicks )
{
public void render(@Nonnull PoseStack stack, int mouseX, int mouseY, float partialTicks) {
renderBackground(stack);
super.render(stack, mouseX, mouseY, partialTicks);
renderTooltip(stack, mouseX, mouseY);

View File

@ -22,27 +22,25 @@ 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 )
{
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);
@ -50,18 +48,15 @@ public class GuiPrintout extends AbstractContainerScreen<ContainerHeldItem>
}
@Override
public boolean keyPressed( int key, int scancode, int modifiers )
{
public boolean keyPressed(int key, int scancode, int modifiers) {
if (super.keyPressed(key, scancode, modifiers)) return true;
if( key == GLFW.GLFW_KEY_RIGHT )
{
if (key == GLFW.GLFW_KEY_RIGHT) {
if (page < pages - 1) page++;
return true;
}
if( key == GLFW.GLFW_KEY_LEFT )
{
if (key == GLFW.GLFW_KEY_LEFT) {
if (page > 0) page--;
return true;
}
@ -70,18 +65,15 @@ public class GuiPrintout extends AbstractContainerScreen<ContainerHeldItem>
}
@Override
public boolean mouseScrolled( double x, double y, double delta )
{
public boolean mouseScrolled(double x, double y, double delta) {
if (super.mouseScrolled(x, y, delta)) return true;
if( delta < 0 )
{
if (delta < 0) {
// Scroll up goes to the next 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--;
return true;
@ -91,21 +83,19 @@ 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.enableDepthTest();
MultiBufferSource.BufferSource renderer = MultiBufferSource.immediate( Tesselator.getInstance().getBuilder() );
var renderer = MultiBufferSource.immediate(Tesselator.getInstance().getBuilder());
drawBorder(transform, renderer, leftPos, topPos, getBlitOffset(), page, pages, book, FULL_BRIGHT_LIGHTMAP);
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);
@ -115,8 +105,7 @@ public class GuiPrintout extends AbstractContainerScreen<ContainerHeldItem>
}
@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,8 +21,7 @@ import javax.annotation.Nonnull;
import static dan200.computercraft.shared.turtle.inventory.ContainerTurtle.*;
public class GuiTurtle extends ComputerScreenBase<ContainerTurtle>
{
public class GuiTurtle extends ComputerScreenBase<ContainerTurtle> {
private static final ResourceLocation BACKGROUND_NORMAL = new ResourceLocation(ComputerCraft.MOD_ID, "textures/gui/turtle_normal.png");
private static final ResourceLocation BACKGROUND_ADVANCED = new ResourceLocation(ComputerCraft.MOD_ID, "textures/gui/turtle_advanced.png");
@ -31,8 +30,7 @@ public class GuiTurtle extends ComputerScreenBase<ContainerTurtle>
private final ComputerFamily family;
public GuiTurtle( ContainerTurtle container, Inventory player, Component title )
{
public GuiTurtle(ContainerTurtle container, Inventory player, Component title) {
super(container, player, title, BORDER);
family = container.getFamily();
@ -41,24 +39,21 @@ public class GuiTurtle extends ComputerScreenBase<ContainerTurtle>
}
@Override
protected WidgetTerminal createTerminal()
{
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;
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 )
{
var slot = getMenu().getSelectedSlot();
if (slot >= 0) {
RenderSystem.setShaderColor(1.0F, 1.0F, 1.0F, 1.0F);
int slotX = slot % 4;
int slotY = slot / 4;
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

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,55 +39,45 @@ 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;
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
{
} 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;
@ -98,50 +86,42 @@ public class ItemToast implements Toast
RenderSystem.setShaderTexture(0, TEXTURE);
RenderSystem.setShaderColor(1.0F, 1.0F, 1.0F, 1.0F);
if( width == 160 && message.size() <= 1 )
{
if (width == 160 && message.size() <= 1) {
component.blit(transform, 0, 0, 0, 64, width, height());
}
else
{
} else {
int height = height();
var height = height();
int bottom = Math.min( 4, height - 28 );
var bottom = Math.min(4, height - 28);
renderBackgroundRow(transform, component, width, 0, 0, 28);
for( int i = 28; i < height - bottom; i += 10 )
{
for (var i = 28; i < height - bottom; i += 10) {
renderBackgroundRow(transform, component, width, 16, i, Math.min(16, height - i - bottom));
}
renderBackgroundRow(transform, component, width, 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().font.draw(transform, title, textX, MARGIN, 0xff500050);
for( int i = 0; i < message.size(); ++i )
{
for (var i = 0; i < message.size(); ++i) {
component.getMinecraft().font.draw(transform, message.get(i), textX, (float) (LINE_SPACING + (i + 1) * LINE_SPACING), 0xff000000);
}
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 )
{
for (var k = leftOffset; k < x - rightOffset; k += 64) {
component.blit(transform, k, y, 32, 32 + u, Math.min(64, x - k - rightOffset), height);
}

View File

@ -10,25 +10,20 @@ 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 )
{
public NoTermComputerScreen(T menu, Inventory player, Component title) {
super(title);
this.menu = menu;
terminalData = menu.getTerminal();
@ -36,14 +31,12 @@ public class NoTermComputerScreen<T extends ContainerComputerBase> extends Scree
@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.
@ -61,45 +54,38 @@ public class NoTermComputerScreen<T extends ContainerComputerBase> extends Scree
}
@Override
public final void removed()
{
public final void removed() {
super.removed();
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 )
{
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 )
{
if (key == GLFW.GLFW_KEY_TAB && getFocused() != null && getFocused() == terminal) {
return getFocused().keyPressed(key, scancode, modifiers);
}
@ -107,15 +93,13 @@ public class NoTermComputerScreen<T extends ContainerComputerBase> extends Scree
}
@Override
public void render( @Nonnull PoseStack transform, int mouseX, int mouseY, float partialTicks )
{
public void render(@Nonnull PoseStack transform, int mouseX, int mouseY, float partialTicks) {
super.render(transform, mouseX, mouseY, partialTicks);
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 )
{
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,8 +18,7 @@ import net.minecraft.resources.ResourceLocation;
import javax.annotation.Nonnull;
import java.util.List;
public final class OptionScreen extends Screen
{
public final class OptionScreen extends Screen {
private static final ResourceLocation BACKGROUND = new ResourceLocation("computercraft", "textures/gui/blank_screen.png");
public static final int BUTTON_WIDTH = 100;
@ -40,8 +39,7 @@ public final class OptionScreen extends Screen
private final Screen originalScreen;
private OptionScreen( Component title, Component message, List<AbstractWidget> buttons, Runnable exit, Screen originalScreen )
{
private OptionScreen(Component title, Component message, List<AbstractWidget> buttons, Runnable exit, Screen originalScreen) {
super(title);
this.message = message;
this.buttons = buttons;
@ -49,35 +47,31 @@ public final class OptionScreen extends Screen
this.originalScreen = originalScreen;
}
public static void show( Minecraft minecraft, Component title, Component message, List<AbstractWidget> buttons, Runnable exit )
{
public static void show(Minecraft minecraft, Component title, Component message, List<AbstractWidget> buttons, Runnable exit) {
minecraft.setScreen(new OptionScreen(title, message, buttons, exit, unwrap(minecraft.screen)));
}
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);
int textHeight = messageRenderer.getLineCount() * FONT_HEIGHT + PADDING * 2;
var textHeight = messageRenderer.getLineCount() * FONT_HEIGHT + PADDING * 2;
innerHeight = textHeight + (buttons.isEmpty() ? 0 : buttons.get(0).getHeight()) + PADDING;
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);
@ -87,8 +81,7 @@ public final class OptionScreen extends Screen
}
@Override
public void render( @Nonnull PoseStack transform, int mouseX, int mouseY, float partialTicks )
{
public void render(@Nonnull PoseStack transform, int mouseX, int mouseY, float partialTicks) {
renderBackground(transform);
// Render the actual texture.
@ -105,24 +98,20 @@ public final class OptionScreen extends Screen
}
@Override
public void onClose()
{
public void onClose() {
exit.run();
}
public static AbstractWidget newButton( Component component, Button.OnPress clicked )
{
public static AbstractWidget newButton(Component component, Button.OnPress clicked) {
return new Button(0, 0, BUTTON_WIDTH, BUTTON_HEIGHT, component, clicked);
}
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