1
0
mirror of https://github.com/SquidDev-CC/CC-Tweaked synced 2025-03-04 10:38:12 +00:00

Turn inspections up to 11

OK, so let's get this out of the way, there's some actual changes mixed
in here too. I'm really sorry:
 - Turtles can now not be renamed with unnamed item tags (previously it
   would clear the name, this seemed a little unideal).
 - commands.getBlock(s)Data will also include NBT.

Now, onto the horror story which is these inspection changes:
 - Make a lot of methods static
 - Typo fixes
 - Make utility classes final + private constructor
 - Lots of reformatting (ifs -> ternary, invert control flow, etc...)
 - ???
 - Profit!

I'm so going to regret this - can pretty much guarantee this is going to
break something.
This commit is contained in:
SquidDev 2019-03-29 21:21:39 +00:00
parent 1230cabcb0
commit 173ea72001
205 changed files with 3653 additions and 1888 deletions

2491
codeInspectionSettings.xml Normal file

File diff suppressed because it is too large Load Diff

View File

@ -157,7 +157,7 @@ public class ComputerCraft
public static final int terminalHeight_pocketComputer = 20; public static final int terminalHeight_pocketComputer = 20;
// Blocks and Items // Blocks and Items
public static class Blocks public static final class Blocks
{ {
public static BlockComputer computer; public static BlockComputer computer;
public static BlockCommandComputer commandComputer; public static BlockCommandComputer commandComputer;
@ -172,7 +172,7 @@ public class ComputerCraft
public static BlockWiredModemFull wiredModemFull; public static BlockWiredModemFull wiredModemFull;
} }
public static class Items public static final class Items
{ {
public static ItemComputer computer; public static ItemComputer computer;
public static ItemCommandComputer commandComputer; public static ItemCommandComputer commandComputer;
@ -195,7 +195,7 @@ public class ComputerCraft
public static ItemBlock wiredModemFull; public static ItemBlock wiredModemFull;
} }
public static class TurtleUpgrades public static final class TurtleUpgrades
{ {
public static TurtleModem wirelessModem; public static TurtleModem wirelessModem;
public static TurtleModem advancedModem; public static TurtleModem advancedModem;
@ -209,7 +209,7 @@ public class ComputerCraft
public static TurtleHoe diamondHoe; public static TurtleHoe diamondHoe;
} }
public static class PocketUpgrades public static final class PocketUpgrades
{ {
public static PocketModem wirelessModem; public static PocketModem wirelessModem;
public static PocketModem advancedModem; public static PocketModem advancedModem;
@ -220,7 +220,7 @@ public class ComputerCraft
} }
@Deprecated @Deprecated
public static class Upgrades public static final class Upgrades
{ {
public static TurtleModem advancedModem; public static TurtleModem advancedModem;
} }
@ -239,7 +239,7 @@ public class ComputerCraft
public static List<IPeripheralProvider> peripheralProviders = new ArrayList<>(); public static List<IPeripheralProvider> peripheralProviders = new ArrayList<>();
// Implementation // Implementation
@Mod.Instance( value = ComputerCraft.MOD_ID ) @Mod.Instance( ComputerCraft.MOD_ID )
public static ComputerCraft instance; public static ComputerCraft instance;
@SidedProxy( @SidedProxy(
@ -556,7 +556,7 @@ public class ComputerCraft
private static File getContainingJar( Class<?> modClass ) private static File getContainingJar( Class<?> modClass )
{ {
String path = modClass.getProtectionDomain().getCodeSource().getLocation().getPath(); String path = modClass.getProtectionDomain().getCodeSource().getLocation().getPath();
int bangIndex = path.indexOf( "!" ); int bangIndex = path.indexOf( '!' );
if( bangIndex >= 0 ) if( bangIndex >= 0 )
{ {
path = path.substring( 0, bangIndex ); path = path.substring( 0, bangIndex );
@ -587,7 +587,7 @@ public class ComputerCraft
private static File getDebugCodeDir( Class<?> modClass ) private static File getDebugCodeDir( Class<?> modClass )
{ {
String path = modClass.getProtectionDomain().getCodeSource().getLocation().getPath(); String path = modClass.getProtectionDomain().getCodeSource().getLocation().getPath();
int bangIndex = path.indexOf( "!" ); int bangIndex = path.indexOf( '!' );
return bangIndex >= 0 ? null : new File( new File( path ).getParentFile(), "../.." ); return bangIndex >= 0 ? null : new File( new File( path ).getParentFile(), "../.." );
} }

View File

@ -173,8 +173,8 @@ public final class ComputerCraftAPI
* Registers a peripheral provider to convert blocks into {@link IPeripheral} implementations. * Registers a peripheral provider to convert blocks into {@link IPeripheral} implementations.
* *
* @param provider The peripheral provider to register. * @param provider The peripheral provider to register.
* @see dan200.computercraft.api.peripheral.IPeripheral * @see IPeripheral
* @see dan200.computercraft.api.peripheral.IPeripheralProvider * @see IPeripheralProvider
*/ */
public static void registerPeripheralProvider( @Nonnull IPeripheralProvider provider ) public static void registerPeripheralProvider( @Nonnull IPeripheralProvider provider )
{ {
@ -198,7 +198,7 @@ public final class ComputerCraftAPI
* this during the load() method of your mod. * this during the load() method of your mod.
* *
* @param upgrade The turtle upgrade to register. * @param upgrade The turtle upgrade to register.
* @see dan200.computercraft.api.turtle.ITurtleUpgrade * @see ITurtleUpgrade
*/ */
public static void registerTurtleUpgrade( @Nonnull ITurtleUpgrade upgrade ) public static void registerTurtleUpgrade( @Nonnull ITurtleUpgrade upgrade )
{ {
@ -223,7 +223,7 @@ public final class ComputerCraftAPI
* Registers a bundled redstone provider to provide bundled redstone output for blocks. * Registers a bundled redstone provider to provide bundled redstone output for blocks.
* *
* @param provider The bundled redstone provider to register. * @param provider The bundled redstone provider to register.
* @see dan200.computercraft.api.redstone.IBundledRedstoneProvider * @see IBundledRedstoneProvider
*/ */
public static void registerBundledRedstoneProvider( @Nonnull IBundledRedstoneProvider provider ) public static void registerBundledRedstoneProvider( @Nonnull IBundledRedstoneProvider provider )
{ {
@ -249,7 +249,7 @@ public final class ComputerCraftAPI
* @param side The side to extract the bundled redstone output from. * @param side The side to extract the bundled redstone output from.
* @return If there is a block capable of emitting bundled redstone at the location, it's signal (0-65535) will be returned. * @return If there is a block capable of emitting bundled redstone at the location, it's signal (0-65535) will be returned.
* If there is no block capable of emitting bundled redstone at the location, -1 will be returned. * If there is no block capable of emitting bundled redstone at the location, -1 will be returned.
* @see dan200.computercraft.api.redstone.IBundledRedstoneProvider * @see IBundledRedstoneProvider
*/ */
public static int getBundledRedstoneOutput( @Nonnull World world, @Nonnull BlockPos pos, @Nonnull EnumFacing side ) public static int getBundledRedstoneOutput( @Nonnull World world, @Nonnull BlockPos pos, @Nonnull EnumFacing side )
{ {
@ -272,7 +272,7 @@ public final class ComputerCraftAPI
* Registers a media provider to provide {@link IMedia} implementations for Items * Registers a media provider to provide {@link IMedia} implementations for Items
* *
* @param provider The media provider to register. * @param provider The media provider to register.
* @see dan200.computercraft.api.media.IMediaProvider * @see IMediaProvider
*/ */
public static void registerMediaProvider( @Nonnull IMediaProvider provider ) public static void registerMediaProvider( @Nonnull IMediaProvider provider )
{ {
@ -294,7 +294,7 @@ public final class ComputerCraftAPI
* Registers a permission provider to restrict where turtles can move or build. * Registers a permission provider to restrict where turtles can move or build.
* *
* @param provider The turtle permission provider to register. * @param provider The turtle permission provider to register.
* @see dan200.computercraft.api.permissions.ITurtlePermissionProvider * @see ITurtlePermissionProvider
* @deprecated Prefer using {@link dan200.computercraft.api.turtle.event.TurtleBlockEvent} or the standard Forge events. * @deprecated Prefer using {@link dan200.computercraft.api.turtle.event.TurtleBlockEvent} or the standard Forge events.
*/ */
@Deprecated @Deprecated
@ -481,7 +481,7 @@ public final class ComputerCraftAPI
} }
catch( Exception e ) catch( Exception e )
{ {
System.out.println( "ComputerCraftAPI: ComputerCraft not found." ); System.err.println( "ComputerCraftAPI: ComputerCraft not found." );
} }
finally finally
{ {
@ -498,7 +498,7 @@ public final class ComputerCraftAPI
} }
catch( NoSuchMethodException e ) catch( NoSuchMethodException e )
{ {
System.out.println( "ComputerCraftAPI: ComputerCraft method " + name + " not found." ); System.err.println( "ComputerCraftAPI: ComputerCraft method " + name + " not found." );
return null; return null;
} }
} }

View File

@ -17,6 +17,7 @@ import javax.annotation.Nullable;
* @see ILuaAPI * @see ILuaAPI
* @see ComputerCraftAPI#registerAPIFactory(ILuaAPIFactory) * @see ComputerCraftAPI#registerAPIFactory(ILuaAPIFactory)
*/ */
@FunctionalInterface
public interface ILuaAPIFactory public interface ILuaAPIFactory
{ {
/** /**

View File

@ -77,7 +77,7 @@ public interface IMedia
* @param world The world in which the item and disk drive reside. * @param world The world in which the item and disk drive reside.
* @return The mount, or null if this item does not represent an item with data. If the mount returned also * @return The mount, or null if this item does not represent an item with data. If the mount returned also
* implements {@link dan200.computercraft.api.filesystem.IWritableMount}, it will mounted using mountWritable() * implements {@link dan200.computercraft.api.filesystem.IWritableMount}, it will mounted using mountWritable()
* @see dan200.computercraft.api.filesystem.IMount * @see IMount
* @see dan200.computercraft.api.filesystem.IWritableMount * @see dan200.computercraft.api.filesystem.IWritableMount
* @see dan200.computercraft.api.ComputerCraftAPI#createSaveDirMount(World, String, long) * @see dan200.computercraft.api.ComputerCraftAPI#createSaveDirMount(World, String, long)
* @see dan200.computercraft.api.ComputerCraftAPI#createResourceMount(Class, String, String) * @see dan200.computercraft.api.ComputerCraftAPI#createResourceMount(Class, String, String)

View File

@ -148,7 +148,7 @@ public interface IComputerAccess
* *
* You may supply {@code null} to indicate that no arguments are to be supplied. * You may supply {@code null} to indicate that no arguments are to be supplied.
* @throws RuntimeException If the peripheral has been detached. * @throws RuntimeException If the peripheral has been detached.
* @see dan200.computercraft.api.peripheral.IPeripheral#callMethod * @see IPeripheral#callMethod
*/ */
void queueEvent( @Nonnull String event, @Nullable Object[] arguments ); void queueEvent( @Nonnull String event, @Nullable Object[] arguments );
@ -182,7 +182,7 @@ public interface IComputerAccess
/** /**
* Get a reachable peripheral with the given attachment name. This is a equivalent to * Get a reachable peripheral with the given attachment name. This is a equivalent to
* {@link #getAvailablePeripherals()}{@code .get(name)}, though may be more performant. * {@link #getAvailablePeripherals()}{@code .get(name)}, though may be more efficient.
* *
* @param name The peripheral's attached name * @param name The peripheral's attached name
* @return The reachable peripheral, or {@code null} if none can be found. * @return The reachable peripheral, or {@code null} if none can be found.

View File

@ -81,9 +81,9 @@ public interface IPeripheral
* peripheral, when a turtle travels into a square next to a peripheral, or when a wired modem adjacent to this * peripheral, when a turtle travels into a square next to a peripheral, or when a wired modem adjacent to this
* peripheral is does any of the above. * peripheral is does any of the above.
* *
* Between calls to {@link #attach} and {@link #detach}, the attached computer can make method calls on the * Between calls to attach and {@link #detach}, the attached computer can make method calls on the peripheral using
* peripheral using {@code peripheral.call()}. This method can be used to keep track of which computers are attached * {@code peripheral.call()}. This method can be used to keep track of which computers are attached to the
* to the peripheral, or to take action when attachment occurs. * peripheral, or to take action when attachment occurs.
* *
* Be aware that will be called from both the server thread and ComputerCraft Lua thread, and so must be thread-safe * Be aware that will be called from both the server thread and ComputerCraft Lua thread, and so must be thread-safe
* and reentrant. * and reentrant.

View File

@ -38,8 +38,7 @@ public interface IWorkMonitor
* If the owning computer is currently allowed to execute work, and has ample time to do so. * If the owning computer is currently allowed to execute work, and has ample time to do so.
* *
* This is effectively a more restrictive form of {@link #canWork()}. One should use that in order to determine if * This is effectively a more restrictive form of {@link #canWork()}. One should use that in order to determine if
* you may do an initial piece of work, and {@link #shouldWork()} to determine if any additional task may be * you may do an initial piece of work, and shouldWork to determine if any additional task may be performed.
* performed.
* *
* @return If we should execute work right now. * @return If we should execute work right now.
*/ */

View File

@ -19,7 +19,7 @@ import javax.annotation.Nullable;
/** /**
* Additional peripherals for pocket computers. * Additional peripherals for pocket computers.
* *
* This is similar to {@link dan200.computercraft.api.turtle.ITurtleUpgrade}. * This is similar to {@link ITurtleUpgrade}.
*/ */
public interface IPocketUpgrade public interface IPocketUpgrade
{ {

View File

@ -73,6 +73,7 @@ public class TurtleRefuelEvent extends TurtleActionEvent
/** /**
* Handles refuelling a turtle from a specific item. * Handles refuelling a turtle from a specific item.
*/ */
@FunctionalInterface
public interface Handler public interface Handler
{ {
/** /**

View File

@ -9,6 +9,7 @@ package dan200.computercraft.client;
import dan200.computercraft.ComputerCraft; import dan200.computercraft.ComputerCraft;
import dan200.computercraft.client.render.TurtleModelLoader; import dan200.computercraft.client.render.TurtleModelLoader;
import dan200.computercraft.shared.media.items.ItemDiskLegacy; import dan200.computercraft.shared.media.items.ItemDiskLegacy;
import dan200.computercraft.shared.pocket.items.ItemPocketComputer;
import dan200.computercraft.shared.turtle.items.ItemTurtleBase; import dan200.computercraft.shared.turtle.items.ItemTurtleBase;
import net.minecraft.client.Minecraft; import net.minecraft.client.Minecraft;
import net.minecraft.client.renderer.ItemMeshDefinition; import net.minecraft.client.renderer.ItemMeshDefinition;
@ -37,9 +38,9 @@ import javax.annotation.Nonnull;
* Registers textures and models for items. * Registers textures and models for items.
*/ */
@Mod.EventBusSubscriber( modid = ComputerCraft.MOD_ID, value = Side.CLIENT ) @Mod.EventBusSubscriber( modid = ComputerCraft.MOD_ID, value = Side.CLIENT )
public class ClientRegistry public final class ClientRegistry
{ {
private static final String[] EXTRA_MODELS = { private static final String[] EXTRA_MODELS = new String[] {
"turtle_modem_off_left", "turtle_modem_off_left",
"turtle_modem_on_left", "turtle_modem_on_left",
"turtle_modem_off_right", "turtle_modem_off_right",
@ -57,6 +58,8 @@ public class ClientRegistry
"turtle_elf_overlay", "turtle_elf_overlay",
}; };
private ClientRegistry() {}
@SubscribeEvent @SubscribeEvent
public static void registerModels( ModelRegistryEvent event ) public static void registerModels( ModelRegistryEvent event )
{ {
@ -129,7 +132,7 @@ public class ClientRegistry
case 1: // Frame colour case 1: // Frame colour
return ComputerCraft.Items.pocketComputer.getColour( stack ); return ComputerCraft.Items.pocketComputer.getColour( stack );
case 2: // Light colour case 2: // Light colour
return ComputerCraft.Items.pocketComputer.getLightState( stack ); return ItemPocketComputer.getLightState( stack );
} }
}, ComputerCraft.Items.pocketComputer ); }, ComputerCraft.Items.pocketComputer );

View File

@ -28,7 +28,7 @@ public class ClientTableFormatter implements TableFormatter
private static Int2IntOpenHashMap lastHeights = new Int2IntOpenHashMap(); private static Int2IntOpenHashMap lastHeights = new Int2IntOpenHashMap();
private FontRenderer renderer() private static FontRenderer renderer()
{ {
return Minecraft.getMinecraft().fontRenderer; return Minecraft.getMinecraft().fontRenderer;
} }

View File

@ -19,7 +19,7 @@ import org.lwjgl.opengl.GL11;
import java.util.Arrays; import java.util.Arrays;
public class FixedWidthFontRenderer public final class FixedWidthFontRenderer
{ {
private static final ResourceLocation FONT = new ResourceLocation( "computercraft", "textures/gui/term_font.png" ); private static final ResourceLocation FONT = new ResourceLocation( "computercraft", "textures/gui/term_font.png" );
public static final ResourceLocation BACKGROUND = new ResourceLocation( "computercraft", "textures/gui/term_background.png" ); public static final ResourceLocation BACKGROUND = new ResourceLocation( "computercraft", "textures/gui/term_background.png" );
@ -93,7 +93,7 @@ public class FixedWidthFontRenderer
private boolean isGreyScale( int colour ) private boolean isGreyScale( int colour )
{ {
return (colour == 0 || colour == 15 || colour == 7 || colour == 8); return colour == 0 || colour == 15 || colour == 7 || colour == 8;
} }
public void drawStringBackgroundPart( int x, int y, TextBuffer backgroundColour, double leftMarginSize, double rightMarginSize, boolean greyScale, Palette p ) public void drawStringBackgroundPart( int x, int y, TextBuffer backgroundColour, double leftMarginSize, double rightMarginSize, boolean greyScale, Palette p )

View File

@ -80,12 +80,6 @@ public class GuiComputer extends GuiContainer
Keyboard.enableRepeatEvents( false ); Keyboard.enableRepeatEvents( false );
} }
@Override
public boolean doesGuiPauseGame()
{
return false;
}
@Override @Override
public void updateScreen() public void updateScreen()
{ {

View File

@ -22,10 +22,8 @@ public class GuiConfigCC extends GuiConfig
super( parentScreen, Config.getConfigElements(), ComputerCraft.MOD_ID, false, false, "CC: Tweaked" ); super( parentScreen, Config.getConfigElements(), ComputerCraft.MOD_ID, false, false, "CC: Tweaked" );
} }
public static class Factory public static class Factory implements IModGuiFactory
implements IModGuiFactory
{ {
@Override @Override
public void initialize( Minecraft minecraft ) public void initialize( Minecraft minecraft )
{ {

View File

@ -29,7 +29,7 @@ public class GuiDiskDrive extends GuiContainer
{ {
String title = m_container.getDiskDrive().getDisplayName().getUnformattedText(); String title = m_container.getDiskDrive().getDisplayName().getUnformattedText();
fontRenderer.drawString( title, (xSize - fontRenderer.getStringWidth( title )) / 2, 6, 0x404040 ); fontRenderer.drawString( title, (xSize - fontRenderer.getStringWidth( title )) / 2, 6, 0x404040 );
fontRenderer.drawString( I18n.format( "container.inventory" ), 8, (ySize - 96) + 2, 0x404040 ); fontRenderer.drawString( I18n.format( "container.inventory" ), 8, ySize - 96 + 2, 0x404040 );
} }
@Override @Override

View File

@ -8,6 +8,7 @@ package dan200.computercraft.client.gui;
import dan200.computercraft.ComputerCraft; import dan200.computercraft.ComputerCraft;
import dan200.computercraft.shared.media.inventory.ContainerHeldItem; import dan200.computercraft.shared.media.inventory.ContainerHeldItem;
import dan200.computercraft.shared.pocket.items.ItemPocketComputer;
public class GuiPocketComputer extends GuiComputer public class GuiPocketComputer extends GuiComputer
{ {
@ -16,7 +17,7 @@ public class GuiPocketComputer extends GuiComputer
super( super(
container, container,
ComputerCraft.Items.pocketComputer.getFamily( container.getStack() ), ComputerCraft.Items.pocketComputer.getFamily( container.getStack() ),
ComputerCraft.Items.pocketComputer.createClientComputer( container.getStack() ), ItemPocketComputer.createClientComputer( container.getStack() ),
ComputerCraft.terminalWidth_pocketComputer, ComputerCraft.terminalWidth_pocketComputer,
ComputerCraft.terminalHeight_pocketComputer ComputerCraft.terminalHeight_pocketComputer
); );

View File

@ -29,7 +29,7 @@ public class GuiPrinter extends GuiContainer
{ {
String title = container.getPrinter().getDisplayName().getUnformattedText(); String title = container.getPrinter().getDisplayName().getUnformattedText();
fontRenderer.drawString( title, (xSize - fontRenderer.getStringWidth( title )) / 2, 6, 0x404040 ); fontRenderer.drawString( title, (xSize - fontRenderer.getStringWidth( title )) / 2, 6, 0x404040 );
fontRenderer.drawString( I18n.format( "container.inventory" ), 8, (ySize - 96) + 2, 0x404040 ); fontRenderer.drawString( I18n.format( "container.inventory" ), 8, ySize - 96 + 2, 0x404040 );
} }
@Override @Override

View File

@ -44,12 +44,6 @@ public class GuiPrintout extends GuiContainer
m_book = ItemPrintout.getType( container.getStack() ) == ItemPrintout.Type.Book; m_book = ItemPrintout.getType( container.getStack() ) == ItemPrintout.Type.Book;
} }
@Override
public boolean doesGuiPauseGame()
{
return false;
}
@Override @Override
protected void keyTyped( char c, int k ) throws IOException protected void keyTyped( char c, int k ) throws IOException
{ {
@ -80,7 +74,7 @@ public class GuiPrintout extends GuiContainer
} }
else if( mouseWheelChange > 0 ) else if( mouseWheelChange > 0 )
{ {
// Scroll down goes to the next page // Scroll down goes to the previous page
if( m_page > 0 ) m_page--; if( m_page > 0 ) m_page--;
} }
} }
@ -99,9 +93,9 @@ public class GuiPrintout extends GuiContainer
public void drawScreen( int mouseX, int mouseY, float partialTicks ) public void drawScreen( int mouseX, int mouseY, float partialTicks )
{ {
// We must take the background further back in order to not overlap with our printed pages. // We must take the background further back in order to not overlap with our printed pages.
zLevel = zLevel - 1; zLevel--;
drawDefaultBackground(); drawDefaultBackground();
zLevel = zLevel + 1; zLevel++;
super.drawScreen( mouseX, mouseY, partialTicks ); super.drawScreen( mouseX, mouseY, partialTicks );
renderHoveredToolTip( mouseX, mouseY ); renderHoveredToolTip( mouseX, mouseY );

View File

@ -98,8 +98,8 @@ public class GuiTurtle extends GuiContainer
public void handleMouseInput() throws IOException public void handleMouseInput() throws IOException
{ {
super.handleMouseInput(); super.handleMouseInput();
int x = Mouse.getEventX() * this.width / mc.displayWidth; int x = Mouse.getEventX() * width / mc.displayWidth;
int y = this.height - Mouse.getEventY() * this.height / mc.displayHeight - 1; int y = height - Mouse.getEventY() * height / mc.displayHeight - 1;
m_terminalGui.handleMouseInput( x, y ); m_terminalGui.handleMouseInput( x, y );
} }
@ -117,8 +117,8 @@ public class GuiTurtle extends GuiContainer
if( slot >= 0 ) if( slot >= 0 )
{ {
GlStateManager.color( 1.0F, 1.0F, 1.0F, 1.0F ); GlStateManager.color( 1.0F, 1.0F, 1.0F, 1.0F );
int slotX = (slot % 4); int slotX = slot % 4;
int slotY = (slot / 4); int slotY = slot / 4;
mc.getTextureManager().bindTexture( advanced ? BACKGROUND_ADVANCED : BACKGROUND_NORMAL ); mc.getTextureManager().bindTexture( advanced ? BACKGROUND_ADVANCED : BACKGROUND_NORMAL );
drawTexturedModalRect( guiLeft + m_container.m_turtleInvStartX - 2 + slotX * 18, guiTop + m_container.m_playerInvStartY - 2 + slotY * 18, 0, 217, 24, 24 ); drawTexturedModalRect( guiLeft + m_container.m_turtleInvStartX - 2 + slotX * 18, guiTop + m_container.m_playerInvStartY - 2 + slotY * 18, 0, 217, 24, 24 );
} }
@ -128,7 +128,7 @@ public class GuiTurtle extends GuiContainer
protected void drawGuiContainerBackgroundLayer( float partialTicks, int mouseX, int mouseY ) protected void drawGuiContainerBackgroundLayer( float partialTicks, int mouseX, int mouseY )
{ {
// Draw term // Draw term
boolean advanced = (m_family == ComputerFamily.Advanced); boolean advanced = m_family == ComputerFamily.Advanced;
m_terminalGui.draw( Minecraft.getMinecraft(), 0, 0, mouseX, mouseY ); m_terminalGui.draw( Minecraft.getMinecraft(), 0, 0, mouseX, mouseY );
// Draw border/inventory // Draw border/inventory

View File

@ -82,9 +82,9 @@ public class WidgetTerminal extends Widget
String clipboard = GuiScreen.getClipboardString(); String clipboard = GuiScreen.getClipboardString();
if( clipboard != null ) if( clipboard != null )
{ {
// Clip to the first occurance of \r or \n // Clip to the first occurrence of \r or \n
int newLineIndex1 = clipboard.indexOf( "\r" ); int newLineIndex1 = clipboard.indexOf( '\r' );
int newLineIndex2 = clipboard.indexOf( "\n" ); int newLineIndex2 = clipboard.indexOf( '\n' );
if( newLineIndex1 >= 0 && newLineIndex2 >= 0 ) if( newLineIndex1 >= 0 && newLineIndex2 >= 0 )
{ {
clipboard = clipboard.substring( 0, Math.min( newLineIndex1, newLineIndex2 ) ); clipboard = clipboard.substring( 0, Math.min( newLineIndex1, newLineIndex2 ) );
@ -274,11 +274,8 @@ public class WidgetTerminal extends Widget
{ {
if( m_terminateTimer < TERMINATE_TIME ) if( m_terminateTimer < TERMINATE_TIME )
{ {
m_terminateTimer = m_terminateTimer + 0.05f; m_terminateTimer += 0.05f;
if( m_terminateTimer >= TERMINATE_TIME ) if( m_terminateTimer >= TERMINATE_TIME ) queueEvent( "terminate" );
{
queueEvent( "terminate" );
}
} }
} }
else else
@ -291,14 +288,11 @@ public class WidgetTerminal extends Widget
{ {
if( m_rebootTimer < TERMINATE_TIME ) if( m_rebootTimer < TERMINATE_TIME )
{ {
m_rebootTimer = m_rebootTimer + 0.05f; m_rebootTimer += 0.05f;
if( m_rebootTimer >= TERMINATE_TIME ) if( m_rebootTimer >= TERMINATE_TIME )
{ {
IComputer computer = m_computer.getComputer(); IComputer computer = m_computer.getComputer();
if( computer != null ) if( computer != null ) computer.reboot();
{
computer.reboot();
}
} }
} }
} }
@ -312,14 +306,11 @@ public class WidgetTerminal extends Widget
{ {
if( m_shutdownTimer < TERMINATE_TIME ) if( m_shutdownTimer < TERMINATE_TIME )
{ {
m_shutdownTimer = m_shutdownTimer + 0.05f; m_shutdownTimer += 0.05f;
if( m_shutdownTimer >= TERMINATE_TIME ) if( m_shutdownTimer >= TERMINATE_TIME )
{ {
IComputer computer = m_computer.getComputer(); IComputer computer = m_computer.getComputer();
if( computer != null ) if( computer != null ) computer.shutdown();
{
computer.shutdown();
}
} }
} }
} }
@ -346,7 +337,7 @@ public class WidgetTerminal extends Widget
{ {
// Draw the screen contents // Draw the screen contents
IComputer computer = m_computer.getComputer(); IComputer computer = m_computer.getComputer();
Terminal terminal = (computer != null) ? computer.getTerminal() : null; Terminal terminal = computer != null ? computer.getTerminal() : null;
if( terminal != null ) if( terminal != null )
{ {
// Draw the terminal // Draw the terminal

View File

@ -46,7 +46,7 @@ public class ComputerCraftProxyClient extends ComputerCraftProxyCommon
} }
@Mod.EventBusSubscriber( modid = ComputerCraft.MOD_ID, value = Side.CLIENT ) @Mod.EventBusSubscriber( modid = ComputerCraft.MOD_ID, value = Side.CLIENT )
public static class ForgeHandlers public static final class ForgeHandlers
{ {
@SubscribeEvent @SubscribeEvent
public static void onWorldUnload( WorldEvent.Unload event ) public static void onWorldUnload( WorldEvent.Unload event )

View File

@ -57,7 +57,7 @@ public final class ItemPocketRenderer extends ItemMapLikeRenderer
@Override @Override
protected void renderItem( ItemStack stack ) protected void renderItem( ItemStack stack )
{ {
// Setup various transformations. Note that these are partially adapated from the corresponding method // Setup various transformations. Note that these are partially adapted from the corresponding method
// in ItemRenderer // in ItemRenderer
GlStateManager.disableLighting(); GlStateManager.disableLighting();
@ -65,8 +65,7 @@ public final class ItemPocketRenderer extends ItemMapLikeRenderer
GlStateManager.rotate( 180f, 0f, 0f, 1f ); GlStateManager.rotate( 180f, 0f, 0f, 1f );
GlStateManager.scale( 0.5, 0.5, 0.5 ); GlStateManager.scale( 0.5, 0.5, 0.5 );
ItemPocketComputer pocketComputer = ComputerCraft.Items.pocketComputer; ClientComputer computer = ItemPocketComputer.createClientComputer( stack );
ClientComputer computer = pocketComputer.createClientComputer( stack );
{ {
// First render the background item. We use the item's model rather than a direct texture as this ensures // First render the background item. We use the item's model rather than a direct texture as this ensures
@ -90,9 +89,9 @@ public final class ItemPocketRenderer extends ItemMapLikeRenderer
GlStateManager.blendFunc( GlStateManager.SourceFactor.SRC_ALPHA, GlStateManager.DestFactor.ONE_MINUS_SRC_ALPHA ); GlStateManager.blendFunc( GlStateManager.SourceFactor.SRC_ALPHA, GlStateManager.DestFactor.ONE_MINUS_SRC_ALPHA );
GlStateManager.color( 1.0F, 1.0F, 1.0F, 1.0F ); GlStateManager.color( 1.0F, 1.0F, 1.0F, 1.0F );
IBakedModel bakedmodel = renderItem.getItemModelWithOverrides( stack, null, null ); IBakedModel baked = renderItem.getItemModelWithOverrides( stack, null, null );
bakedmodel = ForgeHooksClient.handleCameraTransforms( bakedmodel, ItemCameraTransforms.TransformType.GUI, false ); baked = ForgeHooksClient.handleCameraTransforms( baked, ItemCameraTransforms.TransformType.GUI, false );
renderItem.renderItem( stack, bakedmodel ); renderItem.renderItem( stack, baked );
GlStateManager.disableAlpha(); GlStateManager.disableAlpha();
GlStateManager.disableRescaleNormal(); GlStateManager.disableRescaleNormal();

View File

@ -23,7 +23,7 @@ import static dan200.computercraft.shared.media.items.ItemPrintout.LINES_PER_PAG
import static dan200.computercraft.shared.media.items.ItemPrintout.LINE_MAX_LENGTH; import static dan200.computercraft.shared.media.items.ItemPrintout.LINE_MAX_LENGTH;
/** /**
* Emulates map and item-frame rendering for prinouts * Emulates map and item-frame rendering for printouts
*/ */
@Mod.EventBusSubscriber( modid = ComputerCraft.MOD_ID, value = Side.CLIENT ) @Mod.EventBusSubscriber( modid = ComputerCraft.MOD_ID, value = Side.CLIENT )
public final class ItemPrintoutRenderer extends ItemMapLikeRenderer public final class ItemPrintoutRenderer extends ItemMapLikeRenderer

View File

@ -180,7 +180,7 @@ public final class ModelTransformer
* *
* This also provides the ability to swap vertices through {@link #swap(int, int)} to allow reordering. * This also provides the ability to swap vertices through {@link #swap(int, int)} to allow reordering.
*/ */
private static class BakedQuadBuilder implements IVertexConsumer private static final class BakedQuadBuilder implements IVertexConsumer
{ {
private final VertexFormat format; private final VertexFormat format;
@ -195,7 +195,7 @@ public final class ModelTransformer
private BakedQuadBuilder( VertexFormat format ) private BakedQuadBuilder( VertexFormat format )
{ {
this.format = format; this.format = format;
this.vertexData = new int[format.getSize()]; vertexData = new int[format.getSize()];
} }
@Nonnull @Nonnull
@ -208,7 +208,7 @@ public final class ModelTransformer
@Override @Override
public void setQuadTint( int tint ) public void setQuadTint( int tint )
{ {
this.quadTint = tint; quadTint = tint;
} }
@Override @Override

View File

@ -22,7 +22,7 @@ import org.lwjgl.opengl.GL11;
import static dan200.computercraft.client.gui.FixedWidthFontRenderer.FONT_HEIGHT; import static dan200.computercraft.client.gui.FixedWidthFontRenderer.FONT_HEIGHT;
import static dan200.computercraft.shared.media.items.ItemPrintout.LINES_PER_PAGE; import static dan200.computercraft.shared.media.items.ItemPrintout.LINES_PER_PAGE;
public class PrintoutRenderer public final class PrintoutRenderer
{ {
private static final ResourceLocation BG = new ResourceLocation( "computercraft", "textures/gui/printout.png" ); private static final ResourceLocation BG = new ResourceLocation( "computercraft", "textures/gui/printout.png" );
private static final double BG_SIZE = 256.0; private static final double BG_SIZE = 256.0;
@ -60,6 +60,8 @@ public class PrintoutRenderer
private static final int COVER_Y = Y_SIZE; private static final int COVER_Y = Y_SIZE;
private static final int COVER_X = X_SIZE + 4 * X_FOLD_SIZE; private static final int COVER_X = X_SIZE + 4 * X_FOLD_SIZE;
private PrintoutRenderer() {}
public static void drawText( int x, int y, int start, TextBuffer[] text, TextBuffer[] colours ) public static void drawText( int x, int y, int start, TextBuffer[] text, TextBuffer[] colours )
{ {
FixedWidthFontRenderer fontRenderer = FixedWidthFontRenderer.instance(); FixedWidthFontRenderer fontRenderer = FixedWidthFontRenderer.instance();

View File

@ -53,7 +53,7 @@ public final class RenderOverlayCable
state = state.getActualState( world, pos ); state = state.getActualState( world, pos );
event.setCanceled( true ); event.setCanceled( true );
PeripheralType type = ComputerCraft.Blocks.cable.getPeripheralType( state ); PeripheralType type = BlockCable.getPeripheralType( state );
GlStateManager.enableBlend(); GlStateManager.enableBlend();
GlStateManager.tryBlendFuncSeparate( GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA, 1, 0 ); GlStateManager.tryBlendFuncSeparate( GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA, 1, 0 );

View File

@ -37,7 +37,7 @@ public class TileEntityMonitorRenderer extends TileEntitySpecialRenderer<TileMon
} }
} }
private void renderMonitorAt( TileMonitor monitor, double posX, double posY, double posZ, float f, int i ) private static void renderMonitorAt( TileMonitor monitor, double posX, double posY, double posZ, float f, int i )
{ {
// Render from the origin monitor // Render from the origin monitor
ClientMonitor originTerminal = monitor.getClientMonitor(); ClientMonitor originTerminal = monitor.getClientMonitor();
@ -78,7 +78,7 @@ public class TileEntityMonitorRenderer extends TileEntitySpecialRenderer<TileMon
GlStateManager.rotate( pitch, 1.0f, 0.0f, 0.0f ); GlStateManager.rotate( pitch, 1.0f, 0.0f, 0.0f );
GlStateManager.translate( GlStateManager.translate(
-0.5 + TileMonitor.RENDER_BORDER + TileMonitor.RENDER_MARGIN, -0.5 + TileMonitor.RENDER_BORDER + TileMonitor.RENDER_MARGIN,
(origin.getHeight() - 0.5) - (TileMonitor.RENDER_BORDER + TileMonitor.RENDER_MARGIN), origin.getHeight() - 0.5 - (TileMonitor.RENDER_BORDER + TileMonitor.RENDER_MARGIN),
0.5 0.5
); );
double xSize = origin.getWidth() - 2.0 * (TileMonitor.RENDER_MARGIN + TileMonitor.RENDER_BORDER); double xSize = origin.getWidth() - 2.0 * (TileMonitor.RENDER_MARGIN + TileMonitor.RENDER_BORDER);

View File

@ -45,9 +45,9 @@ public class TileEntityTurtleRenderer extends TileEntitySpecialRenderer<TileTurt
private static final ModelResourceLocation ELF_OVERLAY_MODEL = new ModelResourceLocation( "computercraft:turtle_elf_overlay", "inventory" ); private static final ModelResourceLocation ELF_OVERLAY_MODEL = new ModelResourceLocation( "computercraft:turtle_elf_overlay", "inventory" );
@Override @Override
public void render( TileTurtle tileEntity, double posX, double posY, double posZ, float f, int i, float f2 ) public void render( TileTurtle tileEntity, double posX, double posY, double posZ, float partialTicks, int breaking, float f2 )
{ {
if( tileEntity != null ) renderTurtleAt( tileEntity, posX, posY, posZ, f, i ); if( tileEntity != null ) renderTurtleAt( tileEntity, posX, posY, posZ, partialTicks );
} }
public static ModelResourceLocation getTurtleModel( ComputerFamily family, boolean coloured ) public static ModelResourceLocation getTurtleModel( ComputerFamily family, boolean coloured )
@ -78,7 +78,7 @@ public class TileEntityTurtleRenderer extends TileEntitySpecialRenderer<TileTurt
} }
} }
private void renderTurtleAt( TileTurtle turtle, double posX, double posY, double posZ, float partialTicks, int i ) private void renderTurtleAt( TileTurtle turtle, double posX, double posY, double posZ, float partialTicks )
{ {
// Render the label // Render the label
String label = turtle.createProxy().getLabel(); String label = turtle.createProxy().getLabel();
@ -113,12 +113,9 @@ public class TileEntityTurtleRenderer extends TileEntitySpecialRenderer<TileTurt
} }
GlStateManager.translate( -0.5f, -0.5f, -0.5f ); GlStateManager.translate( -0.5f, -0.5f, -0.5f );
// Render the turtle // Render the turtle
int colour; int colour = turtle.getColour();
ComputerFamily family; ComputerFamily family = turtle.getFamily();
ResourceLocation overlay; ResourceLocation overlay = turtle.getOverlay();
colour = turtle.getColour();
family = turtle.getFamily();
overlay = turtle.getOverlay();
renderModel( state, getTurtleModel( family, colour != -1 ), colour == -1 ? null : new int[] { colour } ); renderModel( state, getTurtleModel( family, colour != -1 ), colour == -1 ? null : new int[] { colour } );
@ -154,7 +151,7 @@ public class TileEntityTurtleRenderer extends TileEntitySpecialRenderer<TileTurt
} }
} }
private void renderUpgrade( IBlockState state, TileTurtle turtle, TurtleSide side, float f ) private static void renderUpgrade( IBlockState state, TileTurtle turtle, TurtleSide side, float f )
{ {
ITurtleUpgrade upgrade = turtle.getUpgrade( side ); ITurtleUpgrade upgrade = turtle.getUpgrade( side );
if( upgrade != null ) if( upgrade != null )
@ -187,14 +184,14 @@ public class TileEntityTurtleRenderer extends TileEntitySpecialRenderer<TileTurt
} }
} }
private void renderModel( IBlockState state, ModelResourceLocation modelLocation, int[] tints ) private static void renderModel( IBlockState state, ModelResourceLocation modelLocation, int[] tints )
{ {
Minecraft mc = Minecraft.getMinecraft(); Minecraft mc = Minecraft.getMinecraft();
ModelManager modelManager = mc.getRenderItem().getItemModelMesher().getModelManager(); ModelManager modelManager = mc.getRenderItem().getItemModelMesher().getModelManager();
renderModel( state, modelManager.getModel( modelLocation ), tints ); renderModel( state, modelManager.getModel( modelLocation ), tints );
} }
private void renderModel( IBlockState state, IBakedModel model, int[] tints ) private static void renderModel( IBlockState state, IBakedModel model, int[] tints )
{ {
Minecraft mc = Minecraft.getMinecraft(); Minecraft mc = Minecraft.getMinecraft();
Tessellator tessellator = Tessellator.getInstance(); Tessellator tessellator = Tessellator.getInstance();
@ -206,7 +203,7 @@ public class TileEntityTurtleRenderer extends TileEntitySpecialRenderer<TileTurt
} }
} }
private void renderQuads( Tessellator tessellator, List<BakedQuad> quads, int[] tints ) private static void renderQuads( Tessellator tessellator, List<BakedQuad> quads, int[] tints )
{ {
BufferBuilder buffer = tessellator.getBuffer(); BufferBuilder buffer = tessellator.getBuffer();
VertexFormat format = DefaultVertexFormats.ITEM; VertexFormat format = DefaultVertexFormats.ITEM;

View File

@ -21,7 +21,7 @@ import net.minecraftforge.common.model.IModelState;
import javax.annotation.Nonnull; import javax.annotation.Nonnull;
import java.util.function.Function; import java.util.function.Function;
public class TurtleModelLoader implements ICustomModelLoader public final class TurtleModelLoader implements ICustomModelLoader
{ {
private static final ResourceLocation NORMAL_TURTLE_MODEL = new ResourceLocation( ComputerCraft.MOD_ID, "block/turtle" ); private static final ResourceLocation NORMAL_TURTLE_MODEL = new ResourceLocation( ComputerCraft.MOD_ID, "block/turtle" );
private static final ResourceLocation ADVANCED_TURTLE_MODEL = new ResourceLocation( ComputerCraft.MOD_ID, "block/advanced_turtle" ); private static final ResourceLocation ADVANCED_TURTLE_MODEL = new ResourceLocation( ComputerCraft.MOD_ID, "block/advanced_turtle" );
@ -64,7 +64,7 @@ public class TurtleModelLoader implements ICustomModelLoader
throw new IllegalStateException( "Loader does not accept " + name ); throw new IllegalStateException( "Loader does not accept " + name );
} }
private static class TurtleModel implements IModel private static final class TurtleModel implements IModel
{ {
private final IModel family; private final IModel family;
private final IModel colour; private final IModel colour;

View File

@ -17,7 +17,7 @@ import net.minecraft.util.EnumFacing;
import javax.annotation.Nonnull; import javax.annotation.Nonnull;
import javax.vecmath.Matrix4f; import javax.vecmath.Matrix4f;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.HashMap; import java.util.EnumMap;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
@ -30,8 +30,8 @@ public class TurtleMultiModel implements IBakedModel
private final Matrix4f m_leftUpgradeTransform; private final Matrix4f m_leftUpgradeTransform;
private final IBakedModel m_rightUpgradeModel; private final IBakedModel m_rightUpgradeModel;
private final Matrix4f m_rightUpgradeTransform; private final Matrix4f m_rightUpgradeTransform;
private List<BakedQuad> m_generalQuads; private List<BakedQuad> m_generalQuads = null;
private Map<EnumFacing, List<BakedQuad>> m_faceQuads; private Map<EnumFacing, List<BakedQuad>> m_faceQuads = new EnumMap<>( EnumFacing.class );
public TurtleMultiModel( IBakedModel baseModel, IBakedModel overlayModel, Matrix4f generalTransform, IBakedModel leftUpgradeModel, Matrix4f leftUpgradeTransform, IBakedModel rightUpgradeModel, Matrix4f rightUpgradeTransform ) public TurtleMultiModel( IBakedModel baseModel, IBakedModel overlayModel, Matrix4f generalTransform, IBakedModel leftUpgradeModel, Matrix4f leftUpgradeTransform, IBakedModel rightUpgradeModel, Matrix4f rightUpgradeTransform )
{ {
@ -43,8 +43,6 @@ public class TurtleMultiModel implements IBakedModel
m_rightUpgradeModel = rightUpgradeModel; m_rightUpgradeModel = rightUpgradeModel;
m_rightUpgradeTransform = rightUpgradeTransform; m_rightUpgradeTransform = rightUpgradeTransform;
m_generalTransform = generalTransform; m_generalTransform = generalTransform;
m_generalQuads = null;
m_faceQuads = new HashMap<>();
} }
@Nonnull @Nonnull

View File

@ -143,10 +143,10 @@ public class TurtleSmartItemModel implements IBakedModel
ModelResourceLocation overlayModelLocation = TileEntityTurtleRenderer.getTurtleOverlayModel( combo.m_overlay, combo.m_christmas ); ModelResourceLocation overlayModelLocation = TileEntityTurtleRenderer.getTurtleOverlayModel( combo.m_overlay, combo.m_christmas );
IBakedModel baseModel = combo.m_colour ? colourModel : familyModel; IBakedModel baseModel = combo.m_colour ? colourModel : familyModel;
IBakedModel overlayModel = (overlayModelLocation != null) ? modelManager.getModel( overlayModelLocation ) : null; IBakedModel overlayModel = overlayModelLocation != null ? modelManager.getModel( overlayModelLocation ) : null;
Matrix4f transform = combo.m_flip ? s_flip : s_identity; Matrix4f transform = combo.m_flip ? s_flip : s_identity;
Pair<IBakedModel, Matrix4f> leftModel = (combo.m_leftUpgrade != null) ? combo.m_leftUpgrade.getModel( null, TurtleSide.Left ) : null; Pair<IBakedModel, Matrix4f> leftModel = combo.m_leftUpgrade != null ? combo.m_leftUpgrade.getModel( null, TurtleSide.Left ) : null;
Pair<IBakedModel, Matrix4f> rightModel = (combo.m_rightUpgrade != null) ? combo.m_rightUpgrade.getModel( null, TurtleSide.Right ) : null; Pair<IBakedModel, Matrix4f> rightModel = combo.m_rightUpgrade != null ? combo.m_rightUpgrade.getModel( null, TurtleSide.Right ) : null;
if( leftModel != null && rightModel != null ) if( leftModel != null && rightModel != null )
{ {
return new TurtleMultiModel( baseModel, overlayModel, transform, leftModel.getLeft(), leftModel.getRight(), rightModel.getLeft(), rightModel.getRight() ); return new TurtleMultiModel( baseModel, overlayModel, transform, leftModel.getLeft(), leftModel.getRight(), rightModel.getLeft(), rightModel.getRight() );

View File

@ -20,7 +20,7 @@ import java.util.regex.Pattern;
*/ */
public class AddressPredicate public class AddressPredicate
{ {
private static class HostRange private static final class HostRange
{ {
private final byte[] min; private final byte[] min;
private final byte[] max; private final byte[] max;

View File

@ -353,10 +353,8 @@ public class FSAPI implements ILuaAPI
return new Object[] { FileSystem.getDirectory( path ) }; return new Object[] { FileSystem.getDirectory( path ) };
} }
default: default:
{ assert false;
assert (false);
return null; return null;
} }
} }
}
} }

View File

@ -199,24 +199,22 @@ public class HTTPAPI implements ILuaAPI
} }
} }
default: default:
{
return null; return null;
} }
} }
}
@Nonnull @Nonnull
private static HttpHeaders getHeaders( @Nonnull Map<?, ?> headerTable ) throws LuaException private static HttpHeaders getHeaders( @Nonnull Map<?, ?> headerTable ) throws LuaException
{ {
HttpHeaders headers = new DefaultHttpHeaders(); HttpHeaders headers = new DefaultHttpHeaders();
for( Object key : headerTable.keySet() ) for( Map.Entry<?, ?> entry : headerTable.entrySet() )
{ {
Object value = headerTable.get( key ); Object value = entry.getValue();
if( key instanceof String && value instanceof String ) if( entry.getKey() instanceof String && value instanceof String )
{ {
try try
{ {
headers.add( (String) key, value ); headers.add( (String) entry.getKey(), value );
} }
catch( IllegalArgumentException e ) catch( IllegalArgumentException e )
{ {

View File

@ -24,6 +24,7 @@ public interface IAPIEnvironment
int SIDE_COUNT = 6; int SIDE_COUNT = 6;
@FunctionalInterface
interface IPeripheralChangeListener interface IPeripheralChangeListener
{ {
void onPeripheralChanged( int side, @Nullable IPeripheral newPeripheral ); void onPeripheralChanged( int side, @Nullable IPeripheral newPeripheral );

View File

@ -39,7 +39,7 @@ public class OSAPI implements ILuaAPI
} }
} }
private class Alarm implements Comparable<Alarm> private static class Alarm implements Comparable<Alarm>
{ {
public final double m_time; public final double m_time;
public final int m_day; public final int m_day;
@ -110,7 +110,7 @@ public class OSAPI implements ILuaAPI
{ {
Map.Entry<Integer, Timer> entry = it.next(); Map.Entry<Integer, Timer> entry = it.next();
Timer timer = entry.getValue(); Timer timer = entry.getValue();
timer.m_ticksLeft = timer.m_ticksLeft - 1; timer.m_ticksLeft--;
if( timer.m_ticksLeft <= 0 ) if( timer.m_ticksLeft <= 0 )
{ {
// Queue the "timer" event // Queue the "timer" event
@ -198,7 +198,7 @@ public class OSAPI implements ILuaAPI
private int getDayForCalendar( Calendar c ) private int getDayForCalendar( Calendar c )
{ {
GregorianCalendar g = (c instanceof GregorianCalendar) ? (GregorianCalendar) c : new GregorianCalendar(); GregorianCalendar g = c instanceof GregorianCalendar ? (GregorianCalendar) c : new GregorianCalendar();
int year = c.get( Calendar.YEAR ); int year = c.get( Calendar.YEAR );
int day = 0; int day = 0;
for( int y = 1970; y < year; y++ ) for( int y = 1970; y < year; y++ )
@ -219,12 +219,9 @@ public class OSAPI implements ILuaAPI
{ {
switch( method ) switch( method )
{ {
case 0: case 0: // queueEvent
{
// queueEvent
queueLuaEvent( getString( args, 0 ), trimArray( args, 1 ) ); queueLuaEvent( getString( args, 0 ), trimArray( args, 1 ) );
return null; return null;
}
case 1: case 1:
{ {
// startTimer // startTimer
@ -245,29 +242,20 @@ public class OSAPI implements ILuaAPI
} }
synchronized( m_alarms ) synchronized( m_alarms )
{ {
int day = (time > m_time) ? m_day : (m_day + 1); int day = time > m_time ? m_day : m_day + 1;
m_alarms.put( m_nextAlarmToken, new Alarm( time, day ) ); m_alarms.put( m_nextAlarmToken, new Alarm( time, day ) );
return new Object[] { m_nextAlarmToken++ }; return new Object[] { m_nextAlarmToken++ };
} }
} }
case 3: case 3: // shutdown
{
// shutdown
m_apiEnvironment.shutdown(); m_apiEnvironment.shutdown();
return null; return null;
} case 4: // reboot
case 4:
{
// reboot
m_apiEnvironment.reboot(); m_apiEnvironment.reboot();
return null; return null;
}
case 5: case 5:
case 6: case 6: // computerID/getComputerID
{
// computerID/getComputerID
return new Object[] { getComputerID() }; return new Object[] { getComputerID() };
}
case 7: case 7:
{ {
// setComputerLabel // setComputerLabel
@ -286,14 +274,11 @@ public class OSAPI implements ILuaAPI
} }
return null; return null;
} }
case 10: case 10: // clock
{
// clock
synchronized( m_timers ) synchronized( m_timers )
{ {
return new Object[] { m_clock * 0.05 }; return new Object[] { m_clock * 0.05 };
} }
}
case 11: case 11:
{ {
// time // time
@ -355,12 +340,9 @@ public class OSAPI implements ILuaAPI
// cancelTimer // cancelTimer
int token = getInt( args, 0 ); int token = getInt( args, 0 );
synchronized( m_timers ) synchronized( m_timers )
{
if( m_timers.containsKey( token ) )
{ {
m_timers.remove( token ); m_timers.remove( token );
} }
}
return null; return null;
} }
case 14: case 14:
@ -368,12 +350,9 @@ public class OSAPI implements ILuaAPI
// cancelAlarm // cancelAlarm
int token = getInt( args, 0 ); int token = getInt( args, 0 );
synchronized( m_alarms ) synchronized( m_alarms )
{
if( m_alarms.containsKey( token ) )
{ {
m_alarms.remove( token ); m_alarms.remove( token );
} }
}
return null; return null;
} }
case 15: case 15:
@ -407,11 +386,9 @@ public class OSAPI implements ILuaAPI
} }
} }
default: default:
{
return null; return null;
} }
} }
}
// Private methods // Private methods

View File

@ -44,8 +44,8 @@ public class PeripheralAPI implements ILuaAPI, IAPIEnvironment.IPeripheralChange
m_type = peripheral.getType(); m_type = peripheral.getType();
m_methods = peripheral.getMethodNames(); m_methods = peripheral.getMethodNames();
assert (m_type != null); assert m_type != null;
assert (m_methods != null); assert m_methods != null;
m_methodMap = new HashMap<>(); m_methodMap = new HashMap<>();
for( int i = 0; i < m_methods.length; i++ ) for( int i = 0; i < m_methods.length; i++ )
@ -422,11 +422,9 @@ public class PeripheralAPI implements ILuaAPI, IAPIEnvironment.IPeripheralChange
throw new LuaException( "No peripheral attached" ); throw new LuaException( "No peripheral attached" );
} }
default: default:
{
return null; return null;
} }
} }
}
// Privates // Privates

View File

@ -116,7 +116,7 @@ public class RedstoneAPI implements ILuaAPI
int side = parseSide( args ); int side = parseSide( args );
int mask = getInt( args, 1 ); int mask = getInt( args, 1 );
int input = m_environment.getBundledInput( side ); int input = m_environment.getBundledInput( side );
return new Object[] { ((input & mask) == mask) }; return new Object[] { (input & mask) == mask };
} }
case 8: case 8:
case 9: case 9:
@ -146,13 +146,11 @@ public class RedstoneAPI implements ILuaAPI
return new Object[] { m_environment.getInput( side ) }; return new Object[] { m_environment.getInput( side ) };
} }
default: default:
{
return null; return null;
} }
} }
}
private int parseSide( Object[] args ) throws LuaException private static int parseSide( Object[] args ) throws LuaException
{ {
String side = getString( args, 0 ); String side = getString( args, 0 );
for( int n = 0; n < IAPIEnvironment.SIDE_NAMES.length; n++ ) for( int n = 0; n < IAPIEnvironment.SIDE_NAMES.length; n++ )

View File

@ -111,16 +111,7 @@ public class TermAPI implements ILuaAPI
case 0: case 0:
{ {
// write // write
String text; String text = args.length > 0 && args[0] != null ? args[0].toString() : "";
if( args.length > 0 && args[0] != null )
{
text = args[0].toString();
}
else
{
text = "";
}
synchronized( m_terminal ) synchronized( m_terminal )
{ {
m_terminal.write( text ); m_terminal.write( text );
@ -181,24 +172,18 @@ public class TermAPI implements ILuaAPI
} }
return new Object[] { width, height }; return new Object[] { width, height };
} }
case 6: case 6: // clear
{
// clear
synchronized( m_terminal ) synchronized( m_terminal )
{ {
m_terminal.clear(); m_terminal.clear();
} }
return null; return null;
} case 7: // clearLine
case 7:
{
// clearLine
synchronized( m_terminal ) synchronized( m_terminal )
{ {
m_terminal.clearLine(); m_terminal.clearLine();
} }
return null; return null;
}
case 8: case 8:
case 9: case 9:
{ {
@ -222,23 +207,14 @@ public class TermAPI implements ILuaAPI
return null; return null;
} }
case 12: case 12:
case 13: case 13: // isColour/isColor
{
// isColour/isColor
return new Object[] { m_environment.isColour() }; return new Object[] { m_environment.isColour() };
}
case 14: case 14:
case 15: case 15: // getTextColour/getTextColor
{
// getTextColour/getTextColor
return encodeColour( m_terminal.getTextColour() ); return encodeColour( m_terminal.getTextColour() );
}
case 16: case 16:
case 17: case 17: // getBackgroundColour/getBackgroundColor
{
// getBackgroundColour/getBackgroundColor
return encodeColour( m_terminal.getBackgroundColour() ); return encodeColour( m_terminal.getBackgroundColour() );
}
case 18: case 18:
{ {
// blit // blit
@ -308,11 +284,9 @@ public class TermAPI implements ILuaAPI
// getCursorBlink // getCursorBlink
return new Object[] { m_terminal.getCursorBlink() }; return new Object[] { m_terminal.getCursorBlink() };
default: default:
{
return null; return null;
} }
} }
}
private static int getHighestBit( int group ) private static int getHighestBit( int group )
{ {

View File

@ -6,13 +6,11 @@
package dan200.computercraft.core.apis.handles; package dan200.computercraft.core.apis.handles;
import com.google.common.base.Preconditions;
import java.io.IOException;
import java.nio.ByteBuffer; import java.nio.ByteBuffer;
import java.nio.channels.ClosedChannelException; import java.nio.channels.ClosedChannelException;
import java.nio.channels.NonWritableChannelException; import java.nio.channels.NonWritableChannelException;
import java.nio.channels.SeekableByteChannel; import java.nio.channels.SeekableByteChannel;
import java.util.Objects;
/** /**
* A seekable, readable byte channel which is backed by a simple byte array. * A seekable, readable byte channel which is backed by a simple byte array.
@ -30,10 +28,10 @@ public class ArrayByteChannel implements SeekableByteChannel
} }
@Override @Override
public int read( ByteBuffer destination ) throws IOException public int read( ByteBuffer destination ) throws ClosedChannelException
{ {
if( closed ) throw new ClosedChannelException(); if( closed ) throw new ClosedChannelException();
Preconditions.checkNotNull( destination, "destination" ); Objects.requireNonNull( destination, "destination" );
if( position >= backing.length ) return -1; if( position >= backing.length ) return -1;
@ -44,21 +42,21 @@ public class ArrayByteChannel implements SeekableByteChannel
} }
@Override @Override
public int write( ByteBuffer src ) throws IOException public int write( ByteBuffer src ) throws ClosedChannelException
{ {
if( closed ) throw new ClosedChannelException(); if( closed ) throw new ClosedChannelException();
throw new NonWritableChannelException(); throw new NonWritableChannelException();
} }
@Override @Override
public long position() throws IOException public long position() throws ClosedChannelException
{ {
if( closed ) throw new ClosedChannelException(); if( closed ) throw new ClosedChannelException();
return position; return position;
} }
@Override @Override
public SeekableByteChannel position( long newPosition ) throws IOException public SeekableByteChannel position( long newPosition ) throws ClosedChannelException
{ {
if( closed ) throw new ClosedChannelException(); if( closed ) throw new ClosedChannelException();
if( newPosition < 0 || newPosition > Integer.MAX_VALUE ) if( newPosition < 0 || newPosition > Integer.MAX_VALUE )
@ -70,14 +68,14 @@ public class ArrayByteChannel implements SeekableByteChannel
} }
@Override @Override
public long size() throws IOException public long size() throws ClosedChannelException
{ {
if( closed ) throw new ClosedChannelException(); if( closed ) throw new ClosedChannelException();
return backing.length; return backing.length;
} }
@Override @Override
public SeekableByteChannel truncate( long size ) throws IOException public SeekableByteChannel truncate( long size ) throws ClosedChannelException
{ {
if( closed ) throw new ClosedChannelException(); if( closed ) throw new ClosedChannelException();
throw new NonWritableChannelException(); throw new NonWritableChannelException();

View File

@ -38,8 +38,8 @@ public class BinaryReadableHandle extends HandleGeneric
public BinaryReadableHandle( ReadableByteChannel channel, Closeable closeable ) public BinaryReadableHandle( ReadableByteChannel channel, Closeable closeable )
{ {
super( closeable ); super( closeable );
this.m_reader = channel; m_reader = channel;
this.m_seekable = asSeekable( channel ); m_seekable = asSeekable( channel );
} }
public BinaryReadableHandle( ReadableByteChannel channel ) public BinaryReadableHandle( ReadableByteChannel channel )

View File

@ -32,8 +32,8 @@ public class BinaryWritableHandle extends HandleGeneric
public BinaryWritableHandle( WritableByteChannel channel, Closeable closeable ) public BinaryWritableHandle( WritableByteChannel channel, Closeable closeable )
{ {
super( closeable ); super( closeable );
this.m_writer = channel; m_writer = channel;
this.m_seekable = asSeekable( channel ); m_seekable = asSeekable( channel );
} }
public BinaryWritableHandle( WritableByteChannel channel ) public BinaryWritableHandle( WritableByteChannel channel )

View File

@ -32,7 +32,7 @@ public class EncodedReadableHandle extends HandleGeneric
public EncodedReadableHandle( @Nonnull BufferedReader reader, @Nonnull Closeable closable ) public EncodedReadableHandle( @Nonnull BufferedReader reader, @Nonnull Closeable closable )
{ {
super( closable ); super( closable );
this.m_reader = reader; m_reader = reader;
} }
public EncodedReadableHandle( @Nonnull BufferedReader reader ) public EncodedReadableHandle( @Nonnull BufferedReader reader )
@ -84,7 +84,7 @@ public class EncodedReadableHandle extends HandleGeneric
checkOpen(); checkOpen();
try try
{ {
StringBuilder result = new StringBuilder( "" ); StringBuilder result = new StringBuilder();
String line = m_reader.readLine(); String line = m_reader.readLine();
while( line != null ) while( line != null )
{ {

View File

@ -27,7 +27,7 @@ public class EncodedWritableHandle extends HandleGeneric
public EncodedWritableHandle( @Nonnull BufferedWriter writer, @Nonnull Closeable closable ) public EncodedWritableHandle( @Nonnull BufferedWriter writer, @Nonnull Closeable closable )
{ {
super( closable ); super( closable );
this.m_writer = writer; m_writer = writer;
} }
public EncodedWritableHandle( @Nonnull BufferedWriter writer ) public EncodedWritableHandle( @Nonnull BufferedWriter writer )

View File

@ -26,7 +26,7 @@ public abstract class HandleGeneric implements ILuaObject
protected HandleGeneric( @Nonnull Closeable closable ) protected HandleGeneric( @Nonnull Closeable closable )
{ {
this.m_closable = closable; m_closable = closable;
} }
protected void checkOpen() throws LuaException protected void checkOpen() throws LuaException
@ -46,7 +46,7 @@ public abstract class HandleGeneric implements ILuaObject
* *
* @param channel The channel to seek in * @param channel The channel to seek in
* @param args The Lua arguments to process, like Lua's {@code file:seek}. * @param args The Lua arguments to process, like Lua's {@code file:seek}.
* @return The new position of the file, or null if some error occured. * @return The new position of the file, or null if some error occurred.
* @throws LuaException If the arguments were invalid * @throws LuaException If the arguments were invalid
* @see <a href="https://www.lua.org/manual/5.1/manual.html#pdf-file:seek">{@code file:seek} in the Lua manual.</a> * @see <a href="https://www.lua.org/manual/5.1/manual.html#pdf-file:seek">{@code file:seek} in the Lua manual.</a>
*/ */

View File

@ -31,7 +31,7 @@ public class CheckUrl extends Resource<CheckUrl>
super( limiter ); super( limiter );
this.environment = environment; this.environment = environment;
this.address = address; this.address = address;
this.host = uri.getHost(); host = uri.getHost();
} }
public void run() public void run()

View File

@ -140,6 +140,6 @@ public abstract class Resource<T extends Resource<T>> implements Closeable
public static void cleanup() public static void cleanup()
{ {
Reference<?> reference; Reference<?> reference;
while( (reference = QUEUE.poll()) != null ) ((CloseReference) reference).resource.close(); while( (reference = QUEUE.poll()) != null ) ((CloseReference<?>) reference).resource.close();
} }
} }

View File

@ -32,7 +32,7 @@ public class ResourceGroup<T extends Resource<T>>
public ResourceGroup() public ResourceGroup()
{ {
this.limit = ZERO; limit = ZERO;
} }
public void startup() public void startup()

View File

@ -67,12 +67,12 @@ public class HttpRequest extends Resource<HttpRequest>
super( limiter ); super( limiter );
this.environment = environment; this.environment = environment;
this.address = address; this.address = address;
this.postBuffer = postText != null postBuffer = postText != null
? Unpooled.wrappedBuffer( postText.getBytes( StandardCharsets.UTF_8 ) ) ? Unpooled.wrappedBuffer( postText.getBytes( StandardCharsets.UTF_8 ) )
: Unpooled.buffer( 0 ); : Unpooled.buffer( 0 );
this.headers = headers; this.headers = headers;
this.binary = binary; this.binary = binary;
this.redirects = new AtomicInteger( followRedirects ? MAX_REDIRECTS : 0 ); redirects = new AtomicInteger( followRedirects ? MAX_REDIRECTS : 0 );
if( postText != null ) if( postText != null )
{ {

View File

@ -37,7 +37,7 @@ public final class HttpRequestHandler extends SimpleChannelInboundHandler<HttpOb
/** /**
* Same as {@link io.netty.handler.codec.MessageAggregator}. * Same as {@link io.netty.handler.codec.MessageAggregator}.
*/ */
private static final int DEFAULT_MAX_COMPOSITEBUFFER_COMPONENTS = 1024; private static final int DEFAULT_MAX_COMPOSITE_BUFFER_COMPONENTS = 1024;
private static final byte[] EMPTY_BYTES = new byte[0]; private static final byte[] EMPTY_BYTES = new byte[0];
@ -147,7 +147,7 @@ public final class HttpRequestHandler extends SimpleChannelInboundHandler<HttpOb
if( responseBody == null ) if( responseBody == null )
{ {
responseBody = ctx.alloc().compositeBuffer( DEFAULT_MAX_COMPOSITEBUFFER_COMPONENTS ); responseBody = ctx.alloc().compositeBuffer( DEFAULT_MAX_COMPOSITE_BUFFER_COMPONENTS );
} }
ByteBuf partial = content.content(); ByteBuf partial = content.content();

View File

@ -95,7 +95,7 @@ public class Websocket extends Resource<Websocket>
{ {
try try
{ {
uri = new URI( "ws://" + uri.toString() ); uri = new URI( "ws://" + uri );
} }
catch( URISyntaxException e ) catch( URISyntaxException e )
{ {
@ -186,7 +186,7 @@ public class Websocket extends Resource<Websocket>
WebsocketHandle handle = new WebsocketHandle( this, channel ); WebsocketHandle handle = new WebsocketHandle( this, channel );
environment().queueEvent( SUCCESS_EVENT, new Object[] { address, handle } ); environment().queueEvent( SUCCESS_EVENT, new Object[] { address, handle } );
this.websocketHandle = createOwnerReference( handle ); websocketHandle = createOwnerReference( handle );
checkClosed(); checkClosed();
} }
@ -216,7 +216,7 @@ public class Websocket extends Resource<Websocket>
executorFuture = closeFuture( executorFuture ); executorFuture = closeFuture( executorFuture );
connectFuture = closeChannel( connectFuture ); connectFuture = closeChannel( connectFuture );
WeakReference<WebsocketHandle> websocketHandleRef = this.websocketHandle; WeakReference<WebsocketHandle> websocketHandleRef = websocketHandle;
WebsocketHandle websocketHandle = websocketHandleRef == null ? null : websocketHandleRef.get(); WebsocketHandle websocketHandle = websocketHandleRef == null ? null : websocketHandleRef.get();
if( websocketHandle != null ) IoUtil.closeQuietly( websocketHandle ); if( websocketHandle != null ) IoUtil.closeQuietly( websocketHandle );
this.websocketHandle = null; this.websocketHandle = null;

View File

@ -233,7 +233,7 @@ final class ComputerExecutor
synchronized( queueLock ) synchronized( queueLock )
{ {
if( closed ) return; if( closed ) return;
this.closed = close; closed = close;
StateCommand newCommand = reboot ? StateCommand.REBOOT : StateCommand.SHUTDOWN; StateCommand newCommand = reboot ? StateCommand.REBOOT : StateCommand.SHUTDOWN;
@ -425,7 +425,7 @@ final class ComputerExecutor
} }
// Init filesystem // Init filesystem
if( (this.fileSystem = createFileSystem()) == null ) if( (fileSystem = createFileSystem()) == null )
{ {
shutdown(); shutdown();
return; return;
@ -435,7 +435,7 @@ final class ComputerExecutor
for( ILuaAPI api : apis ) api.startup(); for( ILuaAPI api : apis ) api.startup();
// Init lua // Init lua
if( (this.machine = createLuaMachine()) == null ) if( (machine = createLuaMachine()) == null )
{ {
shutdown(); shutdown();
return; return;
@ -650,7 +650,7 @@ final class ComputerExecutor
ABORT, ABORT,
} }
private static class Event private static final class Event
{ {
final String name; final String name;
final Object[] args; final Object[] args;

View File

@ -47,7 +47,7 @@ import static dan200.computercraft.core.computer.TimeoutState.TIMEOUT;
* @see TimeoutState For how hard timeouts are handled. * @see TimeoutState For how hard timeouts are handled.
* @see ComputerExecutor For how computers actually do execution. * @see ComputerExecutor For how computers actually do execution.
*/ */
public class ComputerThread public final class ComputerThread
{ {
/** /**
* How often the computer thread monitor should run, in milliseconds * How often the computer thread monitor should run, in milliseconds
@ -123,6 +123,8 @@ public class ComputerThread
private static final ThreadFactory monitorFactory = ThreadUtils.factory( "Computer-Monitor" ); private static final ThreadFactory monitorFactory = ThreadUtils.factory( "Computer-Monitor" );
private static final ThreadFactory runnerFactory = ThreadUtils.factory( "Computer-Runner" ); private static final ThreadFactory runnerFactory = ThreadUtils.factory( "Computer-Runner" );
private ComputerThread() {}
/** /**
* Start the computer thread * Start the computer thread
*/ */
@ -339,7 +341,7 @@ public class ComputerThread
*/ */
static boolean hasPendingWork() static boolean hasPendingWork()
{ {
return computerQueue.size() > 0; return !computerQueue.isEmpty();
} }
/** /**

View File

@ -22,7 +22,7 @@ import java.util.Arrays;
* *
* This handles storing and updating of peripherals and redstone. * This handles storing and updating of peripherals and redstone.
* *
* <h2>Redstone</h2> * <h1>Redstone</h1>
* We holds three kinds of arrays for redstone, in normal and bundled versions: * We holds three kinds of arrays for redstone, in normal and bundled versions:
* <ul> * <ul>
* <li>{@link #internalOutput} is the redstone output which the computer has currently set. This is read on both * <li>{@link #internalOutput} is the redstone output which the computer has currently set. This is read on both
@ -33,7 +33,7 @@ import java.util.Arrays;
* thread.</li> * thread.</li>
* </ul> * </ul>
* *
* <h2>Peripheral</h2> * <h1>Peripheral</h1>
* We also keep track of peripherals. These are read on both threads, and only written on the main thread. * We also keep track of peripherals. These are read on both threads, and only written on the main thread.
*/ */
public final class Environment implements IAPIEnvironment public final class Environment implements IAPIEnvironment
@ -215,7 +215,7 @@ public final class Environment implements IAPIEnvironment
*/ */
boolean updateOutput() boolean updateOutput()
{ {
// Set outputchanged if the internal redstone has changed // Mark output as changed if the internal redstone has changed
synchronized( internalOutput ) synchronized( internalOutput )
{ {
if( !internalOutputChanged ) return false; if( !internalOutputChanged ) return false;

View File

@ -27,7 +27,7 @@ import java.util.concurrent.atomic.AtomicLong;
* Next tick, we put {@link ComputerCraft#maxMainGlobalTime} into our budget (and clamp it to that value to). If we're * Next tick, we put {@link ComputerCraft#maxMainGlobalTime} into our budget (and clamp it to that value to). If we're
* still over budget, then we should not execute <em>any</em> work (either as part of {@link MainThread} or externally). * still over budget, then we should not execute <em>any</em> work (either as part of {@link MainThread} or externally).
*/ */
public class MainThread public final class MainThread
{ {
/** /**
* An internal counter for {@link ILuaTask} ids. * An internal counter for {@link ILuaTask} ids.
@ -47,7 +47,6 @@ public class MainThread
if( at == bt ) return Integer.compare( a.hashCode(), b.hashCode() ); if( at == bt ) return Integer.compare( a.hashCode(), b.hashCode() );
return at < bt ? -1 : 1; return at < bt ? -1 : 1;
} ); } );
;
/** /**
* The set of executors which went over budget in a previous tick, and are waiting for their time to run down. * The set of executors which went over budget in a previous tick, and are waiting for their time to run down.
@ -79,6 +78,8 @@ public class MainThread
private static long minimumTime = 0; private static long minimumTime = 0;
private MainThread() {}
public static long getUniqueTaskID() public static long getUniqueTaskID()
{ {
return lastTaskId.incrementAndGet(); return lastTaskId.incrementAndGet();

View File

@ -93,7 +93,7 @@ public final class TimeoutState
// need to handle overflow. // need to handle overflow.
long now = System.nanoTime(); long now = System.nanoTime();
if( !paused ) paused = currentDeadline - now <= 0 && ComputerThread.hasPendingWork(); // now >= currentDeadline if( !paused ) paused = currentDeadline - now <= 0 && ComputerThread.hasPendingWork(); // now >= currentDeadline
if( !softAbort ) softAbort = (now - cumulativeStart - TIMEOUT) >= 0; // now - cumulativeStart >= TIMEOUT if( !softAbort ) softAbort = now - cumulativeStart - TIMEOUT >= 0; // now - cumulativeStart >= TIMEOUT
} }
/** /**

View File

@ -55,16 +55,10 @@ public class FileMount implements IWritableMount
m_ignoredBytesLeft = 0; m_ignoredBytesLeft = 0;
long bytesLeft = m_capacity - m_usedSpace; long bytesLeft = m_capacity - m_usedSpace;
if( newBytes > bytesLeft ) if( newBytes > bytesLeft ) throw new IOException( "Out of space" );
{
throw new IOException( "Out of space" );
}
else
{
m_usedSpace += newBytes; m_usedSpace += newBytes;
} }
} }
}
@Override @Override
public boolean isOpen() public boolean isOpen()
@ -86,14 +80,17 @@ public class FileMount implements IWritableMount
SeekableCountingChannel( SeekableByteChannel inner, long bytesToIgnore ) SeekableCountingChannel( SeekableByteChannel inner, long bytesToIgnore )
{ {
super( inner, bytesToIgnore ); super( inner, bytesToIgnore );
this.m_inner = inner; m_inner = inner;
} }
@Override @Override
public SeekableByteChannel position( long newPosition ) throws IOException public SeekableByteChannel position( long newPosition ) throws IOException
{ {
if( !isOpen() ) throw new ClosedChannelException(); if( !isOpen() ) throw new ClosedChannelException();
if( newPosition < 0 ) throw new IllegalArgumentException(); if( newPosition < 0 )
{
throw new IllegalArgumentException( "Cannot seek before the beginning of the stream" );
}
long delta = newPosition - m_inner.position(); long delta = newPosition - m_inner.position();
if( delta < 0 ) if( delta < 0 )
@ -115,7 +112,7 @@ public class FileMount implements IWritableMount
} }
@Override @Override
public int read( ByteBuffer dst ) throws IOException public int read( ByteBuffer dst ) throws ClosedChannelException
{ {
if( !m_inner.isOpen() ) throw new ClosedChannelException(); if( !m_inner.isOpen() ) throw new ClosedChannelException();
throw new NonReadableChannelException(); throw new NonReadableChannelException();
@ -150,59 +147,37 @@ public class FileMount implements IWritableMount
@Override @Override
public boolean exists( @Nonnull String path ) public boolean exists( @Nonnull String path )
{ {
if( !created() ) if( !created() ) return path.isEmpty();
{
return path.length() == 0;
}
else
{
File file = getRealPath( path ); File file = getRealPath( path );
return file.exists(); return file.exists();
} }
}
@Override @Override
public boolean isDirectory( @Nonnull String path ) public boolean isDirectory( @Nonnull String path )
{ {
if( !created() ) if( !created() ) return path.isEmpty();
{
return path.length() == 0;
}
else
{
File file = getRealPath( path ); File file = getRealPath( path );
return file.exists() && file.isDirectory(); return file.exists() && file.isDirectory();
} }
}
@Override @Override
public void list( @Nonnull String path, @Nonnull List<String> contents ) throws IOException public void list( @Nonnull String path, @Nonnull List<String> contents ) throws IOException
{ {
if( !created() ) if( !created() )
{ {
if( path.length() != 0 ) if( !path.isEmpty() ) throw new IOException( "/" + path + ": Not a directory" );
{ return;
throw new IOException( "/" + path + ": Not a directory" );
} }
}
else
{
File file = getRealPath( path ); File file = getRealPath( path );
if( file.exists() && file.isDirectory() ) if( !file.exists() || !file.isDirectory() ) throw new IOException( "/" + path + ": Not a directory" );
{
String[] paths = file.list(); String[] paths = file.list();
for( String subPath : paths ) for( String subPath : paths )
{ {
if( new File( file, subPath ).exists() ) if( new File( file, subPath ).exists() ) contents.add( subPath );
{
contents.add( subPath );
}
}
}
else
{
throw new IOException( "/" + path + ": Not a directory" );
}
} }
} }
@ -211,26 +186,14 @@ public class FileMount implements IWritableMount
{ {
if( !created() ) if( !created() )
{ {
if( path.length() == 0 ) if( path.isEmpty() ) return 0;
{
return 0;
}
} }
else else
{ {
File file = getRealPath( path ); File file = getRealPath( path );
if( file.exists() ) if( file.exists() ) return file.isDirectory() ? 0 : file.length();
{
if( file.isDirectory() )
{
return 0;
}
else
{
return file.length();
}
}
} }
throw new IOException( "/" + path + ": No such file" ); throw new IOException( "/" + path + ": No such file" );
} }
@ -242,11 +205,9 @@ public class FileMount implements IWritableMount
if( created() ) if( created() )
{ {
File file = getRealPath( path ); File file = getRealPath( path );
if( file.exists() && !file.isDirectory() ) if( file.exists() && !file.isDirectory() ) return new FileInputStream( file );
{
return new FileInputStream( file );
}
} }
throw new IOException( "/" + path + ": No such file" ); throw new IOException( "/" + path + ": No such file" );
} }
@ -257,11 +218,9 @@ public class FileMount implements IWritableMount
if( created() ) if( created() )
{ {
File file = getRealPath( path ); File file = getRealPath( path );
if( file.exists() && !file.isDirectory() ) if( file.exists() && !file.isDirectory() ) return FileChannel.open( file.toPath(), READ_OPTIONS );
{
return FileChannel.open( file.toPath(), READ_OPTIONS );
}
} }
throw new IOException( "/" + path + ": No such file" ); throw new IOException( "/" + path + ": No such file" );
} }
@ -274,13 +233,10 @@ public class FileMount implements IWritableMount
File file = getRealPath( path ); File file = getRealPath( path );
if( file.exists() ) if( file.exists() )
{ {
if( !file.isDirectory() ) if( !file.isDirectory() ) throw new IOException( "/" + path + ": File exists" );
{ return;
throw new IOException( "/" + path + ": File exists" );
} }
}
else
{
int dirsToCreate = 1; int dirsToCreate = 1;
File parent = file.getParentFile(); File parent = file.getParentFile();
while( !parent.exists() ) while( !parent.exists() )
@ -294,8 +250,7 @@ public class FileMount implements IWritableMount
throw new IOException( "/" + path + ": Out of space" ); throw new IOException( "/" + path + ": Out of space" );
} }
boolean success = file.mkdirs(); if( file.mkdirs() )
if( success )
{ {
m_usedSpace += dirsToCreate * MINIMUM_FILE_SIZE; m_usedSpace += dirsToCreate * MINIMUM_FILE_SIZE;
} }
@ -304,23 +259,16 @@ public class FileMount implements IWritableMount
throw new IOException( "/" + path + ": Access denied" ); throw new IOException( "/" + path + ": Access denied" );
} }
} }
}
@Override @Override
public void delete( @Nonnull String path ) throws IOException public void delete( @Nonnull String path ) throws IOException
{ {
if( path.length() == 0 ) if( path.isEmpty() ) throw new IOException( "/" + path + ": Access denied" );
{
throw new IOException( "/" + path + ": Access denied" );
}
if( created() ) if( created() )
{ {
File file = getRealPath( path ); File file = getRealPath( path );
if( file.exists() ) if( file.exists() ) deleteRecursively( file );
{
deleteRecursively( file );
}
} }
} }
@ -371,61 +319,40 @@ public class FileMount implements IWritableMount
{ {
create(); create();
File file = getRealPath( path ); File file = getRealPath( path );
if( file.exists() && file.isDirectory() ) if( file.exists() && file.isDirectory() ) throw new IOException( "/" + path + ": Cannot write to directory" );
if( file.exists() )
{ {
throw new IOException( "/" + path + ": Cannot write to directory" ); m_usedSpace -= Math.max( file.length(), MINIMUM_FILE_SIZE );
} }
else else if( getRemainingSpace() < MINIMUM_FILE_SIZE )
{
if( !file.exists() )
{
if( getRemainingSpace() < MINIMUM_FILE_SIZE )
{ {
throw new IOException( "/" + path + ": Out of space" ); throw new IOException( "/" + path + ": Out of space" );
} }
else
{
m_usedSpace += MINIMUM_FILE_SIZE; m_usedSpace += MINIMUM_FILE_SIZE;
}
}
else
{
m_usedSpace -= Math.max( file.length(), MINIMUM_FILE_SIZE );
m_usedSpace += MINIMUM_FILE_SIZE;
}
return new SeekableCountingChannel( Files.newByteChannel( file.toPath(), WRITE_OPTIONS ), MINIMUM_FILE_SIZE ); return new SeekableCountingChannel( Files.newByteChannel( file.toPath(), WRITE_OPTIONS ), MINIMUM_FILE_SIZE );
} }
}
@Nonnull @Nonnull
@Override @Override
public WritableByteChannel openChannelForAppend( @Nonnull String path ) throws IOException public WritableByteChannel openChannelForAppend( @Nonnull String path ) throws IOException
{ {
if( created() ) if( !created() )
{
File file = getRealPath( path );
if( !file.exists() )
{ {
throw new IOException( "/" + path + ": No such file" ); throw new IOException( "/" + path + ": No such file" );
} }
else if( file.isDirectory() )
{ File file = getRealPath( path );
throw new IOException( "/" + path + ": Cannot write to directory" ); if( !file.exists() ) throw new IOException( "/" + path + ": No such file" );
} if( file.isDirectory() ) throw new IOException( "/" + path + ": Cannot write to directory" );
else
{
// Allowing seeking when appending is not recommended, so we use a separate channel. // Allowing seeking when appending is not recommended, so we use a separate channel.
return new WritableCountingChannel( return new WritableCountingChannel(
Files.newByteChannel( file.toPath(), APPEND_OPTIONS ), Files.newByteChannel( file.toPath(), APPEND_OPTIONS ),
Math.max( MINIMUM_FILE_SIZE - file.length(), 0 ) Math.max( MINIMUM_FILE_SIZE - file.length(), 0 )
); );
} }
}
else
{
throw new IOException( "/" + path + ": No such file" );
}
}
@Override @Override
public long getRemainingSpace() public long getRemainingSpace()
@ -433,7 +360,7 @@ public class FileMount implements IWritableMount
return Math.max( m_capacity - m_usedSpace, 0 ); return Math.max( m_capacity - m_usedSpace, 0 );
} }
public File getRealPath( String path ) private File getRealPath( String path )
{ {
return new File( m_rootPath, path ); return new File( m_rootPath, path );
} }
@ -455,12 +382,10 @@ public class FileMount implements IWritableMount
} }
} }
private long measureUsedSpace( File file ) private static long measureUsedSpace( File file )
{ {
if( !file.exists() ) if( !file.exists() ) return 0;
{
return 0;
}
if( file.isDirectory() ) if( file.isDirectory() )
{ {
long size = MINIMUM_FILE_SIZE; long size = MINIMUM_FILE_SIZE;

View File

@ -29,7 +29,7 @@ import java.util.regex.Pattern;
public class FileSystem public class FileSystem
{ {
private class MountWrapper private static class MountWrapper
{ {
private String m_label; private String m_label;
private String m_location; private String m_location;
@ -37,7 +37,7 @@ public class FileSystem
private IMount m_mount; private IMount m_mount;
private IWritableMount m_writableMount; private IWritableMount m_writableMount;
public MountWrapper( String label, String location, IMount mount ) MountWrapper( String label, String location, IMount mount )
{ {
m_label = label; m_label = label;
m_location = location; m_location = location;
@ -80,7 +80,7 @@ public class FileSystem
public boolean isReadOnly( String path ) public boolean isReadOnly( String path )
{ {
return (m_writableMount == null); return m_writableMount == null;
} }
// IMount forwarders: // IMount forwarders:
@ -474,7 +474,7 @@ public class FileSystem
String[] list = list( dir ); String[] list = list( dir );
for( String entry : list ) for( String entry : list )
{ {
String entryPath = dir.isEmpty() ? entry : (dir + "/" + entry); String entryPath = dir.isEmpty() ? entry : dir + "/" + entry;
if( wildPattern.matcher( entryPath ).matches() ) if( wildPattern.matcher( entryPath ).matches() )
{ {
matches.add( entryPath ); matches.add( entryPath );
@ -674,7 +674,7 @@ public class FileSystem
throw new FileSystemException( "Too many files already open" ); throw new FileSystemException( "Too many files already open" );
} }
ChannelWrapper<T> channelWrapper = new ChannelWrapper<T>( file, channel ); ChannelWrapper<T> channelWrapper = new ChannelWrapper<>( file, channel );
FileSystemWrapper<T> fsWrapper = new FileSystemWrapper<>( this, channelWrapper, m_openFileQueue ); FileSystemWrapper<T> fsWrapper = new FileSystemWrapper<>( this, channelWrapper, m_openFileQueue );
m_openFiles.put( fsWrapper.self, channelWrapper ); m_openFiles.put( fsWrapper.self, channelWrapper );
return fsWrapper; return fsWrapper;
@ -768,7 +768,7 @@ public class FileSystem
path = path.replace( '\\', '/' ); path = path.replace( '\\', '/' );
// Clean the path or illegal characters. // Clean the path or illegal characters.
final char[] specialChars = { final char[] specialChars = new char[] {
'"', ':', '<', '>', '?', '|' // Sorted by ascii value (important) '"', ':', '<', '>', '?', '|' // Sorted by ascii value (important)
}; };
@ -788,13 +788,14 @@ public class FileSystem
Stack<String> outputParts = new Stack<>(); Stack<String> outputParts = new Stack<>();
for( String part : parts ) for( String part : parts )
{ {
if( part.length() == 0 || part.equals( "." ) || threeDotsPattern.matcher( part ).matches() ) if( part.isEmpty() || part.equals( "." ) || threeDotsPattern.matcher( part ).matches() )
{ {
// . is redundant // . is redundant
// ... and more are treated as . // ... and more are treated as .
continue; continue;
} }
else if( part.equals( ".." ) )
if( part.equals( ".." ) )
{ {
// .. can cancel out the last folder entered // .. can cancel out the last folder entered
if( !outputParts.empty() ) if( !outputParts.empty() )
@ -827,7 +828,7 @@ public class FileSystem
} }
// Recombine the output parts into a new string // Recombine the output parts into a new string
StringBuilder result = new StringBuilder( "" ); StringBuilder result = new StringBuilder();
Iterator<String> it = outputParts.iterator(); Iterator<String> it = outputParts.iterator();
while( it.hasNext() ) while( it.hasNext() )
{ {
@ -874,7 +875,7 @@ public class FileSystem
path = sanitizePath( path ); path = sanitizePath( path );
location = sanitizePath( location ); location = sanitizePath( location );
assert (contains( location, path )); assert contains( location, path );
String local = path.substring( location.length() ); String local = path.substring( location.length() );
if( local.startsWith( "/" ) ) if( local.startsWith( "/" ) )
{ {

View File

@ -35,7 +35,7 @@ public class FileSystemWrapper<T extends Closeable> implements Closeable
{ {
this.fileSystem = fileSystem; this.fileSystem = fileSystem;
this.closeable = closeable; this.closeable = closeable;
this.self = new WeakReference<>( this, queue ); self = new WeakReference<>( this, queue );
} }
@Override @Override

View File

@ -76,9 +76,9 @@ public class JarMount implements IMount
{ {
zip = new ZipFile( jarFile ); zip = new ZipFile( jarFile );
} }
catch( Exception e ) catch( IOException e )
{ {
throw new IOException( "Error loading zip file" ); throw new IOException( "Error loading zip file", e );
} }
// Ensure the root entry exists. // Ensure the root entry exists.
@ -212,7 +212,7 @@ public class JarMount implements IMount
} }
} }
} }
catch( Exception e ) catch( IOException e )
{ {
// Treat errors as non-existence of file // Treat errors as non-existence of file
} }

View File

@ -68,7 +68,7 @@ public class SubMount implements IMount
private String getFullPath( String path ) private String getFullPath( String path )
{ {
if( path.length() == 0 ) if( path.isEmpty() )
{ {
return m_subPath; return m_subPath;
} }

View File

@ -67,7 +67,7 @@ public class CobaltLuaMachine implements ILuaMachine
debug = new TimeoutDebugHandler(); debug = new TimeoutDebugHandler();
// Create an environment to run in // Create an environment to run in
LuaState state = this.m_state = LuaState.builder() LuaState state = m_state = LuaState.builder()
.resourceManipulator( new VoidResourceManipulator() ) .resourceManipulator( new VoidResourceManipulator() )
.debug( debug ) .debug( debug )
.coroutineExecutor( command -> { .coroutineExecutor( command -> {
@ -254,7 +254,7 @@ public class CobaltLuaMachine implements ILuaMachine
{ {
ComputerCraft.log.error( "Error calling " + methodName + " on " + apiObject, t ); ComputerCraft.log.error( "Error calling " + methodName + " on " + apiObject, t );
} }
throw new LuaError( "Java Exception Thrown: " + t.toString(), 0 ); throw new LuaError( "Java Exception Thrown: " + t, 0 );
} }
return toValues( results ); return toValues( results );
} }
@ -348,22 +348,14 @@ public class CobaltLuaMachine implements ILuaMachine
{ {
case Constants.TNIL: case Constants.TNIL:
case Constants.TNONE: case Constants.TNONE:
{
return null; return null;
}
case Constants.TINT: case Constants.TINT:
case Constants.TNUMBER: case Constants.TNUMBER:
{
return value.toDouble(); return value.toDouble();
}
case Constants.TBOOLEAN: case Constants.TBOOLEAN:
{
return value.toBoolean(); return value.toBoolean();
}
case Constants.TSTRING: case Constants.TSTRING:
{
return value.toString(); return value.toString();
}
case Constants.TTABLE: case Constants.TTABLE:
{ {
// Table: // Table:
@ -411,11 +403,9 @@ public class CobaltLuaMachine implements ILuaMachine
return table; return table;
} }
default: default:
{
return null; return null;
} }
} }
}
private static Object[] toObjects( Varargs values, int startIdx ) private static Object[] toObjects( Varargs values, int startIdx )
{ {
@ -445,7 +435,7 @@ public class CobaltLuaMachine implements ILuaMachine
TimeoutDebugHandler() TimeoutDebugHandler()
{ {
this.timeout = CobaltLuaMachine.this.timeout; timeout = CobaltLuaMachine.this.timeout;
} }
@Override @Override
@ -560,7 +550,7 @@ public class CobaltLuaMachine implements ILuaMachine
{ {
if( ComputerCraft.logPeripheralErrors ) ComputerCraft.log.error( "Error running task", t ); if( ComputerCraft.logPeripheralErrors ) ComputerCraft.log.error( "Error running task", t );
m_computer.queueEvent( "task_complete", new Object[] { m_computer.queueEvent( "task_complete", new Object[] {
taskID, false, "Java Exception Thrown: " + t.toString() taskID, false, "Java Exception Thrown: " + t
} ); } );
} }
}; };
@ -614,7 +604,7 @@ public class CobaltLuaMachine implements ILuaMachine
} }
} }
private static class HardAbortError extends Error private static final class HardAbortError extends Error
{ {
private static final long serialVersionUID = 7954092008586367501L; private static final long serialVersionUID = 7954092008586367501L;

View File

@ -55,7 +55,7 @@ public interface ILuaMachine
* @param eventName The name of the event. This is {@code null} when first starting the machine. Note, this may * @param eventName The name of the event. This is {@code null} when first starting the machine. Note, this may
* do nothing if it does not match the event filter. * do nothing if it does not match the event filter.
* @param arguments The arguments for this event. * @param arguments The arguments for this event.
* @return The result of loading this machine. Will either be OK, or the error message that occurrred when * @return The result of loading this machine. Will either be OK, or the error message that occurred when
* executing. * executing.
*/ */
MachineResult handleEvent( @Nullable String eventName, @Nullable Object[] arguments ); MachineResult handleEvent( @Nullable String eventName, @Nullable Object[] arguments );

View File

@ -22,9 +22,9 @@ public class Terminal
private int m_width; private int m_width;
private int m_height; private int m_height;
private TextBuffer m_text[]; private TextBuffer[] m_text;
private TextBuffer m_textColour[]; private TextBuffer[] m_textColour;
private TextBuffer m_backgroundColour[]; private TextBuffer[] m_backgroundColour;
private final Palette m_palette; private final Palette m_palette;
@ -40,7 +40,7 @@ public class Terminal
{ {
m_width = width; m_width = width;
m_height = height; m_height = height;
this.onChanged = changedCallback; onChanged = changedCallback;
m_cursorColour = 0; m_cursorColour = 0;
m_cursorBackgroundColour = 15; m_cursorBackgroundColour = 15;

View File

@ -29,23 +29,23 @@ public class ComputerTracker
public ComputerTracker( Computer computer ) public ComputerTracker( Computer computer )
{ {
this.computer = new WeakReference<>( computer ); this.computer = new WeakReference<>( computer );
this.computerId = computer.getID(); computerId = computer.getID();
this.fields = new Object2LongOpenHashMap<>(); fields = new Object2LongOpenHashMap<>();
} }
ComputerTracker( ComputerTracker timings ) ComputerTracker( ComputerTracker timings )
{ {
this.computer = timings.computer; computer = timings.computer;
this.computerId = timings.computerId; computerId = timings.computerId;
this.tasks = timings.tasks; tasks = timings.tasks;
this.totalTime = timings.totalTime; totalTime = timings.totalTime;
this.maxTime = timings.maxTime; maxTime = timings.maxTime;
this.serverCount = timings.serverCount; serverCount = timings.serverCount;
this.serverTime = timings.serverTime; serverTime = timings.serverTime;
this.fields = new Object2LongOpenHashMap<>( timings.fields ); fields = new Object2LongOpenHashMap<>( timings.fields );
} }
@Nullable @Nullable

View File

@ -14,7 +14,7 @@ import java.util.List;
import java.util.UUID; import java.util.UUID;
import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicInteger;
public class Tracking public final class Tracking
{ {
static final AtomicInteger tracking = new AtomicInteger( 0 ); static final AtomicInteger tracking = new AtomicInteger( 0 );
@ -22,6 +22,8 @@ public class Tracking
private static final HashMap<UUID, TrackingContext> contexts = new HashMap<>(); private static final HashMap<UUID, TrackingContext> contexts = new HashMap<>();
private static final List<Tracker> trackers = new ArrayList<>(); private static final List<Tracker> trackers = new ArrayList<>();
private Tracking() {}
public static TrackingContext getContext( UUID uuid ) public static TrackingContext getContext( UUID uuid )
{ {
synchronized( lock ) synchronized( lock )

View File

@ -13,7 +13,7 @@ import java.util.HashMap;
import java.util.Map; import java.util.Map;
import java.util.function.LongFunction; import java.util.function.LongFunction;
public class TrackingField public final class TrackingField
{ {
public static final String TRANSLATE_PREFIX = "tracking_field.computercraft."; public static final String TRANSLATE_PREFIX = "tracking_field.computercraft.";
@ -33,7 +33,7 @@ public class TrackingField
public static final TrackingField HTTP_REQUESTS = TrackingField.of( "http", "HTTP requests", TrackingField::formatDefault ); public static final TrackingField HTTP_REQUESTS = TrackingField.of( "http", "HTTP requests", TrackingField::formatDefault );
public static final TrackingField HTTP_UPLOAD = TrackingField.of( "http_upload", "HTTP upload", TrackingField::formatBytes ); public static final TrackingField HTTP_UPLOAD = TrackingField.of( "http_upload", "HTTP upload", TrackingField::formatBytes );
public static final TrackingField HTTP_DOWNLOAD = TrackingField.of( "http_download", "HTTT download", TrackingField::formatBytes ); public static final TrackingField HTTP_DOWNLOAD = TrackingField.of( "http_download", "HTTP download", TrackingField::formatBytes );
public static final TrackingField WEBSOCKET_INCOMING = TrackingField.of( "websocket_incoming", "Websocket incoming", TrackingField::formatBytes ); public static final TrackingField WEBSOCKET_INCOMING = TrackingField.of( "websocket_incoming", "Websocket incoming", TrackingField::formatBytes );
public static final TrackingField WEBSOCKET_OUTGOING = TrackingField.of( "websocket_outgoing", "Websocket outgoing", TrackingField::formatBytes ); public static final TrackingField WEBSOCKET_OUTGOING = TrackingField.of( "websocket_outgoing", "Websocket outgoing", TrackingField::formatBytes );
@ -64,7 +64,7 @@ public class TrackingField
private TrackingField( String id, LongFunction<String> format ) private TrackingField( String id, LongFunction<String> format )
{ {
this.id = id; this.id = id;
this.translationKey = "tracking_field.computercraft." + id + ".name"; translationKey = "tracking_field.computercraft." + id + ".name";
this.format = format; this.format = format;
} }

View File

@ -28,7 +28,7 @@ import java.util.concurrent.TimeUnit;
import static dan200.computercraft.ComputerCraft.DEFAULT_HTTP_BLACKLIST; import static dan200.computercraft.ComputerCraft.DEFAULT_HTTP_BLACKLIST;
import static dan200.computercraft.ComputerCraft.DEFAULT_HTTP_WHITELIST; import static dan200.computercraft.ComputerCraft.DEFAULT_HTTP_WHITELIST;
public class Config public final class Config
{ {
private static final int MODEM_MAX_RANGE = 100000; private static final int MODEM_MAX_RANGE = 100000;
@ -78,6 +78,8 @@ public class Config
private static Property turtlesCanPush; private static Property turtlesCanPush;
private static Property turtleDisabledActions; private static Property turtleDisabledActions;
private Config() {}
public static void load( File configFile ) public static void load( File configFile )
{ {
config = new Configuration( configFile, ComputerCraft.getVersion() ); config = new Configuration( configFile, ComputerCraft.getVersion() );
@ -106,7 +108,7 @@ public class Config
"update. Useful for ensuring forward compatibility of your programs now." ); "update. Useful for ensuring forward compatibility of your programs now." );
defaultComputerSettings = config.get( CATEGORY_GENERAL, "default_computer_settings", ComputerCraft.default_computer_settings ); defaultComputerSettings = config.get( CATEGORY_GENERAL, "default_computer_settings", ComputerCraft.default_computer_settings );
defaultComputerSettings.setComment( "A comma seperated list of default system settings to set on new computers. Example: " + defaultComputerSettings.setComment( "A comma separated list of default system settings to set on new computers. Example: " +
"\"shell.autocomplete=false,lua.autocomplete=false,edit.autocomplete=false\" will disable all autocompletion" ); "\"shell.autocomplete=false,lua.autocomplete=false,edit.autocomplete=false\" will disable all autocompletion" );
debugEnabled = config.get( CATEGORY_GENERAL, "debug_enabled", ComputerCraft.debug_enable ); debugEnabled = config.get( CATEGORY_GENERAL, "debug_enabled", ComputerCraft.debug_enable );

View File

@ -6,7 +6,6 @@
package dan200.computercraft.shared; package dan200.computercraft.shared;
import com.google.common.base.Preconditions;
import dan200.computercraft.ComputerCraft; import dan200.computercraft.ComputerCraft;
import dan200.computercraft.api.media.IMedia; import dan200.computercraft.api.media.IMedia;
import dan200.computercraft.api.media.IMediaProvider; import dan200.computercraft.api.media.IMediaProvider;
@ -14,15 +13,18 @@ import net.minecraft.item.ItemStack;
import javax.annotation.Nonnull; import javax.annotation.Nonnull;
import java.util.LinkedHashSet; import java.util.LinkedHashSet;
import java.util.Objects;
import java.util.Set; import java.util.Set;
public final class MediaProviders public final class MediaProviders
{ {
private static final Set<IMediaProvider> providers = new LinkedHashSet<>(); private static final Set<IMediaProvider> providers = new LinkedHashSet<>();
private MediaProviders() {}
public static void register( @Nonnull IMediaProvider provider ) public static void register( @Nonnull IMediaProvider provider )
{ {
Preconditions.checkNotNull( provider, "provider cannot be null" ); Objects.requireNonNull( provider, "provider cannot be null" );
providers.add( provider ); providers.add( provider );
} }

View File

@ -6,7 +6,6 @@
package dan200.computercraft.shared; package dan200.computercraft.shared;
import com.google.common.base.Preconditions;
import dan200.computercraft.ComputerCraft; import dan200.computercraft.ComputerCraft;
import dan200.computercraft.api.peripheral.IPeripheral; import dan200.computercraft.api.peripheral.IPeripheral;
import dan200.computercraft.api.peripheral.IPeripheralProvider; import dan200.computercraft.api.peripheral.IPeripheralProvider;
@ -16,14 +15,17 @@ import net.minecraft.world.World;
import javax.annotation.Nonnull; import javax.annotation.Nonnull;
import java.util.Collection; import java.util.Collection;
import java.util.Objects;
public final class Peripherals public final class Peripherals
{ {
private static final Collection<IPeripheralProvider> providers = ComputerCraft.peripheralProviders; private static final Collection<IPeripheralProvider> providers = ComputerCraft.peripheralProviders;
private Peripherals() {}
public static void register( @Nonnull IPeripheralProvider provider ) public static void register( @Nonnull IPeripheralProvider provider )
{ {
Preconditions.checkNotNull( provider, "provider cannot be null" ); Objects.requireNonNull( provider, "provider cannot be null" );
if( !providers.contains( provider ) ) providers.add( provider ); if( !providers.contains( provider ) ) providers.add( provider );
} }

View File

@ -6,7 +6,6 @@
package dan200.computercraft.shared; package dan200.computercraft.shared;
import com.google.common.base.Preconditions;
import dan200.computercraft.ComputerCraft; import dan200.computercraft.ComputerCraft;
import dan200.computercraft.api.pocket.IPocketUpgrade; import dan200.computercraft.api.pocket.IPocketUpgrade;
import dan200.computercraft.shared.util.InventoryUtil; import dan200.computercraft.shared.util.InventoryUtil;
@ -23,9 +22,11 @@ public final class PocketUpgrades
private static final Map<String, IPocketUpgrade> upgrades = new HashMap<>(); private static final Map<String, IPocketUpgrade> upgrades = new HashMap<>();
private static final IdentityHashMap<IPocketUpgrade, String> upgradeOwners = new IdentityHashMap<>(); private static final IdentityHashMap<IPocketUpgrade, String> upgradeOwners = new IdentityHashMap<>();
private PocketUpgrades() {}
public static void register( @Nonnull IPocketUpgrade upgrade ) public static void register( @Nonnull IPocketUpgrade upgrade )
{ {
Preconditions.checkNotNull( upgrade, "upgrade cannot be null" ); Objects.requireNonNull( upgrade, "upgrade cannot be null" );
String id = upgrade.getUpgradeID().toString(); String id = upgrade.getUpgradeID().toString();
IPocketUpgrade existing = upgrades.get( id ); IPocketUpgrade existing = upgrades.get( id );

View File

@ -6,7 +6,6 @@
package dan200.computercraft.shared; package dan200.computercraft.shared;
import com.google.common.base.Preconditions;
import dan200.computercraft.ComputerCraft; import dan200.computercraft.ComputerCraft;
import dan200.computercraft.api.turtle.ITurtleUpgrade; import dan200.computercraft.api.turtle.ITurtleUpgrade;
import dan200.computercraft.shared.computer.core.ComputerFamily; import dan200.computercraft.shared.computer.core.ComputerFamily;
@ -27,9 +26,11 @@ public final class TurtleUpgrades
private static final Int2ObjectMap<ITurtleUpgrade> legacyUpgrades = new Int2ObjectOpenHashMap<>(); private static final Int2ObjectMap<ITurtleUpgrade> legacyUpgrades = new Int2ObjectOpenHashMap<>();
private static final IdentityHashMap<ITurtleUpgrade, String> upgradeOwners = new IdentityHashMap<>(); private static final IdentityHashMap<ITurtleUpgrade, String> upgradeOwners = new IdentityHashMap<>();
private TurtleUpgrades() {}
public static void register( @Nonnull ITurtleUpgrade upgrade ) public static void register( @Nonnull ITurtleUpgrade upgrade )
{ {
Preconditions.checkNotNull( upgrade, "upgrade cannot be null" ); Objects.requireNonNull( upgrade, "upgrade cannot be null" );
int id = upgrade.getLegacyUpgradeID(); int id = upgrade.getLegacyUpgradeID();
if( id >= 0 && id < 64 ) if( id >= 0 && id < 64 )
@ -44,7 +45,7 @@ public final class TurtleUpgrades
static void registerInternal( ITurtleUpgrade upgrade ) static void registerInternal( ITurtleUpgrade upgrade )
{ {
Preconditions.checkNotNull( upgrade, "upgrade cannot be null" ); Objects.requireNonNull( upgrade, "upgrade cannot be null" );
// Check conditions // Check conditions
int legacyId = upgrade.getLegacyUpgradeID(); int legacyId = upgrade.getLegacyUpgradeID();

View File

@ -60,7 +60,7 @@ public final class CommandComputerCraft extends CommandDelegate
@Override @Override
public void execute( @Nonnull CommandContext context, @Nonnull List<String> arguments ) throws CommandException public void execute( @Nonnull CommandContext context, @Nonnull List<String> arguments ) throws CommandException
{ {
if( arguments.size() == 0 ) if( arguments.isEmpty() )
{ {
TableBuilder table = new TableBuilder( DUMP_LIST_ID, "Computer", "On", "Position" ); TableBuilder table = new TableBuilder( DUMP_LIST_ID, "Computer", "On", "Position" );
@ -162,7 +162,7 @@ public final class CommandComputerCraft extends CommandDelegate
@Override @Override
public List<String> getCompletion( @Nonnull CommandContext context, @Nonnull List<String> arguments ) public List<String> getCompletion( @Nonnull CommandContext context, @Nonnull List<String> arguments )
{ {
return arguments.size() == 0 return arguments.isEmpty()
? Collections.emptyList() ? Collections.emptyList()
: ComputerSelector.completeComputer( arguments.get( arguments.size() - 1 ) ); : ComputerSelector.completeComputer( arguments.get( arguments.size() - 1 ) );
} }
@ -188,7 +188,7 @@ public final class CommandComputerCraft extends CommandDelegate
@Override @Override
public List<String> getCompletion( @Nonnull CommandContext context, @Nonnull List<String> arguments ) public List<String> getCompletion( @Nonnull CommandContext context, @Nonnull List<String> arguments )
{ {
return arguments.size() == 0 return arguments.isEmpty()
? Collections.emptyList() ? Collections.emptyList()
: ComputerSelector.completeComputer( arguments.get( arguments.size() - 1 ) ); : ComputerSelector.completeComputer( arguments.get( arguments.size() - 1 ) );
} }

View File

@ -21,7 +21,7 @@ import net.minecraftforge.fml.relauncher.SideOnly;
import javax.annotation.Nonnull; import javax.annotation.Nonnull;
public class CommandCopy extends CommandBase implements IClientCommand public final class CommandCopy extends CommandBase implements IClientCommand
{ {
public static final CommandCopy INSTANCE = new CommandCopy(); public static final CommandCopy INSTANCE = new CommandCopy();

View File

@ -10,8 +10,10 @@ import net.minecraft.command.ICommandSender;
import net.minecraft.entity.player.EntityPlayerMP; import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraftforge.common.util.FakePlayer; import net.minecraftforge.common.util.FakePlayer;
public class CommandUtils public final class CommandUtils
{ {
private CommandUtils() {}
public static boolean isPlayer( ICommandSender sender ) public static boolean isPlayer( ICommandSender sender )
{ {
return sender instanceof EntityPlayerMP return sender instanceof EntityPlayerMP

View File

@ -18,6 +18,8 @@ import java.util.function.Predicate;
final class ComputerSelector final class ComputerSelector
{ {
private ComputerSelector() {}
private static List<ServerComputer> getComputers( Predicate<ServerComputer> predicate ) private static List<ServerComputer> getComputers( Predicate<ServerComputer> predicate )
{ {
// We copy it to prevent concurrent modifications. // We copy it to prevent concurrent modifications.
@ -29,7 +31,7 @@ final class ComputerSelector
static ServerComputer getComputer( String selector ) throws CommandException static ServerComputer getComputer( String selector ) throws CommandException
{ {
List<ServerComputer> computers = getComputers( selector ); List<ServerComputer> computers = getComputers( selector );
if( computers.size() == 0 ) if( computers.isEmpty() )
{ {
throw new CommandException( "commands.computercraft.argument.no_matching", selector ); throw new CommandException( "commands.computercraft.argument.no_matching", selector );
} }
@ -53,7 +55,7 @@ final class ComputerSelector
static List<ServerComputer> getComputers( String selector ) throws CommandException static List<ServerComputer> getComputers( String selector ) throws CommandException
{ {
if( selector.length() > 0 && selector.charAt( 0 ) == '#' ) if( !selector.isEmpty() && selector.charAt( 0 ) == '#' )
{ {
selector = selector.substring( 1 ); selector = selector.substring( 1 );
@ -69,12 +71,12 @@ final class ComputerSelector
return getComputers( x -> x.getID() == id ); return getComputers( x -> x.getID() == id );
} }
else if( selector.length() > 0 && selector.charAt( 0 ) == '@' ) else if( !selector.isEmpty() && selector.charAt( 0 ) == '@' )
{ {
String label = selector.substring( 1 ); String label = selector.substring( 1 );
return getComputers( x -> Objects.equals( label, x.getLabel() ) ); return getComputers( x -> Objects.equals( label, x.getLabel() ) );
} }
else if( selector.length() > 0 && selector.charAt( 0 ) == '~' ) else if( !selector.isEmpty() && selector.charAt( 0 ) == '~' )
{ {
String familyName = selector.substring( 1 ); String familyName = selector.substring( 1 );
return getComputers( x -> x.getFamily().name().equalsIgnoreCase( familyName ) ); return getComputers( x -> x.getFamily().name().equalsIgnoreCase( familyName ) );
@ -103,7 +105,7 @@ final class ComputerSelector
// We copy it to prevent concurrent modifications. // We copy it to prevent concurrent modifications.
List<ServerComputer> computers = Lists.newArrayList( ComputerCraft.serverComputerRegistry.getComputers() ); List<ServerComputer> computers = Lists.newArrayList( ComputerCraft.serverComputerRegistry.getComputers() );
if( selector.length() > 0 && selector.charAt( 0 ) == '#' ) if( !selector.isEmpty() && selector.charAt( 0 ) == '#' )
{ {
selector = selector.substring( 1 ); selector = selector.substring( 1 );
@ -113,7 +115,7 @@ final class ComputerSelector
if( id.startsWith( selector ) ) options.add( "#" + id ); if( id.startsWith( selector ) ) options.add( "#" + id );
} }
} }
else if( selector.length() > 0 && selector.charAt( 0 ) == '@' ) else if( !selector.isEmpty() && selector.charAt( 0 ) == '@' )
{ {
String label = selector.substring( 1 ); String label = selector.substring( 1 );
for( ServerComputer computer : computers ) for( ServerComputer computer : computers )
@ -122,7 +124,7 @@ final class ComputerSelector
if( thisLabel != null && thisLabel.startsWith( label ) ) options.add( "@" + thisLabel ); if( thisLabel != null && thisLabel.startsWith( label ) ) options.add( "@" + thisLabel );
} }
} }
else if( selector.length() > 0 && selector.charAt( 0 ) == '~' ) else if( !selector.isEmpty() && selector.charAt( 0 ) == '~' )
{ {
String familyName = selector.substring( 1 ).toLowerCase( Locale.ENGLISH ); String familyName = selector.substring( 1 ).toLowerCase( Locale.ENGLISH );
for( ComputerFamily family : ComputerFamily.values() ) for( ComputerFamily family : ComputerFamily.values() )

View File

@ -30,7 +30,7 @@ public final class CommandContext
{ {
this.server = server; this.server = server;
this.sender = sender; this.sender = sender;
this.path = Collections.singletonList( initial ); path = Collections.singletonList( initial );
} }
private CommandContext( MinecraftServer server, ICommandSender sender, List<ISubCommand> path ) private CommandContext( MinecraftServer server, ICommandSender sender, List<ISubCommand> path )

View File

@ -20,7 +20,7 @@ import java.util.Collections;
import java.util.List; import java.util.List;
/** /**
* {@link net.minecraft.command.ICommand} which delegates to a {@link ISubCommand}. * {@link ICommand} which delegates to a {@link ISubCommand}.
*/ */
public class CommandDelegate implements ICommand public class CommandDelegate implements ICommand
{ {

View File

@ -105,7 +105,7 @@ public class CommandRoot implements ISubCommand
@Override @Override
public void execute( @Nonnull CommandContext context, @Nonnull List<String> arguments ) throws CommandException public void execute( @Nonnull CommandContext context, @Nonnull List<String> arguments ) throws CommandException
{ {
if( arguments.size() == 0 ) if( arguments.isEmpty() )
{ {
context.getSender().sendMessage( ChatHelpers.getHelp( context, this, context.getFullPath() ) ); context.getSender().sendMessage( ChatHelpers.getHelp( context, this, context.getFullPath() ) );
} }
@ -125,7 +125,7 @@ public class CommandRoot implements ISubCommand
@Override @Override
public List<String> getCompletion( @Nonnull CommandContext context, @Nonnull List<String> arguments ) public List<String> getCompletion( @Nonnull CommandContext context, @Nonnull List<String> arguments )
{ {
if( arguments.size() == 0 ) if( arguments.isEmpty() )
{ {
return Lists.newArrayList( subCommands.keySet() ); return Lists.newArrayList( subCommands.keySet() );
} }

View File

@ -20,7 +20,7 @@ public abstract class SubCommandBase implements ISubCommand
protected SubCommandBase( String name, UserLevel level ) protected SubCommandBase( String name, UserLevel level )
{ {
this.name = name; this.name = name;
this.id = name.replace( '-', '_' ); id = name.replace( '-', '_' );
this.level = level; this.level = level;
} }

View File

@ -97,7 +97,7 @@ class SubCommandHelp implements ISubCommand
} }
} }
if( arguments.size() == 0 ) if( arguments.isEmpty() )
{ {
return Lists.newArrayList( command.getSubCommands().keySet() ); return Lists.newArrayList( command.getSubCommands().keySet() );
} }

View File

@ -23,6 +23,8 @@ public final class ChatHelpers
private static final TextFormatting SYNOPSIS = TextFormatting.AQUA; private static final TextFormatting SYNOPSIS = TextFormatting.AQUA;
private static final TextFormatting NAME = TextFormatting.GREEN; private static final TextFormatting NAME = TextFormatting.GREEN;
private ChatHelpers() {}
public static ITextComponent coloured( String text, TextFormatting colour ) public static ITextComponent coloured( String text, TextFormatting colour )
{ {
ITextComponent component = new TextComponentString( text == null ? "" : text ); ITextComponent component = new TextComponentString( text == null ? "" : text );

View File

@ -31,14 +31,14 @@ public class TableBuilder
if( id < 0 ) throw new IllegalArgumentException( "ID must be positive" ); if( id < 0 ) throw new IllegalArgumentException( "ID must be positive" );
this.id = id; this.id = id;
this.headers = headers; this.headers = headers;
this.columns = headers.length; columns = headers.length;
} }
public TableBuilder( int id ) public TableBuilder( int id )
{ {
if( id < 0 ) throw new IllegalArgumentException( "ID must be positive" ); if( id < 0 ) throw new IllegalArgumentException( "ID must be positive" );
this.id = id; this.id = id;
this.headers = null; headers = null;
} }
public TableBuilder( int id, @Nonnull String... headers ) public TableBuilder( int id, @Nonnull String... headers )
@ -46,7 +46,7 @@ public class TableBuilder
if( id < 0 ) throw new IllegalArgumentException( "ID must be positive" ); if( id < 0 ) throw new IllegalArgumentException( "ID must be positive" );
this.id = id; this.id = id;
this.headers = new ITextComponent[headers.length]; this.headers = new ITextComponent[headers.length];
this.columns = headers.length; columns = headers.length;
for( int i = 0; i < headers.length; i++ ) this.headers[i] = ChatHelpers.header( headers[i] ); for( int i = 0; i < headers.length; i++ ) this.headers[i] = ChatHelpers.header( headers[i] );
} }

View File

@ -71,7 +71,7 @@ public interface TableFormatter
for( int i = 0; i < maxWidths.length - 1; i++ ) maxWidths[i] += padding; for( int i = 0; i < maxWidths.length - 1; i++ ) maxWidths[i] += padding;
} }
// And comput the total width // And compute the total width
int totalWidth = (columns - 1) * getWidth( SEPARATOR ); int totalWidth = (columns - 1) * getWidth( SEPARATOR );
for( int x : maxWidths ) totalWidth += x; for( int x : maxWidths ) totalWidth += x;

View File

@ -26,7 +26,7 @@ public abstract class BlockGeneric extends Block implements ITileEntityProvider
protected BlockGeneric( Material material ) protected BlockGeneric( Material material )
{ {
super( material ); super( material );
this.hasTileEntity = true; hasTileEntity = true;
} }
protected abstract TileGeneric createTile( IBlockState state ); protected abstract TileGeneric createTile( IBlockState state );
@ -108,11 +108,7 @@ public abstract class BlockGeneric extends Block implements ITileEntityProvider
public boolean getBundledRedstoneConnectivity( World world, BlockPos pos, EnumFacing side ) public boolean getBundledRedstoneConnectivity( World world, BlockPos pos, EnumFacing side )
{ {
TileEntity tile = world.getTileEntity( pos ); TileEntity tile = world.getTileEntity( pos );
if( tile instanceof TileGeneric ) return tile instanceof TileGeneric && ((TileGeneric) tile).getBundledRedstoneConnectivity( side );
{
return ((TileGeneric) tile).getBundledRedstoneConnectivity( side );
}
return false;
} }
public int getBundledRedstoneOutput( World world, BlockPos pos, EnumFacing side ) public int getBundledRedstoneOutput( World world, BlockPos pos, EnumFacing side )

View File

@ -7,10 +7,41 @@
package dan200.computercraft.shared.common; package dan200.computercraft.shared.common;
import net.minecraft.item.ItemStack; import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
public interface IColouredItem public interface IColouredItem
{ {
int getColour( ItemStack stack ); String NBT_COLOUR = "colour";
ItemStack withColour( ItemStack stack, int colour ); default int getColour( ItemStack stack )
{
return getColourBasic( stack );
}
default ItemStack withColour( ItemStack stack, int colour )
{
ItemStack copy = stack.copy();
setColourBasic( copy, colour );
return copy;
}
static int getColourBasic( ItemStack stack )
{
NBTTagCompound tag = stack.getTagCompound();
return tag != null && tag.hasKey( NBT_COLOUR ) ? tag.getInteger( NBT_COLOUR ) : -1;
}
static void setColourBasic( ItemStack stack, int colour )
{
NBTTagCompound tag = stack.getTagCompound();
if( colour == -1 )
{
if( tag != null ) tag.removeTag( NBT_COLOUR );
}
else
{
if( tag == null ) stack.setTagCompound( tag = new NBTTagCompound() );
tag.setInteger( NBT_COLOUR, colour );
}
}
} }

View File

@ -30,7 +30,7 @@ public abstract class TileGeneric extends TileEntity
@Nullable @Nullable
public BlockGeneric getBlock() public BlockGeneric getBlock()
{ {
Block block = getWorld().getBlockState( getPos() ).getBlock(); Block block = getBlockType();
return block instanceof BlockGeneric ? (BlockGeneric) block : null; return block instanceof BlockGeneric ? (BlockGeneric) block : null;
} }
@ -110,7 +110,7 @@ public abstract class TileGeneric extends TileEntity
double range = getInteractRange( player ); double range = getInteractRange( player );
BlockPos pos = getPos(); BlockPos pos = getPos();
return player.getEntityWorld() == getWorld() && return player.getEntityWorld() == getWorld() &&
player.getDistanceSq( pos.getX() + 0.5, pos.getY() + 0.5, pos.getZ() + 0.5 ) <= (range * range); player.getDistanceSq( pos.getX() + 0.5, pos.getY() + 0.5, pos.getZ() + 0.5 ) <= range * range;
} }
protected void writeDescription( @Nonnull NBTTagCompound nbt ) protected void writeDescription( @Nonnull NBTTagCompound nbt )

View File

@ -12,13 +12,16 @@ import dan200.computercraft.api.lua.ILuaAPI;
import dan200.computercraft.api.lua.ILuaContext; import dan200.computercraft.api.lua.ILuaContext;
import dan200.computercraft.api.lua.LuaException; import dan200.computercraft.api.lua.LuaException;
import dan200.computercraft.shared.computer.blocks.TileCommandComputer; import dan200.computercraft.shared.computer.blocks.TileCommandComputer;
import dan200.computercraft.shared.util.NBTUtil;
import net.minecraft.block.Block; import net.minecraft.block.Block;
import net.minecraft.block.properties.IProperty; import net.minecraft.block.properties.IProperty;
import net.minecraft.block.state.IBlockState; import net.minecraft.block.state.IBlockState;
import net.minecraft.command.ICommand; import net.minecraft.command.ICommand;
import net.minecraft.command.ICommandManager; import net.minecraft.command.ICommandManager;
import net.minecraft.command.ICommandSender; import net.minecraft.command.ICommandSender;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.server.MinecraftServer; import net.minecraft.server.MinecraftServer;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.BlockPos;
import net.minecraft.world.World; import net.minecraft.world.World;
@ -62,7 +65,7 @@ public class CommandAPI implements ILuaAPI
}; };
} }
private Map<Object, Object> createOutput( String output ) private static Map<Object, Object> createOutput( String output )
{ {
Map<Object, Object> result = new HashMap<>( 1 ); Map<Object, Object> result = new HashMap<>( 1 );
result.put( 1, output ); result.put( 1, output );
@ -81,7 +84,7 @@ public class CommandAPI implements ILuaAPI
sender.clearOutput(); sender.clearOutput();
int result = commandManager.executeCommand( sender, command ); int result = commandManager.executeCommand( sender, command );
return new Object[] { (result > 0), sender.copyOutput() }; return new Object[] { result > 0, sender.copyOutput() };
} }
catch( Throwable t ) catch( Throwable t )
{ {
@ -89,7 +92,7 @@ public class CommandAPI implements ILuaAPI
{ {
ComputerCraft.log.error( "Error running command.", t ); ComputerCraft.log.error( "Error running command.", t );
} }
return new Object[] { false, createOutput( "Java Exception Thrown: " + t.toString() ) }; return new Object[] { false, createOutput( "Java Exception Thrown: " + t ) };
} }
} }
else else
@ -98,58 +101,54 @@ public class CommandAPI implements ILuaAPI
} }
} }
private Object getBlockInfo( World world, BlockPos pos ) private static Object getBlockInfo( World world, BlockPos pos )
{ {
// Get the details of the block // Get the details of the block
IBlockState state = world.getBlockState( pos ); IBlockState state = world.getBlockState( pos );
Block block = state.getBlock(); Block block = state.getBlock();
String name = Block.REGISTRY.getNameForObject( block ).toString();
int metadata = block.getMetaFromState( state );
Map<Object, Object> table = new HashMap<>(); Map<Object, Object> table = new HashMap<>( 3 );
table.put( "name", name ); table.put( "name", Block.REGISTRY.getNameForObject( block ).toString() );
table.put( "metadata", metadata ); table.put( "metadata", block.getMetaFromState( state ) );
Map<Object, Object> stateTable = new HashMap<>(); Map<Object, Object> stateTable = new HashMap<>();
for( ImmutableMap.Entry<IProperty<?>, Comparable<?>> entry : state.getActualState( world, pos ).getProperties().entrySet() ) for( ImmutableMap.Entry<IProperty<?>, Comparable<?>> entry : state.getActualState( world, pos ).getProperties().entrySet() )
{ {
String propertyName = entry.getKey().getName(); IProperty<?> property = entry.getKey();
Object value = entry.getValue(); stateTable.put( property.getName(), getPropertyValue( property, entry.getValue() ) );
if( value instanceof String || value instanceof Number || value instanceof Boolean )
{
stateTable.put( propertyName, value );
}
else
{
stateTable.put( propertyName, value.toString() );
}
} }
table.put( "state", stateTable ); table.put( "state", stateTable );
// TODO: NBT data?
TileEntity tile = world.getTileEntity( pos );
if( tile != null ) table.put( "nbt", NBTUtil.toLua( tile.writeToNBT( new NBTTagCompound() ).copy() ) );
return table; return table;
} }
@SuppressWarnings( { "unchecked", "rawtypes" } )
private static Object getPropertyValue( IProperty property, Comparable value )
{
if( value instanceof String || value instanceof Number || value instanceof Boolean ) return value;
return property.getName( value );
}
@Override @Override
public Object[] callMethod( @Nonnull ILuaContext context, int method, @Nonnull Object[] arguments ) throws LuaException, InterruptedException public Object[] callMethod( @Nonnull ILuaContext context, int method, @Nonnull Object[] arguments ) throws LuaException, InterruptedException
{ {
switch( method ) switch( method )
{ {
case 0: case 0: // exec
{ {
// exec
final String command = getString( arguments, 0 ); final String command = getString( arguments, 0 );
return context.executeMainThreadTask( () -> doCommand( command ) ); return context.executeMainThreadTask( () -> doCommand( command ) );
} }
case 1: case 1: // execAsync
{ {
// execAsync
final String command = getString( arguments, 0 ); final String command = getString( arguments, 0 );
long taskID = context.issueMainThreadTask( () -> doCommand( command ) ); long taskID = context.issueMainThreadTask( () -> doCommand( command ) );
return new Object[] { taskID }; return new Object[] { taskID };
} }
case 2: case 2: // list
{
// list
return context.executeMainThreadTask( () -> return context.executeMainThreadTask( () ->
{ {
int i = 1; int i = 1;
@ -158,7 +157,7 @@ public class CommandAPI implements ILuaAPI
if( server != null ) if( server != null )
{ {
ICommandManager commandManager = server.getCommandManager(); ICommandManager commandManager = server.getCommandManager();
ICommandSender commmandSender = m_computer.getCommandSender(); ICommandSender commandSender = m_computer.getCommandSender();
Map<String, ICommand> commands = commandManager.getCommands(); Map<String, ICommand> commands = commandManager.getCommands();
for( Map.Entry<String, ICommand> entry : commands.entrySet() ) for( Map.Entry<String, ICommand> entry : commands.entrySet() )
{ {
@ -166,7 +165,7 @@ public class CommandAPI implements ILuaAPI
ICommand command = entry.getValue(); ICommand command = entry.getValue();
try try
{ {
if( command.checkPermission( server, commmandSender ) ) if( command.checkPermission( server, commandSender ) )
{ {
result.put( i++, name ); result.put( i++, name );
} }
@ -183,10 +182,8 @@ public class CommandAPI implements ILuaAPI
} }
return new Object[] { result }; return new Object[] { result };
} ); } );
} case 3: // getBlockPosition
case 3:
{ {
// getBlockPosition
// This is probably safe to do on the Lua thread. Probably. // This is probably safe to do on the Lua thread. Probably.
BlockPos pos = m_computer.getPos(); BlockPos pos = m_computer.getPos();
return new Object[] { pos.getX(), pos.getY(), pos.getZ() }; return new Object[] { pos.getX(), pos.getY(), pos.getZ() };
@ -194,25 +191,25 @@ public class CommandAPI implements ILuaAPI
case 4: case 4:
{ {
// getBlockInfos // getBlockInfos
final int minx = getInt( arguments, 0 ); final int minX = getInt( arguments, 0 );
final int miny = getInt( arguments, 1 ); final int minY = getInt( arguments, 1 );
final int minz = getInt( arguments, 2 ); final int minZ = getInt( arguments, 2 );
final int maxx = getInt( arguments, 3 ); final int maxX = getInt( arguments, 3 );
final int maxy = getInt( arguments, 4 ); final int maxY = getInt( arguments, 4 );
final int maxz = getInt( arguments, 5 ); final int maxZ = getInt( arguments, 5 );
return context.executeMainThreadTask( () -> return context.executeMainThreadTask( () ->
{ {
// Get the details of the block // Get the details of the block
World world = m_computer.getWorld(); World world = m_computer.getWorld();
BlockPos min = new BlockPos( BlockPos min = new BlockPos(
Math.min( minx, maxx ), Math.min( minX, maxX ),
Math.min( miny, maxy ), Math.min( minY, maxY ),
Math.min( minz, maxz ) Math.min( minZ, maxZ )
); );
BlockPos max = new BlockPos( BlockPos max = new BlockPos(
Math.max( minx, maxx ), Math.max( minX, maxX ),
Math.max( miny, maxy ), Math.max( minY, maxY ),
Math.max( minz, maxz ) Math.max( minZ, maxZ )
); );
if( !world.isValid( min ) || !world.isValid( max ) ) if( !world.isValid( min ) || !world.isValid( max ) )
{ {

View File

@ -26,7 +26,7 @@ public class BlockCommandComputer extends BlockComputerBase
{ {
// Statics // Statics
public static class Properties public static final class Properties
{ {
public static final PropertyDirection FACING = PropertyDirection.create( "facing", EnumFacing.Plane.HORIZONTAL ); public static final PropertyDirection FACING = PropertyDirection.create( "facing", EnumFacing.Plane.HORIZONTAL );
public static final PropertyEnum<ComputerState> STATE = PropertyEnum.create( "state", ComputerState.class ); public static final PropertyEnum<ComputerState> STATE = PropertyEnum.create( "state", ComputerState.class );
@ -41,7 +41,7 @@ public class BlockCommandComputer extends BlockComputerBase
setResistance( 6000000.0F ); setResistance( 6000000.0F );
setTranslationKey( "computercraft:command_computer" ); setTranslationKey( "computercraft:command_computer" );
setCreativeTab( ComputerCraft.mainCreativeTab ); setCreativeTab( ComputerCraft.mainCreativeTab );
setDefaultState( this.blockState.getBaseState() setDefaultState( blockState.getBaseState()
.withProperty( Properties.FACING, EnumFacing.NORTH ) .withProperty( Properties.FACING, EnumFacing.NORTH )
.withProperty( Properties.STATE, ComputerState.Off ) .withProperty( Properties.STATE, ComputerState.Off )
); );

View File

@ -26,7 +26,7 @@ import javax.annotation.Nonnull;
public class BlockComputer extends BlockComputerBase public class BlockComputer extends BlockComputerBase
{ {
// Statics // Statics
public static class Properties public static final class Properties
{ {
public static final PropertyDirection FACING = PropertyDirection.create( "facing", EnumFacing.Plane.HORIZONTAL ); public static final PropertyDirection FACING = PropertyDirection.create( "facing", EnumFacing.Plane.HORIZONTAL );
public static final PropertyBool ADVANCED = PropertyBool.create( "advanced" ); public static final PropertyBool ADVANCED = PropertyBool.create( "advanced" );
@ -41,7 +41,7 @@ public class BlockComputer extends BlockComputerBase
setHardness( 2.0f ); setHardness( 2.0f );
setTranslationKey( "computercraft:computer" ); setTranslationKey( "computercraft:computer" );
setCreativeTab( ComputerCraft.mainCreativeTab ); setCreativeTab( ComputerCraft.mainCreativeTab );
setDefaultState( this.blockState.getBaseState() setDefaultState( blockState.getBaseState()
.withProperty( Properties.FACING, EnumFacing.NORTH ) .withProperty( Properties.FACING, EnumFacing.NORTH )
.withProperty( Properties.ADVANCED, false ) .withProperty( Properties.ADVANCED, false )
.withProperty( Properties.STATE, ComputerState.Off ) .withProperty( Properties.STATE, ComputerState.Off )

View File

@ -12,8 +12,7 @@ import dan200.computercraft.api.peripheral.IPeripheral;
import javax.annotation.Nonnull; import javax.annotation.Nonnull;
public class ComputerPeripheral public class ComputerPeripheral implements IPeripheral
implements IPeripheral
{ {
private final String m_type; private final String m_type;
private final ComputerProxy m_computer; private final ComputerProxy m_computer;
@ -52,50 +51,30 @@ public class ComputerPeripheral
{ {
switch( method ) switch( method )
{ {
case 0: case 0: // turnOn
{
// turnOn
m_computer.turnOn(); m_computer.turnOn();
return null; return null;
} case 1: // shutdown
case 1:
{
// shutdown
m_computer.shutdown(); m_computer.shutdown();
return null; return null;
} case 2: // reboot
case 2:
{
// reboot
m_computer.reboot(); m_computer.reboot();
return null; return null;
} case 3: // getID
case 3: return new Object[] { m_computer.assignID() };
{ case 4: // isOn
// getID
return new Object[] {
m_computer.assignID()
};
}
case 4:
{
// isOn
return new Object[] { m_computer.isOn() }; return new Object[] { m_computer.isOn() };
} case 5: // getLabel
case 5:
// getLabel
return new Object[] { m_computer.getLabel() }; return new Object[] { m_computer.getLabel() };
default: default:
{
return null; return null;
} }
} }
}
@Override @Override
public boolean equals( IPeripheral other ) public boolean equals( IPeripheral other )
{ {
return (other != null && other.getClass() == this.getClass()); return other != null && other.getClass() == getClass();
} }
@Nonnull @Nonnull

View File

@ -21,24 +21,24 @@ public enum ComputerState implements IStringSerializable
// TODO: Move to dan200.computercraft.shared.computer.core in the future. We can't do it now // TODO: Move to dan200.computercraft.shared.computer.core in the future. We can't do it now
// as Plethora depends on it. // as Plethora depends on it.
private String m_name; private final String name;
ComputerState( String name ) ComputerState( String name )
{ {
m_name = name; this.name = name;
} }
@Nonnull @Nonnull
@Override @Override
public String getName() public String getName()
{ {
return m_name; return name;
} }
@Override @Override
public String toString() public String toString()
{ {
return getName(); return name;
} }
public static ComputerState valueOf( int ordinal ) public static ComputerState valueOf( int ordinal )

View File

@ -78,7 +78,7 @@ public class TileCommandComputer extends TileComputer
@Override @Override
public BlockPos getPosition() public BlockPos getPosition()
{ {
return TileCommandComputer.this.getPos(); return getPos();
} }
@Nonnull @Nonnull
@ -93,13 +93,13 @@ public class TileCommandComputer extends TileComputer
@Override @Override
public World getEntityWorld() public World getEntityWorld()
{ {
return TileCommandComputer.this.getWorld(); return getWorld();
} }
@Override @Override
public MinecraftServer getServer() public MinecraftServer getServer()
{ {
return TileCommandComputer.this.getWorld().getMinecraftServer(); return getWorld().getMinecraftServer();
} }
@Override @Override

View File

@ -113,7 +113,7 @@ public class TileComputer extends TileComputerBase
} }
// For legacy reasons, computers invert the meaning of "left" and "right" // For legacy reasons, computers invert the meaning of "left" and "right"
private static final int[] s_remapSide = { 0, 1, 2, 3, 5, 4 }; private static final int[] s_remapSide = new int[] { 0, 1, 2, 3, 5, 4 };
@Override @Override
protected int remapLocalSide( int localSide ) protected int remapLocalSide( int localSide )

View File

@ -28,12 +28,16 @@ import net.minecraft.util.EnumFacing;
import net.minecraft.util.EnumHand; import net.minecraft.util.EnumHand;
import net.minecraft.util.ITickable; import net.minecraft.util.ITickable;
import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.BlockPos;
import net.minecraft.util.text.ITextComponent;
import net.minecraft.util.text.TextComponentString;
import net.minecraft.util.text.TextComponentTranslation;
import net.minecraft.world.IWorldNameable;
import javax.annotation.Nonnull; import javax.annotation.Nonnull;
import javax.annotation.Nullable; import javax.annotation.Nullable;
import java.util.Objects; import java.util.Objects;
public abstract class TileComputerBase extends TileGeneric implements IComputerTile, IDirectionalTile, ITickable, IPeripheralTile public abstract class TileComputerBase extends TileGeneric implements IComputerTile, IDirectionalTile, ITickable, IPeripheralTile, IWorldNameable
{ {
private int m_instanceID = -1; private int m_instanceID = -1;
private int m_computerID = -1; private int m_computerID = -1;
@ -46,11 +50,7 @@ public abstract class TileComputerBase extends TileGeneric implements IComputerT
public BlockComputerBase getBlock() public BlockComputerBase getBlock()
{ {
Block block = super.getBlock(); Block block = super.getBlock();
if( block instanceof BlockComputerBase ) return block instanceof BlockComputerBase ? (BlockComputerBase) block : null;
{
return (BlockComputerBase) block;
}
return null;
} }
protected void unload() protected void unload()
@ -95,29 +95,16 @@ public abstract class TileComputerBase extends TileGeneric implements IComputerT
return false; return false;
} }
protected boolean onDefaultComputerInteract( EntityPlayer player )
{
if( !getWorld().isRemote )
{
if( isUsable( player, false ) )
{
createServerComputer().turnOn();
openGUI( player );
}
}
return true;
}
@Override @Override
public boolean onActivate( EntityPlayer player, EnumHand hand, EnumFacing side, float hitX, float hitY, float hitZ ) public boolean onActivate( EntityPlayer player, EnumHand hand, EnumFacing side, float hitX, float hitY, float hitZ )
{ {
ItemStack currentItem = player.getHeldItem( hand ); ItemStack currentItem = player.getHeldItem( hand );
if( !currentItem.isEmpty() && currentItem.getItem() == Items.NAME_TAG && canNameWithTag( player ) ) if( !currentItem.isEmpty() && currentItem.getItem() == Items.NAME_TAG && canNameWithTag( player ) && currentItem.hasDisplayName() )
{ {
// Label to rename computer // Label to rename computer
if( !getWorld().isRemote ) if( !getWorld().isRemote )
{ {
setLabel( currentItem.hasDisplayName() ? currentItem.getDisplayName() : null ); setLabel( currentItem.getDisplayName() );
currentItem.shrink( 1 ); currentItem.shrink( 1 );
} }
return true; return true;
@ -125,7 +112,12 @@ public abstract class TileComputerBase extends TileGeneric implements IComputerT
else if( !player.isSneaking() ) else if( !player.isSneaking() )
{ {
// Regular right click to activate computer // Regular right click to activate computer
return onDefaultComputerInteract( player ); if( !getWorld().isRemote && isUsable( player, false ) )
{
createServerComputer().turnOn();
openGUI( player );
}
return true;
} }
return false; return false;
} }
@ -201,10 +193,7 @@ public abstract class TileComputerBase extends TileGeneric implements IComputerT
m_startOn = false; m_startOn = false;
} }
computer.keepAlive(); computer.keepAlive();
if( computer.hasOutputChanged() ) if( computer.hasOutputChanged() ) updateOutput();
{
updateOutput();
}
m_fresh = false; m_fresh = false;
m_computerID = computer.getID(); m_computerID = computer.getID();
m_label = computer.getLabel(); m_label = computer.getLabel();
@ -214,13 +203,7 @@ public abstract class TileComputerBase extends TileGeneric implements IComputerT
else else
{ {
ClientComputer computer = createClientComputer(); ClientComputer computer = createClientComputer();
if( computer != null ) if( computer != null && computer.hasOutputChanged() ) updateBlock();
{
if( computer.hasOutputChanged() )
{
updateBlock();
}
}
} }
} }
@ -310,10 +293,7 @@ public abstract class TileComputerBase extends TileGeneric implements IComputerT
public void updateInput() public void updateInput()
{ {
if( getWorld() == null || getWorld().isRemote ) if( getWorld() == null || getWorld().isRemote ) return;
{
return;
}
// Update redstone and peripherals // Update redstone and peripherals
ServerComputer computer = getServerComputer(); ServerComputer computer = getServerComputer();
@ -329,10 +309,7 @@ public abstract class TileComputerBase extends TileGeneric implements IComputerT
public void updateInput( BlockPos neighbour ) public void updateInput( BlockPos neighbour )
{ {
if( getWorld() == null || getWorld().isRemote ) if( getWorld() == null || getWorld().isRemote ) return;
{
return;
}
ServerComputer computer = getServerComputer(); ServerComputer computer = getServerComputer();
if( computer != null ) if( computer != null )
@ -505,4 +482,25 @@ public abstract class TileComputerBase extends TileGeneric implements IComputerT
{ {
return new ComputerPeripheral( "computer", createProxy() ); return new ComputerPeripheral( "computer", createProxy() );
} }
@Nonnull
@Override
public String getName()
{
String label = getLabel();
return label != null && !label.isEmpty() ? label : getBlockType().getTranslationKey();
}
@Override
public boolean hasCustomName()
{
return getLabel() != null;
}
@Nonnull
@Override
public ITextComponent getDisplayName()
{
return hasCustomName() ? new TextComponentString( getName() ) : new TextComponentTranslation( getName() );
}
} }

View File

@ -74,6 +74,6 @@ public class ComputerRegistry<TComputer extends IComputer>
{ {
m_computers.clear(); m_computers.clear();
m_nextUnusedInstanceID = 0; m_nextUnusedInstanceID = 0;
m_sessionID = (new Random().nextInt()); m_sessionID = new Random().nextInt();
} }
} }

View File

@ -6,6 +6,7 @@
package dan200.computercraft.shared.computer.core; package dan200.computercraft.shared.computer.core;
@FunctionalInterface
public interface IComputerContainer public interface IComputerContainer
{ {
IComputer getComputer(); IComputer getComputer();

View File

@ -13,6 +13,7 @@ import javax.annotation.Nullable;
* An instance of {@link net.minecraft.inventory.Container} which provides a computer. You should implement this * An instance of {@link net.minecraft.inventory.Container} which provides a computer. You should implement this
* if you provide custom computers/GUIs to interact with them. * if you provide custom computers/GUIs to interact with them.
*/ */
@FunctionalInterface
public interface IContainerComputer public interface IContainerComputer
{ {
/** /**

View File

@ -376,7 +376,8 @@ public class ServerComputer extends ServerTerminal implements IComputer, IComput
Container container = player.openContainer; Container container = player.openContainer;
if( !(container instanceof IContainerComputer) ) return null; if( !(container instanceof IContainerComputer) ) return null;
return (IContainerComputer) container; IContainerComputer computerContainer = (IContainerComputer) container;
return computerContainer.getComputer() != this ? null : computerContainer;
} }
protected boolean isInteracting( EntityPlayer player ) protected boolean isInteracting( EntityPlayer player )

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