1
0
mirror of https://github.com/SquidDev-CC/CC-Tweaked synced 2024-12-13 03:30:29 +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;
// Blocks and Items
public static class Blocks
public static final class Blocks
{
public static BlockComputer computer;
public static BlockCommandComputer commandComputer;
@ -172,7 +172,7 @@ public class ComputerCraft
public static BlockWiredModemFull wiredModemFull;
}
public static class Items
public static final class Items
{
public static ItemComputer computer;
public static ItemCommandComputer commandComputer;
@ -195,7 +195,7 @@ public class ComputerCraft
public static ItemBlock wiredModemFull;
}
public static class TurtleUpgrades
public static final class TurtleUpgrades
{
public static TurtleModem wirelessModem;
public static TurtleModem advancedModem;
@ -209,7 +209,7 @@ public class ComputerCraft
public static TurtleHoe diamondHoe;
}
public static class PocketUpgrades
public static final class PocketUpgrades
{
public static PocketModem wirelessModem;
public static PocketModem advancedModem;
@ -220,7 +220,7 @@ public class ComputerCraft
}
@Deprecated
public static class Upgrades
public static final class Upgrades
{
public static TurtleModem advancedModem;
}
@ -239,7 +239,7 @@ public class ComputerCraft
public static List<IPeripheralProvider> peripheralProviders = new ArrayList<>();
// Implementation
@Mod.Instance( value = ComputerCraft.MOD_ID )
@Mod.Instance( ComputerCraft.MOD_ID )
public static ComputerCraft instance;
@SidedProxy(
@ -556,7 +556,7 @@ public class ComputerCraft
private static File getContainingJar( Class<?> modClass )
{
String path = modClass.getProtectionDomain().getCodeSource().getLocation().getPath();
int bangIndex = path.indexOf( "!" );
int bangIndex = path.indexOf( '!' );
if( bangIndex >= 0 )
{
path = path.substring( 0, bangIndex );
@ -587,7 +587,7 @@ public class ComputerCraft
private static File getDebugCodeDir( Class<?> modClass )
{
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(), "../.." );
}

View File

@ -173,8 +173,8 @@ public final class ComputerCraftAPI
* Registers a peripheral provider to convert blocks into {@link IPeripheral} implementations.
*
* @param provider The peripheral provider to register.
* @see dan200.computercraft.api.peripheral.IPeripheral
* @see dan200.computercraft.api.peripheral.IPeripheralProvider
* @see IPeripheral
* @see IPeripheralProvider
*/
public static void registerPeripheralProvider( @Nonnull IPeripheralProvider provider )
{
@ -198,7 +198,7 @@ public final class ComputerCraftAPI
* this during the load() method of your mod.
*
* @param upgrade The turtle upgrade to register.
* @see dan200.computercraft.api.turtle.ITurtleUpgrade
* @see ITurtleUpgrade
*/
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.
*
* @param provider The bundled redstone provider to register.
* @see dan200.computercraft.api.redstone.IBundledRedstoneProvider
* @see IBundledRedstoneProvider
*/
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.
* @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.
* @see dan200.computercraft.api.redstone.IBundledRedstoneProvider
* @see IBundledRedstoneProvider
*/
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
*
* @param provider The media provider to register.
* @see dan200.computercraft.api.media.IMediaProvider
* @see IMediaProvider
*/
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.
*
* @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
@ -481,7 +481,7 @@ public final class ComputerCraftAPI
}
catch( Exception e )
{
System.out.println( "ComputerCraftAPI: ComputerCraft not found." );
System.err.println( "ComputerCraftAPI: ComputerCraft not found." );
}
finally
{
@ -498,7 +498,7 @@ public final class ComputerCraftAPI
}
catch( NoSuchMethodException e )
{
System.out.println( "ComputerCraftAPI: ComputerCraft method " + name + " not found." );
System.err.println( "ComputerCraftAPI: ComputerCraft method " + name + " not found." );
return null;
}
}

View File

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

View File

@ -77,7 +77,7 @@ public interface IMedia
* @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
* 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.ComputerCraftAPI#createSaveDirMount(World, String, long)
* @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.
* @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 );
@ -182,7 +182,7 @@ public interface IComputerAccess
/**
* 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
* @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 is does any of the above.
*
* Between calls to {@link #attach} and {@link #detach}, the attached computer can make method calls on the
* peripheral using {@code peripheral.call()}. This method can be used to keep track of which computers are attached
* to the peripheral, or to take action when attachment occurs.
* Between calls to attach and {@link #detach}, the attached computer can make method calls on the peripheral using
* {@code peripheral.call()}. This method can be used to keep track of which computers are attached to the
* 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
* 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.
*
* 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
* performed.
* you may do an initial piece of work, and shouldWork to determine if any additional task may be performed.
*
* @return If we should execute work right now.
*/

View File

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

View File

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

View File

@ -9,6 +9,7 @@ package dan200.computercraft.client;
import dan200.computercraft.ComputerCraft;
import dan200.computercraft.client.render.TurtleModelLoader;
import dan200.computercraft.shared.media.items.ItemDiskLegacy;
import dan200.computercraft.shared.pocket.items.ItemPocketComputer;
import dan200.computercraft.shared.turtle.items.ItemTurtleBase;
import net.minecraft.client.Minecraft;
import net.minecraft.client.renderer.ItemMeshDefinition;
@ -37,9 +38,9 @@ import javax.annotation.Nonnull;
* Registers textures and models for items.
*/
@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_on_left",
"turtle_modem_off_right",
@ -57,6 +58,8 @@ public class ClientRegistry
"turtle_elf_overlay",
};
private ClientRegistry() {}
@SubscribeEvent
public static void registerModels( ModelRegistryEvent event )
{
@ -129,7 +132,7 @@ public class ClientRegistry
case 1: // Frame colour
return ComputerCraft.Items.pocketComputer.getColour( stack );
case 2: // Light colour
return ComputerCraft.Items.pocketComputer.getLightState( stack );
return ItemPocketComputer.getLightState( stack );
}
}, ComputerCraft.Items.pocketComputer );

View File

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

View File

@ -19,7 +19,7 @@ import org.lwjgl.opengl.GL11;
import java.util.Arrays;
public class FixedWidthFontRenderer
public final class FixedWidthFontRenderer
{
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" );
@ -93,7 +93,7 @@ public class FixedWidthFontRenderer
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 )

View File

@ -80,12 +80,6 @@ public class GuiComputer extends GuiContainer
Keyboard.enableRepeatEvents( false );
}
@Override
public boolean doesGuiPauseGame()
{
return false;
}
@Override
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" );
}
public static class Factory
implements IModGuiFactory
public static class Factory implements IModGuiFactory
{
@Override
public void initialize( Minecraft minecraft )
{

View File

@ -29,7 +29,7 @@ public class GuiDiskDrive extends GuiContainer
{
String title = m_container.getDiskDrive().getDisplayName().getUnformattedText();
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

View File

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

View File

@ -29,7 +29,7 @@ public class GuiPrinter extends GuiContainer
{
String title = container.getPrinter().getDisplayName().getUnformattedText();
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

View File

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

View File

@ -98,8 +98,8 @@ public class GuiTurtle extends GuiContainer
public void handleMouseInput() throws IOException
{
super.handleMouseInput();
int x = Mouse.getEventX() * this.width / mc.displayWidth;
int y = this.height - Mouse.getEventY() * this.height / mc.displayHeight - 1;
int x = Mouse.getEventX() * width / mc.displayWidth;
int y = height - Mouse.getEventY() * height / mc.displayHeight - 1;
m_terminalGui.handleMouseInput( x, y );
}
@ -117,8 +117,8 @@ public class GuiTurtle extends GuiContainer
if( slot >= 0 )
{
GlStateManager.color( 1.0F, 1.0F, 1.0F, 1.0F );
int slotX = (slot % 4);
int slotY = (slot / 4);
int slotX = slot % 4;
int slotY = slot / 4;
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 );
}
@ -128,7 +128,7 @@ public class GuiTurtle extends GuiContainer
protected void drawGuiContainerBackgroundLayer( float partialTicks, int mouseX, int mouseY )
{
// Draw term
boolean advanced = (m_family == ComputerFamily.Advanced);
boolean advanced = m_family == ComputerFamily.Advanced;
m_terminalGui.draw( Minecraft.getMinecraft(), 0, 0, mouseX, mouseY );
// Draw border/inventory

View File

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

View File

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

View File

@ -57,7 +57,7 @@ public final class ItemPocketRenderer extends ItemMapLikeRenderer
@Override
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
GlStateManager.disableLighting();
@ -65,8 +65,7 @@ public final class ItemPocketRenderer extends ItemMapLikeRenderer
GlStateManager.rotate( 180f, 0f, 0f, 1f );
GlStateManager.scale( 0.5, 0.5, 0.5 );
ItemPocketComputer pocketComputer = ComputerCraft.Items.pocketComputer;
ClientComputer computer = pocketComputer.createClientComputer( stack );
ClientComputer computer = ItemPocketComputer.createClientComputer( stack );
{
// 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.color( 1.0F, 1.0F, 1.0F, 1.0F );
IBakedModel bakedmodel = renderItem.getItemModelWithOverrides( stack, null, null );
bakedmodel = ForgeHooksClient.handleCameraTransforms( bakedmodel, ItemCameraTransforms.TransformType.GUI, false );
renderItem.renderItem( stack, bakedmodel );
IBakedModel baked = renderItem.getItemModelWithOverrides( stack, null, null );
baked = ForgeHooksClient.handleCameraTransforms( baked, ItemCameraTransforms.TransformType.GUI, false );
renderItem.renderItem( stack, baked );
GlStateManager.disableAlpha();
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;
/**
* 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 )
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.
*/
private static class BakedQuadBuilder implements IVertexConsumer
private static final class BakedQuadBuilder implements IVertexConsumer
{
private final VertexFormat format;
@ -195,7 +195,7 @@ public final class ModelTransformer
private BakedQuadBuilder( VertexFormat format )
{
this.format = format;
this.vertexData = new int[format.getSize()];
vertexData = new int[format.getSize()];
}
@Nonnull
@ -208,7 +208,7 @@ public final class ModelTransformer
@Override
public void setQuadTint( int tint )
{
this.quadTint = tint;
quadTint = tint;
}
@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.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 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_X = X_SIZE + 4 * X_FOLD_SIZE;
private PrintoutRenderer() {}
public static void drawText( int x, int y, int start, TextBuffer[] text, TextBuffer[] colours )
{
FixedWidthFontRenderer fontRenderer = FixedWidthFontRenderer.instance();

View File

@ -53,7 +53,7 @@ public final class RenderOverlayCable
state = state.getActualState( world, pos );
event.setCanceled( true );
PeripheralType type = ComputerCraft.Blocks.cable.getPeripheralType( state );
PeripheralType type = BlockCable.getPeripheralType( state );
GlStateManager.enableBlend();
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
ClientMonitor originTerminal = monitor.getClientMonitor();
@ -78,7 +78,7 @@ public class TileEntityMonitorRenderer extends TileEntitySpecialRenderer<TileMon
GlStateManager.rotate( pitch, 1.0f, 0.0f, 0.0f );
GlStateManager.translate(
-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
);
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" );
@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 )
@ -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
String label = turtle.createProxy().getLabel();
@ -113,12 +113,9 @@ public class TileEntityTurtleRenderer extends TileEntitySpecialRenderer<TileTurt
}
GlStateManager.translate( -0.5f, -0.5f, -0.5f );
// Render the turtle
int colour;
ComputerFamily family;
ResourceLocation overlay;
colour = turtle.getColour();
family = turtle.getFamily();
overlay = turtle.getOverlay();
int colour = turtle.getColour();
ComputerFamily family = turtle.getFamily();
ResourceLocation overlay = turtle.getOverlay();
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 );
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();
ModelManager modelManager = mc.getRenderItem().getItemModelMesher().getModelManager();
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();
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();
VertexFormat format = DefaultVertexFormats.ITEM;

View File

@ -21,7 +21,7 @@ import net.minecraftforge.common.model.IModelState;
import javax.annotation.Nonnull;
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 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 );
}
private static class TurtleModel implements IModel
private static final class TurtleModel implements IModel
{
private final IModel family;
private final IModel colour;

View File

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

View File

@ -143,10 +143,10 @@ public class TurtleSmartItemModel implements IBakedModel
ModelResourceLocation overlayModelLocation = TileEntityTurtleRenderer.getTurtleOverlayModel( combo.m_overlay, combo.m_christmas );
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;
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> 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;
if( leftModel != null && rightModel != null )
{
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
{
private static class HostRange
private static final class HostRange
{
private final byte[] min;
private final byte[] max;

View File

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

View File

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

View File

@ -24,6 +24,7 @@ public interface IAPIEnvironment
int SIDE_COUNT = 6;
@FunctionalInterface
interface IPeripheralChangeListener
{
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 int m_day;
@ -110,7 +110,7 @@ public class OSAPI implements ILuaAPI
{
Map.Entry<Integer, Timer> entry = it.next();
Timer timer = entry.getValue();
timer.m_ticksLeft = timer.m_ticksLeft - 1;
timer.m_ticksLeft--;
if( timer.m_ticksLeft <= 0 )
{
// Queue the "timer" event
@ -198,7 +198,7 @@ public class OSAPI implements ILuaAPI
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 day = 0;
for( int y = 1970; y < year; y++ )
@ -219,12 +219,9 @@ public class OSAPI implements ILuaAPI
{
switch( method )
{
case 0:
{
// queueEvent
case 0: // queueEvent
queueLuaEvent( getString( args, 0 ), trimArray( args, 1 ) );
return null;
}
case 1:
{
// startTimer
@ -245,29 +242,20 @@ public class OSAPI implements ILuaAPI
}
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 ) );
return new Object[] { m_nextAlarmToken++ };
}
}
case 3:
{
// shutdown
case 3: // shutdown
m_apiEnvironment.shutdown();
return null;
}
case 4:
{
// reboot
case 4: // reboot
m_apiEnvironment.reboot();
return null;
}
case 5:
case 6:
{
// computerID/getComputerID
case 6: // computerID/getComputerID
return new Object[] { getComputerID() };
}
case 7:
{
// setComputerLabel
@ -286,14 +274,11 @@ public class OSAPI implements ILuaAPI
}
return null;
}
case 10:
{
// clock
case 10: // clock
synchronized( m_timers )
{
return new Object[] { m_clock * 0.05 };
}
}
case 11:
{
// time
@ -356,10 +341,7 @@ public class OSAPI implements ILuaAPI
int token = getInt( args, 0 );
synchronized( m_timers )
{
if( m_timers.containsKey( token ) )
{
m_timers.remove( token );
}
m_timers.remove( token );
}
return null;
}
@ -369,10 +351,7 @@ public class OSAPI implements ILuaAPI
int token = getInt( args, 0 );
synchronized( m_alarms )
{
if( m_alarms.containsKey( token ) )
{
m_alarms.remove( token );
}
m_alarms.remove( token );
}
return null;
}
@ -407,9 +386,7 @@ public class OSAPI implements ILuaAPI
}
}
default:
{
return null;
}
}
}

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -26,7 +26,7 @@ public abstract class HandleGeneric implements ILuaObject
protected HandleGeneric( @Nonnull Closeable closable )
{
this.m_closable = closable;
m_closable = closable;
}
protected void checkOpen() throws LuaException
@ -46,7 +46,7 @@ public abstract class HandleGeneric implements ILuaObject
*
* @param channel The channel to seek in
* @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
* @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 );
this.environment = environment;
this.address = address;
this.host = uri.getHost();
host = uri.getHost();
}
public void run()

View File

@ -140,6 +140,6 @@ public abstract class Resource<T extends Resource<T>> implements Closeable
public static void cleanup()
{
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()
{
this.limit = ZERO;
limit = ZERO;
}
public void startup()

View File

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

View File

@ -37,7 +37,7 @@ public final class HttpRequestHandler extends SimpleChannelInboundHandler<HttpOb
/**
* 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];
@ -147,7 +147,7 @@ public final class HttpRequestHandler extends SimpleChannelInboundHandler<HttpOb
if( responseBody == null )
{
responseBody = ctx.alloc().compositeBuffer( DEFAULT_MAX_COMPOSITEBUFFER_COMPONENTS );
responseBody = ctx.alloc().compositeBuffer( DEFAULT_MAX_COMPOSITE_BUFFER_COMPONENTS );
}
ByteBuf partial = content.content();

View File

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

View File

@ -233,7 +233,7 @@ final class ComputerExecutor
synchronized( queueLock )
{
if( closed ) return;
this.closed = close;
closed = close;
StateCommand newCommand = reboot ? StateCommand.REBOOT : StateCommand.SHUTDOWN;
@ -425,7 +425,7 @@ final class ComputerExecutor
}
// Init filesystem
if( (this.fileSystem = createFileSystem()) == null )
if( (fileSystem = createFileSystem()) == null )
{
shutdown();
return;
@ -435,7 +435,7 @@ final class ComputerExecutor
for( ILuaAPI api : apis ) api.startup();
// Init lua
if( (this.machine = createLuaMachine()) == null )
if( (machine = createLuaMachine()) == null )
{
shutdown();
return;
@ -650,7 +650,7 @@ final class ComputerExecutor
ABORT,
}
private static class Event
private static final class Event
{
final String name;
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 ComputerExecutor For how computers actually do execution.
*/
public class ComputerThread
public final class ComputerThread
{
/**
* 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 runnerFactory = ThreadUtils.factory( "Computer-Runner" );
private ComputerThread() {}
/**
* Start the computer thread
*/
@ -339,7 +341,7 @@ public class ComputerThread
*/
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.
*
* <h2>Redstone</h2>
* <h1>Redstone</h1>
* We holds three kinds of arrays for redstone, in normal and bundled versions:
* <ul>
* <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>
* </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.
*/
public final class Environment implements IAPIEnvironment
@ -215,7 +215,7 @@ public final class Environment implements IAPIEnvironment
*/
boolean updateOutput()
{
// Set outputchanged if the internal redstone has changed
// Mark output as changed if the internal redstone has changed
synchronized( internalOutput )
{
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
* 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.
@ -47,7 +47,6 @@ public class MainThread
if( at == bt ) return Integer.compare( a.hashCode(), b.hashCode() );
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.
@ -79,6 +78,8 @@ public class MainThread
private static long minimumTime = 0;
private MainThread() {}
public static long getUniqueTaskID()
{
return lastTaskId.incrementAndGet();

View File

@ -93,7 +93,7 @@ public final class TimeoutState
// need to handle overflow.
long now = System.nanoTime();
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,14 +55,8 @@ public class FileMount implements IWritableMount
m_ignoredBytesLeft = 0;
long bytesLeft = m_capacity - m_usedSpace;
if( newBytes > bytesLeft )
{
throw new IOException( "Out of space" );
}
else
{
m_usedSpace += newBytes;
}
if( newBytes > bytesLeft ) throw new IOException( "Out of space" );
m_usedSpace += newBytes;
}
}
@ -86,14 +80,17 @@ public class FileMount implements IWritableMount
SeekableCountingChannel( SeekableByteChannel inner, long bytesToIgnore )
{
super( inner, bytesToIgnore );
this.m_inner = inner;
m_inner = inner;
}
@Override
public SeekableByteChannel position( long newPosition ) throws IOException
{
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();
if( delta < 0 )
@ -115,7 +112,7 @@ public class FileMount implements IWritableMount
}
@Override
public int read( ByteBuffer dst ) throws IOException
public int read( ByteBuffer dst ) throws ClosedChannelException
{
if( !m_inner.isOpen() ) throw new ClosedChannelException();
throw new NonReadableChannelException();
@ -150,29 +147,19 @@ public class FileMount implements IWritableMount
@Override
public boolean exists( @Nonnull String path )
{
if( !created() )
{
return path.length() == 0;
}
else
{
File file = getRealPath( path );
return file.exists();
}
if( !created() ) return path.isEmpty();
File file = getRealPath( path );
return file.exists();
}
@Override
public boolean isDirectory( @Nonnull String path )
{
if( !created() )
{
return path.length() == 0;
}
else
{
File file = getRealPath( path );
return file.exists() && file.isDirectory();
}
if( !created() ) return path.isEmpty();
File file = getRealPath( path );
return file.exists() && file.isDirectory();
}
@Override
@ -180,29 +167,17 @@ public class FileMount implements IWritableMount
{
if( !created() )
{
if( path.length() != 0 )
{
throw new IOException( "/" + path + ": Not a directory" );
}
if( !path.isEmpty() ) throw new IOException( "/" + path + ": Not a directory" );
return;
}
else
File file = getRealPath( path );
if( !file.exists() || !file.isDirectory() ) throw new IOException( "/" + path + ": Not a directory" );
String[] paths = file.list();
for( String subPath : paths )
{
File file = getRealPath( path );
if( file.exists() && file.isDirectory() )
{
String[] paths = file.list();
for( String subPath : paths )
{
if( new File( file, subPath ).exists() )
{
contents.add( subPath );
}
}
}
else
{
throw new IOException( "/" + path + ": Not a directory" );
}
if( new File( file, subPath ).exists() ) contents.add( subPath );
}
}
@ -211,26 +186,14 @@ public class FileMount implements IWritableMount
{
if( !created() )
{
if( path.length() == 0 )
{
return 0;
}
if( path.isEmpty() ) return 0;
}
else
{
File file = getRealPath( path );
if( file.exists() )
{
if( file.isDirectory() )
{
return 0;
}
else
{
return file.length();
}
}
if( file.exists() ) return file.isDirectory() ? 0 : file.length();
}
throw new IOException( "/" + path + ": No such file" );
}
@ -242,11 +205,9 @@ public class FileMount implements IWritableMount
if( created() )
{
File file = getRealPath( path );
if( file.exists() && !file.isDirectory() )
{
return new FileInputStream( file );
}
if( file.exists() && !file.isDirectory() ) return new FileInputStream( file );
}
throw new IOException( "/" + path + ": No such file" );
}
@ -257,11 +218,9 @@ public class FileMount implements IWritableMount
if( created() )
{
File file = getRealPath( path );
if( file.exists() && !file.isDirectory() )
{
return FileChannel.open( file.toPath(), READ_OPTIONS );
}
if( file.exists() && !file.isDirectory() ) return FileChannel.open( file.toPath(), READ_OPTIONS );
}
throw new IOException( "/" + path + ": No such file" );
}
@ -274,53 +233,42 @@ public class FileMount implements IWritableMount
File file = getRealPath( path );
if( file.exists() )
{
if( !file.isDirectory() )
{
throw new IOException( "/" + path + ": File exists" );
}
if( !file.isDirectory() ) throw new IOException( "/" + path + ": File exists" );
return;
}
int dirsToCreate = 1;
File parent = file.getParentFile();
while( !parent.exists() )
{
++dirsToCreate;
parent = parent.getParentFile();
}
if( getRemainingSpace() < dirsToCreate * MINIMUM_FILE_SIZE )
{
throw new IOException( "/" + path + ": Out of space" );
}
if( file.mkdirs() )
{
m_usedSpace += dirsToCreate * MINIMUM_FILE_SIZE;
}
else
{
int dirsToCreate = 1;
File parent = file.getParentFile();
while( !parent.exists() )
{
++dirsToCreate;
parent = parent.getParentFile();
}
if( getRemainingSpace() < dirsToCreate * MINIMUM_FILE_SIZE )
{
throw new IOException( "/" + path + ": Out of space" );
}
boolean success = file.mkdirs();
if( success )
{
m_usedSpace += dirsToCreate * MINIMUM_FILE_SIZE;
}
else
{
throw new IOException( "/" + path + ": Access denied" );
}
throw new IOException( "/" + path + ": Access denied" );
}
}
@Override
public void delete( @Nonnull String path ) throws IOException
{
if( path.length() == 0 )
{
throw new IOException( "/" + path + ": Access denied" );
}
if( path.isEmpty() ) throw new IOException( "/" + path + ": Access denied" );
if( created() )
{
File file = getRealPath( path );
if( file.exists() )
{
deleteRecursively( file );
}
if( file.exists() ) deleteRecursively( file );
}
}
@ -371,60 +319,39 @@ public class FileMount implements IWritableMount
{
create();
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" );
}
else
{
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 );
throw new IOException( "/" + path + ": Out of space" );
}
m_usedSpace += MINIMUM_FILE_SIZE;
return new SeekableCountingChannel( Files.newByteChannel( file.toPath(), WRITE_OPTIONS ), MINIMUM_FILE_SIZE );
}
@Nonnull
@Override
public WritableByteChannel openChannelForAppend( @Nonnull String path ) throws IOException
{
if( created() )
{
File file = getRealPath( path );
if( !file.exists() )
{
throw new IOException( "/" + path + ": No such file" );
}
else 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.
return new WritableCountingChannel(
Files.newByteChannel( file.toPath(), APPEND_OPTIONS ),
Math.max( MINIMUM_FILE_SIZE - file.length(), 0 )
);
}
}
else
if( !created() )
{
throw new IOException( "/" + path + ": No such file" );
}
File file = getRealPath( path );
if( !file.exists() ) throw new IOException( "/" + path + ": No such file" );
if( file.isDirectory() ) throw new IOException( "/" + path + ": Cannot write to directory" );
// Allowing seeking when appending is not recommended, so we use a separate channel.
return new WritableCountingChannel(
Files.newByteChannel( file.toPath(), APPEND_OPTIONS ),
Math.max( MINIMUM_FILE_SIZE - file.length(), 0 )
);
}
@Override
@ -433,7 +360,7 @@ public class FileMount implements IWritableMount
return Math.max( m_capacity - m_usedSpace, 0 );
}
public File getRealPath( String path )
private File getRealPath( String 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() )
{
return 0;
}
if( !file.exists() ) return 0;
if( file.isDirectory() )
{
long size = MINIMUM_FILE_SIZE;

View File

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

View File

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

View File

@ -76,9 +76,9 @@ public class JarMount implements IMount
{
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.
@ -212,7 +212,7 @@ public class JarMount implements IMount
}
}
}
catch( Exception e )
catch( IOException e )
{
// Treat errors as non-existence of file
}

View File

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

View File

@ -67,7 +67,7 @@ public class CobaltLuaMachine implements ILuaMachine
debug = new TimeoutDebugHandler();
// Create an environment to run in
LuaState state = this.m_state = LuaState.builder()
LuaState state = m_state = LuaState.builder()
.resourceManipulator( new VoidResourceManipulator() )
.debug( debug )
.coroutineExecutor( command -> {
@ -254,7 +254,7 @@ public class CobaltLuaMachine implements ILuaMachine
{
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 );
}
@ -348,22 +348,14 @@ public class CobaltLuaMachine implements ILuaMachine
{
case Constants.TNIL:
case Constants.TNONE:
{
return null;
}
case Constants.TINT:
case Constants.TNUMBER:
{
return value.toDouble();
}
case Constants.TBOOLEAN:
{
return value.toBoolean();
}
case Constants.TSTRING:
{
return value.toString();
}
case Constants.TTABLE:
{
// Table:
@ -411,9 +403,7 @@ public class CobaltLuaMachine implements ILuaMachine
return table;
}
default:
{
return null;
}
}
}
@ -445,7 +435,7 @@ public class CobaltLuaMachine implements ILuaMachine
TimeoutDebugHandler()
{
this.timeout = CobaltLuaMachine.this.timeout;
timeout = CobaltLuaMachine.this.timeout;
}
@Override
@ -560,7 +550,7 @@ public class CobaltLuaMachine implements ILuaMachine
{
if( ComputerCraft.logPeripheralErrors ) ComputerCraft.log.error( "Error running task", t );
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;

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
* do nothing if it does not match the event filter.
* @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.
*/
MachineResult handleEvent( @Nullable String eventName, @Nullable Object[] arguments );

View File

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

View File

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

View File

@ -14,7 +14,7 @@ import java.util.List;
import java.util.UUID;
import java.util.concurrent.atomic.AtomicInteger;
public class Tracking
public final class Tracking
{
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 List<Tracker> trackers = new ArrayList<>();
private Tracking() {}
public static TrackingContext getContext( UUID uuid )
{
synchronized( lock )

View File

@ -13,7 +13,7 @@ import java.util.HashMap;
import java.util.Map;
import java.util.function.LongFunction;
public class TrackingField
public final class TrackingField
{
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_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_OUTGOING = TrackingField.of( "websocket_outgoing", "Websocket outgoing", TrackingField::formatBytes );
@ -64,7 +64,7 @@ public class TrackingField
private TrackingField( String id, LongFunction<String> format )
{
this.id = id;
this.translationKey = "tracking_field.computercraft." + id + ".name";
translationKey = "tracking_field.computercraft." + id + ".name";
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_WHITELIST;
public class Config
public final class Config
{
private static final int MODEM_MAX_RANGE = 100000;
@ -78,6 +78,8 @@ public class Config
private static Property turtlesCanPush;
private static Property turtleDisabledActions;
private Config() {}
public static void load( File configFile )
{
config = new Configuration( configFile, ComputerCraft.getVersion() );
@ -106,7 +108,7 @@ public class Config
"update. Useful for ensuring forward compatibility of your programs now." );
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" );
debugEnabled = config.get( CATEGORY_GENERAL, "debug_enabled", ComputerCraft.debug_enable );

View File

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

View File

@ -6,7 +6,6 @@
package dan200.computercraft.shared;
import com.google.common.base.Preconditions;
import dan200.computercraft.ComputerCraft;
import dan200.computercraft.api.peripheral.IPeripheral;
import dan200.computercraft.api.peripheral.IPeripheralProvider;
@ -16,14 +15,17 @@ import net.minecraft.world.World;
import javax.annotation.Nonnull;
import java.util.Collection;
import java.util.Objects;
public final class Peripherals
{
private static final Collection<IPeripheralProvider> providers = ComputerCraft.peripheralProviders;
private Peripherals() {}
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 );
}

View File

@ -6,7 +6,6 @@
package dan200.computercraft.shared;
import com.google.common.base.Preconditions;
import dan200.computercraft.ComputerCraft;
import dan200.computercraft.api.pocket.IPocketUpgrade;
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 IdentityHashMap<IPocketUpgrade, String> upgradeOwners = new IdentityHashMap<>();
private PocketUpgrades() {}
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();
IPocketUpgrade existing = upgrades.get( id );

View File

@ -6,7 +6,6 @@
package dan200.computercraft.shared;
import com.google.common.base.Preconditions;
import dan200.computercraft.ComputerCraft;
import dan200.computercraft.api.turtle.ITurtleUpgrade;
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 IdentityHashMap<ITurtleUpgrade, String> upgradeOwners = new IdentityHashMap<>();
private TurtleUpgrades() {}
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();
if( id >= 0 && id < 64 )
@ -44,7 +45,7 @@ public final class TurtleUpgrades
static void registerInternal( ITurtleUpgrade upgrade )
{
Preconditions.checkNotNull( upgrade, "upgrade cannot be null" );
Objects.requireNonNull( upgrade, "upgrade cannot be null" );
// Check conditions
int legacyId = upgrade.getLegacyUpgradeID();

View File

@ -60,7 +60,7 @@ public final class CommandComputerCraft extends CommandDelegate
@Override
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" );
@ -162,7 +162,7 @@ public final class CommandComputerCraft extends CommandDelegate
@Override
public List<String> getCompletion( @Nonnull CommandContext context, @Nonnull List<String> arguments )
{
return arguments.size() == 0
return arguments.isEmpty()
? Collections.emptyList()
: ComputerSelector.completeComputer( arguments.get( arguments.size() - 1 ) );
}
@ -188,7 +188,7 @@ public final class CommandComputerCraft extends CommandDelegate
@Override
public List<String> getCompletion( @Nonnull CommandContext context, @Nonnull List<String> arguments )
{
return arguments.size() == 0
return arguments.isEmpty()
? Collections.emptyList()
: ComputerSelector.completeComputer( arguments.get( arguments.size() - 1 ) );
}

View File

@ -21,7 +21,7 @@ import net.minecraftforge.fml.relauncher.SideOnly;
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();

View File

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

View File

@ -18,6 +18,8 @@ import java.util.function.Predicate;
final class ComputerSelector
{
private ComputerSelector() {}
private static List<ServerComputer> getComputers( Predicate<ServerComputer> predicate )
{
// We copy it to prevent concurrent modifications.
@ -29,7 +31,7 @@ final class ComputerSelector
static ServerComputer getComputer( String selector ) throws CommandException
{
List<ServerComputer> computers = getComputers( selector );
if( computers.size() == 0 )
if( computers.isEmpty() )
{
throw new CommandException( "commands.computercraft.argument.no_matching", selector );
}
@ -53,7 +55,7 @@ final class ComputerSelector
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 );
@ -69,12 +71,12 @@ final class ComputerSelector
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 );
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 );
return getComputers( x -> x.getFamily().name().equalsIgnoreCase( familyName ) );
@ -103,7 +105,7 @@ final class ComputerSelector
// We copy it to prevent concurrent modifications.
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 );
@ -113,7 +115,7 @@ final class ComputerSelector
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 );
for( ServerComputer computer : computers )
@ -122,7 +124,7 @@ final class ComputerSelector
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 );
for( ComputerFamily family : ComputerFamily.values() )

View File

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

View File

@ -20,7 +20,7 @@ import java.util.Collections;
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
{

View File

@ -105,7 +105,7 @@ public class CommandRoot implements ISubCommand
@Override
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() ) );
}
@ -125,7 +125,7 @@ public class CommandRoot implements ISubCommand
@Override
public List<String> getCompletion( @Nonnull CommandContext context, @Nonnull List<String> arguments )
{
if( arguments.size() == 0 )
if( arguments.isEmpty() )
{
return Lists.newArrayList( subCommands.keySet() );
}

View File

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

View File

@ -23,6 +23,8 @@ public final class ChatHelpers
private static final TextFormatting SYNOPSIS = TextFormatting.AQUA;
private static final TextFormatting NAME = TextFormatting.GREEN;
private ChatHelpers() {}
public static ITextComponent coloured( String text, TextFormatting colour )
{
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" );
this.id = id;
this.headers = headers;
this.columns = headers.length;
columns = headers.length;
}
public TableBuilder( int id )
{
if( id < 0 ) throw new IllegalArgumentException( "ID must be positive" );
this.id = id;
this.headers = null;
headers = null;
}
public TableBuilder( int id, @Nonnull String... headers )
@ -46,7 +46,7 @@ public class TableBuilder
if( id < 0 ) throw new IllegalArgumentException( "ID must be positive" );
this.id = id;
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] );
}

View File

@ -71,7 +71,7 @@ public interface TableFormatter
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 );
for( int x : maxWidths ) totalWidth += x;

View File

@ -26,7 +26,7 @@ public abstract class BlockGeneric extends Block implements ITileEntityProvider
protected BlockGeneric( Material material )
{
super( material );
this.hasTileEntity = true;
hasTileEntity = true;
}
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 )
{
TileEntity tile = world.getTileEntity( pos );
if( tile instanceof TileGeneric )
{
return ((TileGeneric) tile).getBundledRedstoneConnectivity( side );
}
return false;
return tile instanceof TileGeneric && ((TileGeneric) tile).getBundledRedstoneConnectivity( side );
}
public int getBundledRedstoneOutput( World world, BlockPos pos, EnumFacing side )

View File

@ -7,10 +7,41 @@
package dan200.computercraft.shared.common;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
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
public BlockGeneric getBlock()
{
Block block = getWorld().getBlockState( getPos() ).getBlock();
Block block = getBlockType();
return block instanceof BlockGeneric ? (BlockGeneric) block : null;
}
@ -110,7 +110,7 @@ public abstract class TileGeneric extends TileEntity
double range = getInteractRange( player );
BlockPos pos = getPos();
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 )

View File

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

View File

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

View File

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

View File

@ -12,8 +12,7 @@ import dan200.computercraft.api.peripheral.IPeripheral;
import javax.annotation.Nonnull;
public class ComputerPeripheral
implements IPeripheral
public class ComputerPeripheral implements IPeripheral
{
private final String m_type;
private final ComputerProxy m_computer;
@ -52,50 +51,30 @@ public class ComputerPeripheral
{
switch( method )
{
case 0:
{
// turnOn
case 0: // turnOn
m_computer.turnOn();
return null;
}
case 1:
{
// shutdown
case 1: // shutdown
m_computer.shutdown();
return null;
}
case 2:
{
// reboot
case 2: // reboot
m_computer.reboot();
return null;
}
case 3:
{
// getID
return new Object[] {
m_computer.assignID()
};
}
case 4:
{
// isOn
case 3: // getID
return new Object[] { m_computer.assignID() };
case 4: // isOn
return new Object[] { m_computer.isOn() };
}
case 5:
// getLabel
case 5: // getLabel
return new Object[] { m_computer.getLabel() };
default:
{
return null;
}
}
}
@Override
public boolean equals( IPeripheral other )
{
return (other != null && other.getClass() == this.getClass());
return other != null && other.getClass() == getClass();
}
@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
// as Plethora depends on it.
private String m_name;
private final String name;
ComputerState( String name )
{
m_name = name;
this.name = name;
}
@Nonnull
@Override
public String getName()
{
return m_name;
return name;
}
@Override
public String toString()
{
return getName();
return name;
}
public static ComputerState valueOf( int ordinal )

View File

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

View File

@ -113,7 +113,7 @@ public class TileComputer extends TileComputerBase
}
// 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
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.ITickable;
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.Nullable;
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_computerID = -1;
@ -46,11 +50,7 @@ public abstract class TileComputerBase extends TileGeneric implements IComputerT
public BlockComputerBase getBlock()
{
Block block = super.getBlock();
if( block instanceof BlockComputerBase )
{
return (BlockComputerBase) block;
}
return null;
return block instanceof BlockComputerBase ? (BlockComputerBase) block : null;
}
protected void unload()
@ -95,29 +95,16 @@ public abstract class TileComputerBase extends TileGeneric implements IComputerT
return false;
}
protected boolean onDefaultComputerInteract( EntityPlayer player )
{
if( !getWorld().isRemote )
{
if( isUsable( player, false ) )
{
createServerComputer().turnOn();
openGUI( player );
}
}
return true;
}
@Override
public boolean onActivate( EntityPlayer player, EnumHand hand, EnumFacing side, float hitX, float hitY, float hitZ )
{
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
if( !getWorld().isRemote )
{
setLabel( currentItem.hasDisplayName() ? currentItem.getDisplayName() : null );
setLabel( currentItem.getDisplayName() );
currentItem.shrink( 1 );
}
return true;
@ -125,7 +112,12 @@ public abstract class TileComputerBase extends TileGeneric implements IComputerT
else if( !player.isSneaking() )
{
// Regular right click to activate computer
return onDefaultComputerInteract( player );
if( !getWorld().isRemote && isUsable( player, false ) )
{
createServerComputer().turnOn();
openGUI( player );
}
return true;
}
return false;
}
@ -201,10 +193,7 @@ public abstract class TileComputerBase extends TileGeneric implements IComputerT
m_startOn = false;
}
computer.keepAlive();
if( computer.hasOutputChanged() )
{
updateOutput();
}
if( computer.hasOutputChanged() ) updateOutput();
m_fresh = false;
m_computerID = computer.getID();
m_label = computer.getLabel();
@ -214,13 +203,7 @@ public abstract class TileComputerBase extends TileGeneric implements IComputerT
else
{
ClientComputer computer = createClientComputer();
if( computer != null )
{
if( computer.hasOutputChanged() )
{
updateBlock();
}
}
if( computer != null && computer.hasOutputChanged() ) updateBlock();
}
}
@ -310,10 +293,7 @@ public abstract class TileComputerBase extends TileGeneric implements IComputerT
public void updateInput()
{
if( getWorld() == null || getWorld().isRemote )
{
return;
}
if( getWorld() == null || getWorld().isRemote ) return;
// Update redstone and peripherals
ServerComputer computer = getServerComputer();
@ -329,10 +309,7 @@ public abstract class TileComputerBase extends TileGeneric implements IComputerT
public void updateInput( BlockPos neighbour )
{
if( getWorld() == null || getWorld().isRemote )
{
return;
}
if( getWorld() == null || getWorld().isRemote ) return;
ServerComputer computer = getServerComputer();
if( computer != null )
@ -505,4 +482,25 @@ public abstract class TileComputerBase extends TileGeneric implements IComputerT
{
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_nextUnusedInstanceID = 0;
m_sessionID = (new Random().nextInt());
m_sessionID = new Random().nextInt();
}
}

View File

@ -6,6 +6,7 @@
package dan200.computercraft.shared.computer.core;
@FunctionalInterface
public interface IComputerContainer
{
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
* if you provide custom computers/GUIs to interact with them.
*/
@FunctionalInterface
public interface IContainerComputer
{
/**

View File

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

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