From b202b7b8a5aafd1c5286fce45fb1af1857918d37 Mon Sep 17 00:00:00 2001 From: Daniel Ratcliffe Date: Mon, 1 May 2017 15:48:44 +0100 Subject: [PATCH] Converted tabs to spaces throughout --- .../dan200/computercraft/ComputerCraft.java | 352 ++-- .../computercraft/api/ComputerCraftAPI.java | 276 +-- .../computercraft/api/filesystem/IMount.java | 62 +- .../api/filesystem/IWritableMount.java | 54 +- .../api/filesystem/package-info.java | 2 +- .../computercraft/api/lua/ILuaContext.java | 54 +- .../computercraft/api/lua/ILuaObject.java | 16 +- .../computercraft/api/media/IMedia.java | 74 +- .../computercraft/api/package-info.java | 2 +- .../api/peripheral/IComputerAccess.java | 138 +- .../api/peripheral/IPeripheral.java | 134 +- .../api/peripheral/IPeripheralProvider.java | 2 +- .../api/permissions/package-info.java | 2 +- .../api/turtle/ITurtleAccess.java | 84 +- .../api/turtle/ITurtleCommand.java | 16 +- .../api/turtle/ITurtleUpgrade.java | 92 +- .../computercraft/api/turtle/TurtleSide.java | 16 +- .../api/turtle/TurtleUpgradeType.java | 22 +- .../computercraft/api/turtle/TurtleVerb.java | 18 +- .../client/gui/FixedWidthFontRenderer.java | 18 +- .../computercraft/client/gui/GuiComputer.java | 92 +- .../computercraft/client/gui/GuiPrinter.java | 2 +- .../computercraft/client/gui/GuiPrintout.java | 252 +-- .../computercraft/client/gui/GuiTurtle.java | 88 +- .../client/gui/widgets/WidgetTerminal.java | 214 +- .../client/proxy/CCTurtleProxyClient.java | 32 +- .../proxy/ComputerCraftProxyClient.java | 188 +- .../computercraft/core/apis/BitAPI.java | 44 +- .../dan200/computercraft/core/apis/FSAPI.java | 1072 +++++----- .../computercraft/core/apis/HTTPAPI.java | 272 +-- .../computercraft/core/apis/HTTPRequest.java | 120 +- .../core/apis/IAPIEnvironment.java | 44 +- .../computercraft/core/apis/ILuaAPI.java | 6 +- .../dan200/computercraft/core/apis/OSAPI.java | 480 ++--- .../core/apis/PeripheralAPI.java | 912 ++++----- .../computercraft/core/apis/RedstoneAPI.java | 328 +-- .../computercraft/core/apis/TermAPI.java | 418 ++-- .../computercraft/core/computer/Computer.java | 1162 +++++------ .../core/computer/ComputerThread.java | 402 ++-- .../core/computer/IComputerEnvironment.java | 8 +- .../core/filesystem/ComboMount.java | 216 +- .../core/filesystem/EmptyMount.java | 68 +- .../core/filesystem/FileMount.java | 712 +++---- .../core/filesystem/FileSystem.java | 1786 ++++++++--------- .../core/filesystem/FileSystemException.java | 6 +- .../core/filesystem/IMountedFile.java | 2 +- .../core/filesystem/IMountedFileBinary.java | 8 +- .../core/filesystem/IMountedFileNormal.java | 8 +- .../core/filesystem/JarMount.java | 440 ++-- .../core/filesystem/SubMount.java | 104 +- .../computercraft/core/lua/ILuaMachine.java | 26 +- .../core/lua/LuaJLuaMachine.java | 802 ++++---- .../computercraft/core/terminal/Terminal.java | 252 +-- .../server/proxy/CCTurtleProxyServer.java | 22 +- .../proxy/ComputerCraftProxyServer.java | 98 +- .../shared/common/BlockGeneric.java | 8 +- .../shared/computer/blocks/BlockComputer.java | 6 +- .../computer/blocks/ComputerPeripheral.java | 96 +- .../shared/computer/blocks/TileComputer.java | 2 +- .../computer/inventory/ContainerComputer.java | 22 +- .../shared/computer/items/ItemComputer.java | 36 +- .../shared/media/items/ItemDiskExpanded.java | 70 +- .../shared/media/items/ItemDiskLegacy.java | 126 +- .../shared/media/items/ItemPrintout.java | 234 +-- .../shared/media/items/ItemTreasureDisk.java | 116 +- .../shared/media/items/RecordMedia.java | 60 +- .../shared/media/recipes/DiskRecipe.java | 30 +- .../shared/media/recipes/PrintoutRecipe.java | 224 +-- .../shared/network/ComputerCraftPacket.java | 26 +- .../shared/network/INetworkedThing.java | 2 +- .../commandblock/CommandBlockPeripheral.java | 98 +- .../CommandBlockPeripheralProvider.java | 10 +- .../shared/peripheral/common/BlockCable.java | 2 +- .../peripheral/common/BlockPeripheral.java | 44 +- .../peripheral/common/ItemAdvancedModem.java | 4 +- .../shared/peripheral/common/ItemCable.java | 138 +- .../peripheral/common/ItemPeripheral.java | 4 +- .../peripheral/common/TilePeripheralBase.java | 66 +- .../diskdrive/ContainerDiskDrive.java | 6 +- .../peripheral/diskdrive/TileDiskDrive.java | 472 ++--- .../shared/peripheral/modem/INetwork.java | 8 +- .../shared/peripheral/modem/IReceiver.java | 8 +- .../peripheral/modem/ModemPeripheral.java | 442 ++-- .../peripheral/modem/TileAdvancedModem.java | 26 +- .../shared/peripheral/modem/TileCable.java | 908 ++++----- .../peripheral/modem/TileModemBase.java | 48 +- .../peripheral/modem/TileWirelessModem.java | 40 +- .../modem/WirelessModemPeripheral.java | 6 +- .../peripheral/modem/WirelessNetwork.java | 102 +- .../peripheral/monitor/TileMonitor.java | 774 +++---- .../peripheral/printer/ContainerPrinter.java | 110 +- .../peripheral/printer/TilePrinter.java | 578 +++--- .../shared/proxy/CCTurtleProxyCommon.java | 334 +-- .../proxy/ComputerCraftProxyCommon.java | 542 ++--- .../shared/proxy/ICCTurtleProxy.java | 16 +- .../shared/proxy/IComputerCraftProxy.java | 24 +- .../shared/turtle/apis/TurtleAPI.java | 460 ++--- .../shared/turtle/blocks/BlockTurtle.java | 4 +- .../shared/turtle/blocks/TileTurtle.java | 90 +- .../turtle/blocks/TileTurtleAdvanced.java | 6 +- .../turtle/blocks/TileTurtleExpanded.java | 6 +- .../shared/turtle/core/TurtlePlayer.java | 52 +- .../turtle/inventory/ContainerTurtle.java | 46 +- .../shared/turtle/items/ItemTurtleLegacy.java | 14 +- .../shared/turtle/items/ItemTurtleNormal.java | 46 +- .../shared/turtle/recipes/TurtleRecipe.java | 72 +- .../turtle/recipes/TurtleUpgradeRecipe.java | 194 +- .../upgrades/CraftingTablePeripheral.java | 88 +- .../shared/turtle/upgrades/TurtleAxe.java | 8 +- .../turtle/upgrades/TurtleCraftingTable.java | 54 +- .../shared/turtle/upgrades/TurtleHoe.java | 30 +- .../upgrades/TurtleInventoryCrafting.java | 128 +- .../shared/turtle/upgrades/TurtleModem.java | 100 +- .../shared/turtle/upgrades/TurtleShovel.java | 18 +- .../shared/turtle/upgrades/TurtleSword.java | 34 +- .../shared/turtle/upgrades/TurtleTool.java | 126 +- .../shared/util/CreativeTabMain.java | 2 +- .../shared/util/CreativeTabTreasure.java | 2 +- .../computercraft/shared/util/IDAssigner.java | 176 +- .../shared/util/IEntityDropConsumer.java | 2 +- .../shared/util/ImpostorRecipe.java | 24 +- .../shared/util/ImpostorShapelessRecipe.java | 22 +- .../shared/util/InventoryUtil.java | 292 +-- 123 files changed, 10042 insertions(+), 10042 deletions(-) diff --git a/src/main/java/dan200/computercraft/ComputerCraft.java b/src/main/java/dan200/computercraft/ComputerCraft.java index 33386f69e..95c468b06 100644 --- a/src/main/java/dan200/computercraft/ComputerCraft.java +++ b/src/main/java/dan200/computercraft/ComputerCraft.java @@ -84,22 +84,22 @@ @Mod( modid = "ComputerCraft", name = "ComputerCraft", version = "${version}" ) public class ComputerCraft { - // GUI IDs - public static final int diskDriveGUIID = 100; - public static final int computerGUIID = 101; - public static final int printerGUIID = 102; + // GUI IDs + public static final int diskDriveGUIID = 100; + public static final int computerGUIID = 101; + public static final int printerGUIID = 102; public static final int turtleGUIID = 103; - // ComputerCraftEdu uses ID 104 + // ComputerCraftEdu uses ID 104 public static final int printoutGUIID = 105; public static final int pocketComputerGUIID = 106; - // Configuration options - public static boolean http_enable = true; + // Configuration options + public static boolean http_enable = true; public static String http_whitelist = "*"; public static boolean disable_lua51_features = false; public static String default_computer_settings = ""; - public static boolean enableCommandBlock = false; + public static boolean enableCommandBlock = false; public static boolean turtlesNeedFuel = true; public static int turtleFuelLimit = 20000; public static int advancedTurtleFuelLimit = 100000; @@ -107,7 +107,7 @@ public class ComputerCraft public static boolean turtlesCanPush = true; public static final int terminalWidth_computer = 51; - public static final int terminalHeight_computer = 19; + public static final int terminalHeight_computer = 19; public static final int terminalWidth_turtle = 39; public static final int terminalHeight_turtle = 13; @@ -116,19 +116,19 @@ public class ComputerCraft public static final int terminalHeight_pocketComputer = 20; public static int modem_range = 64; - public static int modem_highAltitudeRange = 384; - public static int modem_rangeDuringStorm = 64; - public static int modem_highAltitudeRangeDuringStorm = 384; + public static int modem_highAltitudeRange = 384; + public static int modem_rangeDuringStorm = 64; + public static int modem_highAltitudeRangeDuringStorm = 384; - public static int computerSpaceLimit = 1000 * 1000; - public static int floppySpaceLimit = 125 * 1000; + public static int computerSpaceLimit = 1000 * 1000; + public static int floppySpaceLimit = 125 * 1000; // Blocks and Items - public static class Blocks - { - public static BlockComputer computer; - public static BlockPeripheral peripheral; - public static BlockCable cable; + public static class Blocks + { + public static BlockComputer computer; + public static BlockPeripheral peripheral; + public static BlockCable cable; public static BlockTurtle turtle; public static BlockTurtle turtleExpanded; public static BlockTurtle turtleAdvanced; @@ -136,14 +136,14 @@ public static class Blocks public static BlockAdvancedModem advancedModem; } - public static class Items - { - public static ItemDiskLegacy disk; - public static ItemDiskExpanded diskExpanded; - public static ItemPrintout printout; - public static ItemTreasureDisk treasureDisk; + public static class Items + { + public static ItemDiskLegacy disk; + public static ItemDiskExpanded diskExpanded; + public static ItemPrintout printout; + public static ItemTreasureDisk treasureDisk; public static ItemPocketComputer pocketComputer; - } + } public static class Upgrades { @@ -164,40 +164,40 @@ public static class Upgrades // Networking public static FMLEventChannel networkEventChannel; - // Creative - public static CreativeTabMain mainCreativeTab; + // Creative + public static CreativeTabMain mainCreativeTab; // API users - private static List peripheralProviders = new ArrayList(); + private static List peripheralProviders = new ArrayList(); private static List bundledRedstoneProviders = new ArrayList(); private static List mediaProviders = new ArrayList(); private static List permissionProviders = new ArrayList(); // Implementation - @Mod.Instance( value = "ComputerCraft" ) - public static ComputerCraft instance; + @Mod.Instance( value = "ComputerCraft" ) + public static ComputerCraft instance; - @SidedProxy( clientSide = "dan200.computercraft.client.proxy.ComputerCraftProxyClient", serverSide = "dan200.computercraft.server.proxy.ComputerCraftProxyServer" ) - public static IComputerCraftProxy proxy; + @SidedProxy( clientSide = "dan200.computercraft.client.proxy.ComputerCraftProxyClient", serverSide = "dan200.computercraft.server.proxy.ComputerCraftProxyServer" ) + public static IComputerCraftProxy proxy; @SidedProxy( clientSide = "dan200.computercraft.client.proxy.CCTurtleProxyClient", serverSide = "dan200.computercraft.server.proxy.CCTurtleProxyServer" ) public static ICCTurtleProxy turtleProxy; - public ComputerCraft() - { - } + public ComputerCraft() + { + } - @Mod.EventHandler - public void preInit( FMLPreInitializationEvent event ) - { + @Mod.EventHandler + public void preInit( FMLPreInitializationEvent event ) + { // Load config - Configuration config = new Configuration( event.getSuggestedConfigurationFile() ); - config.load(); + Configuration config = new Configuration( event.getSuggestedConfigurationFile() ); + config.load(); // Setup general - Property prop = config.get(Configuration.CATEGORY_GENERAL, "http_enable", http_enable); - prop.setComment( "Enable the \"http\" API on Computers (see \"http_whitelist\" for more fine grained control than this)" ); + Property prop = config.get(Configuration.CATEGORY_GENERAL, "http_enable", http_enable); + prop.setComment( "Enable the \"http\" API on Computers (see \"http_whitelist\" for more fine grained control than this)" ); http_enable = prop.getBoolean(http_enable); prop = config.get(Configuration.CATEGORY_GENERAL, "http_whitelist", http_whitelist ); @@ -213,32 +213,32 @@ public void preInit( FMLPreInitializationEvent event ) default_computer_settings = prop.getString(); prop = config.get(Configuration.CATEGORY_GENERAL, "enableCommandBlock", enableCommandBlock); - prop.setComment( "Enable Command Block peripheral support" ); - enableCommandBlock = prop.getBoolean(enableCommandBlock); + prop.setComment( "Enable Command Block peripheral support" ); + enableCommandBlock = prop.getBoolean(enableCommandBlock); - prop = config.get(Configuration.CATEGORY_GENERAL, "modem_range", modem_range); - prop.setComment( "The range of Wireless Modems at low altitude in clear weather, in meters" ); - modem_range = Math.min( prop.getInt(), 100000 ); + prop = config.get(Configuration.CATEGORY_GENERAL, "modem_range", modem_range); + prop.setComment( "The range of Wireless Modems at low altitude in clear weather, in meters" ); + modem_range = Math.min( prop.getInt(), 100000 ); - prop = config.get(Configuration.CATEGORY_GENERAL, "modem_highAltitudeRange", modem_highAltitudeRange); - prop.setComment( "The range of Wireless Modems at maximum altitude in clear weather, in meters" ); - modem_highAltitudeRange = Math.min( prop.getInt(), 100000 ); + prop = config.get(Configuration.CATEGORY_GENERAL, "modem_highAltitudeRange", modem_highAltitudeRange); + prop.setComment( "The range of Wireless Modems at maximum altitude in clear weather, in meters" ); + modem_highAltitudeRange = Math.min( prop.getInt(), 100000 ); - prop = config.get(Configuration.CATEGORY_GENERAL, "modem_rangeDuringStorm", modem_rangeDuringStorm); - prop.setComment( "The range of Wireless Modems at low altitude in stormy weather, in meters" ); - modem_rangeDuringStorm = Math.min( prop.getInt(), 100000 ); + prop = config.get(Configuration.CATEGORY_GENERAL, "modem_rangeDuringStorm", modem_rangeDuringStorm); + prop.setComment( "The range of Wireless Modems at low altitude in stormy weather, in meters" ); + modem_rangeDuringStorm = Math.min( prop.getInt(), 100000 ); - prop = config.get(Configuration.CATEGORY_GENERAL, "modem_highAltitudeRangeDuringStorm", modem_highAltitudeRangeDuringStorm); - prop.setComment( "The range of Wireless Modems at maximum altitude in stormy weather, in meters" ); - modem_highAltitudeRangeDuringStorm = Math.min( prop.getInt(), 100000 ); + prop = config.get(Configuration.CATEGORY_GENERAL, "modem_highAltitudeRangeDuringStorm", modem_highAltitudeRangeDuringStorm); + prop.setComment( "The range of Wireless Modems at maximum altitude in stormy weather, in meters" ); + modem_highAltitudeRangeDuringStorm = Math.min( prop.getInt(), 100000 ); - prop = config.get(Configuration.CATEGORY_GENERAL, "computerSpaceLimit", computerSpaceLimit); - prop.setComment( "The disk space limit for computers and turtles, in bytes" ); - computerSpaceLimit = prop.getInt(); + prop = config.get(Configuration.CATEGORY_GENERAL, "computerSpaceLimit", computerSpaceLimit); + prop.setComment( "The disk space limit for computers and turtles, in bytes" ); + computerSpaceLimit = prop.getInt(); - prop = config.get(Configuration.CATEGORY_GENERAL, "floppySpaceLimit", floppySpaceLimit); - prop.setComment( "The disk space limit for floppy disks, in bytes" ); - floppySpaceLimit = prop.getInt(); + prop = config.get(Configuration.CATEGORY_GENERAL, "floppySpaceLimit", floppySpaceLimit); + prop.setComment( "The disk space limit for floppy disks, in bytes" ); + floppySpaceLimit = prop.getInt(); prop = config.get(Configuration.CATEGORY_GENERAL, "turtlesNeedFuel", turtlesNeedFuel); prop.setComment( "Set whether Turtles require fuel to move" ); @@ -266,16 +266,16 @@ public void preInit( FMLPreInitializationEvent event ) networkEventChannel = NetworkRegistry.INSTANCE.newEventDrivenChannel( "CC" ); networkEventChannel.register( new PacketHandler() ); - proxy.preInit(); + proxy.preInit(); turtleProxy.preInit(); - } + } - @Mod.EventHandler - public void init( FMLInitializationEvent event ) - { - proxy.init(); + @Mod.EventHandler + public void init( FMLInitializationEvent event ) + { + proxy.init(); turtleProxy.init(); - } + } @Mod.EventHandler public void onServerStarting( FMLServerStartingEvent event ) @@ -308,14 +308,14 @@ public static String getVersion() } public static boolean isClient() - { - return proxy.isClient(); - } + { + return proxy.isClient(); + } - public static boolean getGlobalCursorBlink() - { - return proxy.getGlobalCursorBlink(); - } + public static boolean getGlobalCursorBlink() + { + return proxy.getGlobalCursorBlink(); + } public static long getRenderFrame() { @@ -328,37 +328,37 @@ public static void deleteDisplayLists( int list, int range ) } public static Object getFixedWidthFontRenderer() - { - return proxy.getFixedWidthFontRenderer(); - } + { + return proxy.getFixedWidthFontRenderer(); + } - public static void playRecord( SoundEvent record, String recordInfo, World world, BlockPos pos ) - { - proxy.playRecord( record, recordInfo, world, pos ); - } + public static void playRecord( SoundEvent record, String recordInfo, World world, BlockPos pos ) + { + proxy.playRecord( record, recordInfo, world, pos ); + } - public static String getRecordInfo( ItemStack recordStack ) - { - return proxy.getRecordInfo( recordStack ); - } + public static String getRecordInfo( ItemStack recordStack ) + { + return proxy.getRecordInfo( recordStack ); + } - public static void openDiskDriveGUI( EntityPlayer player, TileDiskDrive drive ) - { + public static void openDiskDriveGUI( EntityPlayer player, TileDiskDrive drive ) + { BlockPos pos = drive.getPos(); - player.openGui( ComputerCraft.instance, ComputerCraft.diskDriveGUIID, player.getEntityWorld(), pos.getX(), pos.getY(), pos.getZ() ); - } + player.openGui( ComputerCraft.instance, ComputerCraft.diskDriveGUIID, player.getEntityWorld(), pos.getX(), pos.getY(), pos.getZ() ); + } - public static void openComputerGUI( EntityPlayer player, TileComputer computer ) - { + public static void openComputerGUI( EntityPlayer player, TileComputer computer ) + { BlockPos pos = computer.getPos(); - player.openGui( ComputerCraft.instance, ComputerCraft.computerGUIID, player.getEntityWorld(), pos.getX(), pos.getY(), pos.getZ() ); - } + player.openGui( ComputerCraft.instance, ComputerCraft.computerGUIID, player.getEntityWorld(), pos.getX(), pos.getY(), pos.getZ() ); + } - public static void openPrinterGUI( EntityPlayer player, TilePrinter printer ) - { + public static void openPrinterGUI( EntityPlayer player, TilePrinter printer ) + { BlockPos pos = printer.getPos(); - player.openGui( ComputerCraft.instance, ComputerCraft.printerGUIID, player.getEntityWorld(), pos.getX(), pos.getY(), pos.getZ() ); - } + player.openGui( ComputerCraft.instance, ComputerCraft.printerGUIID, player.getEntityWorld(), pos.getX(), pos.getY(), pos.getZ() ); + } public static void openTurtleGUI( EntityPlayer player, TileTurtle turtle ) { @@ -366,8 +366,8 @@ public static void openTurtleGUI( EntityPlayer player, TileTurtle turtle ) player.openGui( instance, ComputerCraft.turtleGUIID, player.getEntityWorld(), pos.getX(), pos.getY(), pos.getZ() ); } - public static void openPrintoutGUI( EntityPlayer player ) - { + public static void openPrintoutGUI( EntityPlayer player ) + { player.openGui( ComputerCraft.instance, ComputerCraft.printoutGUIID, player.getEntityWorld(), 0, 0, 0 ); } @@ -377,19 +377,19 @@ public static void openPocketComputerGUI( EntityPlayer player ) } public static File getBaseDir() - { - return FMLCommonHandler.instance().getMinecraftServerInstance().getFile("."); - } + { + return FMLCommonHandler.instance().getMinecraftServerInstance().getFile("."); + } - public static File getResourcePackDir() - { - return new File( getBaseDir(), "resourcepacks" ); - } + public static File getResourcePackDir() + { + return new File( getBaseDir(), "resourcepacks" ); + } - public static File getWorldDir( World world ) - { - return proxy.getWorldDir( world ); - } + public static File getWorldDir( World world ) + { + return proxy.getWorldDir( world ); + } private static FMLProxyPacket encode( ComputerCraftPacket packet ) { @@ -398,25 +398,25 @@ private static FMLProxyPacket encode( ComputerCraftPacket packet ) return new FMLProxyPacket( buffer, "CC" ); } - public static void sendToPlayer( EntityPlayer player, ComputerCraftPacket packet ) - { + public static void sendToPlayer( EntityPlayer player, ComputerCraftPacket packet ) + { networkEventChannel.sendTo( encode( packet ), (EntityPlayerMP)player ); - } + } - public static void sendToAllPlayers( ComputerCraftPacket packet ) - { + public static void sendToAllPlayers( ComputerCraftPacket packet ) + { networkEventChannel.sendToAll( encode( packet ) ); - } + } - public static void sendToServer( ComputerCraftPacket packet ) - { + public static void sendToServer( ComputerCraftPacket packet ) + { networkEventChannel.sendToServer( encode( packet ) ); - } + } - public static void handlePacket( ComputerCraftPacket packet, EntityPlayer player ) - { - proxy.handlePacket( packet, player ); - } + public static void handlePacket( ComputerCraftPacket packet, EntityPlayer player ) + { + proxy.handlePacket( packet, player ); + } public static boolean canPlayerUseCommands( EntityPlayer player ) { @@ -491,12 +491,12 @@ public static boolean isBlockEditable( World world, BlockPos pos, EntityPlayer p } public static void registerPeripheralProvider( IPeripheralProvider provider ) - { + { if( provider != null && !peripheralProviders.contains( provider ) ) { peripheralProviders.add( provider ); } - } + } public static void registerBundledRedstoneProvider( IBundledRedstoneProvider provider ) { @@ -515,11 +515,11 @@ public static void registerMediaProvider( IMediaProvider provider ) } public static IPeripheral getPeripheralAt( World world, BlockPos pos, EnumFacing side ) - { - // Try the handlers in order: - Iterator it = peripheralProviders.iterator(); - while( it.hasNext() ) - { + { + // Try the handlers in order: + Iterator it = peripheralProviders.iterator(); + while( it.hasNext() ) + { try { IPeripheralProvider handler = it.next(); @@ -533,9 +533,9 @@ public static IPeripheral getPeripheralAt( World world, BlockPos pos, EnumFacing { // mod misbehaved, ignore it } - } - return null; - } + } + return null; + } public static int getDefaultBundledRedstoneOutput( World world, BlockPos pos, EnumFacing side ) { @@ -610,25 +610,25 @@ public static IMedia getMedia( ItemStack stack ) return null; } - public static int createUniqueNumberedSaveDir( World world, String parentSubPath ) - { - return IDAssigner.getNextIDFromDirectory(new File(getWorldDir(world), parentSubPath)); - } + public static int createUniqueNumberedSaveDir( World world, String parentSubPath ) + { + return IDAssigner.getNextIDFromDirectory(new File(getWorldDir(world), parentSubPath)); + } - public static IWritableMount createSaveDirMount( World world, String subPath, long capacity ) - { - try - { - return new FileMount( new File( getWorldDir( world ), subPath ), capacity ); - } - catch( Exception e ) - { - return null; - } - } + public static IWritableMount createSaveDirMount( World world, String subPath, long capacity ) + { + try + { + return new FileMount( new File( getWorldDir( world ), subPath ), capacity ); + } + catch( Exception e ) + { + return null; + } + } - public static IMount createResourceMount( Class modClass, String domain, String subPath ) - { + public static IMount createResourceMount( Class modClass, String domain, String subPath ) + { // Start building list of mounts List mounts = new ArrayList(); subPath = "assets/" + domain + "/" + subPath; @@ -709,32 +709,32 @@ else if( mounts.size() == 1 ) { return null; } - } + } - private static File getContainingJar( Class modClass ) - { - String path = modClass.getProtectionDomain().getCodeSource().getLocation().getPath(); - int bangIndex = path.indexOf( "!" ); - if( bangIndex >= 0 ) - { - path = path.substring( 0, bangIndex ); - } + private static File getContainingJar( Class modClass ) + { + String path = modClass.getProtectionDomain().getCodeSource().getLocation().getPath(); + int bangIndex = path.indexOf( "!" ); + if( bangIndex >= 0 ) + { + path = path.substring( 0, bangIndex ); + } - URL url; - try { - url = new URL( path ); - } catch (MalformedURLException e1) { - return null; - } + URL url; + try { + url = new URL( path ); + } catch (MalformedURLException e1) { + return null; + } - File file; - try { - file = new File( url.toURI() ); - } catch(URISyntaxException e) { - file = new File( url.getPath() ); - } - return file; - } + File file; + try { + file = new File( url.toURI() ); + } catch(URISyntaxException e) { + file = new File( url.getPath() ); + } + return file; + } private static File getDebugCodeDir( Class modClass ) { diff --git a/src/main/java/dan200/computercraft/api/ComputerCraftAPI.java b/src/main/java/dan200/computercraft/api/ComputerCraftAPI.java index 40acca58e..49471e552 100644 --- a/src/main/java/dan200/computercraft/api/ComputerCraftAPI.java +++ b/src/main/java/dan200/computercraft/api/ComputerCraftAPI.java @@ -51,103 +51,103 @@ public static String getAPIVersion() return "${version}"; } - /** - * Creates a numbered directory in a subfolder of the save directory for a given world, and returns that number.
- * Use in conjuction with createSaveDirMount() to create a unique place for your peripherals or media items to store files.
- * @param world The world for which the save dir should be created. This should be the serverside world object. - * @param parentSubPath The folder path within the save directory where the new directory should be created. eg: "computercraft/disk" - * @return The numerical value of the name of the new folder, or -1 if the folder could not be created for some reason.
- * eg: if createUniqueNumberedSaveDir( world, "computer/disk" ) was called returns 42, then "computer/disk/42" is now available for writing. - * @see #createSaveDirMount(World, String, long) - */ - public static int createUniqueNumberedSaveDir( World world, String parentSubPath ) - { - findCC(); - if( computerCraft_createUniqueNumberedSaveDir != null ) - { - try { - return (Integer)computerCraft_createUniqueNumberedSaveDir.invoke( null, world, parentSubPath ); - } catch (Exception e) { - // It failed - } - } - return -1; - } - - /** - * Creates a file system mount that maps to a subfolder of the save directory for a given world, and returns it.
- * Use in conjuction with IComputerAccess.mount() or IComputerAccess.mountWritable() to mount a folder from the - * users save directory onto a computers file system.
- * @param world The world for which the save dir can be found. This should be the serverside world object. - * @param subPath The folder path within the save directory that the mount should map to. eg: "computer/disk/42".
- * Use createUniqueNumberedSaveDir() to create a new numbered folder to use. - * @param capacity The ammount of data that can be stored in the directory before it fills up, in bytes. - * @return The mount, or null if it could be created for some reason. Use IComputerAccess.mount() or IComputerAccess.mountWritable() - * to mount this on a Computers' file system. - * @see #createUniqueNumberedSaveDir(World, String) - * @see dan200.computercraft.api.peripheral.IComputerAccess#mount(String, dan200.computercraft.api.filesystem.IMount) - * @see dan200.computercraft.api.peripheral.IComputerAccess#mountWritable(String, dan200.computercraft.api.filesystem.IWritableMount) - * @see dan200.computercraft.api.filesystem.IMount - * @see IWritableMount - */ - public static IWritableMount createSaveDirMount( World world, String subPath, long capacity ) - { - findCC(); - if( computerCraft_createSaveDirMount != null ) - { - try { - return (IWritableMount)computerCraft_createSaveDirMount.invoke( null, world, subPath, capacity ); - } catch (Exception e){ - // It failed - } - } - return null; - } - - /** - * Creates a file system mount to a resource folder, and returns it.
- * Use in conjuction with IComputerAccess.mount() or IComputerAccess.mountWritable() to mount a resource folder onto a computers file system.
- * The files in this mount will be a combination of files in the specified mod jar, and resource packs that contain resources with the same domain and path.
- * @param modClass A class in whose jar to look first for the resources to mount. Using your main mod class is recommended. eg: MyMod.class - * @param domain The domain under which to look for resources. eg: "mymod" - * @param subPath The domain under which to look for resources. eg: "mymod/lua/myfiles" - * @return The mount, or null if it could be created for some reason. Use IComputerAccess.mount() or IComputerAccess.mountWritable() - * to mount this on a Computers' file system. - * @see dan200.computercraft.api.peripheral.IComputerAccess#mount(String, dan200.computercraft.api.filesystem.IMount) - * @see dan200.computercraft.api.peripheral.IComputerAccess#mountWritable(String, IWritableMount) - * @see dan200.computercraft.api.filesystem.IMount - */ - public static IMount createResourceMount( Class modClass, String domain, String subPath ) - { - findCC(); - if( computerCraft_createResourceMount != null ) - { - try { - return (IMount)computerCraft_createResourceMount.invoke( null, modClass, domain, subPath ); - } catch (Exception e){ - // It failed - } - } - return null; - } - - /** - * Registers a peripheral handler to convert blocks into IPeripheral implementations. - * @see dan200.computercraft.api.peripheral.IPeripheral - * @see dan200.computercraft.api.peripheral.IPeripheralProvider - */ - public static void registerPeripheralProvider( IPeripheralProvider handler ) - { - findCC(); - if ( computerCraft_registerPeripheralProvider != null) - { - try { - computerCraft_registerPeripheralProvider.invoke( null, handler ); - } catch (Exception e){ - // It failed - } - } - } + /** + * Creates a numbered directory in a subfolder of the save directory for a given world, and returns that number.
+ * Use in conjuction with createSaveDirMount() to create a unique place for your peripherals or media items to store files.
+ * @param world The world for which the save dir should be created. This should be the serverside world object. + * @param parentSubPath The folder path within the save directory where the new directory should be created. eg: "computercraft/disk" + * @return The numerical value of the name of the new folder, or -1 if the folder could not be created for some reason.
+ * eg: if createUniqueNumberedSaveDir( world, "computer/disk" ) was called returns 42, then "computer/disk/42" is now available for writing. + * @see #createSaveDirMount(World, String, long) + */ + public static int createUniqueNumberedSaveDir( World world, String parentSubPath ) + { + findCC(); + if( computerCraft_createUniqueNumberedSaveDir != null ) + { + try { + return (Integer)computerCraft_createUniqueNumberedSaveDir.invoke( null, world, parentSubPath ); + } catch (Exception e) { + // It failed + } + } + return -1; + } + + /** + * Creates a file system mount that maps to a subfolder of the save directory for a given world, and returns it.
+ * Use in conjuction with IComputerAccess.mount() or IComputerAccess.mountWritable() to mount a folder from the + * users save directory onto a computers file system.
+ * @param world The world for which the save dir can be found. This should be the serverside world object. + * @param subPath The folder path within the save directory that the mount should map to. eg: "computer/disk/42".
+ * Use createUniqueNumberedSaveDir() to create a new numbered folder to use. + * @param capacity The ammount of data that can be stored in the directory before it fills up, in bytes. + * @return The mount, or null if it could be created for some reason. Use IComputerAccess.mount() or IComputerAccess.mountWritable() + * to mount this on a Computers' file system. + * @see #createUniqueNumberedSaveDir(World, String) + * @see dan200.computercraft.api.peripheral.IComputerAccess#mount(String, dan200.computercraft.api.filesystem.IMount) + * @see dan200.computercraft.api.peripheral.IComputerAccess#mountWritable(String, dan200.computercraft.api.filesystem.IWritableMount) + * @see dan200.computercraft.api.filesystem.IMount + * @see IWritableMount + */ + public static IWritableMount createSaveDirMount( World world, String subPath, long capacity ) + { + findCC(); + if( computerCraft_createSaveDirMount != null ) + { + try { + return (IWritableMount)computerCraft_createSaveDirMount.invoke( null, world, subPath, capacity ); + } catch (Exception e){ + // It failed + } + } + return null; + } + + /** + * Creates a file system mount to a resource folder, and returns it.
+ * Use in conjuction with IComputerAccess.mount() or IComputerAccess.mountWritable() to mount a resource folder onto a computers file system.
+ * The files in this mount will be a combination of files in the specified mod jar, and resource packs that contain resources with the same domain and path.
+ * @param modClass A class in whose jar to look first for the resources to mount. Using your main mod class is recommended. eg: MyMod.class + * @param domain The domain under which to look for resources. eg: "mymod" + * @param subPath The domain under which to look for resources. eg: "mymod/lua/myfiles" + * @return The mount, or null if it could be created for some reason. Use IComputerAccess.mount() or IComputerAccess.mountWritable() + * to mount this on a Computers' file system. + * @see dan200.computercraft.api.peripheral.IComputerAccess#mount(String, dan200.computercraft.api.filesystem.IMount) + * @see dan200.computercraft.api.peripheral.IComputerAccess#mountWritable(String, IWritableMount) + * @see dan200.computercraft.api.filesystem.IMount + */ + public static IMount createResourceMount( Class modClass, String domain, String subPath ) + { + findCC(); + if( computerCraft_createResourceMount != null ) + { + try { + return (IMount)computerCraft_createResourceMount.invoke( null, modClass, domain, subPath ); + } catch (Exception e){ + // It failed + } + } + return null; + } + + /** + * Registers a peripheral handler to convert blocks into IPeripheral implementations. + * @see dan200.computercraft.api.peripheral.IPeripheral + * @see dan200.computercraft.api.peripheral.IPeripheralProvider + */ + public static void registerPeripheralProvider( IPeripheralProvider handler ) + { + findCC(); + if ( computerCraft_registerPeripheralProvider != null) + { + try { + computerCraft_registerPeripheralProvider.invoke( null, handler ); + } catch (Exception e){ + // It failed + } + } + } /** * Registers a new turtle turtle for use in ComputerCraft. After calling this, @@ -243,28 +243,28 @@ public static void registerPermissionProvider( ITurtlePermissionProvider handler } // The functions below here are private, and are used to interface with the non-API ComputerCraft classes. - // Reflection is used here so you can develop your mod without decompiling ComputerCraft and including - // it in your solution, and so your mod won't crash if ComputerCraft is installed. - - private static void findCC() - { - if( !ccSearched ) { - try { - computerCraft = Class.forName( "dan200.computercraft.ComputerCraft" ); + // Reflection is used here so you can develop your mod without decompiling ComputerCraft and including + // it in your solution, and so your mod won't crash if ComputerCraft is installed. + + private static void findCC() + { + if( !ccSearched ) { + try { + computerCraft = Class.forName( "dan200.computercraft.ComputerCraft" ); computerCraft_getVersion = findCCMethod( "getVersion", new Class[]{ } ); - computerCraft_createUniqueNumberedSaveDir = findCCMethod( "createUniqueNumberedSaveDir", new Class[]{ + computerCraft_createUniqueNumberedSaveDir = findCCMethod( "createUniqueNumberedSaveDir", new Class[]{ World.class, String.class } ); - computerCraft_createSaveDirMount = findCCMethod( "createSaveDirMount", new Class[] { - World.class, String.class, Long.TYPE - } ); - computerCraft_createResourceMount = findCCMethod( "createResourceMount", new Class[] { - Class.class, String.class, String.class - } ); - computerCraft_registerPeripheralProvider = findCCMethod( "registerPeripheralProvider", new Class[] { - IPeripheralProvider.class - } ); + computerCraft_createSaveDirMount = findCCMethod( "createSaveDirMount", new Class[] { + World.class, String.class, Long.TYPE + } ); + computerCraft_createResourceMount = findCCMethod( "createResourceMount", new Class[] { + Class.class, String.class, String.class + } ); + computerCraft_registerPeripheralProvider = findCCMethod( "registerPeripheralProvider", new Class[] { + IPeripheralProvider.class + } ); computerCraft_registerTurtleUpgrade = findCCMethod( "registerTurtleUpgrade", new Class[] { ITurtleUpgrade.class } ); @@ -280,35 +280,35 @@ private static void findCC() computerCraft_registerPermissionProvider = findCCMethod( "registerPermissionProvider", new Class[] { ITurtlePermissionProvider.class } ); - } catch( Exception e ) { - System.out.println( "ComputerCraftAPI: ComputerCraft not found." ); - } finally { - ccSearched = true; - } - } - } + } catch( Exception e ) { + System.out.println( "ComputerCraftAPI: ComputerCraft not found." ); + } finally { + ccSearched = true; + } + } + } - private static Method findCCMethod( String name, Class[] args ) - { - try { + private static Method findCCMethod( String name, Class[] args ) + { + try { if( computerCraft != null ) { - return computerCraft.getMethod( name, args ); + return computerCraft.getMethod( name, args ); } return null; - } catch( NoSuchMethodException e ) { - System.out.println( "ComputerCraftAPI: ComputerCraft method " + name + " not found." ); - return null; - } - } - - private static boolean ccSearched = false; - private static Class computerCraft = null; + } catch( NoSuchMethodException e ) { + System.out.println( "ComputerCraftAPI: ComputerCraft method " + name + " not found." ); + return null; + } + } + + private static boolean ccSearched = false; + private static Class computerCraft = null; private static Method computerCraft_getVersion = null; - private static Method computerCraft_createUniqueNumberedSaveDir = null; - private static Method computerCraft_createSaveDirMount = null; - private static Method computerCraft_createResourceMount = null; - private static Method computerCraft_registerPeripheralProvider = null; + private static Method computerCraft_createUniqueNumberedSaveDir = null; + private static Method computerCraft_createSaveDirMount = null; + private static Method computerCraft_createResourceMount = null; + private static Method computerCraft_registerPeripheralProvider = null; private static Method computerCraft_registerTurtleUpgrade = null; private static Method computerCraft_registerBundledRedstoneProvider = null; private static Method computerCraft_getDefaultBundledRedstoneOutput = null; diff --git a/src/main/java/dan200/computercraft/api/filesystem/IMount.java b/src/main/java/dan200/computercraft/api/filesystem/IMount.java index 1538edbed..d26537d61 100644 --- a/src/main/java/dan200/computercraft/api/filesystem/IMount.java +++ b/src/main/java/dan200/computercraft/api/filesystem/IMount.java @@ -20,38 +20,38 @@ */ public interface IMount { - /** - * Returns whether a file with a given path exists or not. - * @param path A file path in normalised format, relative to the mount location. ie: "programs/myprogram" - * @return true if the file exists, false otherwise - */ - public boolean exists( String path ) throws IOException; + /** + * Returns whether a file with a given path exists or not. + * @param path A file path in normalised format, relative to the mount location. ie: "programs/myprogram" + * @return true if the file exists, false otherwise + */ + public boolean exists( String path ) throws IOException; - /** - * Returns whether a file with a given path is a directory or not. - * @param path A file path in normalised format, relative to the mount location. ie: "programs/myprograms" - * @return true if the file exists and is a directory, false otherwise - */ - public boolean isDirectory( String path ) throws IOException; + /** + * Returns whether a file with a given path is a directory or not. + * @param path A file path in normalised format, relative to the mount location. ie: "programs/myprograms" + * @return true if the file exists and is a directory, false otherwise + */ + public boolean isDirectory( String path ) throws IOException; - /** - * Returns the file names of all the files in a directory. - * @param path A file path in normalised format, relative to the mount location. ie: "programs/myprograms" - * @param contents A list of strings. Add all the file names to this list - */ - public void list( String path, List contents ) throws IOException; + /** + * Returns the file names of all the files in a directory. + * @param path A file path in normalised format, relative to the mount location. ie: "programs/myprograms" + * @param contents A list of strings. Add all the file names to this list + */ + public void list( String path, List contents ) throws IOException; - /** - * Returns the size of a file with a given path, in bytes - * @param path A file path in normalised format, relative to the mount location. ie: "programs/myprogram" - * @return the size of the file, in bytes - */ - public long getSize( String path ) throws IOException; - - /** - * Opens a file with a given path, and returns an inputstream representing it's contents. - * @param path A file path in normalised format, relative to the mount location. ie: "programs/myprogram" - * @return a stream representing the contents of the file - */ - public InputStream openForRead( String path ) throws IOException; + /** + * Returns the size of a file with a given path, in bytes + * @param path A file path in normalised format, relative to the mount location. ie: "programs/myprogram" + * @return the size of the file, in bytes + */ + public long getSize( String path ) throws IOException; + + /** + * Opens a file with a given path, and returns an inputstream representing it's contents. + * @param path A file path in normalised format, relative to the mount location. ie: "programs/myprogram" + * @return a stream representing the contents of the file + */ + public InputStream openForRead( String path ) throws IOException; } diff --git a/src/main/java/dan200/computercraft/api/filesystem/IWritableMount.java b/src/main/java/dan200/computercraft/api/filesystem/IWritableMount.java index f8053d070..429b73fdc 100644 --- a/src/main/java/dan200/computercraft/api/filesystem/IWritableMount.java +++ b/src/main/java/dan200/computercraft/api/filesystem/IWritableMount.java @@ -18,35 +18,35 @@ */ public interface IWritableMount extends IMount { - /** - * Creates a directory at a given path inside the virtual file system. - * @param path A file path in normalised format, relative to the mount location. ie: "programs/mynewprograms" - */ - public void makeDirectory( String path ) throws IOException; + /** + * Creates a directory at a given path inside the virtual file system. + * @param path A file path in normalised format, relative to the mount location. ie: "programs/mynewprograms" + */ + public void makeDirectory( String path ) throws IOException; - /** - * Deletes a directory at a given path inside the virtual file system. - * @param path A file path in normalised format, relative to the mount location. ie: "programs/myoldprograms" - */ - public void delete( String path ) throws IOException; + /** + * Deletes a directory at a given path inside the virtual file system. + * @param path A file path in normalised format, relative to the mount location. ie: "programs/myoldprograms" + */ + public void delete( String path ) throws IOException; - /** - * Opens a file with a given path, and returns an outputstream for writing to it. - * @param path A file path in normalised format, relative to the mount location. ie: "programs/myprogram" - * @return a stream for writing to - */ - public OutputStream openForWrite( String path ) throws IOException; + /** + * Opens a file with a given path, and returns an outputstream for writing to it. + * @param path A file path in normalised format, relative to the mount location. ie: "programs/myprogram" + * @return a stream for writing to + */ + public OutputStream openForWrite( String path ) throws IOException; - /** - * Opens a file with a given path, and returns an outputstream for appending to it. - * @param path A file path in normalised format, relative to the mount location. ie: "programs/myprogram" - * @return a stream for writing to - */ - public OutputStream openForAppend( String path ) throws IOException; + /** + * Opens a file with a given path, and returns an outputstream for appending to it. + * @param path A file path in normalised format, relative to the mount location. ie: "programs/myprogram" + * @return a stream for writing to + */ + public OutputStream openForAppend( String path ) throws IOException; - /** - * Get the ammount of free space on the mount, in bytes. You should decrease this value as the user writes to the mount, and write operations should fail once it reaches zero. - * @return The ammount of free space, in bytes. - */ - public long getRemainingSpace() throws IOException; + /** + * Get the ammount of free space on the mount, in bytes. You should decrease this value as the user writes to the mount, and write operations should fail once it reaches zero. + * @return The ammount of free space, in bytes. + */ + public long getRemainingSpace() throws IOException; } diff --git a/src/main/java/dan200/computercraft/api/filesystem/package-info.java b/src/main/java/dan200/computercraft/api/filesystem/package-info.java index bd0b57710..dc0fb7927 100644 --- a/src/main/java/dan200/computercraft/api/filesystem/package-info.java +++ b/src/main/java/dan200/computercraft/api/filesystem/package-info.java @@ -7,4 +7,4 @@ @API( owner="ComputerCraft", provides="ComputerCraft|API|FileSystem", apiVersion="${version}" ) package dan200.computercraft.api.filesystem; -import net.minecraftforge.fml.common.API; \ No newline at end of file +import net.minecraftforge.fml.common.API; diff --git a/src/main/java/dan200/computercraft/api/lua/ILuaContext.java b/src/main/java/dan200/computercraft/api/lua/ILuaContext.java index fe821e90c..9c5a7168f 100644 --- a/src/main/java/dan200/computercraft/api/lua/ILuaContext.java +++ b/src/main/java/dan200/computercraft/api/lua/ILuaContext.java @@ -14,33 +14,33 @@ */ public interface ILuaContext { - /** - * Wait for an event to occur on the computercraft, suspending the thread until it arises. This method is exactly equivalent to os.pullEvent() in lua. - * @param filter A specific event to wait for, or null to wait for any event - * @return An object array containing the name of the event that occurred, and any event parameters - * @throws Exception If the user presses CTRL+T to terminate the current program while pullEvent() is waiting for an event, a "Terminated" exception will be thrown here. - * Do not attempt to common this exception, unless you wish to prevent termination, which is not recommended. - * @throws InterruptedException If the user shuts down or reboots the computercraft while pullEvent() is waiting for an event, InterruptedException will be thrown. This exception must not be caught or intercepted, or the computercraft will leak memory and end up in a broken state. - */ - public Object[] pullEvent( String filter ) throws LuaException, InterruptedException; - - /** - * The same as pullEvent(), except "terminated" events are ignored. Only use this if you want to prevent program termination, which is not recommended. This method is exactly equivalent to os.pullEventRaw() in lua. - * @param filter A specific event to wait for, or null to wait for any event - * @return An object array containing the name of the event that occurred, and any event parameters - * @throws InterruptedException If the user shuts down or reboots the computercraft while pullEventRaw() is waiting for an event, InterruptedException will be thrown. This exception must not be caught or intercepted, or the computercraft will leak memory and end up in a broken state. - * @see #pullEvent(String) - */ - public Object[] pullEventRaw( String filter ) throws InterruptedException; - - /** - * Yield the current coroutine with some arguments until it is resumed. This method is exactly equivalent to coroutine.yield() in lua. Use pullEvent() if you wish to wait for events. - * @param arguments An object array containing the arguments to pass to coroutine.yield() - * @return An object array containing the return values from coroutine.yield() - * @throws InterruptedException If the user shuts down or reboots the computercraft the coroutine is suspended, InterruptedException will be thrown. This exception must not be caught or intercepted, or the computercraft will leak memory and end up in a broken state. - * @see #pullEvent(String) - */ - public Object[] yield( Object[] arguments ) throws InterruptedException; + /** + * Wait for an event to occur on the computercraft, suspending the thread until it arises. This method is exactly equivalent to os.pullEvent() in lua. + * @param filter A specific event to wait for, or null to wait for any event + * @return An object array containing the name of the event that occurred, and any event parameters + * @throws Exception If the user presses CTRL+T to terminate the current program while pullEvent() is waiting for an event, a "Terminated" exception will be thrown here. + * Do not attempt to common this exception, unless you wish to prevent termination, which is not recommended. + * @throws InterruptedException If the user shuts down or reboots the computercraft while pullEvent() is waiting for an event, InterruptedException will be thrown. This exception must not be caught or intercepted, or the computercraft will leak memory and end up in a broken state. + */ + public Object[] pullEvent( String filter ) throws LuaException, InterruptedException; + + /** + * The same as pullEvent(), except "terminated" events are ignored. Only use this if you want to prevent program termination, which is not recommended. This method is exactly equivalent to os.pullEventRaw() in lua. + * @param filter A specific event to wait for, or null to wait for any event + * @return An object array containing the name of the event that occurred, and any event parameters + * @throws InterruptedException If the user shuts down or reboots the computercraft while pullEventRaw() is waiting for an event, InterruptedException will be thrown. This exception must not be caught or intercepted, or the computercraft will leak memory and end up in a broken state. + * @see #pullEvent(String) + */ + public Object[] pullEventRaw( String filter ) throws InterruptedException; + + /** + * Yield the current coroutine with some arguments until it is resumed. This method is exactly equivalent to coroutine.yield() in lua. Use pullEvent() if you wish to wait for events. + * @param arguments An object array containing the arguments to pass to coroutine.yield() + * @return An object array containing the return values from coroutine.yield() + * @throws InterruptedException If the user shuts down or reboots the computercraft the coroutine is suspended, InterruptedException will be thrown. This exception must not be caught or intercepted, or the computercraft will leak memory and end up in a broken state. + * @see #pullEvent(String) + */ + public Object[] yield( Object[] arguments ) throws InterruptedException; /** * TODO: Document me diff --git a/src/main/java/dan200/computercraft/api/lua/ILuaObject.java b/src/main/java/dan200/computercraft/api/lua/ILuaObject.java index e795a36aa..4f8954fd4 100644 --- a/src/main/java/dan200/computercraft/api/lua/ILuaObject.java +++ b/src/main/java/dan200/computercraft/api/lua/ILuaObject.java @@ -12,15 +12,15 @@ */ public interface ILuaObject { - /** - * Get the names of the methods that this object implements. This works the same as IPeripheral.getMethodNames(). See that method for detailed documentation. - * @see dan200.computercraft.api.peripheral.IPeripheral#getMethodNames() - */ + /** + * Get the names of the methods that this object implements. This works the same as IPeripheral.getMethodNames(). See that method for detailed documentation. + * @see dan200.computercraft.api.peripheral.IPeripheral#getMethodNames() + */ public String[] getMethodNames(); - /** - * Called when a user calls one of the methods that this object implements. This works the same as IPeripheral.callMethod(). See that method for detailed documentation. - * @see dan200.computercraft.api.peripheral.IPeripheral#callMethod(dan200.computercraft.api.peripheral.IComputerAccess, ILuaContext, int, Object[]) - */ + /** + * Called when a user calls one of the methods that this object implements. This works the same as IPeripheral.callMethod(). See that method for detailed documentation. + * @see dan200.computercraft.api.peripheral.IPeripheral#callMethod(dan200.computercraft.api.peripheral.IComputerAccess, ILuaContext, int, Object[]) + */ public Object[] callMethod( ILuaContext context, int method, Object[] arguments ) throws LuaException, InterruptedException; } diff --git a/src/main/java/dan200/computercraft/api/media/IMedia.java b/src/main/java/dan200/computercraft/api/media/IMedia.java index 3bd5199ae..39bb2cefb 100644 --- a/src/main/java/dan200/computercraft/api/media/IMedia.java +++ b/src/main/java/dan200/computercraft/api/media/IMedia.java @@ -17,44 +17,44 @@ */ public interface IMedia { - /** - * Get a string representing the label of this item. Will be called vi disk.getLabel() in lua. - * @param stack The itemstack to inspect - * @return The label. ie: "Dan's Programs" - */ - public String getLabel( ItemStack stack ); + /** + * Get a string representing the label of this item. Will be called vi disk.getLabel() in lua. + * @param stack The itemstack to inspect + * @return The label. ie: "Dan's Programs" + */ + public String getLabel( ItemStack stack ); - /** - * Set a string representing the label of this item. Will be called vi disk.setLabel() in lua. - * @param stack The itemstack to modify. - * @param label The string to set the label to. - * @return true if the label was updated, false if the label may not be modified. - */ - public boolean setLabel( ItemStack stack, String label ); - - /** - * If this disk represents an item with audio (like a record), get the readable name of the audio track. ie: "Jonathon Coulton - Still Alive" - * @param stack The itemstack to inspect. - * @return The name, or null if this item does not represent an item with audio. - */ - public String getAudioTitle( ItemStack stack ); - - /** - * If this disk represents an item with audio (like a record), get the resource name of the audio track to play. - * @param stack The itemstack to inspect. - * @return The name, or null if this item does not represent an item with audio. - */ - public SoundEvent getAudio( ItemStack stack ); + /** + * Set a string representing the label of this item. Will be called vi disk.setLabel() in lua. + * @param stack The itemstack to modify. + * @param label The string to set the label to. + * @return true if the label was updated, false if the label may not be modified. + */ + public boolean setLabel( ItemStack stack, String label ); - /** - * If this disk represents an item with data (like a floppy disk), get a mount representing it's contents. This will be mounted onto the filesystem of the computercraft while the media is in the disk drive. - * @param stack The itemstack to inspect. - * @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 IMount returned also implements IWritableMount, it will mounted using mountWritable() - * @see dan200.computercraft.api.filesystem.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) - */ + /** + * If this disk represents an item with audio (like a record), get the readable name of the audio track. ie: "Jonathon Coulton - Still Alive" + * @param stack The itemstack to inspect. + * @return The name, or null if this item does not represent an item with audio. + */ + public String getAudioTitle( ItemStack stack ); + + /** + * If this disk represents an item with audio (like a record), get the resource name of the audio track to play. + * @param stack The itemstack to inspect. + * @return The name, or null if this item does not represent an item with audio. + */ + public SoundEvent getAudio( ItemStack stack ); + + /** + * If this disk represents an item with data (like a floppy disk), get a mount representing it's contents. This will be mounted onto the filesystem of the computercraft while the media is in the disk drive. + * @param stack The itemstack to inspect. + * @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 IMount returned also implements IWritableMount, it will mounted using mountWritable() + * @see dan200.computercraft.api.filesystem.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) + */ public IMount createDataMount( ItemStack stack, World world ); } diff --git a/src/main/java/dan200/computercraft/api/package-info.java b/src/main/java/dan200/computercraft/api/package-info.java index 83ef25e57..1ed08dddb 100644 --- a/src/main/java/dan200/computercraft/api/package-info.java +++ b/src/main/java/dan200/computercraft/api/package-info.java @@ -7,4 +7,4 @@ @API( owner="ComputerCraft", provides="ComputerCraft|API", apiVersion="${version}" ) package dan200.computercraft.api; -import net.minecraftforge.fml.common.API; \ No newline at end of file +import net.minecraftforge.fml.common.API; diff --git a/src/main/java/dan200/computercraft/api/peripheral/IComputerAccess.java b/src/main/java/dan200/computercraft/api/peripheral/IComputerAccess.java index baca44395..498881a92 100644 --- a/src/main/java/dan200/computercraft/api/peripheral/IComputerAccess.java +++ b/src/main/java/dan200/computercraft/api/peripheral/IComputerAccess.java @@ -16,87 +16,87 @@ */ public interface IComputerAccess { - /** - * Mount a mount onto the computers' file system in a read only mode.
- * @param desiredLocation The location on the computercraft's file system where you would like the mount to be mounted. - * @param mount The mount object to mount on the computercraft. These can be obtained by calling ComputerCraftAPI.createSaveDirMount(), ComputerCraftAPI.createResourceMount() or by creating your own objects that implement the IMount interface. - * @return The location on the computercraft's file system where you the mount mounted, or null if there was already a file in the desired location. Store this value if you wish to unmount the mount later. - * @see dan200.computercraft.api.ComputerCraftAPI#createSaveDirMount(World, String) - * @see dan200.computercraft.api.ComputerCraftAPI#createResourceMount(Class, String, String) - * @see #mountWritable(String, dan200.computercraft.api.filesystem.IWritableMount) - * @see #unmount(String) - * @see dan200.computercraft.api.filesystem.IMount - */ - public String mount( String desiredLocation, IMount mount ); + /** + * Mount a mount onto the computers' file system in a read only mode.
+ * @param desiredLocation The location on the computercraft's file system where you would like the mount to be mounted. + * @param mount The mount object to mount on the computercraft. These can be obtained by calling ComputerCraftAPI.createSaveDirMount(), ComputerCraftAPI.createResourceMount() or by creating your own objects that implement the IMount interface. + * @return The location on the computercraft's file system where you the mount mounted, or null if there was already a file in the desired location. Store this value if you wish to unmount the mount later. + * @see dan200.computercraft.api.ComputerCraftAPI#createSaveDirMount(World, String) + * @see dan200.computercraft.api.ComputerCraftAPI#createResourceMount(Class, String, String) + * @see #mountWritable(String, dan200.computercraft.api.filesystem.IWritableMount) + * @see #unmount(String) + * @see dan200.computercraft.api.filesystem.IMount + */ + public String mount( String desiredLocation, IMount mount ); /** * TODO: Document me */ public String mount( String desiredLocation, IMount mount, String driveName ); - /** - * Mount a mount onto the computers' file system in a writable mode.
- * @param desiredLocation The location on the computercraft's file system where you would like the mount to be mounted. - * @param mount The mount object to mount on the computercraft. These can be obtained by calling ComputerCraftAPI.createSaveDirMount() or by creating your own objects that implement the IWritableMount interface. - * @return The location on the computercraft's file system where you the mount mounted, or null if there was already a file in the desired location. Store this value if you wish to unmount the mount later. - * @see dan200.computercraft.api.ComputerCraftAPI#createSaveDirMount(World, String) - * @see dan200.computercraft.api.ComputerCraftAPI#createResourceMount(Class, String, String) - * @see #mount(String, IMount) - * @see #unmount(String) - * @see IMount - */ - public String mountWritable( String desiredLocation, IWritableMount mount ); + /** + * Mount a mount onto the computers' file system in a writable mode.
+ * @param desiredLocation The location on the computercraft's file system where you would like the mount to be mounted. + * @param mount The mount object to mount on the computercraft. These can be obtained by calling ComputerCraftAPI.createSaveDirMount() or by creating your own objects that implement the IWritableMount interface. + * @return The location on the computercraft's file system where you the mount mounted, or null if there was already a file in the desired location. Store this value if you wish to unmount the mount later. + * @see dan200.computercraft.api.ComputerCraftAPI#createSaveDirMount(World, String) + * @see dan200.computercraft.api.ComputerCraftAPI#createResourceMount(Class, String, String) + * @see #mount(String, IMount) + * @see #unmount(String) + * @see IMount + */ + public String mountWritable( String desiredLocation, IWritableMount mount ); /** * TODO: Document me */ public String mountWritable( String desiredLocation, IWritableMount mount, String driveName ); - /** - * Unmounts a directory previously mounted onto the computers file system by mount() or mountWritable().
- * When a directory is unmounted, it will disappear from the computers file system, and the user will no longer be able to - * access it. All directories mounted by a mount or mountWritable are automatically unmounted when the peripheral - * is attached if they have not been explicitly unmounted. - * @param location The desired location in the computers file system of the directory to unmount. - * This must be the location of a directory previously mounted by mount() or mountWritable(), as - * indicated by their return value. - * @see #mount(String, IMount) - * @see #mountWritable(String, IWritableMount) - */ - public void unmount( String location ); - - /** - * Returns the numerical ID of this computercraft.
- * This is the same number obtained by calling os.getComputerID() or running the "id" program from lua, - * and is guarunteed unique. This number will be positive. - * @return The identifier. - */ - public int getID(); + /** + * Unmounts a directory previously mounted onto the computers file system by mount() or mountWritable().
+ * When a directory is unmounted, it will disappear from the computers file system, and the user will no longer be able to + * access it. All directories mounted by a mount or mountWritable are automatically unmounted when the peripheral + * is attached if they have not been explicitly unmounted. + * @param location The desired location in the computers file system of the directory to unmount. + * This must be the location of a directory previously mounted by mount() or mountWritable(), as + * indicated by their return value. + * @see #mount(String, IMount) + * @see #mountWritable(String, IWritableMount) + */ + public void unmount( String location ); + + /** + * Returns the numerical ID of this computercraft.
+ * This is the same number obtained by calling os.getComputerID() or running the "id" program from lua, + * and is guarunteed unique. This number will be positive. + * @return The identifier. + */ + public int getID(); - /** - * Causes an event to be raised on this computercraft, which the computercraft can respond to by calling - * os.pullEvent(). This can be used to notify the computercraft when things happen in the world or to - * this peripheral. - * @param event A string identifying the type of event that has occurred, this will be - * returned as the first value from os.pullEvent(). It is recommended that you - * you choose a name that is unique, and recognisable as originating from your - * peripheral. eg: If your peripheral type is "button", a suitable event would be - * "button_pressed". - * @param arguments In addition to a name, you may pass an array of extra arguments to the event, that will - * be supplied as extra return values to os.pullEvent(). Objects in the array will be converted - * to lua data types in the same fashion as the return values of IPeripheral.callMethod().
- * You may supply null to indicate that no arguments are to be supplied. - * @see dan200.computercraft.api.peripheral.IPeripheral#callMethod - */ - public void queueEvent( String event, Object[] arguments ); + /** + * Causes an event to be raised on this computercraft, which the computercraft can respond to by calling + * os.pullEvent(). This can be used to notify the computercraft when things happen in the world or to + * this peripheral. + * @param event A string identifying the type of event that has occurred, this will be + * returned as the first value from os.pullEvent(). It is recommended that you + * you choose a name that is unique, and recognisable as originating from your + * peripheral. eg: If your peripheral type is "button", a suitable event would be + * "button_pressed". + * @param arguments In addition to a name, you may pass an array of extra arguments to the event, that will + * be supplied as extra return values to os.pullEvent(). Objects in the array will be converted + * to lua data types in the same fashion as the return values of IPeripheral.callMethod().
+ * You may supply null to indicate that no arguments are to be supplied. + * @see dan200.computercraft.api.peripheral.IPeripheral#callMethod + */ + public void queueEvent( String event, Object[] arguments ); - /** - * Get a string, unique to the computercraft, by which the computercraft refers to this peripheral. - * For directly attached peripherals this will be "left","right","front","back",etc, but - * for peripherals attached remotely it will be different. It is good practice to supply - * this string when raising events to the computercraft, so that the computercraft knows from - * which peripheral the event came. - * @return A string unique to the computercraft, but not globally. - */ - public String getAttachmentName(); + /** + * Get a string, unique to the computercraft, by which the computercraft refers to this peripheral. + * For directly attached peripherals this will be "left","right","front","back",etc, but + * for peripherals attached remotely it will be different. It is good practice to supply + * this string when raising events to the computercraft, so that the computercraft knows from + * which peripheral the event came. + * @return A string unique to the computercraft, but not globally. + */ + public String getAttachmentName(); } diff --git a/src/main/java/dan200/computercraft/api/peripheral/IPeripheral.java b/src/main/java/dan200/computercraft/api/peripheral/IPeripheral.java index 12381814a..063767bbe 100644 --- a/src/main/java/dan200/computercraft/api/peripheral/IPeripheral.java +++ b/src/main/java/dan200/computercraft/api/peripheral/IPeripheral.java @@ -14,81 +14,81 @@ */ public interface IPeripheral { - /** - * Should return a string that uniquely identifies this type of peripheral. - * This can be queried from lua by calling peripheral.getType() - * @return A string identifying the type of peripheral. - */ + /** + * Should return a string that uniquely identifies this type of peripheral. + * This can be queried from lua by calling peripheral.getType() + * @return A string identifying the type of peripheral. + */ public String getType(); - /** - * Should return an array of strings that identify the methods that this - * peripheral exposes to Lua. This will be called once before each attachment, - * and should not change when called multiple times. - * @return An array of strings representing method names. - * @see #callMethod - */ + /** + * Should return an array of strings that identify the methods that this + * peripheral exposes to Lua. This will be called once before each attachment, + * and should not change when called multiple times. + * @return An array of strings representing method names. + * @see #callMethod + */ public String[] getMethodNames(); - /** - * This is called when a lua program on an attached computercraft calls peripheral.call() with - * one of the methods exposed by getMethodNames().
- *
- * Be aware that this will be called from the ComputerCraft Lua thread, and must be thread-safe - * when interacting with minecraft objects. - * @param computer The interface to the computercraft that is making the call. Remember that multiple - * computers can be attached to a peripheral at once. - * @param context The context of the currently running lua thread. This can be used to wait for events - * or otherwise yield. - * @param method An integer identifying which of the methods from getMethodNames() the computercraft - * wishes to call. The integer indicates the index into the getMethodNames() table - * that corresponds to the string passed into peripheral.call() - * @param arguments An array of objects, representing the arguments passed into peripheral.call().
- * Lua values of type "string" will be represented by Object type String.
- * Lua values of type "number" will be represented by Object type Double.
- * Lua values of type "boolean" will be represented by Object type Boolean.
- * Lua values of any other type will be represented by a null object.
- * This array will be empty if no arguments are passed. - * @return An array of objects, representing values you wish to return to the lua program.
- * Integers, Doubles, Floats, Strings, Booleans and null be converted to their corresponding lua type.
- * All other types will be converted to nil.
- * You may return null to indicate no values should be returned. - * @throws Exception If you throw any exception from this function, a lua error will be raised with the - * same message as your exception. Use this to throw appropriate errors if the wrong - * arguments are supplied to your method. - * @see #getMethodNames - */ + /** + * This is called when a lua program on an attached computercraft calls peripheral.call() with + * one of the methods exposed by getMethodNames().
+ *
+ * Be aware that this will be called from the ComputerCraft Lua thread, and must be thread-safe + * when interacting with minecraft objects. + * @param computer The interface to the computercraft that is making the call. Remember that multiple + * computers can be attached to a peripheral at once. + * @param context The context of the currently running lua thread. This can be used to wait for events + * or otherwise yield. + * @param method An integer identifying which of the methods from getMethodNames() the computercraft + * wishes to call. The integer indicates the index into the getMethodNames() table + * that corresponds to the string passed into peripheral.call() + * @param arguments An array of objects, representing the arguments passed into peripheral.call().
+ * Lua values of type "string" will be represented by Object type String.
+ * Lua values of type "number" will be represented by Object type Double.
+ * Lua values of type "boolean" will be represented by Object type Boolean.
+ * Lua values of any other type will be represented by a null object.
+ * This array will be empty if no arguments are passed. + * @return An array of objects, representing values you wish to return to the lua program.
+ * Integers, Doubles, Floats, Strings, Booleans and null be converted to their corresponding lua type.
+ * All other types will be converted to nil.
+ * You may return null to indicate no values should be returned. + * @throws Exception If you throw any exception from this function, a lua error will be raised with the + * same message as your exception. Use this to throw appropriate errors if the wrong + * arguments are supplied to your method. + * @see #getMethodNames + */ public Object[] callMethod( IComputerAccess computer, ILuaContext context, int method, Object[] arguments ) throws LuaException, InterruptedException; - /** - * Is called when canAttachToSide has returned true, and a computercraft is attaching to the peripheral. - * This will occur when a peripheral is placed next to an active computercraft, when a computercraft is turned on next to a peripheral, - * or when a turtle travels into a square next to a peripheral. - * Between calls to attach() and detach(), the attached computercraft can make method calls on the peripheral using 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 this will be called from the ComputerCraft Lua thread, and must be thread-safe - * when interacting with minecraft objects. - * @param computer The interface to the computercraft that is being attached. Remember that multiple - * computers can be attached to a peripheral at once. - * @see #detach - */ + /** + * Is called when canAttachToSide has returned true, and a computercraft is attaching to the peripheral. + * This will occur when a peripheral is placed next to an active computercraft, when a computercraft is turned on next to a peripheral, + * or when a turtle travels into a square next to a peripheral. + * Between calls to attach() and detach(), the attached computercraft can make method calls on the peripheral using 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 this will be called from the ComputerCraft Lua thread, and must be thread-safe + * when interacting with minecraft objects. + * @param computer The interface to the computercraft that is being attached. Remember that multiple + * computers can be attached to a peripheral at once. + * @see #detach + */ public void attach( IComputerAccess computer ); - /** - * Is called when a computercraft is detaching from the peripheral. - * This will occur when a computercraft shuts down, when the peripheral is removed while attached to computers, - * or when a turtle moves away from a square attached to a peripheral. - * This method can be used to keep track of which computers are attached to the peripheral, or to take action when detachment - * occurs.
- *
- * Be aware that this will be called from the ComputerCraft Lua thread, and must be thread-safe - * when interacting with minecraft objects. - * @param computer The interface to the computercraft that is being detached. Remember that multiple - * computers can be attached to a peripheral at once. - * @see #detach - */ + /** + * Is called when a computercraft is detaching from the peripheral. + * This will occur when a computercraft shuts down, when the peripheral is removed while attached to computers, + * or when a turtle moves away from a square attached to a peripheral. + * This method can be used to keep track of which computers are attached to the peripheral, or to take action when detachment + * occurs.
+ *
+ * Be aware that this will be called from the ComputerCraft Lua thread, and must be thread-safe + * when interacting with minecraft objects. + * @param computer The interface to the computercraft that is being detached. Remember that multiple + * computers can be attached to a peripheral at once. + * @see #detach + */ public void detach( IComputerAccess computer ); /** diff --git a/src/main/java/dan200/computercraft/api/peripheral/IPeripheralProvider.java b/src/main/java/dan200/computercraft/api/peripheral/IPeripheralProvider.java index 723c1f66a..6ac05be64 100644 --- a/src/main/java/dan200/computercraft/api/peripheral/IPeripheralProvider.java +++ b/src/main/java/dan200/computercraft/api/peripheral/IPeripheralProvider.java @@ -21,5 +21,5 @@ public interface IPeripheralProvider * @see dan200.computercraft.api.ComputerCraftAPI#registerPeripheralProvider(IPeripheralProvider) * @return a peripheral, or null if there is not a peripheral here you'd like to handle. */ - public IPeripheral getPeripheral( World world, BlockPos pos, EnumFacing side ); + public IPeripheral getPeripheral( World world, BlockPos pos, EnumFacing side ); } diff --git a/src/main/java/dan200/computercraft/api/permissions/package-info.java b/src/main/java/dan200/computercraft/api/permissions/package-info.java index d39021728..84bb7a169 100755 --- a/src/main/java/dan200/computercraft/api/permissions/package-info.java +++ b/src/main/java/dan200/computercraft/api/permissions/package-info.java @@ -7,4 +7,4 @@ @API( owner="ComputerCraft", provides="ComputerCraft|API|Permissions", apiVersion="${version}" ) package dan200.computercraft.api.permissions; -import net.minecraftforge.fml.common.API; \ No newline at end of file +import net.minecraftforge.fml.common.API; diff --git a/src/main/java/dan200/computercraft/api/turtle/ITurtleAccess.java b/src/main/java/dan200/computercraft/api/turtle/ITurtleAccess.java index f66e98642..802ddb22a 100644 --- a/src/main/java/dan200/computercraft/api/turtle/ITurtleAccess.java +++ b/src/main/java/dan200/computercraft/api/turtle/ITurtleAccess.java @@ -22,41 +22,41 @@ */ public interface ITurtleAccess { - /** - * Returns the world in which the turtle resides. - * @return the world in which the turtle resides. - */ - public World getWorld(); + /** + * Returns the world in which the turtle resides. + * @return the world in which the turtle resides. + */ + public World getWorld(); - /** - * Returns a vector containing the integer co-ordinates at which the turtle resides. - * @return a vector containing the integer co-ordinates at which the turtle resides. - */ - public BlockPos getPosition(); + /** + * Returns a vector containing the integer co-ordinates at which the turtle resides. + * @return a vector containing the integer co-ordinates at which the turtle resides. + */ + public BlockPos getPosition(); /** * TODO: Document me */ public boolean teleportTo( World world, BlockPos pos ); - /** - * Returns a vector containing the floating point co-ordinates at which the turtle is rendered. - * This will shift when the turtle is moving. - * @param f The subframe fraction - * @return a vector containing the floating point co-ordinates at which the turtle resides. - */ - public Vec3d getVisualPosition( float f ); + /** + * Returns a vector containing the floating point co-ordinates at which the turtle is rendered. + * This will shift when the turtle is moving. + * @param f The subframe fraction + * @return a vector containing the floating point co-ordinates at which the turtle resides. + */ + public Vec3d getVisualPosition( float f ); /** * TODO: Document me */ public float getVisualYaw( float f ); - /** - * Returns the world direction the turtle is currently facing. - * @return the world direction the turtle is currently facing. - */ - public EnumFacing getDirection(); + /** + * Returns the world direction the turtle is currently facing. + * @return the world direction the turtle is currently facing. + */ + public EnumFacing getDirection(); /** * TODO: Document me @@ -66,7 +66,7 @@ public interface ITurtleAccess /** * TODO: Document me */ - public int getSelectedSlot(); + public int getSelectedSlot(); /** * TODO: Document me @@ -95,10 +95,10 @@ public interface ITurtleAccess */ public boolean isFuelNeeded(); - /** - * TODO: Document me - */ - public int getFuelLevel(); + /** + * TODO: Document me + */ + public int getFuelLevel(); /** * TODO: Document me @@ -111,11 +111,11 @@ public interface ITurtleAccess public int getFuelLimit(); /** - * Removes some fuel from the turtles fuel supply. Negative numbers can be passed in to INCREASE the fuel level of the turtle. - * @return Whether the turtle was able to consume the ammount of fuel specified. Will return false if you supply a number - * greater than the current fuel level of the turtle. - */ - public boolean consumeFuel( int fuel ); + * Removes some fuel from the turtles fuel supply. Negative numbers can be passed in to INCREASE the fuel level of the turtle. + * @return Whether the turtle was able to consume the ammount of fuel specified. Will return false if you supply a number + * greater than the current fuel level of the turtle. + */ + public boolean consumeFuel( int fuel ); /** * TODO: Document me @@ -140,22 +140,22 @@ public interface ITurtleAccess */ public void playAnimation( TurtleAnimation animation ); - /** - * Returns the turtle on the specified side of the turtle, if there is one. - * @return the turtle on the specified side of the turtle, if there is one. - */ - public ITurtleUpgrade getUpgrade( TurtleSide side ); + /** + * Returns the turtle on the specified side of the turtle, if there is one. + * @return the turtle on the specified side of the turtle, if there is one. + */ + public ITurtleUpgrade getUpgrade( TurtleSide side ); /** * TODO: Document me */ public void setUpgrade( TurtleSide side, ITurtleUpgrade upgrade ); - /** - * Returns the peripheral created by the upgrade on the specified side of the turtle, if there is one. - * @return the peripheral created by the upgrade on the specified side of the turtle, if there is one. - */ - public IPeripheral getPeripheral( TurtleSide side ); + /** + * Returns the peripheral created by the upgrade on the specified side of the turtle, if there is one. + * @return the peripheral created by the upgrade on the specified side of the turtle, if there is one. + */ + public IPeripheral getPeripheral( TurtleSide side ); /** * TODO: Document me diff --git a/src/main/java/dan200/computercraft/api/turtle/ITurtleCommand.java b/src/main/java/dan200/computercraft/api/turtle/ITurtleCommand.java index 370f7707e..c4454881e 100644 --- a/src/main/java/dan200/computercraft/api/turtle/ITurtleCommand.java +++ b/src/main/java/dan200/computercraft/api/turtle/ITurtleCommand.java @@ -12,14 +12,14 @@ */ public interface ITurtleCommand { - /** - * Will be called by the turtle on the main thread when it is time to execute the custom command. - * The handler should either perform the work of the command, and return success, or return - * failure with an error message to indicate the command cannot be executed at this time. - * @param turtle access to the turtle for whom the command was issued - * @return TurtleCommandResult.success() or TurtleCommandResult.failure( errorMessage ) + /** + * Will be called by the turtle on the main thread when it is time to execute the custom command. + * The handler should either perform the work of the command, and return success, or return + * failure with an error message to indicate the command cannot be executed at this time. + * @param turtle access to the turtle for whom the command was issued + * @return TurtleCommandResult.success() or TurtleCommandResult.failure( errorMessage ) * @see ITurtleAccess#executeCommand(dan200.computercraft.api.lua.ILuaContext,ITurtleCommand) * @see dan200.computercraft.api.turtle.TurtleCommandResult - */ - public TurtleCommandResult execute( ITurtleAccess turtle ); + */ + public TurtleCommandResult execute( ITurtleAccess turtle ); } diff --git a/src/main/java/dan200/computercraft/api/turtle/ITurtleUpgrade.java b/src/main/java/dan200/computercraft/api/turtle/ITurtleUpgrade.java index 96645a10e..25188f606 100644 --- a/src/main/java/dan200/computercraft/api/turtle/ITurtleUpgrade.java +++ b/src/main/java/dan200/computercraft/api/turtle/ITurtleUpgrade.java @@ -25,13 +25,13 @@ */ public interface ITurtleUpgrade { - /** - * Gets a unique identifier representing this type of turtle upgrade. eg: "computercraft:wireless_modem" or "my_mod:my_upgrade". - * You should use a unique resource domain to ensure this upgrade is uniquely identified. + /** + * Gets a unique identifier representing this type of turtle upgrade. eg: "computercraft:wireless_modem" or "my_mod:my_upgrade". + * You should use a unique resource domain to ensure this upgrade is uniquely identified. * The turtle will fail registration if an already used ID is specified. - * @see dan200.computercraft.api.ComputerCraftAPI#registerTurtleUpgrade( dan200.computercraft.api.turtle.ITurtleUpgrade ) - */ - public ResourceLocation getUpgradeID(); + * @see dan200.computercraft.api.ComputerCraftAPI#registerTurtleUpgrade( dan200.computercraft.api.turtle.ITurtleUpgrade ) + */ + public ResourceLocation getUpgradeID(); /** * Gets a numerical identifier representing this type of turtle upgrade, @@ -43,52 +43,52 @@ public interface ITurtleUpgrade public int getLegacyUpgradeID(); /** - * Return a String to describe this type of turtle in turtle item names. - * Examples of built-in adjectives are "Wireless", "Mining" and "Crafty". - */ - public String getUnlocalisedAdjective(); - - /** - * Return whether this turtle adds a tool or a peripheral to the turtle. - * @see TurtleUpgradeType for the differences between the two. - */ - public TurtleUpgradeType getType(); - - /** - * Return an item stack representing the type of item that a turtle must be crafted - * with to create a turtle which holds this upgrade. This item stack is also used - * to determine the upgrade given by turtle.equip() - */ - public ItemStack getCraftingItem(); + * Return a String to describe this type of turtle in turtle item names. + * Examples of built-in adjectives are "Wireless", "Mining" and "Crafty". + */ + public String getUnlocalisedAdjective(); /** - * Will only be called for peripheral upgrades. Creates a peripheral for a turtle - * being placed using this upgrade. The peripheral created will be stored - * for the lifetime of the upgrade, will have update() called once-per-tick, and will be - * attached, detached and have methods called in the same manner as a Computer peripheral. - * + * Return whether this turtle adds a tool or a peripheral to the turtle. + * @see TurtleUpgradeType for the differences between the two. + */ + public TurtleUpgradeType getType(); + + /** + * Return an item stack representing the type of item that a turtle must be crafted + * with to create a turtle which holds this upgrade. This item stack is also used + * to determine the upgrade given by turtle.equip() + */ + public ItemStack getCraftingItem(); + + /** + * Will only be called for peripheral upgrades. Creates a peripheral for a turtle + * being placed using this upgrade. The peripheral created will be stored + * for the lifetime of the upgrade, will have update() called once-per-tick, and will be + * attached, detached and have methods called in the same manner as a Computer peripheral. + * * @param turtle Access to the turtle that the peripheral is being created for. * @param side Which side of the turtle (left or right) that the upgrade resides on. * @return The newly created peripheral. You may return null if this upgrade is a Tool - * and this method is not expected to be called. - */ - public IPeripheral createPeripheral( ITurtleAccess turtle, TurtleSide side ); + * and this method is not expected to be called. + */ + public IPeripheral createPeripheral( ITurtleAccess turtle, TurtleSide side ); - /** - * Will only be called for Tool turtle. Called when turtle.dig() or turtle.attack() is called - * by the turtle, and the tool is required to do some work. - * @param turtle Access to the turtle that the tool resides on. - * @param side Which side of the turtle (left or right) the tool resides on. - * @param verb Which action (dig or attack) the turtle is being called on to perform. - * @param direction Which world direction the action should be performed in, relative to the turtles - * position. This will either be up, down, or the direction the turtle is facing, depending on - * whether dig, digUp or digDown was called. - * @return Whether the turtle was able to perform the action, and hence whether the turtle.dig() - * or turtle.attack() lua method should return true. If true is returned, the tool will perform - * a swinging animation. You may return null if this turtle is a Peripheral - * and this method is not expected to be called. - */ - public TurtleCommandResult useTool( ITurtleAccess turtle, TurtleSide side, TurtleVerb verb, EnumFacing direction ); + /** + * Will only be called for Tool turtle. Called when turtle.dig() or turtle.attack() is called + * by the turtle, and the tool is required to do some work. + * @param turtle Access to the turtle that the tool resides on. + * @param side Which side of the turtle (left or right) the tool resides on. + * @param verb Which action (dig or attack) the turtle is being called on to perform. + * @param direction Which world direction the action should be performed in, relative to the turtles + * position. This will either be up, down, or the direction the turtle is facing, depending on + * whether dig, digUp or digDown was called. + * @return Whether the turtle was able to perform the action, and hence whether the turtle.dig() + * or turtle.attack() lua method should return true. If true is returned, the tool will perform + * a swinging animation. You may return null if this turtle is a Peripheral + * and this method is not expected to be called. + */ + public TurtleCommandResult useTool( ITurtleAccess turtle, TurtleSide side, TurtleVerb verb, EnumFacing direction ); /** * Called to obtain the model to be used when rendering a turtle peripheral. diff --git a/src/main/java/dan200/computercraft/api/turtle/TurtleSide.java b/src/main/java/dan200/computercraft/api/turtle/TurtleSide.java index 410794c71..d7c75cf59 100644 --- a/src/main/java/dan200/computercraft/api/turtle/TurtleSide.java +++ b/src/main/java/dan200/computercraft/api/turtle/TurtleSide.java @@ -11,13 +11,13 @@ */ public enum TurtleSide { - /** - * The turtles left side (where the pickaxe usually is on a Wireless Mining Turtle) - */ - Left, + /** + * The turtles left side (where the pickaxe usually is on a Wireless Mining Turtle) + */ + Left, - /** - * The turtles right side (where the modem usually is on a Wireless Mining Turtle) - */ - Right, + /** + * The turtles right side (where the modem usually is on a Wireless Mining Turtle) + */ + Right, } diff --git a/src/main/java/dan200/computercraft/api/turtle/TurtleUpgradeType.java b/src/main/java/dan200/computercraft/api/turtle/TurtleUpgradeType.java index b7c39d959..d86982368 100644 --- a/src/main/java/dan200/computercraft/api/turtle/TurtleUpgradeType.java +++ b/src/main/java/dan200/computercraft/api/turtle/TurtleUpgradeType.java @@ -13,15 +13,15 @@ */ public enum TurtleUpgradeType { - /** - * A tool is rendered as an item on the side of the turtle, and responds to the turtle.dig() - * and turtle.attack() methods (Such as pickaxe or sword on Mining and Melee turtles). - */ - Tool, - - /** - * A peripheral adds a special peripheral which is attached to the side of the turtle, - * and can be interacted with the peripheral API (Such as the modem on Wireless Turtles). - */ - Peripheral, + /** + * A tool is rendered as an item on the side of the turtle, and responds to the turtle.dig() + * and turtle.attack() methods (Such as pickaxe or sword on Mining and Melee turtles). + */ + Tool, + + /** + * A peripheral adds a special peripheral which is attached to the side of the turtle, + * and can be interacted with the peripheral API (Such as the modem on Wireless Turtles). + */ + Peripheral, } diff --git a/src/main/java/dan200/computercraft/api/turtle/TurtleVerb.java b/src/main/java/dan200/computercraft/api/turtle/TurtleVerb.java index 4471eff48..174e2599c 100644 --- a/src/main/java/dan200/computercraft/api/turtle/TurtleVerb.java +++ b/src/main/java/dan200/computercraft/api/turtle/TurtleVerb.java @@ -14,13 +14,13 @@ */ public enum TurtleVerb { - /** - * The turtle called turtle.dig(), turtle.digUp() or turtle.digDown() - */ - Dig, - - /** - * The turtle called turtle.attack(), turtle.attackUp() or turtle.attackDown() - */ - Attack, + /** + * The turtle called turtle.dig(), turtle.digUp() or turtle.digDown() + */ + Dig, + + /** + * The turtle called turtle.attack(), turtle.attackUp() or turtle.attackDown() + */ + Attack, } diff --git a/src/main/java/dan200/computercraft/client/gui/FixedWidthFontRenderer.java b/src/main/java/dan200/computercraft/client/gui/FixedWidthFontRenderer.java index 52b190694..91838519d 100644 --- a/src/main/java/dan200/computercraft/client/gui/FixedWidthFontRenderer.java +++ b/src/main/java/dan200/computercraft/client/gui/FixedWidthFontRenderer.java @@ -122,22 +122,22 @@ public void drawString( TextBuffer s, int x, int y, TextBuffer textColour, TextB // Draw background if( backgroundColour != null ) { - // Bind the background texture - m_textureManager.bindTexture( background ); + // Bind the background texture + m_textureManager.bindTexture( background ); // Draw the quads drawStringBackgroundPart( x, y, backgroundColour, leftMarginSize, rightMarginSize, greyScale ); - } - - // Draw text + } + + // Draw text if( s != null && textColour != null ) - { - // Bind the font texture + { + // Bind the font texture m_textureManager.bindTexture( font ); - + // Draw the quads drawStringTextPart( x, y, s, textColour, greyScale ); - } + } } public int getStringWidth(String s) diff --git a/src/main/java/dan200/computercraft/client/gui/GuiComputer.java b/src/main/java/dan200/computercraft/client/gui/GuiComputer.java index 81dcd3bcc..6df2721ed 100644 --- a/src/main/java/dan200/computercraft/client/gui/GuiComputer.java +++ b/src/main/java/dan200/computercraft/client/gui/GuiComputer.java @@ -32,7 +32,7 @@ public class GuiComputer extends GuiContainer private final IComputer m_computer; private final int m_termWidth; private final int m_termHeight; - private WidgetTerminal m_terminal; + private WidgetTerminal m_terminal; protected GuiComputer( Container container, ComputerFamily family, IComputer computer, int termWidth, int termHeight ) { @@ -46,22 +46,22 @@ protected GuiComputer( Container container, ComputerFamily family, IComputer com public GuiComputer( TileComputer computer ) { - this( + this( new ContainerComputer( computer ), computer.getFamily(), computer.createComputer(), ComputerCraft.terminalWidth_computer, ComputerCraft.terminalHeight_computer ); - } + } @Override public void initGui() { - super.initGui(); - Keyboard.enableRepeatEvents( true ); + super.initGui(); + Keyboard.enableRepeatEvents( true ); - m_terminal = new WidgetTerminal( 0, 0, m_termWidth, m_termHeight, new IComputerContainer() + m_terminal = new WidgetTerminal( 0, 0, m_termWidth, m_termHeight, new IComputerContainer() { @Override public IComputer getComputer() @@ -72,59 +72,59 @@ public IComputer getComputer() m_terminal.setAllowFocusLoss( false ); xSize = m_terminal.getWidth() + 24; ySize = m_terminal.getHeight() + 24; - } + } @Override public void onGuiClosed() { - super.onGuiClosed(); + super.onGuiClosed(); Keyboard.enableRepeatEvents( false ); } @Override - public boolean doesGuiPauseGame() - { - return false; - } + public boolean doesGuiPauseGame() + { + return false; + } @Override public void updateScreen() { - super.updateScreen(); - m_terminal.update(); + super.updateScreen(); + m_terminal.update(); } - @Override + @Override protected void keyTyped(char c, int k) throws IOException { - if( k == 1 ) - { - super.keyTyped( c, k ); - } - else - { - m_terminal.keyTyped( c, k ); - } + if( k == 1 ) + { + super.keyTyped( c, k ); + } + else + { + m_terminal.keyTyped( c, k ); + } } - @Override + @Override protected void mouseClicked( int x, int y, int button ) { int startX = (width - m_terminal.getWidth()) / 2; int startY = (height - m_terminal.getHeight()) / 2; - m_terminal.mouseClicked( x - startX, y - startY, button ); + m_terminal.mouseClicked( x - startX, y - startY, button ); } - @Override + @Override public void handleMouseInput() throws IOException { - super.handleMouseInput(); + super.handleMouseInput(); int x = Mouse.getEventX() * width / mc.displayWidth; int y = height - Mouse.getEventY() * height / mc.displayHeight - 1; int startX = (width - m_terminal.getWidth()) / 2; int startY = (height - m_terminal.getHeight()) / 2; - m_terminal.handleMouseInput( x - startX, y - startY ); + m_terminal.handleMouseInput( x - startX, y - startY ); } @Override @@ -134,17 +134,17 @@ public void handleKeyboardInput() throws IOException m_terminal.handleKeyboardInput(); } - @Override + @Override protected void drawGuiContainerForegroundLayer(int par1, int par2) { } - @Override + @Override protected void drawGuiContainerBackgroundLayer( float var1, int var2, int var3 ) { } - @Override + @Override public void drawScreen( int mouseX, int mouseY, float f ) { // Work out where to draw @@ -153,14 +153,14 @@ public void drawScreen( int mouseX, int mouseY, float f ) int endX = startX + m_terminal.getWidth(); int endY = startY + m_terminal.getHeight(); - // Draw background - drawDefaultBackground(); + // Draw background + drawDefaultBackground(); - // Draw terminal + // Draw terminal m_terminal.draw( this.mc, startX, startY, mouseX, mouseY ); - - // Draw a border around the terminal - GlStateManager.color( 1.0f, 1.0f, 1.0f, 1.0f ); + + // Draw a border around the terminal + GlStateManager.color( 1.0f, 1.0f, 1.0f, 1.0f ); switch( m_family ) { case Normal: @@ -181,15 +181,15 @@ public void drawScreen( int mouseX, int mouseY, float f ) } } - drawTexturedModalRect(startX - 12, startY - 12, 12, 28, 12, 12); - drawTexturedModalRect(startX - 12, endY, 12, 40, 12, 16); - drawTexturedModalRect(endX, startY - 12, 24, 28, 12, 12); - drawTexturedModalRect(endX, endY, 24, 40, 12, 16); + drawTexturedModalRect(startX - 12, startY - 12, 12, 28, 12, 12); + drawTexturedModalRect(startX - 12, endY, 12, 40, 12, 16); + drawTexturedModalRect(endX, startY - 12, 24, 28, 12, 12); + drawTexturedModalRect(endX, endY, 24, 40, 12, 16); - drawTexturedModalRect(startX, startY-12, 0, 0, endX - startX, 12); - drawTexturedModalRect(startX, endY, 0, 12, endX - startX, 16); + drawTexturedModalRect(startX, startY-12, 0, 0, endX - startX, 12); + drawTexturedModalRect(startX, endY, 0, 12, endX - startX, 16); - drawTexturedModalRect(startX-12, startY, 0, 28, 12, endY - startY); - drawTexturedModalRect(endX, startY, 36, 28, 12, endY - startY); - } + drawTexturedModalRect(startX-12, startY, 0, 28, 12, endY - startY); + drawTexturedModalRect(endX, startY, 36, 28, 12, endY - startY); + } } diff --git a/src/main/java/dan200/computercraft/client/gui/GuiPrinter.java b/src/main/java/dan200/computercraft/client/gui/GuiPrinter.java index fa529fffd..053505d0d 100644 --- a/src/main/java/dan200/computercraft/client/gui/GuiPrinter.java +++ b/src/main/java/dan200/computercraft/client/gui/GuiPrinter.java @@ -48,7 +48,7 @@ protected void drawGuiContainerBackgroundLayer(float f, int i, int j) boolean printing = m_container.isPrinting(); if( printing ) { - drawTexturedModalRect(startX + 34, startY + 21, 176, 0, 25, 45); + drawTexturedModalRect(startX + 34, startY + 21, 176, 0, 25, 45); } } } diff --git a/src/main/java/dan200/computercraft/client/gui/GuiPrintout.java b/src/main/java/dan200/computercraft/client/gui/GuiPrintout.java index 98f3cb9b1..75c8f97d0 100644 --- a/src/main/java/dan200/computercraft/client/gui/GuiPrintout.java +++ b/src/main/java/dan200/computercraft/client/gui/GuiPrintout.java @@ -22,106 +22,106 @@ public class GuiPrintout extends GuiContainer { private static final ResourceLocation background = new ResourceLocation( "computercraft", "textures/gui/printout.png" ); - private static final int xSize = 172; - private static final int ySize = 209; - - private final boolean m_book; - private final int m_pages; - private final TextBuffer[] m_text; - private final TextBuffer[] m_colours; - private int m_page; + private static final int xSize = 172; + private static final int ySize = 209; + + private final boolean m_book; + private final int m_pages; + private final TextBuffer[] m_text; + private final TextBuffer[] m_colours; + private int m_page; public GuiPrintout( ContainerHeldItem container ) { super( container ); - m_book = (ItemPrintout.getType( container.getStack() ) == ItemPrintout.Type.Book); + m_book = (ItemPrintout.getType( container.getStack() ) == ItemPrintout.Type.Book); String[] text = ItemPrintout.getText( container.getStack() ); - m_text = new TextBuffer[ text.length ]; + m_text = new TextBuffer[ text.length ]; for( int i=0; i 0 ) - { - m_page = m_page - 1; - } - } + if( k == 205 ) + { + // Right + if( m_page < m_pages - 1 ) + { + m_page = m_page + 1; + } + } + else if( k == 203 ) + { + // Left + if( m_page > 0 ) + { + m_page = m_page - 1; + } + } } @Override public void handleMouseInput() throws IOException { - super.handleMouseInput(); + super.handleMouseInput(); - int mouseWheelChange = Mouse.getEventDWheel(); - if (mouseWheelChange < 0) - { - // Up - if( m_page < m_pages - 1 ) - { - m_page = m_page + 1; - } - } - else if (mouseWheelChange > 0) - { - // Down - if( m_page > 0 ) - { - m_page = m_page - 1; - } - } + int mouseWheelChange = Mouse.getEventDWheel(); + if (mouseWheelChange < 0) + { + // Up + if( m_page < m_pages - 1 ) + { + m_page = m_page + 1; + } + } + else if (mouseWheelChange > 0) + { + // Down + if( m_page > 0 ) + { + m_page = m_page - 1; + } + } } @Override @@ -137,76 +137,76 @@ protected void drawGuiContainerBackgroundLayer( float var1, int var2, int var3 ) @Override public void drawScreen(int mouseX, int mouseY, float f) { - // Draw background - drawDefaultBackground(); - - // Draw the printout + // Draw background + drawDefaultBackground(); + + // Draw the printout GlStateManager.color( 1.0f, 1.0f, 1.0f, 1.0f ); this.mc.getTextureManager().bindTexture( background ); - - int startY = (height - ySize) / 2; - //int startX = (width - xSize) / 2 - (m_page * 8); - int startX = (width - (xSize + (m_pages - 1)*8)) / 2; - - if( m_book ) - { - // Border - drawTexturedModalRect( startX - 8, startY - 8, xSize + 48, 0, 12, ySize + 24); - drawTexturedModalRect( startX + xSize + (m_pages - 1)*8 - 4, startY - 8, xSize + 48 + 12, 0, 12, ySize + 24); - - drawTexturedModalRect( startX, startY - 8, 0, ySize, xSize, 12); - drawTexturedModalRect( startX, startY + ySize - 4, 0, ySize + 12, xSize, 12); - for( int n=1; n=m_page; --n ) - { - drawTexturedModalRect( startX + n*8 + (xSize - 12), startY, 24 + xSize, 0, 12, ySize); - } - drawTexturedModalRect( startX + m_page*8 + xSize/2, startY, 24 + xSize / 2, 0, xSize / 2, ySize); - } + + int startY = (height - ySize) / 2; + //int startX = (width - xSize) / 2 - (m_page * 8); + int startX = (width - (xSize + (m_pages - 1)*8)) / 2; + + if( m_book ) + { + // Border + drawTexturedModalRect( startX - 8, startY - 8, xSize + 48, 0, 12, ySize + 24); + drawTexturedModalRect( startX + xSize + (m_pages - 1)*8 - 4, startY - 8, xSize + 48 + 12, 0, 12, ySize + 24); + + drawTexturedModalRect( startX, startY - 8, 0, ySize, xSize, 12); + drawTexturedModalRect( startX, startY + ySize - 4, 0, ySize + 12, xSize, 12); + for( int n=1; n=m_page; --n ) + { + drawTexturedModalRect( startX + n*8 + (xSize - 12), startY, 24 + xSize, 0, 12, ySize); + } + drawTexturedModalRect( startX + m_page*8 + xSize/2, startY, 24 + xSize / 2, 0, xSize / 2, ySize); + } - // Draw the text - FixedWidthFontRenderer fontRenderer = (FixedWidthFontRenderer)ComputerCraft.getFixedWidthFontRenderer(); - int x = startX + m_page * 8 + 13; - int y = startY + 11; - for( int line=0; line= 0 && lineIdx < m_text.length ) - { - fontRenderer.drawString( m_text[lineIdx], x, y, m_colours[lineIdx], null, 0, 0, false ); - } - y = y + FixedWidthFontRenderer.FONT_HEIGHT; - } - } + // Draw the text + FixedWidthFontRenderer fontRenderer = (FixedWidthFontRenderer)ComputerCraft.getFixedWidthFontRenderer(); + int x = startX + m_page * 8 + 13; + int y = startY + 11; + for( int line=0; line= 0 && lineIdx < m_text.length ) + { + fontRenderer.drawString( m_text[lineIdx], x, y, m_colours[lineIdx], null, 0, 0, false ); + } + y = y + FixedWidthFontRenderer.FONT_HEIGHT; + } + } } diff --git a/src/main/java/dan200/computercraft/client/gui/GuiTurtle.java b/src/main/java/dan200/computercraft/client/gui/GuiTurtle.java index 8a8e181ff..c326e3cb0 100644 --- a/src/main/java/dan200/computercraft/client/gui/GuiTurtle.java +++ b/src/main/java/dan200/computercraft/client/gui/GuiTurtle.java @@ -30,8 +30,8 @@ public class GuiTurtle extends GuiContainer private static final ResourceLocation background = new ResourceLocation( "computercraft", "textures/gui/turtle.png" ); private static final ResourceLocation backgroundAdvanced = new ResourceLocation( "computercraft", "textures/gui/turtle2.png" ); - protected World m_world; - protected ContainerTurtle m_container; + protected World m_world; + protected ContainerTurtle m_container; protected final ComputerFamily m_family; protected final ITurtleAccess m_turtle; @@ -40,15 +40,15 @@ public class GuiTurtle extends GuiContainer public GuiTurtle( World world, InventoryPlayer inventoryplayer, TileTurtle turtle ) { - this( world, turtle, new ContainerTurtle( inventoryplayer, turtle.getAccess() ) ); + this( world, turtle, new ContainerTurtle( inventoryplayer, turtle.getAccess() ) ); } protected GuiTurtle( World world, TileTurtle turtle, ContainerTurtle container ) { - super( container ); + super( container ); - m_world = world; - m_container = container; + m_world = world; + m_container = container; m_family = turtle.getFamily(); m_turtle = turtle.getAccess(); m_computer = turtle.createComputer(); @@ -60,9 +60,9 @@ protected GuiTurtle( World world, TileTurtle turtle, ContainerTurtle container ) @Override public void initGui() { - super.initGui(); - Keyboard.enableRepeatEvents(true); - m_terminalGui = new WidgetTerminal( + super.initGui(); + Keyboard.enableRepeatEvents(true); + m_terminalGui = new WidgetTerminal( ( width - xSize ) / 2 + 8, ( height - ySize ) / 2 + 8, ComputerCraft.terminalWidth_turtle, @@ -78,49 +78,49 @@ public IComputer getComputer() 2, 2, 2, 2 ); m_terminalGui.setAllowFocusLoss( false ); - } + } @Override public void onGuiClosed() { - super.onGuiClosed(); + super.onGuiClosed(); Keyboard.enableRepeatEvents(false); } @Override public void updateScreen() { - super.updateScreen(); - m_terminalGui.update(); + super.updateScreen(); + m_terminalGui.update(); } @Override protected void keyTyped(char c, int k) throws IOException { - if( k == 1 ) - { - super.keyTyped( c, k ); - } - else - { - m_terminalGui.keyTyped( c, k ); - } + if( k == 1 ) + { + super.keyTyped( c, k ); + } + else + { + m_terminalGui.keyTyped( c, k ); + } } - @Override + @Override protected void mouseClicked(int x, int y, int button) throws IOException { - super.mouseClicked( x, y, button ); - m_terminalGui.mouseClicked( x, y, button ); + super.mouseClicked( x, y, button ); + m_terminalGui.mouseClicked( x, y, button ); } - - @Override + + @Override public void handleMouseInput() throws IOException { - super.handleMouseInput(); + super.handleMouseInput(); int x = Mouse.getEventX() * this.width / mc.displayWidth; int y = this.height - Mouse.getEventY() * this.height / mc.displayHeight - 1; - m_terminalGui.handleMouseInput( x, y ); + m_terminalGui.handleMouseInput( x, y ); } @Override @@ -135,28 +135,28 @@ protected void drawSelectionSlot( boolean advanced ) int x = (width - xSize) / 2; int y = (height - ySize) / 2; - // Draw selection slot - int slot = m_container.getSelectedSlot(); - if( slot >= 0 ) - { - GlStateManager.color( 1.0F, 1.0F, 1.0F, 1.0F ); - int slotX = (slot%4); - int slotY = (slot/4); - this.mc.getTextureManager().bindTexture( advanced ? backgroundAdvanced : background ); - drawTexturedModalRect(x + m_container.m_turtleInvStartX - 2 + slotX * 18, y + m_container.m_playerInvStartY - 2 + slotY * 18, 0, 217, 24, 24); - } + // Draw selection slot + int slot = m_container.getSelectedSlot(); + if( slot >= 0 ) + { + GlStateManager.color( 1.0F, 1.0F, 1.0F, 1.0F ); + int slotX = (slot%4); + int slotY = (slot/4); + this.mc.getTextureManager().bindTexture( advanced ? backgroundAdvanced : background ); + drawTexturedModalRect(x + m_container.m_turtleInvStartX - 2 + slotX * 18, y + m_container.m_playerInvStartY - 2 + slotY * 18, 0, 217, 24, 24); + } } - @Override + @Override protected void drawGuiContainerBackgroundLayer( float f, int mouseX, int mouseY ) { - // Draw term + // Draw term boolean advanced = (m_family == ComputerFamily.Advanced); - m_terminalGui.draw( Minecraft.getMinecraft(), 0, 0, mouseX, mouseY ); - - // Draw border/inventory + m_terminalGui.draw( Minecraft.getMinecraft(), 0, 0, mouseX, mouseY ); + + // Draw border/inventory GlStateManager.color( 1.0F, 1.0F, 1.0F, 1.0F ); - this.mc.getTextureManager().bindTexture( advanced ? backgroundAdvanced : background ); + this.mc.getTextureManager().bindTexture( advanced ? backgroundAdvanced : background ); int x = (width - xSize) / 2; int y = (height - ySize) / 2; drawTexturedModalRect(x, y, 0, 0, xSize, ySize); diff --git a/src/main/java/dan200/computercraft/client/gui/widgets/WidgetTerminal.java b/src/main/java/dan200/computercraft/client/gui/widgets/WidgetTerminal.java index b875653b7..9eb6ddbb4 100644 --- a/src/main/java/dan200/computercraft/client/gui/widgets/WidgetTerminal.java +++ b/src/main/java/dan200/computercraft/client/gui/widgets/WidgetTerminal.java @@ -34,9 +34,9 @@ public class WidgetTerminal extends Widget private float m_rebootTimer; private float m_shutdownTimer; - private int m_lastClickButton; - private int m_lastClickX; - private int m_lastClickY; + private int m_lastClickButton; + private int m_lastClickX; + private int m_lastClickY; private boolean m_focus; private boolean m_allowFocusLoss; @@ -167,9 +167,9 @@ else if( newLineIndex2 >= 0 ) @Override public void mouseClicked( int mouseX, int mouseY, int button ) { - if( mouseX >= getXPosition() && mouseX < getXPosition() + getWidth() && - mouseY >= getYPosition() && mouseY < getYPosition() + getHeight() ) - { + if( mouseX >= getXPosition() && mouseX < getXPosition() + getWidth() && + mouseY >= getYPosition() && mouseY < getYPosition() + getHeight() ) + { if( !m_focus && button == 0) { m_focus = true; @@ -198,7 +198,7 @@ public void mouseClicked( int mouseX, int mouseY, int button ) } } } - } + } else { if( m_focus && button == 0 && m_allowFocusLoss ) @@ -229,8 +229,8 @@ public void handleKeyboardInput() } @Override - public void handleMouseInput( int mouseX, int mouseY ) - { + public void handleMouseInput( int mouseX, int mouseY ) + { IComputer computer = m_computer.getComputer(); if( mouseX >= getXPosition() && mouseX < getXPosition() + getWidth() && mouseY >= getYPosition() && mouseY < getYPosition() + getHeight() && @@ -287,110 +287,110 @@ else if( wheelChange > 0 ) } } } - } + } @Override public void update() - { + { // Handle special keys - if( m_focus && !m_locked && (Keyboard.isKeyDown( 29 ) || Keyboard.isKeyDown( 157 )) ) - { - // Ctrl+T for terminate - if( Keyboard.isKeyDown( 20 ) ) - { - if( m_terminateTimer < TERMINATE_TIME ) - { - m_terminateTimer = m_terminateTimer + 0.05f; - if( m_terminateTimer >= TERMINATE_TIME ) - { + if( m_focus && !m_locked && (Keyboard.isKeyDown( 29 ) || Keyboard.isKeyDown( 157 )) ) + { + // Ctrl+T for terminate + if( Keyboard.isKeyDown( 20 ) ) + { + if( m_terminateTimer < TERMINATE_TIME ) + { + m_terminateTimer = m_terminateTimer + 0.05f; + if( m_terminateTimer >= TERMINATE_TIME ) + { queueEvent( "terminate" ); - } - } - } - else - { - m_terminateTimer = 0.0f; - } - - // Ctrl+R for reboot - if( Keyboard.isKeyDown(19) ) - { - if( m_rebootTimer < TERMINATE_TIME ) - { - m_rebootTimer = m_rebootTimer + 0.05f; - if( m_rebootTimer >= TERMINATE_TIME ) - { + } + } + } + else + { + m_terminateTimer = 0.0f; + } + + // Ctrl+R for reboot + if( Keyboard.isKeyDown(19) ) + { + if( m_rebootTimer < TERMINATE_TIME ) + { + m_rebootTimer = m_rebootTimer + 0.05f; + if( m_rebootTimer >= TERMINATE_TIME ) + { IComputer computer = m_computer.getComputer(); - if( computer != null ) - { + if( computer != null ) + { computer.reboot(); - } - } - } - } - else - { - m_rebootTimer = 0.0f; - } + } + } + } + } + else + { + m_rebootTimer = 0.0f; + } - // Ctrl+S for shutdown - if( Keyboard.isKeyDown(31) ) - { - if( m_shutdownTimer < TERMINATE_TIME ) - { - m_shutdownTimer = m_shutdownTimer + 0.05f; - if( m_shutdownTimer >= TERMINATE_TIME ) - { + // Ctrl+S for shutdown + if( Keyboard.isKeyDown(31) ) + { + if( m_shutdownTimer < TERMINATE_TIME ) + { + m_shutdownTimer = m_shutdownTimer + 0.05f; + if( m_shutdownTimer >= TERMINATE_TIME ) + { IComputer computer = m_computer.getComputer(); if( computer != null ) { computer.shutdown(); - } - } - } - } - else - { - m_shutdownTimer = 0.0f; - } - } - else - { - m_terminateTimer = 0.0f; - m_rebootTimer = 0.0f; - m_shutdownTimer = 0.0f; - } - } + } + } + } + } + else + { + m_shutdownTimer = 0.0f; + } + } + else + { + m_terminateTimer = 0.0f; + m_rebootTimer = 0.0f; + m_shutdownTimer = 0.0f; + } + } @Override public void draw( Minecraft mc, int xOrigin, int yOrigin, int mouseX, int mouseY ) { - int startX = xOrigin + getXPosition(); - int startY = yOrigin + getYPosition(); + int startX = xOrigin + getXPosition(); + int startY = yOrigin + getYPosition(); - // Draw the screen contents + // Draw the screen contents IComputer computer = m_computer.getComputer(); - Terminal terminal = (computer != null) ? computer.getTerminal() : null; - if( terminal != null ) - { + Terminal terminal = (computer != null) ? computer.getTerminal() : null; + if( terminal != null ) + { // Draw the terminal boolean greyscale = !computer.isColour(); - synchronized( terminal ) - { - // Get the data from the terminal first - // Unfortunately we have to keep the lock for the whole of drawing, so the text doesn't change under us. - FixedWidthFontRenderer fontRenderer = (FixedWidthFontRenderer)ComputerCraft.getFixedWidthFontRenderer(); - boolean tblink = m_focus && terminal.getCursorBlink() && ComputerCraft.getGlobalCursorBlink(); - int tw = terminal.getWidth(); - int th = terminal.getHeight(); - int tx = terminal.getCursorX(); - int ty = terminal.getCursorY(); - - int x = startX + m_leftMargin; - int y = startY + m_topMargin; + synchronized( terminal ) + { + // Get the data from the terminal first + // Unfortunately we have to keep the lock for the whole of drawing, so the text doesn't change under us. + FixedWidthFontRenderer fontRenderer = (FixedWidthFontRenderer)ComputerCraft.getFixedWidthFontRenderer(); + boolean tblink = m_focus && terminal.getCursorBlink() && ComputerCraft.getGlobalCursorBlink(); + int tw = terminal.getWidth(); + int th = terminal.getHeight(); + int tx = terminal.getCursorX(); + int ty = terminal.getCursorY(); + + int x = startX + m_leftMargin; + int y = startY + m_topMargin; // Draw margins - TextBuffer emptyLine = new TextBuffer( ' ', tw ); + TextBuffer emptyLine = new TextBuffer( ' ', tw ); if( m_topMargin > 0 ) { fontRenderer.drawString( emptyLine, x, startY, terminal.getTextColourLine( 0 ), terminal.getBackgroundColourLine( 0 ), m_leftMargin, m_rightMargin, greyscale ); @@ -401,32 +401,32 @@ public void draw( Minecraft mc, int xOrigin, int yOrigin, int mouseX, int mouseY } // Draw lines - for( int line=0; line= 0 && tx < tw ) + if( tx >= 0 && tx < tw ) { TextBuffer cursor = new TextBuffer( '_', 1 ); TextBuffer cursorColour = new TextBuffer( "0123456789abcdef".charAt( terminal.getTextColour() ), 1 ); - fontRenderer.drawString( + fontRenderer.drawString( cursor, - x + FixedWidthFontRenderer.FONT_WIDTH * tx, - y, - cursorColour, null, + x + FixedWidthFontRenderer.FONT_WIDTH * tx, + y, + cursorColour, null, 0, 0, greyscale ); - } - } - y = y + FixedWidthFontRenderer.FONT_HEIGHT; - } - } - } + } + } + y = y + FixedWidthFontRenderer.FONT_HEIGHT; + } + } + } else { // Draw a black background diff --git a/src/main/java/dan200/computercraft/client/proxy/CCTurtleProxyClient.java b/src/main/java/dan200/computercraft/client/proxy/CCTurtleProxyClient.java index ad99e536b..cc6ce9f4e 100644 --- a/src/main/java/dan200/computercraft/client/proxy/CCTurtleProxyClient.java +++ b/src/main/java/dan200/computercraft/client/proxy/CCTurtleProxyClient.java @@ -40,16 +40,16 @@ public class CCTurtleProxyClient extends CCTurtleProxyCommon { - public CCTurtleProxyClient() - { - } - - // IComputerCraftProxy implementation - - @Override - public void init() - { - super.init(); + public CCTurtleProxyClient() + { + } + + // IComputerCraftProxy implementation + + @Override + public void init() + { + super.init(); // Register item models ItemMeshDefinition turtleMeshDefinition = new ItemMeshDefinition() @@ -78,9 +78,9 @@ public ModelResourceLocation getModelLocation( ItemStack stack ) // Setup renderers ClientRegistry.bindTileEntitySpecialRenderer( TileTurtle.class, new TileEntityTurtleRenderer() ); - // Setup client forge handlers - registerForgeHandlers(); - } + // Setup client forge handlers + registerForgeHandlers(); + } private void registerItemModel( Block block, ItemMeshDefinition definition, String[] names ) { @@ -98,11 +98,11 @@ private void registerItemModel( Item item, ItemMeshDefinition definition, String Minecraft.getMinecraft().getRenderItem().getItemModelMesher().register( item, definition ); } - private void registerForgeHandlers() - { + private void registerForgeHandlers() + { ForgeHandlers handlers = new ForgeHandlers(); MinecraftForge.EVENT_BUS.register( handlers ); - } + } public class ForgeHandlers { diff --git a/src/main/java/dan200/computercraft/client/proxy/ComputerCraftProxyClient.java b/src/main/java/dan200/computercraft/client/proxy/ComputerCraftProxyClient.java index 85ceb9fa1..213c32522 100644 --- a/src/main/java/dan200/computercraft/client/proxy/ComputerCraftProxyClient.java +++ b/src/main/java/dan200/computercraft/client/proxy/ComputerCraftProxyClient.java @@ -55,26 +55,26 @@ public class ComputerCraftProxyClient extends ComputerCraftProxyCommon { - private long m_tick; + private long m_tick; private long m_renderFrame; - private FixedWidthFontRenderer m_fixedWidthFontRenderer; + private FixedWidthFontRenderer m_fixedWidthFontRenderer; - public ComputerCraftProxyClient() - { - } - - // IComputerCraftProxy implementation - - @Override - public void init() - { - super.init(); - m_tick = 0; + public ComputerCraftProxyClient() + { + } + + // IComputerCraftProxy implementation + + @Override + public void init() + { + super.init(); + m_tick = 0; m_renderFrame = 0; - // Load textures - Minecraft mc = Minecraft.getMinecraft(); - m_fixedWidthFontRenderer = new FixedWidthFontRenderer( mc.getTextureManager() ); + // Load textures + Minecraft mc = Minecraft.getMinecraft(); + m_fixedWidthFontRenderer = new FixedWidthFontRenderer( mc.getTextureManager() ); // Register item models registerItemModel( ComputerCraft.Blocks.computer, new ItemMeshDefinition() @@ -175,9 +175,9 @@ public ModelResourceLocation getModelLocation( ItemStack stack ) // Setup renderers ClientRegistry.bindTileEntitySpecialRenderer( TileMonitor.class, new TileEntityMonitorRenderer() ); - // Setup client forge handlers - registerForgeHandlers(); - } + // Setup client forge handlers + registerForgeHandlers(); + } private void registerItemModel( Block block, int damage, String name ) { @@ -225,18 +225,18 @@ private void registerItemModel( Item item, ItemMeshDefinition definition, String ModelBakery.registerItemVariants( item, resources ); Minecraft.getMinecraft().getRenderItem().getItemModelMesher().register( item, definition ); } - - @Override - public boolean isClient() - { - return true; - } + + @Override + public boolean isClient() + { + return true; + } - @Override - public boolean getGlobalCursorBlink() - { - return ( m_tick / 8) % 2 == 0; - } + @Override + public boolean getGlobalCursorBlink() + { + return ( m_tick / 8) % 2 == 0; + } @Override public long getRenderFrame() @@ -251,51 +251,51 @@ public void deleteDisplayLists( int list, int range ) } @Override - public Object getFixedWidthFontRenderer() - { - return m_fixedWidthFontRenderer; - } - - @Override - public String getRecordInfo( ItemStack recordStack ) - { - List info = new ArrayList(1); - recordStack.getItem().addInformation( recordStack, null, info, false ); - if( info.size() > 0 ) { - return info.get(0).toString(); - } else { - return super.getRecordInfo( recordStack ); - } - } - - @Override - public void playRecord( SoundEvent record, String recordInfo, World world, BlockPos pos ) - { - Minecraft mc = FMLClientHandler.instance().getClient(); - world.playRecord( pos, record ); - if( record != null ) - { - mc.ingameGUI.setRecordPlayingMessage( recordInfo ); - } - } - - @Override - public Object getDiskDriveGUI( InventoryPlayer inventory, TileDiskDrive drive ) - { - return new GuiDiskDrive( inventory, drive ); - } - - @Override - public Object getComputerGUI( TileComputer computer ) - { - return new GuiComputer( computer ); - } - - @Override - public Object getPrinterGUI( InventoryPlayer inventory, TilePrinter printer ) - { - return new GuiPrinter( inventory, printer ); - } + public Object getFixedWidthFontRenderer() + { + return m_fixedWidthFontRenderer; + } + + @Override + public String getRecordInfo( ItemStack recordStack ) + { + List info = new ArrayList(1); + recordStack.getItem().addInformation( recordStack, null, info, false ); + if( info.size() > 0 ) { + return info.get(0).toString(); + } else { + return super.getRecordInfo( recordStack ); + } + } + + @Override + public void playRecord( SoundEvent record, String recordInfo, World world, BlockPos pos ) + { + Minecraft mc = FMLClientHandler.instance().getClient(); + world.playRecord( pos, record ); + if( record != null ) + { + mc.ingameGUI.setRecordPlayingMessage( recordInfo ); + } + } + + @Override + public Object getDiskDriveGUI( InventoryPlayer inventory, TileDiskDrive drive ) + { + return new GuiDiskDrive( inventory, drive ); + } + + @Override + public Object getComputerGUI( TileComputer computer ) + { + return new GuiComputer( computer ); + } + + @Override + public Object getPrinterGUI( InventoryPlayer inventory, TilePrinter printer ) + { + return new GuiPrinter( inventory, printer ); + } @Override public Object getTurtleGUI( InventoryPlayer inventory, TileTurtle turtle ) @@ -304,15 +304,15 @@ public Object getTurtleGUI( InventoryPlayer inventory, TileTurtle turtle ) } @Override - public Object getPrintoutGUI( InventoryPlayer inventory ) - { + public Object getPrintoutGUI( InventoryPlayer inventory ) + { ContainerHeldItem container = new ContainerHeldItem( inventory ); if( container.getStack() != null && container.getStack().getItem() instanceof ItemPrintout ) { - return new GuiPrintout( container ); + return new GuiPrintout( container ); } return null; - } + } @Override public Object getPocketComputerGUI( InventoryPlayer inventory ) @@ -325,11 +325,11 @@ public Object getPocketComputerGUI( InventoryPlayer inventory ) return null; } - @Override - public File getWorldDir( World world ) - { + @Override + public File getWorldDir( World world ) + { return world.getSaveHandler().getWorldDirectory(); - } + } @Override public void handlePacket( final ComputerCraftPacket packet, final EntityPlayer player ) @@ -399,18 +399,18 @@ private void processPacket( ComputerCraftPacket packet, EntityPlayer player ) } } - private void registerForgeHandlers() - { - ForgeHandlers handlers = new ForgeHandlers(); + private void registerForgeHandlers() + { + ForgeHandlers handlers = new ForgeHandlers(); FMLCommonHandler.instance().bus().register( handlers ); MinecraftForge.EVENT_BUS.register( handlers ); - } - - public class ForgeHandlers - { - public ForgeHandlers() - { - } + } + + public class ForgeHandlers + { + public ForgeHandlers() + { + } @SubscribeEvent public void onRenderHand( RenderHandEvent event ) @@ -490,5 +490,5 @@ public void onRenderTick( TickEvent.RenderTickEvent event ) m_renderFrame++; } } - } + } } diff --git a/src/main/java/dan200/computercraft/core/apis/BitAPI.java b/src/main/java/dan200/computercraft/core/apis/BitAPI.java index a7f5e7824..b3a2cfdea 100644 --- a/src/main/java/dan200/computercraft/core/apis/BitAPI.java +++ b/src/main/java/dan200/computercraft/core/apis/BitAPI.java @@ -18,9 +18,9 @@ public class BitAPI implements ILuaAPI private static final int BAND = 1; private static final int BOR = 2; private static final int BXOR = 3; - private static final int BRSHIFT = 4; - private static final int BLSHIFT = 5; - private static final int BLOGIC_RSHIFT = 6; + private static final int BRSHIFT = 4; + private static final int BLSHIFT = 5; + private static final int BLOGIC_RSHIFT = 6; private static int checkInt( Object o, int count ) throws LuaException { @@ -45,30 +45,30 @@ public BitAPI( IAPIEnvironment _environment ) { } - @Override + @Override public String[] getNames() { - return new String[] { - "bit" - }; + return new String[] { + "bit" + }; } - @Override - public void startup( ) - { - } + @Override + public void startup( ) + { + } - @Override - public void advance( double _dt ) - { - } - - @Override - public void shutdown( ) - { - } - - @Override + @Override + public void advance( double _dt ) + { + } + + @Override + public void shutdown( ) + { + } + + @Override public String[] getMethodNames() { return new String[] { "bnot", "band", "bor", "bxor", diff --git a/src/main/java/dan200/computercraft/core/apis/FSAPI.java b/src/main/java/dan200/computercraft/core/apis/FSAPI.java index 0eaf49ba5..e244353a9 100644 --- a/src/main/java/dan200/computercraft/core/apis/FSAPI.java +++ b/src/main/java/dan200/computercraft/core/apis/FSAPI.java @@ -20,316 +20,316 @@ public class FSAPI implements ILuaAPI { - private IAPIEnvironment m_env; - private FileSystem m_fileSystem; - - public FSAPI( IAPIEnvironment _env ) - { - m_env = _env; - m_fileSystem = null; - } - - @Override + private IAPIEnvironment m_env; + private FileSystem m_fileSystem; + + public FSAPI( IAPIEnvironment _env ) + { + m_env = _env; + m_fileSystem = null; + } + + @Override public String[] getNames() { - return new String[] { - "fs" - }; + return new String[] { + "fs" + }; } - @Override - public void startup( ) - { - m_fileSystem = m_env.getFileSystem(); - } + @Override + public void startup( ) + { + m_fileSystem = m_env.getFileSystem(); + } - @Override - public void advance( double _dt ) - { - } - - @Override - public void shutdown( ) - { - m_fileSystem = null; - } + @Override + public void advance( double _dt ) + { + } + + @Override + public void shutdown( ) + { + m_fileSystem = null; + } - @Override + @Override public String[] getMethodNames() { - return new String[] { - "list", - "combine", - "getName", - "getSize", - "exists", - "isDir", - "isReadOnly", - "makeDir", - "move", - "copy", - "delete", - "open", - "getDrive", - "getFreeSpace", + return new String[] { + "list", + "combine", + "getName", + "getSize", + "exists", + "isDir", + "isReadOnly", + "makeDir", + "move", + "copy", + "delete", + "open", + "getDrive", + "getFreeSpace", "find", "getDir", - }; + }; } - @Override + @Override public Object[] callMethod( ILuaContext context, int method, Object[] args ) throws LuaException { - switch( method ) - { - case 0: - { - // list - if( args.length != 1 || args[0] == null || !(args[0] instanceof String) ) - { - throw new LuaException( "Expected string" ); - } - String path = (String)args[0]; - try { - String[] results = m_fileSystem.list( path ); - Map table = new HashMap(); - for(int i=0; i table = new HashMap(); + for(int i=0; i= 0 ) { return new Object[]{ freeSpace }; } return new Object[]{ "unlimited" }; - } catch( FileSystemException e ) { - throw new LuaException( e.getMessage() ); - } - } + } catch( FileSystemException e ) { + throw new LuaException( e.getMessage() ); + } + } case 14: { // find @@ -359,272 +359,272 @@ public Object[] callMethod( ILuaContext context, int method, Object[] args ) thr String path = (String)args[0]; return new Object[]{ m_fileSystem.getDirectory( path ) }; } - default: - { - assert( false ); - return null; - } - } - } - - private static Object[] wrapBufferedReader( final IMountedFileNormal reader ) - { - return new Object[] { new ILuaObject() { - @Override - public String[] getMethodNames() - { - return new String[] { - "readLine", - "readAll", - "close" - }; - } - - @Override - public Object[] callMethod( ILuaContext context, int method, Object[] args ) throws LuaException - { - switch( method ) - { - case 0: - { - // readLine - try { - String line = reader.readLine(); - if( line != null ) { - return new Object[] { line }; - } else { - return null; - } - } catch( IOException e ) { - return null; - } - } - case 1: - { - // readAll - try { - StringBuilder result = new StringBuilder( "" ); - String line = reader.readLine(); - while( line != null ) { - result.append( line ); - line = reader.readLine(); - if( line != null ) { - result.append( "\n" ); - } - } - return new Object[] { result.toString() }; - } catch( IOException e ) { - return null; - } - } - case 2: - { - // close - try { - reader.close(); - return null; - } catch( IOException e ) { - return null; - } - } - default: - { - return null; - } - } - } - } }; - } + default: + { + assert( false ); + return null; + } + } + } + + private static Object[] wrapBufferedReader( final IMountedFileNormal reader ) + { + return new Object[] { new ILuaObject() { + @Override + public String[] getMethodNames() + { + return new String[] { + "readLine", + "readAll", + "close" + }; + } + + @Override + public Object[] callMethod( ILuaContext context, int method, Object[] args ) throws LuaException + { + switch( method ) + { + case 0: + { + // readLine + try { + String line = reader.readLine(); + if( line != null ) { + return new Object[] { line }; + } else { + return null; + } + } catch( IOException e ) { + return null; + } + } + case 1: + { + // readAll + try { + StringBuilder result = new StringBuilder( "" ); + String line = reader.readLine(); + while( line != null ) { + result.append( line ); + line = reader.readLine(); + if( line != null ) { + result.append( "\n" ); + } + } + return new Object[] { result.toString() }; + } catch( IOException e ) { + return null; + } + } + case 2: + { + // close + try { + reader.close(); + return null; + } catch( IOException e ) { + return null; + } + } + default: + { + return null; + } + } + } + } }; + } - private static Object[] wrapBufferedWriter( final IMountedFileNormal writer ) - { - return new Object[] { new ILuaObject() { - @Override - public String[] getMethodNames() - { - return new String[] { - "write", - "writeLine", - "close", - "flush" - }; - } - - @Override - public Object[] callMethod( ILuaContext context, int method, Object[] args ) throws LuaException - { - switch( method ) - { - case 0: - { - // write - String text; + private static Object[] wrapBufferedWriter( final IMountedFileNormal writer ) + { + return new Object[] { new ILuaObject() { + @Override + public String[] getMethodNames() + { + return new String[] { + "write", + "writeLine", + "close", + "flush" + }; + } + + @Override + public Object[] callMethod( ILuaContext context, int method, Object[] args ) throws LuaException + { + switch( method ) + { + case 0: + { + // write + String text; if( args.length > 0 && args[0] != null ) { text = args[0].toString(); } else { text = ""; } - try { - writer.write( text, 0, text.length(), false ); - return null; - } catch( IOException e ) { - throw new LuaException( e.getMessage() ); - } - } - case 1: - { - // writeLine - String text; + try { + writer.write( text, 0, text.length(), false ); + return null; + } catch( IOException e ) { + throw new LuaException( e.getMessage() ); + } + } + case 1: + { + // writeLine + String text; if( args.length > 0 && args[0] != null ) { - text = args[0].toString(); - } else { - text = ""; - } - try { - writer.write( text, 0, text.length(), true ); - return null; - } catch( IOException e ) { - throw new LuaException( e.getMessage() ); - } - } - case 2: - { - // close - try { - writer.close(); - return null; - } catch( IOException e ) { - return null; - } - } - case 3: - { - try { - writer.flush(); - return null; - } catch ( IOException e ) { - return null; - } - } - default: - { - assert( false ); - return null; - } - } - } - } }; - } - - private static Object[] wrapInputStream( final IMountedFileBinary reader ) - { - - return new Object[] { new ILuaObject() { + text = args[0].toString(); + } else { + text = ""; + } + try { + writer.write( text, 0, text.length(), true ); + return null; + } catch( IOException e ) { + throw new LuaException( e.getMessage() ); + } + } + case 2: + { + // close + try { + writer.close(); + return null; + } catch( IOException e ) { + return null; + } + } + case 3: + { + try { + writer.flush(); + return null; + } catch ( IOException e ) { + return null; + } + } + default: + { + assert( false ); + return null; + } + } + } + } }; + } + + private static Object[] wrapInputStream( final IMountedFileBinary reader ) + { + + return new Object[] { new ILuaObject() { - @Override - public String[] getMethodNames() { - return new String[] { - "read", - "close" - }; - } + @Override + public String[] getMethodNames() { + return new String[] { + "read", + "close" + }; + } - @Override - public Object[] callMethod( ILuaContext context, int method, Object[] args) throws LuaException { - switch( method ) - { - case 0: - { - // read - try { - int b = reader.read(); - if( b != -1 ) { - return new Object[] { b }; - } else { - return null; - } - } catch( IOException e ) { - return null; - } - } - case 1: - { - //close - try { - reader.close(); - return null; - } catch( IOException e ) { - return null; - } - } - default: - { - assert( false ); - return null; - } - } - } - }}; - } + @Override + public Object[] callMethod( ILuaContext context, int method, Object[] args) throws LuaException { + switch( method ) + { + case 0: + { + // read + try { + int b = reader.read(); + if( b != -1 ) { + return new Object[] { b }; + } else { + return null; + } + } catch( IOException e ) { + return null; + } + } + case 1: + { + //close + try { + reader.close(); + return null; + } catch( IOException e ) { + return null; + } + } + default: + { + assert( false ); + return null; + } + } + } + }}; + } - private static Object[] wrapOutputStream( final IMountedFileBinary writer ) - { - - return new Object[] { new ILuaObject() { + private static Object[] wrapOutputStream( final IMountedFileBinary writer ) + { + + return new Object[] { new ILuaObject() { - @Override - public String[] getMethodNames() { - return new String[] { - "write", - "close", - "flush" - }; - } + @Override + public String[] getMethodNames() { + return new String[] { + "write", + "close", + "flush" + }; + } - @Override - public Object[] callMethod( ILuaContext context, int method, Object[] args) throws LuaException { - switch( method ) - { - case 0: - { - // write - try { - if( args.length > 0 && args[0] instanceof Number ) - { - int number = ((Number)args[0]).intValue(); - writer.write( number ); - } - return null; - } catch( IOException e ) { - throw new LuaException(e.getMessage()); - } - } - case 1: - { - //close - try { - writer.close(); - return null; - } catch( IOException e ) { - return null; - } - } - case 2: - { - try { - writer.flush(); - return null; - } catch ( IOException e ) { - return null; - } - } - default: - { - assert( false ); - return null; - } - } - } - }}; - } + @Override + public Object[] callMethod( ILuaContext context, int method, Object[] args) throws LuaException { + switch( method ) + { + case 0: + { + // write + try { + if( args.length > 0 && args[0] instanceof Number ) + { + int number = ((Number)args[0]).intValue(); + writer.write( number ); + } + return null; + } catch( IOException e ) { + throw new LuaException(e.getMessage()); + } + } + case 1: + { + //close + try { + writer.close(); + return null; + } catch( IOException e ) { + return null; + } + } + case 2: + { + try { + writer.flush(); + return null; + } catch ( IOException e ) { + return null; + } + } + default: + { + assert( false ); + return null; + } + } + } + }}; + } } diff --git a/src/main/java/dan200/computercraft/core/apis/HTTPAPI.java b/src/main/java/dan200/computercraft/core/apis/HTTPAPI.java index 706880851..cc31d8fe1 100644 --- a/src/main/java/dan200/computercraft/core/apis/HTTPAPI.java +++ b/src/main/java/dan200/computercraft/core/apis/HTTPAPI.java @@ -16,154 +16,154 @@ public class HTTPAPI implements ILuaAPI { - private IAPIEnvironment m_apiEnvironment; - private List m_httpRequests; - - public HTTPAPI( IAPIEnvironment environment ) - { - m_apiEnvironment = environment; - m_httpRequests = new ArrayList(); - } - - @Override + private IAPIEnvironment m_apiEnvironment; + private List m_httpRequests; + + public HTTPAPI( IAPIEnvironment environment ) + { + m_apiEnvironment = environment; + m_httpRequests = new ArrayList(); + } + + @Override public String[] getNames() { - return new String[] { - "http" - }; + return new String[] { + "http" + }; } - @Override - public void startup( ) - { - } + @Override + public void startup( ) + { + } - @Override - public void advance( double _dt ) - { - // Wait for all of our http requests - synchronized( m_httpRequests ) - { - Iterator it = m_httpRequests.iterator(); - while( it.hasNext() ) { - final HTTPRequest h = it.next(); - if( h.isComplete() ) { - final String url = h.getURL(); - if( h.wasSuccessful() ) { - // Queue the "http_success" event - final BufferedReader contents = h.getContents(); - final int responseCode = h.getResponseCode(); - final Object result = wrapBufferedReader( contents, responseCode ); - m_apiEnvironment.queueEvent( "http_success", new Object[] { url, result } ); - } else { - // Queue the "http_failure" event - m_apiEnvironment.queueEvent( "http_failure", new Object[] { url, "Could not connect" } ); - } - it.remove(); - } - } - } - } - - private static ILuaObject wrapBufferedReader( final BufferedReader reader, final int responseCode ) - { - return new ILuaObject() { - @Override - public String[] getMethodNames() - { - return new String[] { - "readLine", - "readAll", - "close", - "getResponseCode" - }; - } - - @Override - public Object[] callMethod( ILuaContext context, int method, Object[] args ) throws LuaException - { - switch( method ) - { - case 0: - { - // readLine - try { - String line = reader.readLine(); - if( line != null ) { - return new Object[] { line }; - } else { - return null; - } - } catch( IOException e ) { - return null; - } - } - case 1: - { - // readAll - try { - StringBuilder result = new StringBuilder( "" ); - String line = reader.readLine(); - while( line != null ) { - result.append( line ); - line = reader.readLine(); - if( line != null ) { - result.append( "\n" ); - } - } - return new Object[] { result.toString() }; - } catch( IOException e ) { - return null; - } - } - case 2: - { - // close - try { - reader.close(); - return null; - } catch( IOException e ) { - return null; - } - } - case 3: - { + @Override + public void advance( double _dt ) + { + // Wait for all of our http requests + synchronized( m_httpRequests ) + { + Iterator it = m_httpRequests.iterator(); + while( it.hasNext() ) { + final HTTPRequest h = it.next(); + if( h.isComplete() ) { + final String url = h.getURL(); + if( h.wasSuccessful() ) { + // Queue the "http_success" event + final BufferedReader contents = h.getContents(); + final int responseCode = h.getResponseCode(); + final Object result = wrapBufferedReader( contents, responseCode ); + m_apiEnvironment.queueEvent( "http_success", new Object[] { url, result } ); + } else { + // Queue the "http_failure" event + m_apiEnvironment.queueEvent( "http_failure", new Object[] { url, "Could not connect" } ); + } + it.remove(); + } + } + } + } + + private static ILuaObject wrapBufferedReader( final BufferedReader reader, final int responseCode ) + { + return new ILuaObject() { + @Override + public String[] getMethodNames() + { + return new String[] { + "readLine", + "readAll", + "close", + "getResponseCode" + }; + } + + @Override + public Object[] callMethod( ILuaContext context, int method, Object[] args ) throws LuaException + { + switch( method ) + { + case 0: + { + // readLine + try { + String line = reader.readLine(); + if( line != null ) { + return new Object[] { line }; + } else { + return null; + } + } catch( IOException e ) { + return null; + } + } + case 1: + { + // readAll + try { + StringBuilder result = new StringBuilder( "" ); + String line = reader.readLine(); + while( line != null ) { + result.append( line ); + line = reader.readLine(); + if( line != null ) { + result.append( "\n" ); + } + } + return new Object[] { result.toString() }; + } catch( IOException e ) { + return null; + } + } + case 2: + { + // close + try { + reader.close(); + return null; + } catch( IOException e ) { + return null; + } + } + case 3: + { // getResponseCode - return new Object[] { responseCode }; - } - default: - { - return null; - } - } - } - }; - } - - @Override - public void shutdown( ) - { - synchronized( m_httpRequests ) - { - Iterator it = m_httpRequests.iterator(); - while( it.hasNext() ) { - HTTPRequest r = it.next(); - r.cancel(); - } - m_httpRequests.clear(); - } - } + return new Object[] { responseCode }; + } + default: + { + return null; + } + } + } + }; + } + + @Override + public void shutdown( ) + { + synchronized( m_httpRequests ) + { + Iterator it = m_httpRequests.iterator(); + while( it.hasNext() ) { + HTTPRequest r = it.next(); + r.cancel(); + } + m_httpRequests.clear(); + } + } - @Override + @Override public String[] getMethodNames() { - return new String[] { + return new String[] { "request", "checkURL" }; } - @Override + @Override public Object[] callMethod( ILuaContext context, int method, Object[] args ) throws LuaException { switch( method ) @@ -242,5 +242,5 @@ public Object[] callMethod( ILuaContext context, int method, Object[] args ) thr return null; } } - } -} \ No newline at end of file + } +} diff --git a/src/main/java/dan200/computercraft/core/apis/HTTPRequest.java b/src/main/java/dan200/computercraft/core/apis/HTTPRequest.java index cd6b4effe..c0525504b 100644 --- a/src/main/java/dan200/computercraft/core/apis/HTTPRequest.java +++ b/src/main/java/dan200/computercraft/core/apis/HTTPRequest.java @@ -16,9 +16,9 @@ import java.util.regex.Pattern; class HTTPRequestException extends Exception { - public HTTPRequestException( String s ) { - super( s ); - } + public HTTPRequestException( String s ) { + super( s ); + } } public class HTTPRequest @@ -64,18 +64,18 @@ public static URL checkURL( String urlString ) throws HTTPRequestException return url; } - public HTTPRequest( String url, final String postText, final Map headers ) throws HTTPRequestException - { - // Parse the URL - m_urlString = url; + public HTTPRequest( String url, final String postText, final Map headers ) throws HTTPRequestException + { + // Parse the URL + m_urlString = url; m_url = checkURL( m_urlString ); // Start the thread - m_cancelled = false; - m_complete = false; - m_success = false; - m_result = null; - m_responseCode = -1; + m_cancelled = false; + m_complete = false; + m_success = false; + m_result = null; + m_responseCode = -1; Thread thread = new Thread( new Runnable() { @Override @@ -213,27 +213,27 @@ public void run() } } } ); - - thread.start(); - } - - public String getURL() { - return m_urlString; - } - - public void cancel() - { - synchronized(m_lock) { - m_cancelled = true; - } - } - - public boolean isComplete() - { - synchronized(m_lock) { - return m_complete; - } - } + + thread.start(); + } + + public String getURL() { + return m_urlString; + } + + public void cancel() + { + synchronized(m_lock) { + m_cancelled = true; + } + } + + public boolean isComplete() + { + synchronized(m_lock) { + return m_complete; + } + } public int getResponseCode() { synchronized(m_lock) { @@ -242,32 +242,32 @@ public int getResponseCode() { } public boolean wasSuccessful() - { - synchronized(m_lock) { - return m_success; - } - } - - public BufferedReader getContents() - { - String result = null; - synchronized(m_lock) { - result = m_result; - } - - if( result != null ) { - return new BufferedReader( new StringReader( result ) ); - } - return null; - } - - private Object m_lock = new Object(); - private URL m_url; + { + synchronized(m_lock) { + return m_success; + } + } + + public BufferedReader getContents() + { + String result = null; + synchronized(m_lock) { + result = m_result; + } + + if( result != null ) { + return new BufferedReader( new StringReader( result ) ); + } + return null; + } + + private Object m_lock = new Object(); + private URL m_url; private final String m_urlString; - - private boolean m_complete; - private boolean m_cancelled; - private boolean m_success; - private String m_result; - private int m_responseCode; + + private boolean m_complete; + private boolean m_cancelled; + private boolean m_success; + private String m_result; + private int m_responseCode; } diff --git a/src/main/java/dan200/computercraft/core/apis/IAPIEnvironment.java b/src/main/java/dan200/computercraft/core/apis/IAPIEnvironment.java index 9a14ece99..cc2f9bc7f 100644 --- a/src/main/java/dan200/computercraft/core/apis/IAPIEnvironment.java +++ b/src/main/java/dan200/computercraft/core/apis/IAPIEnvironment.java @@ -14,31 +14,31 @@ public interface IAPIEnvironment { - public static interface IPeripheralChangeListener - { - public void onPeripheralChanged( int side, IPeripheral newPeripheral ); - } - - public Computer getComputer(); - public int getComputerID(); - public IComputerEnvironment getComputerEnvironment(); - public Terminal getTerminal(); - public FileSystem getFileSystem(); - - public void shutdown(); - public void reboot(); + public static interface IPeripheralChangeListener + { + public void onPeripheralChanged( int side, IPeripheral newPeripheral ); + } + + public Computer getComputer(); + public int getComputerID(); + public IComputerEnvironment getComputerEnvironment(); + public Terminal getTerminal(); + public FileSystem getFileSystem(); + + public void shutdown(); + public void reboot(); public void queueEvent( String event, Object[] args ); - public void setOutput( int side, int output ); - public int getOutput( int side ); - public int getInput( int side ); + public void setOutput( int side, int output ); + public int getOutput( int side ); + public int getInput( int side ); - public void setBundledOutput( int side, int output ); - public int getBundledOutput( int side ); - public int getBundledInput( int side ); - - public void setPeripheralChangeListener( IPeripheralChangeListener listener ); - public IPeripheral getPeripheral( int side ); + public void setBundledOutput( int side, int output ); + public int getBundledOutput( int side ); + public int getBundledInput( int side ); + + public void setPeripheralChangeListener( IPeripheralChangeListener listener ); + public IPeripheral getPeripheral( int side ); public String getLabel(); public void setLabel( String label ); diff --git a/src/main/java/dan200/computercraft/core/apis/ILuaAPI.java b/src/main/java/dan200/computercraft/core/apis/ILuaAPI.java index 14baa685b..9e4acf31c 100644 --- a/src/main/java/dan200/computercraft/core/apis/ILuaAPI.java +++ b/src/main/java/dan200/computercraft/core/apis/ILuaAPI.java @@ -11,7 +11,7 @@ public interface ILuaAPI extends ILuaObject { public String[] getNames(); - public void startup(); // LT - public void advance( double _dt ); // MT - public void shutdown(); // LT + public void startup(); // LT + public void advance( double _dt ); // MT + public void shutdown(); // LT } diff --git a/src/main/java/dan200/computercraft/core/apis/OSAPI.java b/src/main/java/dan200/computercraft/core/apis/OSAPI.java index d415d0a82..4b3a11a11 100644 --- a/src/main/java/dan200/computercraft/core/apis/OSAPI.java +++ b/src/main/java/dan200/computercraft/core/apis/OSAPI.java @@ -16,70 +16,70 @@ public class OSAPI implements ILuaAPI { - private IAPIEnvironment m_apiEnvironment; + private IAPIEnvironment m_apiEnvironment; - private final Map m_timers; - private final Map m_alarms; - private int m_clock; - private double m_time; + private final Map m_timers; + private final Map m_alarms; + private int m_clock; + private double m_time; private int m_day; - private int m_nextTimerToken; - private int m_nextAlarmToken; - - private static class Timer + private int m_nextTimerToken; + private int m_nextAlarmToken; + + private static class Timer { public int m_ticksLeft; - public Timer( int ticksLeft ) + public Timer( int ticksLeft ) { m_ticksLeft = ticksLeft; - } - } - - private class Alarm implements Comparable + } + } + + private class Alarm implements Comparable { public final double m_time; public final int m_day; - public Alarm( double time, int day ) + public Alarm( double time, int day ) { - m_time = time; + m_time = time; m_day = day; - } + } @Override - public int compareTo( Alarm o ) + public int compareTo( Alarm o ) { - double t = (double)m_day * 24.0 + m_time; - double ot = (double)m_day * 24.0 + m_time; - if( t < ot ) { - return -1; - } else if( t > ot ) { - return 1; - } else { - return 0; - } - } - } - - public OSAPI( IAPIEnvironment environment ) - { - m_apiEnvironment = environment; - m_nextTimerToken = 0; - m_nextAlarmToken = 0; + double t = (double)m_day * 24.0 + m_time; + double ot = (double)m_day * 24.0 + m_time; + if( t < ot ) { + return -1; + } else if( t > ot ) { + return 1; + } else { + return 0; + } + } + } + + public OSAPI( IAPIEnvironment environment ) + { + m_apiEnvironment = environment; + m_nextTimerToken = 0; + m_nextAlarmToken = 0; m_timers = new HashMap(); m_alarms = new HashMap(); - } - - // ILuaAPI implementation - - @Override + } + + // ILuaAPI implementation + + @Override public String[] getNames() { - return new String[] { - "os" - }; + return new String[] { + "os" + }; } @Override @@ -87,7 +87,7 @@ public void startup() { m_time = m_apiEnvironment.getComputerEnvironment().getTimeOfDay(); m_day = m_apiEnvironment.getComputerEnvironment().getDay(); - m_clock = 0; + m_clock = 0; synchronized( m_timers ) { @@ -99,40 +99,40 @@ public void startup() m_alarms.clear(); } } - - @Override - public void advance( double dt ) - { - synchronized( m_timers ) - { - // Update the clock - m_clock++; - - // Countdown all of our active timers - Iterator> it = m_timers.entrySet().iterator(); - while( it.hasNext() ) + + @Override + public void advance( double dt ) + { + synchronized( m_timers ) + { + // Update the clock + m_clock++; + + // Countdown all of our active timers + Iterator> it = m_timers.entrySet().iterator(); + while( it.hasNext() ) { Map.Entry entry = it.next(); Timer timer = entry.getValue(); - timer.m_ticksLeft = timer.m_ticksLeft - 1; - if( timer.m_ticksLeft <= 0 ) + timer.m_ticksLeft = timer.m_ticksLeft - 1; + if( timer.m_ticksLeft <= 0 ) { - // Queue the "timer" event - queueLuaEvent( "timer", new Object[] { entry.getKey() } ); - it.remove(); - } - } - } - - // Wait for all of our alarms - synchronized( m_alarms ) - { - double previousTime = m_time; + // Queue the "timer" event + queueLuaEvent( "timer", new Object[] { entry.getKey() } ); + it.remove(); + } + } + } + + // Wait for all of our alarms + synchronized( m_alarms ) + { + double previousTime = m_time; int previousDay = m_day; - double time = m_apiEnvironment.getComputerEnvironment().getTimeOfDay(); + double time = m_apiEnvironment.getComputerEnvironment().getTimeOfDay(); int day = m_apiEnvironment.getComputerEnvironment().getDay(); - - if( time > previousTime || day > previousDay ) + + if( time > previousTime || day > previousDay ) { double now = (double)m_day * 24.0 + m_time; Iterator> it = m_alarms.entrySet().iterator(); @@ -149,167 +149,167 @@ public void advance( double dt ) } } - m_time = time; + m_time = time; m_day = day; - } - } - - @Override - public void shutdown( ) - { - synchronized( m_timers ) - { - m_timers.clear(); - } - - synchronized( m_alarms ) - { - m_alarms.clear(); - } - } - - @Override - public String[] getMethodNames() + } + } + + @Override + public void shutdown( ) { - return new String[] { - "queueEvent", - "startTimer", - "setAlarm", - "shutdown", - "reboot", - "computerID", - "getComputerID", - "setComputerLabel", - "computerLabel", - "getComputerLabel", - "clock", - "time", - "day", - "cancelTimer", - "cancelAlarm", - }; + synchronized( m_timers ) + { + m_timers.clear(); + } + + synchronized( m_alarms ) + { + m_alarms.clear(); + } } - @Override + @Override + public String[] getMethodNames() + { + return new String[] { + "queueEvent", + "startTimer", + "setAlarm", + "shutdown", + "reboot", + "computerID", + "getComputerID", + "setComputerLabel", + "computerLabel", + "getComputerLabel", + "clock", + "time", + "day", + "cancelTimer", + "cancelAlarm", + }; + } + + @Override public Object[] callMethod( ILuaContext context, int method, Object[] args ) throws LuaException { - switch( method ) - { - case 0: - { - // queueEvent - if( args.length == 0 || args[0] == null || !(args[0] instanceof String) ) - { - throw new LuaException( "Expected string" ); - } - queueLuaEvent( (String)args[0], trimArray( args, 1 ) ); - return null; - } - case 1: - { - // startTimer - if( args.length < 1 || args[0] == null || !(args[0] instanceof Number) ) - { - throw new LuaException( "Expected number" ); - } - double timer = ((Number)args[0]).doubleValue(); - synchronized( m_timers ) - { - m_timers.put( m_nextTimerToken, new Timer( (int)Math.round( timer / 0.05 ) ) ); + switch( method ) + { + case 0: + { + // queueEvent + if( args.length == 0 || args[0] == null || !(args[0] instanceof String) ) + { + throw new LuaException( "Expected string" ); + } + queueLuaEvent( (String)args[0], trimArray( args, 1 ) ); + return null; + } + case 1: + { + // startTimer + if( args.length < 1 || args[0] == null || !(args[0] instanceof Number) ) + { + throw new LuaException( "Expected number" ); + } + double timer = ((Number)args[0]).doubleValue(); + synchronized( m_timers ) + { + m_timers.put( m_nextTimerToken, new Timer( (int)Math.round( timer / 0.05 ) ) ); return new Object[] { m_nextTimerToken++ }; - } - } - case 2: - { - // setAlarm - if( args.length < 1 || args[0] == null || !(args[0] instanceof Number) ) - { - throw new LuaException( "Expected number" ); - } - double time = ((Number)args[0]).doubleValue(); - if( time < 0.0 || time >= 24.0 ) - { - throw new LuaException( "Number out of range" ); - } - synchronized( m_alarms ) - { + } + } + case 2: + { + // setAlarm + if( args.length < 1 || args[0] == null || !(args[0] instanceof Number) ) + { + throw new LuaException( "Expected number" ); + } + double time = ((Number)args[0]).doubleValue(); + if( time < 0.0 || time >= 24.0 ) + { + throw new LuaException( "Number out of range" ); + } + synchronized( m_alarms ) + { int day = (time > m_time) ? m_day : (m_day + 1); - m_alarms.put( m_nextAlarmToken, new Alarm( time, day ) ); + m_alarms.put( m_nextAlarmToken, new Alarm( time, day ) ); return new Object[] { m_nextAlarmToken++ }; - } - } - case 3: - { - // shutdown - m_apiEnvironment.shutdown(); - return null; - } - case 4: - { - // reboot - m_apiEnvironment.reboot(); - return null; - } - case 5: - case 6: - { - // computerID/getComputerID - return new Object[] { getComputerID() }; - } - case 7: - { - // setComputerLabel - String label = null; - if( args.length > 0 && args[0] != null ) - { - if(!(args[0] instanceof String)) - { - throw new LuaException( "Expected string or nil" ); - } - label = (String)args[0]; + } + } + case 3: + { + // shutdown + m_apiEnvironment.shutdown(); + return null; + } + case 4: + { + // reboot + m_apiEnvironment.reboot(); + return null; + } + case 5: + case 6: + { + // computerID/getComputerID + return new Object[] { getComputerID() }; + } + case 7: + { + // setComputerLabel + String label = null; + if( args.length > 0 && args[0] != null ) + { + if(!(args[0] instanceof String)) + { + throw new LuaException( "Expected string or nil" ); + } + label = (String)args[0]; if( label.length() > 32 ) { label = label.substring( 0, 32 ); } - } + } m_apiEnvironment.setLabel( label ); - return null; - } - case 8: - case 9: - { - // computerLabel/getComputerLabel - String label = m_apiEnvironment.getLabel(); - if( label != null ) - { - return new Object[] { label }; - } - return null; - } - case 10: - { - // clock - synchronized( m_timers ) - { - return new Object[] { (double)m_clock * 0.05 }; - } - } - case 11: - { - // m_time - synchronized( m_alarms ) - { - return new Object[] { m_time }; - } - } - case 12: - { - // day - synchronized( m_alarms ) - { - return new Object[] { m_day }; - } - } + return null; + } + case 8: + case 9: + { + // computerLabel/getComputerLabel + String label = m_apiEnvironment.getLabel(); + if( label != null ) + { + return new Object[] { label }; + } + return null; + } + case 10: + { + // clock + synchronized( m_timers ) + { + return new Object[] { (double)m_clock * 0.05 }; + } + } + case 11: + { + // m_time + synchronized( m_alarms ) + { + return new Object[] { m_time }; + } + } + case 12: + { + // day + synchronized( m_alarms ) + { + return new Object[] { m_day }; + } + } case 13: { // cancelTimer @@ -344,27 +344,27 @@ public Object[] callMethod( ILuaContext context, int method, Object[] args ) thr } return null; } - default: - { - return null; - } - } - } + default: + { + return null; + } + } + } - // Private methods + // Private methods - private void queueLuaEvent( String event, Object[] args ) - { - m_apiEnvironment.queueEvent( event, args ); - } - - private Object[] trimArray( Object[] array, int skip ) - { - return Arrays.copyOfRange( array, skip, array.length ); - } - - private int getComputerID() - { - return m_apiEnvironment.getComputerID(); - } + private void queueLuaEvent( String event, Object[] args ) + { + m_apiEnvironment.queueEvent( event, args ); + } + + private Object[] trimArray( Object[] array, int skip ) + { + return Arrays.copyOfRange( array, skip, array.length ); + } + + private int getComputerID() + { + return m_apiEnvironment.getComputerID(); + } } diff --git a/src/main/java/dan200/computercraft/core/apis/PeripheralAPI.java b/src/main/java/dan200/computercraft/core/apis/PeripheralAPI.java index dbe2f1dae..8f5f64586 100644 --- a/src/main/java/dan200/computercraft/core/apis/PeripheralAPI.java +++ b/src/main/java/dan200/computercraft/core/apis/PeripheralAPI.java @@ -22,100 +22,100 @@ public class PeripheralAPI implements ILuaAPI, IAPIEnvironment.IPeripheralChangeListener { - private class PeripheralWrapper implements IComputerAccess - { - private final String m_side; + private class PeripheralWrapper implements IComputerAccess + { + private final String m_side; private final IPeripheral m_peripheral; - private String m_type; - private String[] m_methods; - private Map m_methodMap; - private boolean m_attached; - - private Set m_mounts; - - public PeripheralWrapper( IPeripheral peripheral, String side ) - { - m_side = side; - m_peripheral = peripheral; - m_attached = false; - - m_type = peripheral.getType(); - m_methods = peripheral.getMethodNames(); - assert( m_type != null ); - assert( m_methods != null ); - - m_methodMap = new HashMap(); - for(int i=0; i(); - } - - public IPeripheral getPeripheral() - { - return m_peripheral; - } - - public String getType() - { - return m_type; - } - - public String[] getMethods() - { - return m_methods; - } - - public synchronized boolean isAttached() - { - return m_attached; - } - - public synchronized void attach() - { - m_attached = true; - m_peripheral.attach( this ); - } - - public synchronized void detach() - { - // Call detach - m_peripheral.detach( this ); - m_attached = false; - - // Unmount everything the detach function forgot to do - Iterator it = m_mounts.iterator(); - while( it.hasNext() ) { - m_fileSystem.unmount( it.next() ); - } - m_mounts.clear(); - } - - public Object[] call( ILuaContext context, String methodName, Object[] arguments ) throws LuaException, InterruptedException - { - int method = -1; - synchronized( this ) - { - if( m_methodMap.containsKey( methodName ) ) - { - method = m_methodMap.get( methodName ); - } - } - if( method >= 0 ) - { - return m_peripheral.callMethod( this, context, method, arguments ); - } - else - { - throw new LuaException( "No such method " + methodName ); - } - } + private String m_type; + private String[] m_methods; + private Map m_methodMap; + private boolean m_attached; + + private Set m_mounts; + + public PeripheralWrapper( IPeripheral peripheral, String side ) + { + m_side = side; + m_peripheral = peripheral; + m_attached = false; + + m_type = peripheral.getType(); + m_methods = peripheral.getMethodNames(); + assert( m_type != null ); + assert( m_methods != null ); + + m_methodMap = new HashMap(); + for(int i=0; i(); + } + + public IPeripheral getPeripheral() + { + return m_peripheral; + } + + public String getType() + { + return m_type; + } + + public String[] getMethods() + { + return m_methods; + } + + public synchronized boolean isAttached() + { + return m_attached; + } + + public synchronized void attach() + { + m_attached = true; + m_peripheral.attach( this ); + } + + public synchronized void detach() + { + // Call detach + m_peripheral.detach( this ); + m_attached = false; + + // Unmount everything the detach function forgot to do + Iterator it = m_mounts.iterator(); + while( it.hasNext() ) { + m_fileSystem.unmount( it.next() ); + } + m_mounts.clear(); + } + + public Object[] call( ILuaContext context, String methodName, Object[] arguments ) throws LuaException, InterruptedException + { + int method = -1; + synchronized( this ) + { + if( m_methodMap.containsKey( methodName ) ) + { + method = m_methodMap.get( methodName ); + } + } + if( method >= 0 ) + { + return m_peripheral.callMethod( this, context, method, arguments ); + } + else + { + throw new LuaException( "No such method " + methodName ); + } + } - // IComputerAccess implementation + // IComputerAccess implementation @Override public String mount( String desiredLoc, IMount mount ) @@ -124,33 +124,33 @@ public String mount( String desiredLoc, IMount mount ) } @Override - public synchronized String mount( String desiredLoc, IMount mount, String driveName ) - { - if( !m_attached ) - { - throw new RuntimeException( "You are not attached to this Computer" ); - } - - // Mount the location - String location = null; - synchronized( m_fileSystem ) - { - location = findFreeLocation( desiredLoc ); - if( location != null ) - { - try { - m_fileSystem.mount( driveName, location, mount ); - } catch( FileSystemException e ) { - // fail and return null - } - } - } - if( location != null ) - { - m_mounts.add( location ); - } - return location; - } + public synchronized String mount( String desiredLoc, IMount mount, String driveName ) + { + if( !m_attached ) + { + throw new RuntimeException( "You are not attached to this Computer" ); + } + + // Mount the location + String location = null; + synchronized( m_fileSystem ) + { + location = findFreeLocation( desiredLoc ); + if( location != null ) + { + try { + m_fileSystem.mount( driveName, location, mount ); + } catch( FileSystemException e ) { + // fail and return null + } + } + } + if( location != null ) + { + m_mounts.add( location ); + } + return location; + } @Override public String mountWritable( String desiredLoc, IWritableMount mount ) @@ -158,112 +158,112 @@ public String mountWritable( String desiredLoc, IWritableMount mount ) return mountWritable( desiredLoc, mount, m_side ); } - @Override - public synchronized String mountWritable( String desiredLoc, IWritableMount mount, String driveName ) - { - if( !m_attached ) - { - throw new RuntimeException( "You are not attached to this Computer" ); - } - - // Mount the location - String location = null; - synchronized( m_fileSystem ) - { - location = findFreeLocation( desiredLoc ); - if( location != null ) - { - try { - m_fileSystem.mountWritable( driveName, location, mount ); - } catch( FileSystemException e ) { - // fail and return null - } - } - } - if( location != null ) - { - m_mounts.add( location ); - } - return location; - } - - @Override - public synchronized void unmount( String location ) - { - if( !m_attached ) { - throw new RuntimeException( "You are not attached to this Computer" ); - } - - if( location != null ) - { - if( !m_mounts.contains( location ) ) { - throw new RuntimeException( "You didn't mount this location" ); - } - - m_fileSystem.unmount( location ); - m_mounts.remove( location ); - } - } - - @Override - public synchronized int getID() - { - if( !m_attached ) { - throw new RuntimeException( "You are not attached to this Computer" ); - } - return m_environment.getComputerID(); - } - - @Override - public synchronized void queueEvent( final String event, final Object[] arguments ) - { - if( !m_attached ) { - throw new RuntimeException( "You are not attached to this Computer" ); - } - m_environment.queueEvent( event, arguments ); - } - - @Override - public synchronized String getAttachmentName() - { - if( !m_attached ) { - throw new RuntimeException( "You are not attached to this Computer" ); - } - return m_side; - } - } - - private IAPIEnvironment m_environment; - private FileSystem m_fileSystem; - private PeripheralWrapper[] m_peripherals; - private boolean m_running; + @Override + public synchronized String mountWritable( String desiredLoc, IWritableMount mount, String driveName ) + { + if( !m_attached ) + { + throw new RuntimeException( "You are not attached to this Computer" ); + } + + // Mount the location + String location = null; + synchronized( m_fileSystem ) + { + location = findFreeLocation( desiredLoc ); + if( location != null ) + { + try { + m_fileSystem.mountWritable( driveName, location, mount ); + } catch( FileSystemException e ) { + // fail and return null + } + } + } + if( location != null ) + { + m_mounts.add( location ); + } + return location; + } + + @Override + public synchronized void unmount( String location ) + { + if( !m_attached ) { + throw new RuntimeException( "You are not attached to this Computer" ); + } + + if( location != null ) + { + if( !m_mounts.contains( location ) ) { + throw new RuntimeException( "You didn't mount this location" ); + } + + m_fileSystem.unmount( location ); + m_mounts.remove( location ); + } + } + + @Override + public synchronized int getID() + { + if( !m_attached ) { + throw new RuntimeException( "You are not attached to this Computer" ); + } + return m_environment.getComputerID(); + } + + @Override + public synchronized void queueEvent( final String event, final Object[] arguments ) + { + if( !m_attached ) { + throw new RuntimeException( "You are not attached to this Computer" ); + } + m_environment.queueEvent( event, arguments ); + } + + @Override + public synchronized String getAttachmentName() + { + if( !m_attached ) { + throw new RuntimeException( "You are not attached to this Computer" ); + } + return m_side; + } + } + + private IAPIEnvironment m_environment; + private FileSystem m_fileSystem; + private PeripheralWrapper[] m_peripherals; + private boolean m_running; - public PeripheralAPI( IAPIEnvironment _environment ) - { - m_environment = _environment; - m_environment.setPeripheralChangeListener( this ); - - m_peripherals = new PeripheralWrapper[6]; - for(int i=0; i<6; ++i) - { - m_peripherals[i] = null; - } - - m_running = false; - } - - // IPeripheralChangeListener + public PeripheralAPI( IAPIEnvironment _environment ) + { + m_environment = _environment; + m_environment.setPeripheralChangeListener( this ); + + m_peripherals = new PeripheralWrapper[6]; + for(int i=0; i<6; ++i) + { + m_peripherals[i] = null; + } + + m_running = false; + } + + // IPeripheralChangeListener @Override - public void onPeripheralChanged( int side, IPeripheral newPeripheral ) - { - synchronized( m_peripherals ) - { - if( m_peripherals[side] != null ) - { - // Queue a detachment - final PeripheralWrapper wrapper = m_peripherals[side]; - ComputerThread.queueTask(new ITask() { + public void onPeripheralChanged( int side, IPeripheral newPeripheral ) + { + synchronized( m_peripherals ) + { + if( m_peripherals[side] != null ) + { + // Queue a detachment + final PeripheralWrapper wrapper = m_peripherals[side]; + ComputerThread.queueTask(new ITask() { @Override public Computer getOwner() { return m_environment.getComputer(); @@ -278,257 +278,257 @@ public void execute() { } } }, null); - - // Queue a detachment event - m_environment.queueEvent( "peripheral_detach", new Object[] { Computer.s_sideNames[side] } ); - } - - // Assign the new peripheral - if( newPeripheral != null ) - { - m_peripherals[side] = new PeripheralWrapper( newPeripheral, Computer.s_sideNames[side] ); - } - else - { - m_peripherals[side] = null; - } - - if( m_peripherals[side] != null ) - { - // Queue an attachment - final PeripheralWrapper wrapper = m_peripherals[side]; - ComputerThread.queueTask( new ITask() { + + // Queue a detachment event + m_environment.queueEvent( "peripheral_detach", new Object[] { Computer.s_sideNames[side] } ); + } + + // Assign the new peripheral + if( newPeripheral != null ) + { + m_peripherals[side] = new PeripheralWrapper( newPeripheral, Computer.s_sideNames[side] ); + } + else + { + m_peripherals[side] = null; + } + + if( m_peripherals[side] != null ) + { + // Queue an attachment + final PeripheralWrapper wrapper = m_peripherals[side]; + ComputerThread.queueTask( new ITask() { @Override - public Computer getOwner() { - return m_environment.getComputer(); - } + public Computer getOwner() { + return m_environment.getComputer(); + } @Override - public void execute() { - synchronized( m_peripherals ) - { - if( m_running && !wrapper.isAttached() ) - { - wrapper.attach(); - } - } - } - }, null ); - - // Queue an attachment event - m_environment.queueEvent( "peripheral", new Object[] { Computer.s_sideNames[side] } ); - } - } - } + public void execute() { + synchronized( m_peripherals ) + { + if( m_running && !wrapper.isAttached() ) + { + wrapper.attach(); + } + } + } + }, null ); + + // Queue an attachment event + m_environment.queueEvent( "peripheral", new Object[] { Computer.s_sideNames[side] } ); + } + } + } - // ILuaAPI implementation - - @Override + // ILuaAPI implementation + + @Override public String[] getNames() { - return new String[] { - "peripheral" - }; + return new String[] { + "peripheral" + }; } - @Override - public void startup( ) - { - synchronized( m_peripherals ) - { - m_fileSystem = m_environment.getFileSystem(); - m_running = true; - for( int i=0; i<6; ++i ) - { - PeripheralWrapper wrapper = m_peripherals[i]; - if( wrapper != null && !wrapper.isAttached() ) - { - wrapper.attach(); - } - } - } - } - - @Override - public void advance( double _dt ) - { - } - - @Override - public void shutdown( ) - { - synchronized( m_peripherals ) - { - m_running = false; - for( int i=0; i<6; ++i ) - { - PeripheralWrapper wrapper = m_peripherals[i]; - if( wrapper != null && wrapper.isAttached() ) - { - wrapper.detach(); - } - } - m_fileSystem = null; - } - } + @Override + public void startup( ) + { + synchronized( m_peripherals ) + { + m_fileSystem = m_environment.getFileSystem(); + m_running = true; + for( int i=0; i<6; ++i ) + { + PeripheralWrapper wrapper = m_peripherals[i]; + if( wrapper != null && !wrapper.isAttached() ) + { + wrapper.attach(); + } + } + } + } + + @Override + public void advance( double _dt ) + { + } + + @Override + public void shutdown( ) + { + synchronized( m_peripherals ) + { + m_running = false; + for( int i=0; i<6; ++i ) + { + PeripheralWrapper wrapper = m_peripherals[i]; + if( wrapper != null && wrapper.isAttached() ) + { + wrapper.detach(); + } + } + m_fileSystem = null; + } + } - @Override + @Override public String[] getMethodNames() { - return new String[] { - "isPresent", - "getType", - "getMethods", - "call" - }; + return new String[] { + "isPresent", + "getType", + "getMethods", + "call" + }; } - @Override + @Override public Object[] callMethod( ILuaContext context, int method, Object[] args ) throws LuaException, InterruptedException { - switch( method ) - { - case 0: - { - // isPresent - boolean present = false; - int side = parseSide( args ); - if( side >= 0 ) - { - synchronized( m_peripherals ) - { - PeripheralWrapper p = m_peripherals[ side ]; - if( p != null ) - { - present = true; - } - } - } - return new Object[] { present }; - } - case 1: - { - // getType - String type = null; - int side = parseSide( args ); - if( side >= 0 ) - { - synchronized( m_peripherals ) - { - PeripheralWrapper p = m_peripherals[ side ]; - if( p != null ) - { - type = p.getType(); - } - } - if( type != null ) - { - return new Object[] { type }; - } - } - return null; - } - case 2: - { - // getMethods - String[] methods = null; - int side = parseSide( args ); - if( side >= 0 ) - { - synchronized( m_peripherals ) - { - PeripheralWrapper p = m_peripherals[ side ]; - if( p != null ) - { - methods = p.getMethods(); - } - } - } - if( methods != null ) - { - Map table = new HashMap(); - for(int i=0; i= 0 ) - { - PeripheralWrapper p = null; - synchronized( m_peripherals ) - { - p = m_peripherals[ side ]; - } - if( p != null ) - { - Object[] results = p.call( context, methodName, methodArgs ); - return results; - } - } - throw new LuaException( "No peripheral attached" ); - } - default: - { - return null; - } - } - } - - // Privates - - private Object[] trimArray( Object[] array, int skip ) - { - return Arrays.copyOfRange( array, skip, array.length ); - } - - private int parseSide( Object[] args ) throws LuaException - { - if( args.length < 1 || args[0] == null || !(args[0] instanceof String) ) - { - throw new LuaException( "Expected string" ); - } - String side = (String)args[0]; - for( int n=0; n= 0 ) + { + synchronized( m_peripherals ) + { + PeripheralWrapper p = m_peripherals[ side ]; + if( p != null ) + { + present = true; + } + } + } + return new Object[] { present }; + } + case 1: + { + // getType + String type = null; + int side = parseSide( args ); + if( side >= 0 ) + { + synchronized( m_peripherals ) + { + PeripheralWrapper p = m_peripherals[ side ]; + if( p != null ) + { + type = p.getType(); + } + } + if( type != null ) + { + return new Object[] { type }; + } + } + return null; + } + case 2: + { + // getMethods + String[] methods = null; + int side = parseSide( args ); + if( side >= 0 ) + { + synchronized( m_peripherals ) + { + PeripheralWrapper p = m_peripherals[ side ]; + if( p != null ) + { + methods = p.getMethods(); + } + } + } + if( methods != null ) + { + Map table = new HashMap(); + for(int i=0; i= 0 ) + { + PeripheralWrapper p = null; + synchronized( m_peripherals ) + { + p = m_peripherals[ side ]; + } + if( p != null ) + { + Object[] results = p.call( context, methodName, methodArgs ); + return results; + } + } + throw new LuaException( "No peripheral attached" ); + } + default: + { + return null; + } + } + } + + // Privates + + private Object[] trimArray( Object[] array, int skip ) + { + return Arrays.copyOfRange( array, skip, array.length ); + } + + private int parseSide( Object[] args ) throws LuaException + { + if( args.length < 1 || args[0] == null || !(args[0] instanceof String) ) + { + throw new LuaException( "Expected string" ); + } + String side = (String)args[0]; + for( int n=0; n table = new HashMap(); - for(int i=0; i< Computer.s_sideNames.length; ++i ) - { - table.put( i+1, Computer.s_sideNames[i] ); - } - return new Object[] { table }; - } - case 1: - { - // setOutput - if( args.length < 2 || args[0] == null || !(args[0] instanceof String) || args[1] == null || !(args[1] instanceof Boolean) ) - { - throw new LuaException( "Expected string, boolean" ); - } - int side = parseSide( args ); - boolean output = ((Boolean)args[1]).booleanValue(); - m_environment.setOutput( side, output ? 15 : 0 ); - return null; - } - case 2: - { - // getOutput - int side = parseSide( args ); - return new Object[] { m_environment.getOutput( side ) > 0 }; - } - case 3: - { - // getInput - int side = parseSide( args ); - return new Object[] { m_environment.getInput( side ) > 0 }; - } - case 4: - { - // setBundledOutput - if( args.length < 2 || args[0] == null || !(args[0] instanceof String) || args[1] == null || !(args[1] instanceof Double) ) - { - throw new LuaException( "Expected string, number" ); - } - int side = parseSide( args ); - int output = ((Double)args[1]).intValue(); - m_environment.setBundledOutput( side, output ); - return null; - } - case 5: - { - // getBundledOutput - int side = parseSide( args ); - return new Object[] { m_environment.getBundledOutput( side ) }; - } - case 6: - { - // getBundledInput - int side = parseSide( args ); - return new Object[] { m_environment.getBundledInput( side ) }; - } - case 7: - { - // testBundledInput - if( args.length < 2 || args[0] == null || !(args[0] instanceof String) || args[1] == null || !(args[1] instanceof Double) ) - { - throw new LuaException( "Expected string, number" ); - } - int side = parseSide( args ); - int mask = ((Double)args[1]).intValue(); - int input = m_environment.getBundledInput( side ); - return new Object[] { ((input & mask) == mask) }; - } - case 8: - case 9: - { - // setAnalogOutput/setAnalogueOutput - if( args.length < 2 || args[0] == null || !(args[0] instanceof String) || args[1] == null || !(args[1] instanceof Double) ) - { - throw new LuaException( "Expected string, number" ); - } - int side = parseSide( args ); - int output = ((Double)args[1]).intValue(); - if( output < 0 || output > 15 ) - { - throw new LuaException( "Expected number in range 0-15" ); - } - m_environment.setOutput( side, output ); - return null; - } - case 10: - case 11: - { - // getAnalogOutput/getAnalogueOutput - int side = parseSide( args ); - return new Object[] { m_environment.getOutput( side ) }; - } - case 12: - case 13: - { - // getAnalogInput/getAnalogueInput - int side = parseSide( args ); - return new Object[] { m_environment.getInput( side ) }; - } - default: - { - return null; - } - } - } - - private int parseSide( Object[] args ) throws LuaException - { - if( args.length < 1 || args[0] == null || !(args[0] instanceof String) ) - { - throw new LuaException( "Expected string" ); - } - String side = (String)args[0]; - for( int n=0; n table = new HashMap(); + for(int i=0; i< Computer.s_sideNames.length; ++i ) + { + table.put( i+1, Computer.s_sideNames[i] ); + } + return new Object[] { table }; + } + case 1: + { + // setOutput + if( args.length < 2 || args[0] == null || !(args[0] instanceof String) || args[1] == null || !(args[1] instanceof Boolean) ) + { + throw new LuaException( "Expected string, boolean" ); + } + int side = parseSide( args ); + boolean output = ((Boolean)args[1]).booleanValue(); + m_environment.setOutput( side, output ? 15 : 0 ); + return null; + } + case 2: + { + // getOutput + int side = parseSide( args ); + return new Object[] { m_environment.getOutput( side ) > 0 }; + } + case 3: + { + // getInput + int side = parseSide( args ); + return new Object[] { m_environment.getInput( side ) > 0 }; + } + case 4: + { + // setBundledOutput + if( args.length < 2 || args[0] == null || !(args[0] instanceof String) || args[1] == null || !(args[1] instanceof Double) ) + { + throw new LuaException( "Expected string, number" ); + } + int side = parseSide( args ); + int output = ((Double)args[1]).intValue(); + m_environment.setBundledOutput( side, output ); + return null; + } + case 5: + { + // getBundledOutput + int side = parseSide( args ); + return new Object[] { m_environment.getBundledOutput( side ) }; + } + case 6: + { + // getBundledInput + int side = parseSide( args ); + return new Object[] { m_environment.getBundledInput( side ) }; + } + case 7: + { + // testBundledInput + if( args.length < 2 || args[0] == null || !(args[0] instanceof String) || args[1] == null || !(args[1] instanceof Double) ) + { + throw new LuaException( "Expected string, number" ); + } + int side = parseSide( args ); + int mask = ((Double)args[1]).intValue(); + int input = m_environment.getBundledInput( side ); + return new Object[] { ((input & mask) == mask) }; + } + case 8: + case 9: + { + // setAnalogOutput/setAnalogueOutput + if( args.length < 2 || args[0] == null || !(args[0] instanceof String) || args[1] == null || !(args[1] instanceof Double) ) + { + throw new LuaException( "Expected string, number" ); + } + int side = parseSide( args ); + int output = ((Double)args[1]).intValue(); + if( output < 0 || output > 15 ) + { + throw new LuaException( "Expected number in range 0-15" ); + } + m_environment.setOutput( side, output ); + return null; + } + case 10: + case 11: + { + // getAnalogOutput/getAnalogueOutput + int side = parseSide( args ); + return new Object[] { m_environment.getOutput( side ) }; + } + case 12: + case 13: + { + // getAnalogInput/getAnalogueInput + int side = parseSide( args ); + return new Object[] { m_environment.getInput( side ) }; + } + default: + { + return null; + } + } + } + + private int parseSide( Object[] args ) throws LuaException + { + if( args.length < 1 || args[0] == null || !(args[0] instanceof String) ) + { + throw new LuaException( "Expected string" ); + } + String side = (String)args[0]; + for( int n=0; n 15 ) - { - throw new LuaException( "Colour out of range" ); - } - if( !_enableColours && (colour != 0 && colour != 15 && colour != 7 && colour != 8) ) - { - throw new LuaException( "Colour not supported" ); - } - return colour; + if( args.length != 1 || args[0] == null || !(args[0] instanceof Double) ) + { + throw new LuaException( "Expected number" ); + } + int colour = (int)((Double)args[0]).doubleValue(); + if( colour <= 0 ) + { + throw new LuaException( "Colour out of range" ); + } + colour = getHighestBit( colour ) - 1; + if( colour < 0 || colour > 15 ) + { + throw new LuaException( "Colour out of range" ); + } + if( !_enableColours && (colour != 0 && colour != 15 && colour != 7 && colour != 8) ) + { + throw new LuaException( "Colour not supported" ); + } + return colour; } public static Object[] encodeColour( int colour ) throws LuaException @@ -104,137 +104,137 @@ public static Object[] encodeColour( int colour ) throws LuaException @Override public Object[] callMethod( ILuaContext context, int method, Object[] args ) throws LuaException { - switch( method ) - { - case 0: - { - // write - String text; - if( args.length > 0 && args[0] != null ) { - text = args[0].toString(); - } else { - text = ""; - } - - synchronized( m_terminal ) - { - m_terminal.write( text ); - m_terminal.setCursorPos( m_terminal.getCursorX() + text.length(), m_terminal.getCursorY() ); - } - return null; - } - case 1: - { - // scroll - if( args.length != 1 || args[0] == null || !(args[0] instanceof Double) ) - { - throw new LuaException( "Expected number" ); - } - - int y = (int)((Double)args[0]).doubleValue(); - synchronized( m_terminal ) - { - m_terminal.scroll(y); - } - return null; - } - case 2: - { - // setCursorPos - if( args.length != 2 || args[0] == null || !(args[0] instanceof Double) || args[1] == null || !(args[1] instanceof Double) ) - { - throw new LuaException( "Expected number, number" ); - } - int x = (int)((Double)args[0]).doubleValue() - 1; - int y = (int)((Double)args[1]).doubleValue() - 1; - synchronized( m_terminal ) - { - m_terminal.setCursorPos( x, y ); - } - return null; - } - case 3: - { - // setCursorBlink - if( args.length != 1 || args[0] == null || !(args[0] instanceof Boolean) ) - { - throw new LuaException( "Expected boolean" ); - } - boolean b = ((Boolean)args[0]).booleanValue(); - synchronized( m_terminal ) - { - m_terminal.setCursorBlink( b ); - } - return null; - } - case 4: - { - // getCursorPos - int x, y; - synchronized( m_terminal ) - { - x = m_terminal.getCursorX(); - y = m_terminal.getCursorY(); - } - return new Object[] { x + 1, y + 1 }; - } - case 5: - { - // getSize - int width, height; - synchronized( m_terminal ) - { - width = m_terminal.getWidth(); - height = m_terminal.getHeight(); - } - return new Object[] { width, height }; - } - case 6: - { - // clear - synchronized( m_terminal ) - { - m_terminal.clear(); - } - return null; - } - case 7: - { - // clearLine - synchronized( m_terminal ) - { - m_terminal.clearLine(); - } - return null; - } - case 8: - case 9: - { - // setTextColour/setTextColor - int colour = parseColour( args, m_environment.isColour() ); - synchronized( m_terminal ) - { - m_terminal.setTextColour( colour ); - } - return null; - } - case 10: - case 11: - { - // setBackgroundColour/setBackgroundColor - int colour = parseColour( args, m_environment.isColour() ); - synchronized( m_terminal ) - { - m_terminal.setBackgroundColour( colour ); - } - return null; - } - case 12: - case 13: - { - // isColour/isColor - return new Object[] { m_environment.isColour() }; - } + switch( method ) + { + case 0: + { + // write + String text; + if( args.length > 0 && args[0] != null ) { + text = args[0].toString(); + } else { + text = ""; + } + + synchronized( m_terminal ) + { + m_terminal.write( text ); + m_terminal.setCursorPos( m_terminal.getCursorX() + text.length(), m_terminal.getCursorY() ); + } + return null; + } + case 1: + { + // scroll + if( args.length != 1 || args[0] == null || !(args[0] instanceof Double) ) + { + throw new LuaException( "Expected number" ); + } + + int y = (int)((Double)args[0]).doubleValue(); + synchronized( m_terminal ) + { + m_terminal.scroll(y); + } + return null; + } + case 2: + { + // setCursorPos + if( args.length != 2 || args[0] == null || !(args[0] instanceof Double) || args[1] == null || !(args[1] instanceof Double) ) + { + throw new LuaException( "Expected number, number" ); + } + int x = (int)((Double)args[0]).doubleValue() - 1; + int y = (int)((Double)args[1]).doubleValue() - 1; + synchronized( m_terminal ) + { + m_terminal.setCursorPos( x, y ); + } + return null; + } + case 3: + { + // setCursorBlink + if( args.length != 1 || args[0] == null || !(args[0] instanceof Boolean) ) + { + throw new LuaException( "Expected boolean" ); + } + boolean b = ((Boolean)args[0]).booleanValue(); + synchronized( m_terminal ) + { + m_terminal.setCursorBlink( b ); + } + return null; + } + case 4: + { + // getCursorPos + int x, y; + synchronized( m_terminal ) + { + x = m_terminal.getCursorX(); + y = m_terminal.getCursorY(); + } + return new Object[] { x + 1, y + 1 }; + } + case 5: + { + // getSize + int width, height; + synchronized( m_terminal ) + { + width = m_terminal.getWidth(); + height = m_terminal.getHeight(); + } + return new Object[] { width, height }; + } + case 6: + { + // clear + synchronized( m_terminal ) + { + m_terminal.clear(); + } + return null; + } + case 7: + { + // clearLine + synchronized( m_terminal ) + { + m_terminal.clearLine(); + } + return null; + } + case 8: + case 9: + { + // setTextColour/setTextColor + int colour = parseColour( args, m_environment.isColour() ); + synchronized( m_terminal ) + { + m_terminal.setTextColour( colour ); + } + return null; + } + case 10: + case 11: + { + // setBackgroundColour/setBackgroundColor + int colour = parseColour( args, m_environment.isColour() ); + synchronized( m_terminal ) + { + m_terminal.setBackgroundColour( colour ); + } + return null; + } + case 12: + case 13: + { + // isColour/isColor + return new Object[] { m_environment.isColour() }; + } case 14: case 15: { @@ -270,21 +270,21 @@ public Object[] callMethod( ILuaContext context, int method, Object[] args ) thr } return null; } - default: - { - return null; - } - } - } - - private static int getHighestBit( int group ) - { - int bit = 0; - while( group > 0 ) - { - group >>= 1; - bit++; - } - return bit; - } + default: + { + return null; + } + } + } + + private static int getHighestBit( int group ) + { + int bit = 0; + while( group > 0 ) + { + group >>= 1; + bit++; + } + return bit; + } } diff --git a/src/main/java/dan200/computercraft/core/computer/Computer.java b/src/main/java/dan200/computercraft/core/computer/Computer.java index 5d47982bd..6b3840e8f 100644 --- a/src/main/java/dan200/computercraft/core/computer/Computer.java +++ b/src/main/java/dan200/computercraft/core/computer/Computer.java @@ -25,71 +25,71 @@ import java.util.List; public class Computer -{ - public static final String[] s_sideNames = new String[] { - "bottom", "top", "back", "front", "right", "left", - }; - - private static enum State - { - Off, +{ + public static final String[] s_sideNames = new String[] { + "bottom", "top", "back", "front", "right", "left", + }; + + private static enum State + { + Off, Starting, Running, Stopping, - } - - private static class APIEnvironment implements IAPIEnvironment - { - private Computer m_computer; - private IAPIEnvironment.IPeripheralChangeListener m_peripheralListener; - - public APIEnvironment( Computer computer ) - { - m_computer = computer; - m_peripheralListener = null; - } - - @Override - public Computer getComputer() - { - return m_computer; - } + } + + private static class APIEnvironment implements IAPIEnvironment + { + private Computer m_computer; + private IAPIEnvironment.IPeripheralChangeListener m_peripheralListener; + + public APIEnvironment( Computer computer ) + { + m_computer = computer; + m_peripheralListener = null; + } + + @Override + public Computer getComputer() + { + return m_computer; + } - @Override - public int getComputerID() - { - return m_computer.assignID(); - } - - @Override - public IComputerEnvironment getComputerEnvironment() - { - return m_computer.m_environment; - } - - @Override - public Terminal getTerminal() - { - return m_computer.m_terminal; - } - - @Override - public FileSystem getFileSystem() - { - return m_computer.m_fileSystem; - } + @Override + public int getComputerID() + { + return m_computer.assignID(); + } + + @Override + public IComputerEnvironment getComputerEnvironment() + { + return m_computer.m_environment; + } + + @Override + public Terminal getTerminal() + { + return m_computer.m_terminal; + } + + @Override + public FileSystem getFileSystem() + { + return m_computer.m_fileSystem; + } - @Override - public void shutdown() - { - m_computer.shutdown(); - } + @Override + public void shutdown() + { + m_computer.shutdown(); + } - @Override - public void reboot() - { - m_computer.reboot(); - } + @Override + public void reboot() + { + m_computer.reboot(); + } @Override public void queueEvent( String event, Object[] args ) @@ -97,59 +97,59 @@ public void queueEvent( String event, Object[] args ) m_computer.queueEvent( event, args ); } - @Override - public void setOutput( int side, int output ) - { - m_computer.setRedstoneOutput( side, output ); - } - - @Override - public int getOutput( int side ) - { - return m_computer.getInternalRedstoneOutput( side ); - } - - @Override - public int getInput( int side ) - { - return m_computer.getRedstoneInput( side ); - } - - @Override - public void setBundledOutput( int side, int output ) - { - m_computer.setBundledRedstoneOutput( side, output ); - } + @Override + public void setOutput( int side, int output ) + { + m_computer.setRedstoneOutput( side, output ); + } + + @Override + public int getOutput( int side ) + { + return m_computer.getInternalRedstoneOutput( side ); + } + + @Override + public int getInput( int side ) + { + return m_computer.getRedstoneInput( side ); + } + + @Override + public void setBundledOutput( int side, int output ) + { + m_computer.setBundledRedstoneOutput( side, output ); + } - @Override - public int getBundledOutput( int side ) - { - return m_computer.getInternalBundledRedstoneOutput( side ); - } - - @Override - public int getBundledInput( int side ) - { - return m_computer.getBundledRedstoneInput( side ); - } - - @Override - public IPeripheral getPeripheral( int side ) - { - synchronized( m_computer.m_peripherals ) - { - return m_computer.m_peripherals[ side ]; - } - } - - @Override - public void setPeripheralChangeListener( IPeripheralChangeListener listener ) - { - synchronized( m_computer.m_peripherals ) - { - m_peripheralListener = listener; - } - } + @Override + public int getBundledOutput( int side ) + { + return m_computer.getInternalBundledRedstoneOutput( side ); + } + + @Override + public int getBundledInput( int side ) + { + return m_computer.getBundledRedstoneInput( side ); + } + + @Override + public IPeripheral getPeripheral( int side ) + { + synchronized( m_computer.m_peripherals ) + { + return m_computer.m_peripherals[ side ]; + } + } + + @Override + public void setPeripheralChangeListener( IPeripheralChangeListener listener ) + { + synchronized( m_computer.m_peripherals ) + { + m_peripheralListener = listener; + } + } @Override public String getLabel() @@ -164,148 +164,148 @@ public void setLabel( String label ) } public void onPeripheralChanged( int side, IPeripheral peripheral ) - { - synchronized( m_computer.m_peripherals ) - { - if( m_peripheralListener != null ) - { - m_peripheralListener.onPeripheralChanged( side, peripheral ); - } - } - } - } - - private static IMount s_romMount = null; + { + synchronized( m_computer.m_peripherals ) + { + if( m_peripheralListener != null ) + { + m_peripheralListener.onPeripheralChanged( side, peripheral ); + } + } + } + } + + private static IMount s_romMount = null; private int m_id; private String m_label; - private final IComputerEnvironment m_environment; + private final IComputerEnvironment m_environment; private int m_ticksSinceStart; private boolean m_startRequested; - private State m_state; + private State m_state; private boolean m_blinking; - private ILuaMachine m_machine; - private List m_apis; - private APIEnvironment m_apiEnvironment; - - private Terminal m_terminal; - private FileSystem m_fileSystem; + private ILuaMachine m_machine; + private List m_apis; + private APIEnvironment m_apiEnvironment; + + private Terminal m_terminal; + private FileSystem m_fileSystem; private IWritableMount m_rootMount; - private int[] m_internalOutput; - private int[] m_internalBundledOutput; - private boolean m_internalOutputChanged; + private int[] m_internalOutput; + private int[] m_internalBundledOutput; + private boolean m_internalOutputChanged; private int[] m_externalOutput; private int[] m_externalBundledOutput; private boolean m_externalOutputChanged; private int[] m_input; - private int[] m_bundledInput; - private boolean m_inputChanged; - - private IPeripheral[] m_peripherals; + private int[] m_bundledInput; + private boolean m_inputChanged; + + private IPeripheral[] m_peripherals; - public Computer( IComputerEnvironment environment, Terminal terminal, int id ) - { - ComputerThread.start(); + public Computer( IComputerEnvironment environment, Terminal terminal, int id ) + { + ComputerThread.start(); m_id = id; m_label = null; - m_environment = environment; + m_environment = environment; m_ticksSinceStart = -1; m_startRequested = false; - m_state = State.Off; + m_state = State.Off; m_blinking = false; - m_terminal = terminal; - m_fileSystem = null; + m_terminal = terminal; + m_fileSystem = null; - m_machine = null; - m_apis = new ArrayList(); - m_apiEnvironment = new APIEnvironment( this ); + m_machine = null; + m_apis = new ArrayList(); + m_apiEnvironment = new APIEnvironment( this ); - m_internalOutput = new int[6]; - m_internalBundledOutput = new int[6]; - m_internalOutputChanged = true; + m_internalOutput = new int[6]; + m_internalBundledOutput = new int[6]; + m_internalOutputChanged = true; m_externalOutput = new int[6]; m_externalBundledOutput = new int[6]; m_externalOutputChanged = true; m_input = new int[6]; - m_bundledInput = new int[6]; - m_inputChanged = false; - - m_peripherals = new IPeripheral[6]; - for( int i=0; i<6; ++i ) + m_bundledInput = new int[6]; + m_inputChanged = false; + + m_peripherals = new IPeripheral[6]; + for( int i=0; i<6; ++i ) { - m_peripherals[i] = null; - } + m_peripherals[i] = null; + } m_rootMount = null; createAPIs(); - } - - public IAPIEnvironment getAPIEnvironment() - { - return m_apiEnvironment; - } - - public void turnOn() - { + } + + public IAPIEnvironment getAPIEnvironment() + { + return m_apiEnvironment; + } + + public void turnOn() + { if( m_state == State.Off ) { m_startRequested = true; } - } - - public void shutdown() - { - stopComputer( false ); - } - - public void reboot() - { - stopComputer( true ); - } - - public boolean isOn() - { - synchronized( this ) - { - return m_state == State.Running; - } - } - - public void abort( boolean hard ) - { - synchronized( this ) - { - if( m_state == State.Running ) - { - if( hard ) - { - m_machine.hardAbort( "Too long without yielding" ); - } - else - { - m_machine.softAbort( "Too long without yielding" ); - } - } - } - } - - public void unload() - { - synchronized( this ) - { + } + + public void shutdown() + { + stopComputer( false ); + } + + public void reboot() + { + stopComputer( true ); + } + + public boolean isOn() + { + synchronized( this ) + { + return m_state == State.Running; + } + } + + public void abort( boolean hard ) + { + synchronized( this ) + { + if( m_state == State.Running ) + { + if( hard ) + { + m_machine.hardAbort( "Too long without yielding" ); + } + else + { + m_machine.softAbort( "Too long without yielding" ); + } + } + } + } + + public void unload() + { + synchronized( this ) + { stopComputer( false ); - } - } + } + } public int getID() { @@ -340,45 +340,45 @@ public void setLabel( String label ) } } - public void advance( double _dt ) - { - synchronized( this ) - { - // Start after a number of ticks + public void advance( double _dt ) + { + synchronized( this ) + { + // Start after a number of ticks if( m_ticksSinceStart >= 0 ) { m_ticksSinceStart++; } if( m_startRequested && (m_ticksSinceStart < 0 || m_ticksSinceStart > 50) ) - { + { startComputer(); m_startRequested = false; - } - - if( m_state == State.Running ) - { - // Fire the redstone event if our redstone input has changed - synchronized( m_input ) - { - if( m_inputChanged ) - { - queueEvent( "redstone", null ); - m_inputChanged = false; - } - } + } + + if( m_state == State.Running ) + { + // Fire the redstone event if our redstone input has changed + synchronized( m_input ) + { + if( m_inputChanged ) + { + queueEvent( "redstone", null ); + m_inputChanged = false; + } + } - // Advance our APIs - synchronized( m_apis ) - { - Iterator it = m_apis.iterator(); - while( it.hasNext() ) - { - ILuaAPI api = it.next(); - api.advance( _dt ); - } - } - } - } + // Advance our APIs + synchronized( m_apis ) + { + Iterator it = m_apis.iterator(); + while( it.hasNext() ) + { + ILuaAPI api = it.next(); + api.advance( _dt ); + } + } + } + } // Set outputchanged if the internal redstone has changed synchronized( m_internalOutput ) @@ -406,40 +406,40 @@ public void advance( double _dt ) } } } - - // Set outputchanged if the terminal has changed from blinking to not - synchronized( m_terminal ) - { - boolean blinking = - m_terminal.getCursorBlink() && - m_terminal.getCursorX() >= 0 && m_terminal.getCursorX() < m_terminal.getWidth() && - m_terminal.getCursorY() >= 0 && m_terminal.getCursorY() < m_terminal.getHeight(); + + // Set outputchanged if the terminal has changed from blinking to not + synchronized( m_terminal ) + { + boolean blinking = + m_terminal.getCursorBlink() && + m_terminal.getCursorX() >= 0 && m_terminal.getCursorX() < m_terminal.getWidth() && + m_terminal.getCursorY() >= 0 && m_terminal.getCursorY() < m_terminal.getHeight(); - if( blinking != m_blinking ) - { + if( blinking != m_blinking ) + { m_blinking = blinking; m_externalOutputChanged = true; - } - } - } - - public boolean pollChanged() - { + } + } + } + + public boolean pollChanged() + { return m_externalOutputChanged; - } + } public void clearChanged() { m_externalOutputChanged = false; } - public boolean isBlinking() - { - synchronized( m_terminal ) - { - return isOn() && m_blinking; - } - } + public boolean isBlinking() + { + synchronized( m_terminal ) + { + return isOn() && m_blinking; + } + } public IWritableMount getRootMount() { @@ -449,35 +449,35 @@ public IWritableMount getRootMount() } return m_rootMount; } - - // FileSystem - - private boolean initFileSystem() - { - // Create the file system - int id = assignID(); - try - { - m_fileSystem = new FileSystem( "hdd", getRootMount() ); - if( s_romMount == null ) - { - s_romMount = m_environment.createResourceMount( "computercraft", "lua/rom" ); - } - if( s_romMount != null ) - { - m_fileSystem.mount( "rom", "rom", s_romMount ); - return true; - } - return false; - } - catch( FileSystemException e ) - { - e.printStackTrace(); - return false; - } - } - - // Redstone + + // FileSystem + + private boolean initFileSystem() + { + // Create the file system + int id = assignID(); + try + { + m_fileSystem = new FileSystem( "hdd", getRootMount() ); + if( s_romMount == null ) + { + s_romMount = m_environment.createResourceMount( "computercraft", "lua/rom" ); + } + if( s_romMount != null ) + { + m_fileSystem.mount( "rom", "rom", s_romMount ); + return true; + } + return false; + } + catch( FileSystemException e ) + { + e.printStackTrace(); + return false; + } + } + + // Redstone public int getRedstoneOutput( int side ) { @@ -528,12 +528,12 @@ private int getRedstoneInput( int side ) } public int getBundledRedstoneOutput( int side ) - { - synchronized( m_internalOutput ) - { - return isOn() ? m_externalBundledOutput[side] : 0; - } - } + { + synchronized( m_internalOutput ) + { + return isOn() ? m_externalBundledOutput[side] : 0; + } + } private int getInternalBundledRedstoneOutput( int side ) { @@ -555,47 +555,47 @@ private void setBundledRedstoneOutput( int side, int combination ) } } - public void setBundledRedstoneInput( int side, int combination ) - { - synchronized( m_input ) - { - if( m_bundledInput[side] != combination ) + public void setBundledRedstoneInput( int side, int combination ) + { + synchronized( m_input ) + { + if( m_bundledInput[side] != combination ) { - m_bundledInput[side] = combination; - m_inputChanged = true; - } - } - } - - private int getBundledRedstoneInput( int side ) - { - synchronized( m_input ) - { - return m_bundledInput[side]; - } - } + m_bundledInput[side] = combination; + m_inputChanged = true; + } + } + } + + private int getBundledRedstoneInput( int side ) + { + synchronized( m_input ) + { + return m_bundledInput[side]; + } + } - // Peripherals - - public void addAPI( ILuaAPI api ) - { - m_apis.add( api ); - } - - public void setPeripheral( int side, IPeripheral peripheral ) - { - synchronized( m_peripherals ) - { + // Peripherals + + public void addAPI( ILuaAPI api ) + { + m_apis.add( api ); + } + + public void setPeripheral( int side, IPeripheral peripheral ) + { + synchronized( m_peripherals ) + { IPeripheral existing = m_peripherals[side]; - if( (existing == null && peripheral != null) || + if( (existing == null && peripheral != null) || (existing != null && peripheral == null) || (existing != null && !existing.equals( peripheral )) ) - { - m_peripherals[side] = peripheral; - m_apiEnvironment.onPeripheralChanged( side, peripheral ); - } - } - } + { + m_peripherals[side] = peripheral; + m_apiEnvironment.onPeripheralChanged( side, peripheral ); + } + } + } public IPeripheral getPeripheral( int side ) { @@ -604,291 +604,291 @@ public IPeripheral getPeripheral( int side ) return m_peripherals[side]; } } - - // Lua - - private void createAPIs() - { - m_apis.add( new TermAPI( m_apiEnvironment ) ); - m_apis.add( new RedstoneAPI( m_apiEnvironment ) ); - m_apis.add( new FSAPI( m_apiEnvironment ) ); - m_apis.add( new PeripheralAPI( m_apiEnvironment ) ); - m_apis.add( new OSAPI( m_apiEnvironment ) ); - m_apis.add( new BitAPI( m_apiEnvironment ) ); + + // Lua + + private void createAPIs() + { + m_apis.add( new TermAPI( m_apiEnvironment ) ); + m_apis.add( new RedstoneAPI( m_apiEnvironment ) ); + m_apis.add( new FSAPI( m_apiEnvironment ) ); + m_apis.add( new PeripheralAPI( m_apiEnvironment ) ); + m_apis.add( new OSAPI( m_apiEnvironment ) ); + m_apis.add( new BitAPI( m_apiEnvironment ) ); //m_apis.add( new BufferAPI( m_apiEnvironment ) ); - if( ComputerCraft.http_enable ) - { - m_apis.add( new HTTPAPI( m_apiEnvironment ) ); - } - } - - private void initLua() - { - // Create the lua machine - ILuaMachine machine = new LuaJLuaMachine( this ); - - // Add the APIs - Iterator it = m_apis.iterator(); - while( it.hasNext() ) - { - ILuaAPI api = it.next(); - machine.addAPI( api ); - api.startup(); - } - - // Load the bios resource - InputStream biosStream; - try - { - biosStream = Computer.class.getResourceAsStream( "/assets/computercraft/lua/bios.lua" ); - } - catch( Exception e ) - { - biosStream = null; - } - - // Start the machine running the bios resource - if( biosStream != null ) - { - machine.loadBios( biosStream ); - try { - biosStream.close(); - } catch( IOException e ) { - // meh - } - - if( machine.isFinished() ) - { + if( ComputerCraft.http_enable ) + { + m_apis.add( new HTTPAPI( m_apiEnvironment ) ); + } + } + + private void initLua() + { + // Create the lua machine + ILuaMachine machine = new LuaJLuaMachine( this ); + + // Add the APIs + Iterator it = m_apis.iterator(); + while( it.hasNext() ) + { + ILuaAPI api = it.next(); + machine.addAPI( api ); + api.startup(); + } + + // Load the bios resource + InputStream biosStream; + try + { + biosStream = Computer.class.getResourceAsStream( "/assets/computercraft/lua/bios.lua" ); + } + catch( Exception e ) + { + biosStream = null; + } + + // Start the machine running the bios resource + if( biosStream != null ) + { + machine.loadBios( biosStream ); + try { + biosStream.close(); + } catch( IOException e ) { + // meh + } + + if( machine.isFinished() ) + { m_terminal.reset(); - m_terminal.write("Error starting bios.lua" ); + m_terminal.write("Error starting bios.lua" ); m_terminal.setCursorPos( 0, 1 ); m_terminal.write( "ComputerCraft may be installed incorrectly" ); - machine.unload(); - m_machine = null; - } - else - { - m_machine = machine; - } - } - else - { + machine.unload(); + m_machine = null; + } + else + { + m_machine = machine; + } + } + else + { m_terminal.reset(); m_terminal.write("Error loading bios.lua" ); m_terminal.setCursorPos( 0, 1 ); m_terminal.write( "ComputerCraft may be installed incorrectly" ); - machine.unload(); - m_machine = null; - } - } - - private void startComputer() - { - synchronized( this ) - { - if( m_state != State.Off ) - { - return; - } - m_state = State.Starting; - m_ticksSinceStart = 0; - } - - // Turn the computercraft on - final Computer computer = this; - ComputerThread.queueTask( new ITask() { - @Override - public Computer getOwner() + machine.unload(); + m_machine = null; + } + } + + private void startComputer() + { + synchronized( this ) + { + if( m_state != State.Off ) { - return computer; - } + return; + } + m_state = State.Starting; + m_ticksSinceStart = 0; + } + + // Turn the computercraft on + final Computer computer = this; + ComputerThread.queueTask( new ITask() { + @Override + public Computer getOwner() + { + return computer; + } @Override - public void execute() + public void execute() { - synchronized( this ) - { - if( m_state != State.Starting ) - { - return; - } - - // Init terminal - synchronized( m_terminal ) - { + synchronized( this ) + { + if( m_state != State.Starting ) + { + return; + } + + // Init terminal + synchronized( m_terminal ) + { m_terminal.reset(); - } - - // Init filesystem - if( !initFileSystem() ) - { - // Init failed, so shutdown + } + + // Init filesystem + if( !initFileSystem() ) + { + // Init failed, so shutdown m_terminal.reset(); m_terminal.write( "Error mounting lua/rom" ); m_terminal.setCursorPos( 0, 1 ); m_terminal.write( "ComputerCraft may be installed incorrectly" ); - m_state = State.Running; - stopComputer( false ); - return; - } - - // Init lua - initLua(); - if( m_machine == null ) - { + m_state = State.Running; + stopComputer( false ); + return; + } + + // Init lua + initLua(); + if( m_machine == null ) + { m_terminal.reset(); m_terminal.write( "Error loading bios.lua" ); m_terminal.setCursorPos( 0, 1 ); m_terminal.write( "ComputerCraft may be installed incorrectly" ); - // Init failed, so shutdown - m_state = State.Running; - stopComputer( false ); - return; - } - + // Init failed, so shutdown + m_state = State.Running; + stopComputer( false ); + return; + } + // Start a new state m_state = State.Running; synchronized( m_machine ) { m_machine.handleEvent( null, null ); } - } - } - }, computer ); - } - - private void stopComputer( final boolean reboot ) - { - synchronized( this ) - { - if( m_state != State.Running ) - { - return; - } - m_state = State.Stopping; - } - - // Turn the computercraft off - final Computer computer = this; - ComputerThread.queueTask( new ITask() { - @Override - public Computer getOwner() + } + } + }, computer ); + } + + private void stopComputer( final boolean reboot ) + { + synchronized( this ) + { + if( m_state != State.Running ) { - return computer; - } - + return; + } + m_state = State.Stopping; + } + + // Turn the computercraft off + final Computer computer = this; + ComputerThread.queueTask( new ITask() { @Override - public void execute() - { - synchronized( this ) - { - if( m_state != State.Stopping ) - { - return; - } - - // Shutdown our APIs - synchronized( m_apis ) - { - Iterator it = m_apis.iterator(); - while( it.hasNext() ) - { - ILuaAPI api = it.next(); - api.shutdown(); - } - } - - // Shutdown terminal and filesystem - if( m_fileSystem != null ) - { - m_fileSystem.unload(); - m_fileSystem = null; - } - - if( m_machine != null ) - { - synchronized( m_terminal ) - { - m_terminal.reset(); - } - - synchronized( m_machine ) - { - m_machine.unload(); - m_machine = null; - } - } - - // Reset redstone output - synchronized( m_internalOutput ) - { - for( int i=0; i<6; ++i ) - { - m_internalOutput[i] = 0; - m_internalBundledOutput[i] = 0; - } - m_internalOutputChanged = true; - } - - m_state = State.Off; - if( reboot ) - { - m_startRequested = true; - } - } - } - }, computer ); - } - - public void queueEvent( final String event, final Object[] arguments ) - { - synchronized( this ) - { - if( m_state != State.Running ) - { - return; - } - } - - final Computer computer = this; - ITask task = new ITask() { - @Override - public Computer getOwner() + public Computer getOwner() { - return computer; - } + return computer; + } @Override public void execute() { - synchronized( this ) - { - if( m_state != State.Running ) - { - return; - } - } - - synchronized( m_machine ) - { - m_machine.handleEvent( event, arguments ); - if( m_machine.isFinished() ) - { + synchronized( this ) + { + if( m_state != State.Stopping ) + { + return; + } + + // Shutdown our APIs + synchronized( m_apis ) + { + Iterator it = m_apis.iterator(); + while( it.hasNext() ) + { + ILuaAPI api = it.next(); + api.shutdown(); + } + } + + // Shutdown terminal and filesystem + if( m_fileSystem != null ) + { + m_fileSystem.unload(); + m_fileSystem = null; + } + + if( m_machine != null ) + { + synchronized( m_terminal ) + { + m_terminal.reset(); + } + + synchronized( m_machine ) + { + m_machine.unload(); + m_machine = null; + } + } + + // Reset redstone output + synchronized( m_internalOutput ) + { + for( int i=0; i<6; ++i ) + { + m_internalOutput[i] = 0; + m_internalBundledOutput[i] = 0; + } + m_internalOutputChanged = true; + } + + m_state = State.Off; + if( reboot ) + { + m_startRequested = true; + } + } + } + }, computer ); + } + + public void queueEvent( final String event, final Object[] arguments ) + { + synchronized( this ) + { + if( m_state != State.Running ) + { + return; + } + } + + final Computer computer = this; + ITask task = new ITask() { + @Override + public Computer getOwner() + { + return computer; + } + + @Override + public void execute() + { + synchronized( this ) + { + if( m_state != State.Running ) + { + return; + } + } + + synchronized( m_machine ) + { + m_machine.handleEvent( event, arguments ); + if( m_machine.isFinished() ) + { m_terminal.reset(); m_terminal.write( "Error resuming bios.lua" ); m_terminal.setCursorPos( 0, 1 ); m_terminal.write( "ComputerCraft may be installed incorrectly" ); - stopComputer( false ); - } - } - } - }; - - ComputerThread.queueTask( task, computer ); - } + stopComputer( false ); + } + } + } + }; + + ComputerThread.queueTask( task, computer ); + } } diff --git a/src/main/java/dan200/computercraft/core/computer/ComputerThread.java b/src/main/java/dan200/computercraft/core/computer/ComputerThread.java index def6d3eec..458c0e93a 100644 --- a/src/main/java/dan200/computercraft/core/computer/ComputerThread.java +++ b/src/main/java/dan200/computercraft/core/computer/ComputerThread.java @@ -10,206 +10,206 @@ import java.util.Iterator; import java.util.WeakHashMap; import java.util.concurrent.LinkedBlockingQueue; - + public class ComputerThread { - private static Object m_lock; - - private static Thread m_thread; - private static WeakHashMap > m_computerTasks; - private static ArrayList > m_computerTasksActive; - private static ArrayList > m_computerTasksPending; - private static Object m_defaultQueue; - private static Object m_monitor; + private static Object m_lock; + + private static Thread m_thread; + private static WeakHashMap > m_computerTasks; + private static ArrayList > m_computerTasksActive; + private static ArrayList > m_computerTasksPending; + private static Object m_defaultQueue; + private static Object m_monitor; - private static boolean m_running; - private static boolean m_stopped; - - static - { - m_lock = new Object(); - m_thread = null; - m_computerTasks = new WeakHashMap>(); - m_computerTasksPending = new ArrayList>(); - m_computerTasksActive = new ArrayList>(); - m_defaultQueue = new Object(); - m_monitor = new Object(); - m_running = false; - m_stopped = false; - } - - public static void start() - { - synchronized( m_lock ) - { - if( m_running ) - { - m_stopped = false; - return; - } - - m_thread = new Thread( new Runnable() { - public void run() - { - while( true ) - { - synchronized( m_computerTasksPending ) - { - if (!m_computerTasksPending.isEmpty()) - { - Iterator> it = m_computerTasksPending.iterator(); - while(it.hasNext()) - { - LinkedBlockingQueue queue = it.next(); - - if (!m_computerTasksActive.contains(queue)) - { - m_computerTasksActive.add(queue); - } - it.remove(); - } - /* - m_computerTasksActive.addAll(m_computerTasksPending); // put any that have been added since - m_computerTasksPending.clear(); - */ - } - } - - Iterator> it = m_computerTasksActive.iterator(); - - while (it.hasNext()) - { - LinkedBlockingQueue queue = it.next(); - - if (queue == null || queue.isEmpty()) // we don't need the blocking part of the queue. Null check to ensure it exists due to a weird NPE I got - { - continue; - } - - synchronized( m_lock ) - { - if( m_stopped ) - { - m_running = false; - m_thread = null; - return; - } - } - - try - { - final ITask task = queue.take(); + private static boolean m_running; + private static boolean m_stopped; + + static + { + m_lock = new Object(); + m_thread = null; + m_computerTasks = new WeakHashMap>(); + m_computerTasksPending = new ArrayList>(); + m_computerTasksActive = new ArrayList>(); + m_defaultQueue = new Object(); + m_monitor = new Object(); + m_running = false; + m_stopped = false; + } + + public static void start() + { + synchronized( m_lock ) + { + if( m_running ) + { + m_stopped = false; + return; + } + + m_thread = new Thread( new Runnable() { + public void run() + { + while( true ) + { + synchronized( m_computerTasksPending ) + { + if (!m_computerTasksPending.isEmpty()) + { + Iterator> it = m_computerTasksPending.iterator(); + while(it.hasNext()) + { + LinkedBlockingQueue queue = it.next(); + + if (!m_computerTasksActive.contains(queue)) + { + m_computerTasksActive.add(queue); + } + it.remove(); + } + /* + m_computerTasksActive.addAll(m_computerTasksPending); // put any that have been added since + m_computerTasksPending.clear(); + */ + } + } + + Iterator> it = m_computerTasksActive.iterator(); + + while (it.hasNext()) + { + LinkedBlockingQueue queue = it.next(); + + if (queue == null || queue.isEmpty()) // we don't need the blocking part of the queue. Null check to ensure it exists due to a weird NPE I got + { + continue; + } + + synchronized( m_lock ) + { + if( m_stopped ) + { + m_running = false; + m_thread = null; + return; + } + } + + try + { + final ITask task = queue.take(); - // Create the task - Thread worker = new Thread( new Runnable() { - public void run() { - try { - task.execute(); - } catch( Throwable e ) { - System.out.println( "ComputerCraft: Error running task." ); - e.printStackTrace(); - } - } - } ); - - // Run the task - worker.start(); - worker.join( 7000 ); - - if( worker.isAlive() ) - { - // Task ran for too long - // Initiate escape plan - Computer computer = task.getOwner(); - if( computer != null ) - { - // Step 1: Soft abort - computer.abort( false ); - worker.join( 1500 ); - - if( worker.isAlive() ) - { - // Step 2: Hard abort - computer.abort( true ); - worker.join( 1500 ); - } - } - - // Step 3: abandon - if( worker.isAlive() ) - { - //System.out.println( "computercraft: Warning! Failed to abort Computer " + computercraft.getDescription() + ". Dangling lua thread could cause errors." ); - worker.interrupt(); - } - } - } - catch( InterruptedException e ) - { - continue; - } + // Create the task + Thread worker = new Thread( new Runnable() { + public void run() { + try { + task.execute(); + } catch( Throwable e ) { + System.out.println( "ComputerCraft: Error running task." ); + e.printStackTrace(); + } + } + } ); + + // Run the task + worker.start(); + worker.join( 7000 ); + + if( worker.isAlive() ) + { + // Task ran for too long + // Initiate escape plan + Computer computer = task.getOwner(); + if( computer != null ) + { + // Step 1: Soft abort + computer.abort( false ); + worker.join( 1500 ); + + if( worker.isAlive() ) + { + // Step 2: Hard abort + computer.abort( true ); + worker.join( 1500 ); + } + } + + // Step 3: abandon + if( worker.isAlive() ) + { + //System.out.println( "computercraft: Warning! Failed to abort Computer " + computercraft.getDescription() + ". Dangling lua thread could cause errors." ); + worker.interrupt(); + } + } + } + catch( InterruptedException e ) + { + continue; + } - synchronized (queue) - { - if (queue.isEmpty()) - { - it.remove(); - } - } - } - - while (m_computerTasksActive.isEmpty() && m_computerTasksPending.isEmpty()) - { - synchronized (m_monitor) - { - try - { - m_monitor.wait(); - } - catch( InterruptedException e ) - { - } - } - } - } - } - }, "Computer Dispatch Thread" ); - - m_thread.start(); - m_running = true; - } - } - - public static void stop() - { - synchronized( m_lock ) - { - if( m_running ) - { - m_stopped = true; - m_thread.interrupt(); - } - } - } - - public static void queueTask( ITask _task, Computer computer ) - { - Object queueObject = computer; - - if (queueObject == null) - { - queueObject = m_defaultQueue; - } - - LinkedBlockingQueue queue = m_computerTasks.get(queueObject); + synchronized (queue) + { + if (queue.isEmpty()) + { + it.remove(); + } + } + } + + while (m_computerTasksActive.isEmpty() && m_computerTasksPending.isEmpty()) + { + synchronized (m_monitor) + { + try + { + m_monitor.wait(); + } + catch( InterruptedException e ) + { + } + } + } + } + } + }, "Computer Dispatch Thread" ); + + m_thread.start(); + m_running = true; + } + } + + public static void stop() + { + synchronized( m_lock ) + { + if( m_running ) + { + m_stopped = true; + m_thread.interrupt(); + } + } + } + + public static void queueTask( ITask _task, Computer computer ) + { + Object queueObject = computer; + + if (queueObject == null) + { + queueObject = m_defaultQueue; + } + + LinkedBlockingQueue queue = m_computerTasks.get(queueObject); - if (queue == null) - { - m_computerTasks.put(queueObject, queue = new LinkedBlockingQueue(256)); - } - - synchronized ( m_computerTasksPending ) - { - if( queue.offer( _task ) ) + if (queue == null) + { + m_computerTasks.put(queueObject, queue = new LinkedBlockingQueue(256)); + } + + synchronized ( m_computerTasksPending ) + { + if( queue.offer( _task ) ) { if( !m_computerTasksPending.contains( queue ) ) { @@ -220,11 +220,11 @@ public static void queueTask( ITask _task, Computer computer ) { //System.out.println( "Event queue overflow" ); } - } - - synchronized (m_monitor) - { - m_monitor.notify(); - } - } + } + + synchronized (m_monitor) + { + m_monitor.notify(); + } + } } diff --git a/src/main/java/dan200/computercraft/core/computer/IComputerEnvironment.java b/src/main/java/dan200/computercraft/core/computer/IComputerEnvironment.java index f2edf326f..8e740b21a 100644 --- a/src/main/java/dan200/computercraft/core/computer/IComputerEnvironment.java +++ b/src/main/java/dan200/computercraft/core/computer/IComputerEnvironment.java @@ -11,12 +11,12 @@ public interface IComputerEnvironment { public int getDay(); - public double getTimeOfDay(); - public boolean isColour(); - public long getComputerSpaceLimit(); + public double getTimeOfDay(); + public boolean isColour(); + public long getComputerSpaceLimit(); public String getHostString(); public int assignNewID(); public IWritableMount createSaveDirMount( String subPath, long capacity ); - public IMount createResourceMount( String domain, String subPath ); + public IMount createResourceMount( String domain, String subPath ); } diff --git a/src/main/java/dan200/computercraft/core/filesystem/ComboMount.java b/src/main/java/dan200/computercraft/core/filesystem/ComboMount.java index 8474d1ca7..b02494f22 100644 --- a/src/main/java/dan200/computercraft/core/filesystem/ComboMount.java +++ b/src/main/java/dan200/computercraft/core/filesystem/ComboMount.java @@ -16,113 +16,113 @@ import java.util.Set; public class ComboMount implements IMount -{ - private IMount[] m_parts; - - public ComboMount( IMount[] parts ) - { - m_parts = parts; - } - - // IMount implementation - - @Override - public boolean exists( String path ) throws IOException - { - for( int i=m_parts.length-1; i>=0; --i ) - { - IMount part = m_parts[i]; - if( part.exists( path ) ) - { - return true; - } - } - return false; - } - - @Override - public boolean isDirectory( String path ) throws IOException - { - for( int i=m_parts.length-1; i>=0; --i ) - { - IMount part = m_parts[i]; - if( part.isDirectory( path ) ) - { - return true; - } - } - return false; - } - - @Override - public void list( String path, List contents ) throws IOException - { - // Combine the lists from all the mounts - List foundFiles = null; - int foundDirs = 0; - for( int i=m_parts.length-1; i>=0; --i ) - { - IMount part = m_parts[i]; - if( part.exists( path ) && part.isDirectory( path ) ) - { - if( foundFiles == null ) - { - foundFiles = new ArrayList(); - } - part.list( path, foundFiles ); - foundDirs++; - } - } - - if( foundDirs == 1 ) - { - // We found one directory, so we know it already doesn't contain duplicates - contents.addAll( foundFiles ); - } - else if( foundDirs > 1 ) - { - // We found multiple directories, so filter for duplicates - Set seen = new HashSet(); - for( int i=0; i=0; --i ) - { - IMount part = m_parts[i]; - if( part.exists( path ) ) - { - return part.getSize( path ); - } - } - throw new IOException( "No such file" ); - } +{ + private IMount[] m_parts; + + public ComboMount( IMount[] parts ) + { + m_parts = parts; + } + + // IMount implementation + + @Override + public boolean exists( String path ) throws IOException + { + for( int i=m_parts.length-1; i>=0; --i ) + { + IMount part = m_parts[i]; + if( part.exists( path ) ) + { + return true; + } + } + return false; + } + + @Override + public boolean isDirectory( String path ) throws IOException + { + for( int i=m_parts.length-1; i>=0; --i ) + { + IMount part = m_parts[i]; + if( part.isDirectory( path ) ) + { + return true; + } + } + return false; + } + + @Override + public void list( String path, List contents ) throws IOException + { + // Combine the lists from all the mounts + List foundFiles = null; + int foundDirs = 0; + for( int i=m_parts.length-1; i>=0; --i ) + { + IMount part = m_parts[i]; + if( part.exists( path ) && part.isDirectory( path ) ) + { + if( foundFiles == null ) + { + foundFiles = new ArrayList(); + } + part.list( path, foundFiles ); + foundDirs++; + } + } + + if( foundDirs == 1 ) + { + // We found one directory, so we know it already doesn't contain duplicates + contents.addAll( foundFiles ); + } + else if( foundDirs > 1 ) + { + // We found multiple directories, so filter for duplicates + Set seen = new HashSet(); + for( int i=0; i=0; --i ) + { + IMount part = m_parts[i]; + if( part.exists( path ) ) + { + return part.getSize( path ); + } + } + throw new IOException( "No such file" ); + } - @Override - public InputStream openForRead( String path ) throws IOException - { - for( int i=m_parts.length-1; i>=0; --i ) - { - IMount part = m_parts[i]; - if( part.exists( path ) && !part.isDirectory( path ) ) - { - return part.openForRead( path ); - } - } - throw new IOException( "No such file" ); - } + @Override + public InputStream openForRead( String path ) throws IOException + { + for( int i=m_parts.length-1; i>=0; --i ) + { + IMount part = m_parts[i]; + if( part.exists( path ) && !part.isDirectory( path ) ) + { + return part.openForRead( path ); + } + } + throw new IOException( "No such file" ); + } } diff --git a/src/main/java/dan200/computercraft/core/filesystem/EmptyMount.java b/src/main/java/dan200/computercraft/core/filesystem/EmptyMount.java index 85190b95d..4239762b5 100644 --- a/src/main/java/dan200/computercraft/core/filesystem/EmptyMount.java +++ b/src/main/java/dan200/computercraft/core/filesystem/EmptyMount.java @@ -13,39 +13,39 @@ import java.util.List; public class EmptyMount implements IMount -{ - public EmptyMount() - { - } - - // IMount implementation - - @Override - public boolean exists( String path ) throws IOException - { - return path.isEmpty(); - } - - @Override - public boolean isDirectory( String path ) throws IOException - { - return path.isEmpty(); - } - - @Override - public void list( String path, List contents ) throws IOException - { - } - - @Override - public long getSize( String path ) throws IOException - { - return 0; - } +{ + public EmptyMount() + { + } + + // IMount implementation + + @Override + public boolean exists( String path ) throws IOException + { + return path.isEmpty(); + } + + @Override + public boolean isDirectory( String path ) throws IOException + { + return path.isEmpty(); + } + + @Override + public void list( String path, List contents ) throws IOException + { + } + + @Override + public long getSize( String path ) throws IOException + { + return 0; + } - @Override - public InputStream openForRead( String path ) throws IOException - { - return null; - } + @Override + public InputStream openForRead( String path ) throws IOException + { + return null; + } } diff --git a/src/main/java/dan200/computercraft/core/filesystem/FileMount.java b/src/main/java/dan200/computercraft/core/filesystem/FileMount.java index e6c2e3e12..704702c03 100644 --- a/src/main/java/dan200/computercraft/core/filesystem/FileMount.java +++ b/src/main/java/dan200/computercraft/core/filesystem/FileMount.java @@ -13,203 +13,203 @@ public class FileMount implements IWritableMount { - private static int MINIMUM_FILE_SIZE = 500; - - private class CountingOutputStream extends OutputStream - { - private OutputStream m_innerStream; - private long m_ignoredBytesLeft; - - public CountingOutputStream( OutputStream innerStream, long bytesToIgnore ) - { - m_innerStream = innerStream; - m_ignoredBytesLeft = bytesToIgnore; - } - - @Override - public void close() throws IOException - { - m_innerStream.close(); - } - - @Override - public void flush() throws IOException - { - m_innerStream.flush(); - } - - @Override - public void write( byte[] b ) throws IOException - { - count( b.length ); - m_innerStream.write( b ); - } - - @Override - public void write( byte[] b, int off, int len ) throws IOException - { - count( len ); - m_innerStream.write( b, off, len ); - } + private static int MINIMUM_FILE_SIZE = 500; + + private class CountingOutputStream extends OutputStream + { + private OutputStream m_innerStream; + private long m_ignoredBytesLeft; + + public CountingOutputStream( OutputStream innerStream, long bytesToIgnore ) + { + m_innerStream = innerStream; + m_ignoredBytesLeft = bytesToIgnore; + } + + @Override + public void close() throws IOException + { + m_innerStream.close(); + } + + @Override + public void flush() throws IOException + { + m_innerStream.flush(); + } + + @Override + public void write( byte[] b ) throws IOException + { + count( b.length ); + m_innerStream.write( b ); + } + + @Override + public void write( byte[] b, int off, int len ) throws IOException + { + count( len ); + m_innerStream.write( b, off, len ); + } - @Override - public void write( int b ) throws IOException - { - count( 1 ); - m_innerStream.write( b ); - } + @Override + public void write( int b ) throws IOException + { + count( 1 ); + m_innerStream.write( b ); + } - private void count( long n ) throws IOException - { - m_ignoredBytesLeft -= n; - if( m_ignoredBytesLeft < 0 ) - { - long newBytes = -m_ignoredBytesLeft; - m_ignoredBytesLeft = 0; - - long bytesLeft = m_capacity - m_usedSpace; - if( newBytes > bytesLeft ) - { - throw new IOException( "Out of space" ); - } - else - { - m_usedSpace += newBytes; - } - } - } - } - - private File m_rootPath; - private long m_capacity; - private long m_usedSpace; - - public FileMount( File rootPath, long capacity ) - { - m_rootPath = rootPath; - m_capacity = capacity + MINIMUM_FILE_SIZE; - m_usedSpace = created() ? measureUsedSpace( m_rootPath ) : MINIMUM_FILE_SIZE; - } + private void count( long n ) throws IOException + { + m_ignoredBytesLeft -= n; + if( m_ignoredBytesLeft < 0 ) + { + long newBytes = -m_ignoredBytesLeft; + m_ignoredBytesLeft = 0; + + long bytesLeft = m_capacity - m_usedSpace; + if( newBytes > bytesLeft ) + { + throw new IOException( "Out of space" ); + } + else + { + m_usedSpace += newBytes; + } + } + } + } + + private File m_rootPath; + private long m_capacity; + private long m_usedSpace; + + public FileMount( File rootPath, long capacity ) + { + m_rootPath = rootPath; + m_capacity = capacity + MINIMUM_FILE_SIZE; + m_usedSpace = created() ? measureUsedSpace( m_rootPath ) : MINIMUM_FILE_SIZE; + } - // IMount implementation - - @Override - public boolean exists( String path ) throws IOException - { - if( !created() ) - { - return path.length() == 0; - } - else - { - File file = getRealPath( path ); - return file.exists(); - } - } - - @Override - public boolean isDirectory( String path ) throws IOException - { - if( !created() ) - { - return path.length() == 0; - } - else - { - File file = getRealPath( path ); - return file.exists() && file.isDirectory(); - } - } - - @Override - public void list( String path, List contents ) throws IOException - { - if( !created() ) - { - if( path.length() != 0 ) - { - throw new IOException( "Not a directory" ); - } - } - else - { - 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( "Not a directory" ); - } - } - } + // IMount implementation + + @Override + public boolean exists( String path ) throws IOException + { + if( !created() ) + { + return path.length() == 0; + } + else + { + File file = getRealPath( path ); + return file.exists(); + } + } + + @Override + public boolean isDirectory( String path ) throws IOException + { + if( !created() ) + { + return path.length() == 0; + } + else + { + File file = getRealPath( path ); + return file.exists() && file.isDirectory(); + } + } + + @Override + public void list( String path, List contents ) throws IOException + { + if( !created() ) + { + if( path.length() != 0 ) + { + throw new IOException( "Not a directory" ); + } + } + else + { + 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( "Not a directory" ); + } + } + } - @Override - public long getSize( String path ) throws IOException - { - if( !created() ) - { - if( path.length() == 0 ) - { - return 0; - } - } - else - { - File file = getRealPath( path ); - if( file.exists() ) - { - if( file.isDirectory() ) - { - return 0; - } - else - { - return file.length(); - } - } - } - throw new IOException( "No such file" ); - } - - @Override - public InputStream openForRead( String path ) throws IOException - { - if( created() ) - { - File file = getRealPath( path ); - if( file.exists() && !file.isDirectory() ) - { - return new FileInputStream( file ); - } - } - throw new IOException( "No such file" ); - } - - // IWritableMount implementation - - @Override - public void makeDirectory( String path ) throws IOException - { - create(); - File file = getRealPath( path ); - if( file.exists() ) - { - if( !file.isDirectory() ) - { - throw new IOException( "File exists" ); - } - } - else - { + @Override + public long getSize( String path ) throws IOException + { + if( !created() ) + { + if( path.length() == 0 ) + { + return 0; + } + } + else + { + File file = getRealPath( path ); + if( file.exists() ) + { + if( file.isDirectory() ) + { + return 0; + } + else + { + return file.length(); + } + } + } + throw new IOException( "No such file" ); + } + + @Override + public InputStream openForRead( String path ) throws IOException + { + if( created() ) + { + File file = getRealPath( path ); + if( file.exists() && !file.isDirectory() ) + { + return new FileInputStream( file ); + } + } + throw new IOException( "No such file" ); + } + + // IWritableMount implementation + + @Override + public void makeDirectory( String path ) throws IOException + { + create(); + File file = getRealPath( path ); + if( file.exists() ) + { + if( !file.isDirectory() ) + { + throw new IOException( "File exists" ); + } + } + else + { int dirsToCreate = 1; File parent = file.getParentFile(); while( !parent.exists() ) @@ -218,169 +218,169 @@ public void makeDirectory( String path ) throws IOException parent = parent.getParentFile(); } - if( getRemainingSpace() < dirsToCreate * MINIMUM_FILE_SIZE ) - { - throw new IOException( "Out of space" ); - } - - boolean success = file.mkdirs(); - if( success ) - { - m_usedSpace += dirsToCreate * MINIMUM_FILE_SIZE; - } - else - { - throw new IOException( "Access denied" ); - } - } - } - - @Override - public void delete( String path ) throws IOException - { - if( path.length() == 0 ) - { - throw new IOException( "Access denied" ); - } - - if( created() ) - { - File file = getRealPath( path ); - if( file.exists() ) - { - deleteRecursively( file ); - } - } - } - - private void deleteRecursively( File file ) throws IOException - { - // Empty directories first - if( file.isDirectory() ) - { - String[] children = file.list(); - for( int i=0; i contents ) throws FileSystemException - { - path = toLocal( path ); - try - { - if( m_mount.exists( path ) && m_mount.isDirectory( path ) ) - { - m_mount.list( path, contents ); - } - else - { - throw new FileSystemException( "Not a directory" ); - } - } - catch( IOException e ) - { - throw new FileSystemException( e.getMessage() ); - } - } - - public long getSize( String path ) throws FileSystemException - { - path = toLocal( path ); - try - { - if( m_mount.exists( path ) ) - { - if( m_mount.isDirectory( path ) ) - { - return 0; - } - else - { - return m_mount.getSize( path ); - } - } - else - { - throw new FileSystemException( "No such file" ); - } - } - catch( IOException e ) - { - throw new FileSystemException( e.getMessage() ); - } - } - - public InputStream openForRead( String path ) throws FileSystemException - { - path = toLocal( path ); - try - { - if( m_mount.exists( path ) && !m_mount.isDirectory( path ) ) - { - return m_mount.openForRead( path ); - } - else - { - throw new FileSystemException( "No such file" ); - } - } - catch( IOException e ) - { - throw new FileSystemException( e.getMessage() ); - } - } - - // IWritableMount forwarders: - - public void makeDirectory( String path ) throws FileSystemException - { - if( m_writableMount == null ) - { - throw new FileSystemException( "Access Denied" ); - } - try - { - path = toLocal( path ); - if( m_mount.exists( path ) ) - { - if( !m_mount.isDirectory( path ) ) - { - throw new FileSystemException( "File exists" ); - } - } - else - { - m_writableMount.makeDirectory( path ); - } - } - catch( IOException e ) - { - throw new FileSystemException( e.getMessage() ); - } - } - - public void delete( String path ) throws FileSystemException - { - if( m_writableMount == null ) - { - throw new FileSystemException( "Access Denied" ); - } - try - { - path = toLocal( path ); - if( m_mount.exists( path ) ) - { - m_writableMount.delete( path ); - } - } - catch( IOException e ) - { - throw new FileSystemException( e.getMessage() ); - } - } - - public OutputStream openForWrite( String path ) throws FileSystemException - { - if( m_writableMount == null ) - { - throw new FileSystemException( "Access Denied" ); - } - try - { - path = toLocal( path ); - if( m_mount.exists( path ) && m_mount.isDirectory( path ) ) - { - throw new FileSystemException( "Cannot write to directory" ); - } - else - { - if( !path.isEmpty() ) - { - String dir = getDirectory( path ); - if( !dir.isEmpty() && !m_mount.exists( path ) ) - { - m_writableMount.makeDirectory( dir ); - } - } - return m_writableMount.openForWrite( path ); - } - } - catch( IOException e ) - { - throw new FileSystemException( e.getMessage() ); - } - } - - public OutputStream openForAppend( String path ) throws FileSystemException - { - if( m_writableMount == null ) - { - throw new FileSystemException( "Access Denied" ); - } - try - { - path = toLocal( path ); - if( !m_mount.exists( path ) ) - { - if( !path.isEmpty() ) - { - String dir = getDirectory( path ); - if( !dir.isEmpty() && !m_mount.exists( path ) ) - { - m_writableMount.makeDirectory( dir ); - } - } - return m_writableMount.openForWrite( path ); - } - else if( m_mount.isDirectory( path ) ) - { - throw new FileSystemException( "Cannot write to directory" ); - } - else - { - return m_writableMount.openForAppend( path ); - } - } - catch( IOException e ) - { - throw new FileSystemException( e.getMessage() ); - } - } - - // private members - - private String toLocal( String path ) - { - return FileSystem.toLocal( path, m_location ); - } - } - - private Map m_mounts = new HashMap(); - private Set m_openFiles = new HashSet(); - - public FileSystem( String rootLabel, IMount rootMount ) throws FileSystemException - { - mount( rootLabel, "", rootMount ); - } - - public FileSystem( String rootLabel, IWritableMount rootMount ) throws FileSystemException - { - mountWritable( rootLabel, "", rootMount ); - } - - public void unload() - { - // Close all dangling open files - synchronized( m_openFiles ) - { - while( m_openFiles.size() > 0 ) - { - IMountedFile file = m_openFiles.iterator().next(); - try - { - file.close(); - } - catch( IOException e ) - { - m_openFiles.remove( file ); - } - } - } - } - - public synchronized void mount( String label, String location, IMount mount ) throws FileSystemException - { - if( mount == null ) - { - throw new NullPointerException(); - } - location = sanitizePath( location ); - if( location.indexOf( ".." ) != -1 ) { - throw new FileSystemException( "Cannot mount below the root" ); - } - mount( new MountWrapper( label, location, mount ) ); - } - - public synchronized void mountWritable( String label, String location, IWritableMount mount ) throws FileSystemException - { - if( mount == null ) - { - throw new NullPointerException(); - } - location = sanitizePath( location ); - if( location.contains( ".." ) ) +{ + private class MountWrapper + { + private String m_label; + private String m_location; + + private IMount m_mount; + private IWritableMount m_writableMount; + + public MountWrapper( String label, String location, IMount mount ) { - throw new FileSystemException( "Cannot mount below the root" ); - } - mount( new MountWrapper( label, location, mount ) ); - } - - private synchronized void mount( MountWrapper wrapper ) throws FileSystemException - { - String location = wrapper.getLocation(); - if( m_mounts.containsKey( location ) ) - { - m_mounts.remove( location ); - } - m_mounts.put( location, wrapper ); - } - - public synchronized void unmount( String path ) - { - path = sanitizePath( path ); - if( m_mounts.containsKey( path ) ) - { - m_mounts.remove( path ); - } - } - - public synchronized String combine( String path, String childPath ) - { - path = sanitizePath( path, true ); - childPath = sanitizePath( childPath, true ); - - if( path.isEmpty() ) { - return childPath; - } else if( childPath.isEmpty() ) { - return path; - } else { - return sanitizePath( path + '/' + childPath, true ); - } - } - - public static String getDirectory( String path ) - { - path = sanitizePath( path, true ); - if( path.isEmpty() ) { - return ".."; - } - - int lastSlash = path.lastIndexOf('/'); - if( lastSlash >= 0 ) { - return path.substring( 0, lastSlash ); - } else { - return ""; - } - } + m_label = label; + m_location = location; + m_mount = mount; + m_writableMount = null; + } - public static String getName( String path ) - { - path = sanitizePath( path, true ); - if( path.isEmpty() ) { - return "root"; - } - - int lastSlash = path.lastIndexOf('/'); - if( lastSlash >= 0 ) { - return path.substring( lastSlash + 1 ); - } else { - return path; - } - } - - public synchronized long getSize( String path ) throws FileSystemException - { - path = sanitizePath( path ); - MountWrapper mount = getMount( path ); - return mount.getSize( path ); - } - - public synchronized String[] list( String path ) throws FileSystemException - { - path = sanitizePath( path ); - MountWrapper mount = getMount( path ); - - // Gets a list of the files in the mount - List list = new ArrayList(); - mount.list( path, list ); - - // Add any mounts that are mounted at this location - Iterator it = m_mounts.values().iterator(); - while( it.hasNext() ) { - MountWrapper otherMount = it.next(); - if( getDirectory( otherMount.getLocation() ).equals( path ) ) { - list.add( getName( otherMount.getLocation() ) ); - } - } - - // Return list - String[] array = new String[ list.size() ]; - list.toArray(array); - return array; - } + public MountWrapper( String label, String location, IWritableMount mount ) + { + this( label, location, (IMount)mount ); + m_writableMount = mount; + } + + public String getLabel() + { + return m_label; + } + + public String getLocation() + { + return m_location; + } + + public long getFreeSpace() + { + if( m_writableMount == null ) + { + return 0; + } + + try + { + return m_writableMount.getRemainingSpace(); + } + catch( IOException e ) + { + return 0; + } + } + + public boolean isReadOnly( String path ) throws FileSystemException + { + return (m_writableMount == null); + } + + // IMount forwarders: + + public boolean exists( String path ) throws FileSystemException + { + path = toLocal( path ); + try + { + return m_mount.exists( path ); + } + catch( IOException e ) + { + throw new FileSystemException( e.getMessage() ); + } + } + + public boolean isDirectory( String path ) throws FileSystemException + { + path = toLocal( path ); + try + { + return m_mount.exists( path ) && m_mount.isDirectory( path ); + } + catch( IOException e ) + { + throw new FileSystemException( e.getMessage() ); + } + } + + public void list( String path, List contents ) throws FileSystemException + { + path = toLocal( path ); + try + { + if( m_mount.exists( path ) && m_mount.isDirectory( path ) ) + { + m_mount.list( path, contents ); + } + else + { + throw new FileSystemException( "Not a directory" ); + } + } + catch( IOException e ) + { + throw new FileSystemException( e.getMessage() ); + } + } + + public long getSize( String path ) throws FileSystemException + { + path = toLocal( path ); + try + { + if( m_mount.exists( path ) ) + { + if( m_mount.isDirectory( path ) ) + { + return 0; + } + else + { + return m_mount.getSize( path ); + } + } + else + { + throw new FileSystemException( "No such file" ); + } + } + catch( IOException e ) + { + throw new FileSystemException( e.getMessage() ); + } + } + + public InputStream openForRead( String path ) throws FileSystemException + { + path = toLocal( path ); + try + { + if( m_mount.exists( path ) && !m_mount.isDirectory( path ) ) + { + return m_mount.openForRead( path ); + } + else + { + throw new FileSystemException( "No such file" ); + } + } + catch( IOException e ) + { + throw new FileSystemException( e.getMessage() ); + } + } + + // IWritableMount forwarders: + + public void makeDirectory( String path ) throws FileSystemException + { + if( m_writableMount == null ) + { + throw new FileSystemException( "Access Denied" ); + } + try + { + path = toLocal( path ); + if( m_mount.exists( path ) ) + { + if( !m_mount.isDirectory( path ) ) + { + throw new FileSystemException( "File exists" ); + } + } + else + { + m_writableMount.makeDirectory( path ); + } + } + catch( IOException e ) + { + throw new FileSystemException( e.getMessage() ); + } + } + + public void delete( String path ) throws FileSystemException + { + if( m_writableMount == null ) + { + throw new FileSystemException( "Access Denied" ); + } + try + { + path = toLocal( path ); + if( m_mount.exists( path ) ) + { + m_writableMount.delete( path ); + } + } + catch( IOException e ) + { + throw new FileSystemException( e.getMessage() ); + } + } + + public OutputStream openForWrite( String path ) throws FileSystemException + { + if( m_writableMount == null ) + { + throw new FileSystemException( "Access Denied" ); + } + try + { + path = toLocal( path ); + if( m_mount.exists( path ) && m_mount.isDirectory( path ) ) + { + throw new FileSystemException( "Cannot write to directory" ); + } + else + { + if( !path.isEmpty() ) + { + String dir = getDirectory( path ); + if( !dir.isEmpty() && !m_mount.exists( path ) ) + { + m_writableMount.makeDirectory( dir ); + } + } + return m_writableMount.openForWrite( path ); + } + } + catch( IOException e ) + { + throw new FileSystemException( e.getMessage() ); + } + } + + public OutputStream openForAppend( String path ) throws FileSystemException + { + if( m_writableMount == null ) + { + throw new FileSystemException( "Access Denied" ); + } + try + { + path = toLocal( path ); + if( !m_mount.exists( path ) ) + { + if( !path.isEmpty() ) + { + String dir = getDirectory( path ); + if( !dir.isEmpty() && !m_mount.exists( path ) ) + { + m_writableMount.makeDirectory( dir ); + } + } + return m_writableMount.openForWrite( path ); + } + else if( m_mount.isDirectory( path ) ) + { + throw new FileSystemException( "Cannot write to directory" ); + } + else + { + return m_writableMount.openForAppend( path ); + } + } + catch( IOException e ) + { + throw new FileSystemException( e.getMessage() ); + } + } + + // private members + + private String toLocal( String path ) + { + return FileSystem.toLocal( path, m_location ); + } + } + + private Map m_mounts = new HashMap(); + private Set m_openFiles = new HashSet(); + + public FileSystem( String rootLabel, IMount rootMount ) throws FileSystemException + { + mount( rootLabel, "", rootMount ); + } + + public FileSystem( String rootLabel, IWritableMount rootMount ) throws FileSystemException + { + mountWritable( rootLabel, "", rootMount ); + } + + public void unload() + { + // Close all dangling open files + synchronized( m_openFiles ) + { + while( m_openFiles.size() > 0 ) + { + IMountedFile file = m_openFiles.iterator().next(); + try + { + file.close(); + } + catch( IOException e ) + { + m_openFiles.remove( file ); + } + } + } + } + + public synchronized void mount( String label, String location, IMount mount ) throws FileSystemException + { + if( mount == null ) + { + throw new NullPointerException(); + } + location = sanitizePath( location ); + if( location.indexOf( ".." ) != -1 ) { + throw new FileSystemException( "Cannot mount below the root" ); + } + mount( new MountWrapper( label, location, mount ) ); + } + + public synchronized void mountWritable( String label, String location, IWritableMount mount ) throws FileSystemException + { + if( mount == null ) + { + throw new NullPointerException(); + } + location = sanitizePath( location ); + if( location.contains( ".." ) ) + { + throw new FileSystemException( "Cannot mount below the root" ); + } + mount( new MountWrapper( label, location, mount ) ); + } + + private synchronized void mount( MountWrapper wrapper ) throws FileSystemException + { + String location = wrapper.getLocation(); + if( m_mounts.containsKey( location ) ) + { + m_mounts.remove( location ); + } + m_mounts.put( location, wrapper ); + } + + public synchronized void unmount( String path ) + { + path = sanitizePath( path ); + if( m_mounts.containsKey( path ) ) + { + m_mounts.remove( path ); + } + } + + public synchronized String combine( String path, String childPath ) + { + path = sanitizePath( path, true ); + childPath = sanitizePath( childPath, true ); + + if( path.isEmpty() ) { + return childPath; + } else if( childPath.isEmpty() ) { + return path; + } else { + return sanitizePath( path + '/' + childPath, true ); + } + } + + public static String getDirectory( String path ) + { + path = sanitizePath( path, true ); + if( path.isEmpty() ) { + return ".."; + } + + int lastSlash = path.lastIndexOf('/'); + if( lastSlash >= 0 ) { + return path.substring( 0, lastSlash ); + } else { + return ""; + } + } + + public static String getName( String path ) + { + path = sanitizePath( path, true ); + if( path.isEmpty() ) { + return "root"; + } + + int lastSlash = path.lastIndexOf('/'); + if( lastSlash >= 0 ) { + return path.substring( lastSlash + 1 ); + } else { + return path; + } + } + + public synchronized long getSize( String path ) throws FileSystemException + { + path = sanitizePath( path ); + MountWrapper mount = getMount( path ); + return mount.getSize( path ); + } + + public synchronized String[] list( String path ) throws FileSystemException + { + path = sanitizePath( path ); + MountWrapper mount = getMount( path ); + + // Gets a list of the files in the mount + List list = new ArrayList(); + mount.list( path, list ); + + // Add any mounts that are mounted at this location + Iterator it = m_mounts.values().iterator(); + while( it.hasNext() ) { + MountWrapper otherMount = it.next(); + if( getDirectory( otherMount.getLocation() ).equals( path ) ) { + list.add( getName( otherMount.getLocation() ) ); + } + } + + // Return list + String[] array = new String[ list.size() ]; + list.toArray(array); + return array; + } private void findIn( String dir, List matches, Pattern wildPattern ) throws FileSystemException { @@ -476,171 +476,171 @@ public synchronized String[] find( String wildPath ) throws FileSystemException return array; } - public synchronized boolean exists( String path ) throws FileSystemException - { - path = sanitizePath( path ); - MountWrapper mount = getMount( path ); - return mount.exists( path ); - } - - public synchronized boolean isDir( String path ) throws FileSystemException - { - path = sanitizePath( path ); - MountWrapper mount = getMount( path ); - return mount.isDirectory( path ); - } - - public synchronized boolean isReadOnly( String path ) throws FileSystemException - { - path = sanitizePath( path ); - MountWrapper mount = getMount( path ); - return mount.isReadOnly( path ); - } - - public synchronized String getMountLabel( String path ) throws FileSystemException - { - path = sanitizePath( path ); - MountWrapper mount = getMount( path ); - return mount.getLabel(); - } - - public synchronized void makeDir( String path ) throws FileSystemException - { - path = sanitizePath( path ); - MountWrapper mount = getMount( path ); - mount.makeDirectory( path ); - } - - public synchronized void delete( String path ) throws FileSystemException - { - path = sanitizePath( path ); - MountWrapper mount = getMount( path ); - mount.delete( path ); - } - - public synchronized void move( String sourcePath, String destPath ) throws FileSystemException - { - sourcePath = sanitizePath( sourcePath ); - destPath = sanitizePath( destPath ); - if( isReadOnly( sourcePath ) || isReadOnly( destPath ) ) { - throw new FileSystemException( "Access denied" ); - } - if( !exists( sourcePath ) ) { - throw new FileSystemException( "No such file" ); - } - if( exists( destPath ) ) { - throw new FileSystemException( "File exists" ); - } - if( contains( sourcePath, destPath ) ) { - throw new FileSystemException( "Can't move a directory inside itself" ); - } - copy( sourcePath, destPath ); - delete( sourcePath ); - } - - public synchronized void copy( String sourcePath, String destPath ) throws FileSystemException - { - sourcePath = sanitizePath( sourcePath ); - destPath = sanitizePath( destPath ); - if( isReadOnly( destPath ) ) { - throw new FileSystemException( "Access denied" ); - } - if( !exists( sourcePath ) ) { - throw new FileSystemException( "No such file" ); - } - if( exists( destPath ) ) { - throw new FileSystemException( "File exists" ); - } - if( contains( sourcePath, destPath ) ) { - throw new FileSystemException( "Can't copy a directory inside itself" ); - } - copyRecursive( sourcePath, getMount( sourcePath ), destPath, getMount( destPath ) ); - } - - private synchronized void copyRecursive( String sourcePath, MountWrapper sourceMount, String destinationPath, MountWrapper destinationMount ) throws FileSystemException - { - if( !sourceMount.exists( sourcePath ) ) - { - return; - } - - if( sourceMount.isDirectory( sourcePath ) ) - { - // Copy a directory: - // Make the new directory - destinationMount.makeDirectory( destinationPath ); - - // Copy the source contents into it - List sourceChildren = new ArrayList(); - sourceMount.list( sourcePath, sourceChildren ); - for( String child : sourceChildren ) - { - copyRecursive( - combine( sourcePath, child ), sourceMount, - combine( destinationPath, child ), destinationMount - ); - } - } - else - { - // Copy a file: - InputStream source = null; - OutputStream destination = null; - try - { - // Open both files - source = sourceMount.openForRead( sourcePath ); - destination = destinationMount.openForWrite( destinationPath ); - - // Copy bytes as fast as we can - byte[] buffer = new byte[1024]; - while( true ) - { - int bytesRead = source.read( buffer ); - if( bytesRead >= 0 ) - { - destination.write( buffer, 0, bytesRead ); - } - else - { - break; - } - } - } - catch( IOException e ) - { - throw new FileSystemException( e.getMessage() ); - } - finally - { - // Close both files - if( source != null ) - { - try { - source.close(); - } catch( IOException e ) { - // nobody cares - } - } - if( destination != null ) - { - try { - destination.close(); - } catch( IOException e ) { - // nobody cares - } - } - } - } + public synchronized boolean exists( String path ) throws FileSystemException + { + path = sanitizePath( path ); + MountWrapper mount = getMount( path ); + return mount.exists( path ); } - - public synchronized IMountedFileNormal openForRead( String path ) throws FileSystemException - { - path = sanitizePath ( path ); - MountWrapper mount = getMount( path ); - InputStream stream = mount.openForRead( path ); - if( stream != null ) - { + + public synchronized boolean isDir( String path ) throws FileSystemException + { + path = sanitizePath( path ); + MountWrapper mount = getMount( path ); + return mount.isDirectory( path ); + } + + public synchronized boolean isReadOnly( String path ) throws FileSystemException + { + path = sanitizePath( path ); + MountWrapper mount = getMount( path ); + return mount.isReadOnly( path ); + } + + public synchronized String getMountLabel( String path ) throws FileSystemException + { + path = sanitizePath( path ); + MountWrapper mount = getMount( path ); + return mount.getLabel(); + } + + public synchronized void makeDir( String path ) throws FileSystemException + { + path = sanitizePath( path ); + MountWrapper mount = getMount( path ); + mount.makeDirectory( path ); + } + + public synchronized void delete( String path ) throws FileSystemException + { + path = sanitizePath( path ); + MountWrapper mount = getMount( path ); + mount.delete( path ); + } + + public synchronized void move( String sourcePath, String destPath ) throws FileSystemException + { + sourcePath = sanitizePath( sourcePath ); + destPath = sanitizePath( destPath ); + if( isReadOnly( sourcePath ) || isReadOnly( destPath ) ) { + throw new FileSystemException( "Access denied" ); + } + if( !exists( sourcePath ) ) { + throw new FileSystemException( "No such file" ); + } + if( exists( destPath ) ) { + throw new FileSystemException( "File exists" ); + } + if( contains( sourcePath, destPath ) ) { + throw new FileSystemException( "Can't move a directory inside itself" ); + } + copy( sourcePath, destPath ); + delete( sourcePath ); + } + + public synchronized void copy( String sourcePath, String destPath ) throws FileSystemException + { + sourcePath = sanitizePath( sourcePath ); + destPath = sanitizePath( destPath ); + if( isReadOnly( destPath ) ) { + throw new FileSystemException( "Access denied" ); + } + if( !exists( sourcePath ) ) { + throw new FileSystemException( "No such file" ); + } + if( exists( destPath ) ) { + throw new FileSystemException( "File exists" ); + } + if( contains( sourcePath, destPath ) ) { + throw new FileSystemException( "Can't copy a directory inside itself" ); + } + copyRecursive( sourcePath, getMount( sourcePath ), destPath, getMount( destPath ) ); + } + + private synchronized void copyRecursive( String sourcePath, MountWrapper sourceMount, String destinationPath, MountWrapper destinationMount ) throws FileSystemException + { + if( !sourceMount.exists( sourcePath ) ) + { + return; + } + + if( sourceMount.isDirectory( sourcePath ) ) + { + // Copy a directory: + // Make the new directory + destinationMount.makeDirectory( destinationPath ); + + // Copy the source contents into it + List sourceChildren = new ArrayList(); + sourceMount.list( sourcePath, sourceChildren ); + for( String child : sourceChildren ) + { + copyRecursive( + combine( sourcePath, child ), sourceMount, + combine( destinationPath, child ), destinationMount + ); + } + } + else + { + // Copy a file: + InputStream source = null; + OutputStream destination = null; + try + { + // Open both files + source = sourceMount.openForRead( sourcePath ); + destination = destinationMount.openForWrite( destinationPath ); + + // Copy bytes as fast as we can + byte[] buffer = new byte[1024]; + while( true ) + { + int bytesRead = source.read( buffer ); + if( bytesRead >= 0 ) + { + destination.write( buffer, 0, bytesRead ); + } + else + { + break; + } + } + } + catch( IOException e ) + { + throw new FileSystemException( e.getMessage() ); + } + finally + { + // Close both files + if( source != null ) + { + try { + source.close(); + } catch( IOException e ) { + // nobody cares + } + } + if( destination != null ) + { + try { + destination.close(); + } catch( IOException e ) { + // nobody cares + } + } + } + } + } + + public synchronized IMountedFileNormal openForRead( String path ) throws FileSystemException + { + path = sanitizePath ( path ); + MountWrapper mount = getMount( path ); + InputStream stream = mount.openForRead( path ); + if( stream != null ) + { InputStreamReader isr; try { @@ -650,53 +650,53 @@ public synchronized IMountedFileNormal openForRead( String path ) throws FileSys { isr = new InputStreamReader( stream ); } - final BufferedReader reader = new BufferedReader( isr ); - IMountedFileNormal file = new IMountedFileNormal() - { - @Override - public String readLine() throws IOException - { - return reader.readLine(); - } - - @Override - public void write(String s, int off, int len, boolean newLine) throws IOException - { - throw new UnsupportedOperationException(); - } - - @Override - public void close() throws IOException - { - synchronized( m_openFiles ) - { - m_openFiles.remove( this ); - reader.close(); - } - } - - @Override - public void flush() throws IOException - { - throw new UnsupportedOperationException(); - } - }; - synchronized( m_openFiles ) - { - m_openFiles.add( file ); - } - return file; - } - return null; - } - - public synchronized IMountedFileNormal openForWrite( String path, boolean append ) throws FileSystemException - { - path = sanitizePath ( path ); - MountWrapper mount = getMount( path ); - OutputStream stream = append ? mount.openForAppend( path ) : mount.openForWrite( path ); - if( stream != null ) - { + final BufferedReader reader = new BufferedReader( isr ); + IMountedFileNormal file = new IMountedFileNormal() + { + @Override + public String readLine() throws IOException + { + return reader.readLine(); + } + + @Override + public void write(String s, int off, int len, boolean newLine) throws IOException + { + throw new UnsupportedOperationException(); + } + + @Override + public void close() throws IOException + { + synchronized( m_openFiles ) + { + m_openFiles.remove( this ); + reader.close(); + } + } + + @Override + public void flush() throws IOException + { + throw new UnsupportedOperationException(); + } + }; + synchronized( m_openFiles ) + { + m_openFiles.add( file ); + } + return file; + } + return null; + } + + public synchronized IMountedFileNormal openForWrite( String path, boolean append ) throws FileSystemException + { + path = sanitizePath ( path ); + MountWrapper mount = getMount( path ); + OutputStream stream = append ? mount.openForAppend( path ) : mount.openForWrite( path ); + if( stream != null ) + { OutputStreamWriter osw; try { @@ -707,279 +707,279 @@ public synchronized IMountedFileNormal openForWrite( String path, boolean append osw = new OutputStreamWriter( stream ); } final BufferedWriter writer = new BufferedWriter( osw ); - IMountedFileNormal file = new IMountedFileNormal() - { - @Override - public String readLine() throws IOException - { - throw new UnsupportedOperationException(); - } - - @Override - public void write( String s, int off, int len, boolean newLine ) throws IOException - { + IMountedFileNormal file = new IMountedFileNormal() + { + @Override + public String readLine() throws IOException + { + throw new UnsupportedOperationException(); + } + + @Override + public void write( String s, int off, int len, boolean newLine ) throws IOException + { writer.write( s, off, len ); - if( newLine ) - { + if( newLine ) + { writer.newLine(); - } - } - - @Override - public void close() throws IOException - { - synchronized( m_openFiles ) - { - m_openFiles.remove( this ); - writer.close(); - } - } - - @Override - public void flush() throws IOException - { - writer.flush(); - } - }; - synchronized( m_openFiles ) - { - m_openFiles.add( file ); - } - return file; - } - return null; - } + } + } + + @Override + public void close() throws IOException + { + synchronized( m_openFiles ) + { + m_openFiles.remove( this ); + writer.close(); + } + } + + @Override + public void flush() throws IOException + { + writer.flush(); + } + }; + synchronized( m_openFiles ) + { + m_openFiles.add( file ); + } + return file; + } + return null; + } - public synchronized IMountedFileBinary openForBinaryRead( String path ) throws FileSystemException - { - path = sanitizePath ( path ); - MountWrapper mount = getMount( path ); - final InputStream stream = mount.openForRead( path ); - if( stream != null ) - { - IMountedFileBinary file = new IMountedFileBinary() - { - @Override - public int read() throws IOException - { - return stream.read(); - } - - @Override - public void write(int i) throws IOException - { - throw new UnsupportedOperationException(); - } - - @Override - public void close() throws IOException - { - synchronized( m_openFiles ) - { - m_openFiles.remove( this ); - stream.close(); - } - } - - @Override - public void flush() throws IOException - { - throw new UnsupportedOperationException(); - } - }; - synchronized( m_openFiles ) - { - m_openFiles.add( file ); - } - return file; - } - return null; - } + public synchronized IMountedFileBinary openForBinaryRead( String path ) throws FileSystemException + { + path = sanitizePath ( path ); + MountWrapper mount = getMount( path ); + final InputStream stream = mount.openForRead( path ); + if( stream != null ) + { + IMountedFileBinary file = new IMountedFileBinary() + { + @Override + public int read() throws IOException + { + return stream.read(); + } + + @Override + public void write(int i) throws IOException + { + throw new UnsupportedOperationException(); + } + + @Override + public void close() throws IOException + { + synchronized( m_openFiles ) + { + m_openFiles.remove( this ); + stream.close(); + } + } + + @Override + public void flush() throws IOException + { + throw new UnsupportedOperationException(); + } + }; + synchronized( m_openFiles ) + { + m_openFiles.add( file ); + } + return file; + } + return null; + } - public synchronized IMountedFileBinary openForBinaryWrite( String path, boolean append ) throws FileSystemException - { - path = sanitizePath ( path ); - MountWrapper mount = getMount( path ); - final OutputStream stream = append ? mount.openForAppend( path ) : mount.openForWrite( path ); - if( stream != null ) - { - IMountedFileBinary file = new IMountedFileBinary() - { - @Override - public int read() throws IOException - { - throw new UnsupportedOperationException(); - } - - @Override - public void write(int i) throws IOException - { - stream.write(i); - } - - @Override - public void close() throws IOException - { - synchronized( m_openFiles ) - { - m_openFiles.remove( this ); - stream.close(); - } - } - - @Override - public void flush() throws IOException - { - stream.flush(); - } - }; - synchronized( m_openFiles ) - { - m_openFiles.add( file ); - } - return file; - } - return null; - } - - public long getFreeSpace( String path ) throws FileSystemException - { - path = sanitizePath( path ); - MountWrapper mount = getMount( path ); - return mount.getFreeSpace(); - } - - private MountWrapper getMount( String path ) throws FileSystemException - { - // Return the deepest mount that contains a given path - Iterator it = m_mounts.values().iterator(); - MountWrapper match = null; - int matchLength = 999; - while( it.hasNext() ) - { - MountWrapper mount = it.next(); - if( contains( mount.getLocation(), path ) ) { - int len = toLocal( path, mount.getLocation() ).length(); - if( match == null || len < matchLength ) { - match = mount; - matchLength = len; - } - } - } - if( match == null ) - { - throw new FileSystemException( "Invalid Path" ); - } - return match; - } + public synchronized IMountedFileBinary openForBinaryWrite( String path, boolean append ) throws FileSystemException + { + path = sanitizePath ( path ); + MountWrapper mount = getMount( path ); + final OutputStream stream = append ? mount.openForAppend( path ) : mount.openForWrite( path ); + if( stream != null ) + { + IMountedFileBinary file = new IMountedFileBinary() + { + @Override + public int read() throws IOException + { + throw new UnsupportedOperationException(); + } + + @Override + public void write(int i) throws IOException + { + stream.write(i); + } + + @Override + public void close() throws IOException + { + synchronized( m_openFiles ) + { + m_openFiles.remove( this ); + stream.close(); + } + } + + @Override + public void flush() throws IOException + { + stream.flush(); + } + }; + synchronized( m_openFiles ) + { + m_openFiles.add( file ); + } + return file; + } + return null; + } + + public long getFreeSpace( String path ) throws FileSystemException + { + path = sanitizePath( path ); + MountWrapper mount = getMount( path ); + return mount.getFreeSpace(); + } + + private MountWrapper getMount( String path ) throws FileSystemException + { + // Return the deepest mount that contains a given path + Iterator it = m_mounts.values().iterator(); + MountWrapper match = null; + int matchLength = 999; + while( it.hasNext() ) + { + MountWrapper mount = it.next(); + if( contains( mount.getLocation(), path ) ) { + int len = toLocal( path, mount.getLocation() ).length(); + if( match == null || len < matchLength ) { + match = mount; + matchLength = len; + } + } + } + if( match == null ) + { + throw new FileSystemException( "Invalid Path" ); + } + return match; + } private static String sanitizePath( String path ) { return sanitizePath( path, false ); } - private static String sanitizePath( String path, boolean allowWildcards ) - { - // Allow windowsy slashes - path = path.replace( '\\', '/' ); - - // Clean the path or illegal characters. - final char[] specialChars = { + private static String sanitizePath( String path, boolean allowWildcards ) + { + // Allow windowsy slashes + path = path.replace( '\\', '/' ); + + // Clean the path or illegal characters. + final char[] specialChars = { '"', ':', '<', '>', '?', '|' // Sorted by ascii value (important) }; - StringBuilder cleanName = new StringBuilder(); - for( int i = 0; i < path.length(); i++ ) { - char c = path.charAt(i); - if( c >= 32 && Arrays.binarySearch( specialChars, c ) < 0 && (allowWildcards || c != '*') ) + StringBuilder cleanName = new StringBuilder(); + for( int i = 0; i < path.length(); i++ ) { + char c = path.charAt(i); + if( c >= 32 && Arrays.binarySearch( specialChars, c ) < 0 && (allowWildcards || c != '*') ) { - cleanName.append((char)c); - } - } - path = cleanName.toString(); - - // Collapse the string into its component parts, removing ..'s - String[] parts = path.split("/"); - Stack outputParts = new Stack(); - for( int n=0; n outputParts = new Stack(); + for( int n=0; n= 255) { - // If part length > 255 and it is the last part - outputParts.push( part.substring(0, 255) ); - } else { - // Anything else we add to the stack - outputParts.push(part); - } - } - - // Recombine the output parts into a new string - StringBuilder result = new StringBuilder( "" ); - Iterator it = outputParts.iterator(); - while( it.hasNext() ) { - String part = it.next(); - result.append( part ); - if( it.hasNext() ) { - result.append( '/' ); - } - } + } else if( part.equals("..") || part.equals( "..." ) ) { + // .. or ... can cancel out the last folder entered + if( !outputParts.empty() ) { + String top = outputParts.peek(); + if( !top.equals("..") ) { + outputParts.pop(); + } else { + outputParts.push(".."); + } + } else { + outputParts.push(".."); + } + } else if (part.length() >= 255) { + // If part length > 255 and it is the last part + outputParts.push( part.substring(0, 255) ); + } else { + // Anything else we add to the stack + outputParts.push(part); + } + } + + // Recombine the output parts into a new string + StringBuilder result = new StringBuilder( "" ); + Iterator it = outputParts.iterator(); + while( it.hasNext() ) { + String part = it.next(); + result.append( part ); + if( it.hasNext() ) { + result.append( '/' ); + } + } - return result.toString(); - } - - public static boolean contains( String pathA, String pathB ) - { - pathA = sanitizePath( pathA ); - pathB = sanitizePath( pathB ); + return result.toString(); + } + + public static boolean contains( String pathA, String pathB ) + { + pathA = sanitizePath( pathA ); + pathB = sanitizePath( pathB ); - if( pathB.equals("..") ) - { - return false; - } - else if ( pathB.startsWith("../") ) - { - return false; - } - else if( pathB.equals( pathA ) ) - { - return true; - } - else if( pathA.isEmpty() ) - { - return true; - } - else - { - return pathB.startsWith( pathA + "/" ); - } - } - - public static String toLocal( String path, String location ) - { - path = sanitizePath( path ); - location = sanitizePath( location ); - - assert( contains( location, path ) ); - String local = path.substring( location.length() ); - if( local.startsWith("/") ) { - return local.substring( 1 ); - } else { - return local; - } - } + if( pathB.equals("..") ) + { + return false; + } + else if ( pathB.startsWith("../") ) + { + return false; + } + else if( pathB.equals( pathA ) ) + { + return true; + } + else if( pathA.isEmpty() ) + { + return true; + } + else + { + return pathB.startsWith( pathA + "/" ); + } + } + + public static String toLocal( String path, String location ) + { + path = sanitizePath( path ); + location = sanitizePath( location ); + + assert( contains( location, path ) ); + String local = path.substring( location.length() ); + if( local.startsWith("/") ) { + return local.substring( 1 ); + } else { + return local; + } + } } diff --git a/src/main/java/dan200/computercraft/core/filesystem/FileSystemException.java b/src/main/java/dan200/computercraft/core/filesystem/FileSystemException.java index 08215b336..cbf970ebf 100644 --- a/src/main/java/dan200/computercraft/core/filesystem/FileSystemException.java +++ b/src/main/java/dan200/computercraft/core/filesystem/FileSystemException.java @@ -7,7 +7,7 @@ package dan200.computercraft.core.filesystem; public class FileSystemException extends Exception { - FileSystemException( String s ) { - super( s ); - } + FileSystemException( String s ) { + super( s ); + } } diff --git a/src/main/java/dan200/computercraft/core/filesystem/IMountedFile.java b/src/main/java/dan200/computercraft/core/filesystem/IMountedFile.java index 29aa52815..58a5b43c6 100644 --- a/src/main/java/dan200/computercraft/core/filesystem/IMountedFile.java +++ b/src/main/java/dan200/computercraft/core/filesystem/IMountedFile.java @@ -9,5 +9,5 @@ import java.io.IOException; public interface IMountedFile { - public void close() throws IOException; + public void close() throws IOException; } diff --git a/src/main/java/dan200/computercraft/core/filesystem/IMountedFileBinary.java b/src/main/java/dan200/computercraft/core/filesystem/IMountedFileBinary.java index bb92271a7..a382203dc 100644 --- a/src/main/java/dan200/computercraft/core/filesystem/IMountedFileBinary.java +++ b/src/main/java/dan200/computercraft/core/filesystem/IMountedFileBinary.java @@ -9,8 +9,8 @@ import java.io.IOException; public interface IMountedFileBinary extends IMountedFile { - public int read() throws IOException; - public void write(int i) throws IOException; - public void close() throws IOException; - public void flush() throws IOException; + public int read() throws IOException; + public void write(int i) throws IOException; + public void close() throws IOException; + public void flush() throws IOException; } diff --git a/src/main/java/dan200/computercraft/core/filesystem/IMountedFileNormal.java b/src/main/java/dan200/computercraft/core/filesystem/IMountedFileNormal.java index e94f20e46..78a02961a 100644 --- a/src/main/java/dan200/computercraft/core/filesystem/IMountedFileNormal.java +++ b/src/main/java/dan200/computercraft/core/filesystem/IMountedFileNormal.java @@ -9,8 +9,8 @@ import java.io.IOException; public interface IMountedFileNormal extends IMountedFile { - public String readLine() throws IOException; - public void write(String s, int off, int len, boolean newLine) throws IOException; - public void close() throws IOException; - public void flush() throws IOException; + public String readLine() throws IOException; + public void write(String s, int off, int len, boolean newLine) throws IOException; + public void close() throws IOException; + public void flush() throws IOException; } diff --git a/src/main/java/dan200/computercraft/core/filesystem/JarMount.java b/src/main/java/dan200/computercraft/core/filesystem/JarMount.java index a944f9f45..c82085a63 100644 --- a/src/main/java/dan200/computercraft/core/filesystem/JarMount.java +++ b/src/main/java/dan200/computercraft/core/filesystem/JarMount.java @@ -20,230 +20,230 @@ import java.util.zip.ZipFile; public class JarMount implements IMount -{ - private class FileInZip - { - private String m_path; - private boolean m_directory; - private long m_size; - private Map m_children; - - public FileInZip( String path, boolean directory, long size ) - { - m_path = path; - m_directory = directory; - m_size = m_directory ? 0 : size; - m_children = new LinkedHashMap(); - } - - public String getPath() - { - return m_path; - } - - public boolean isDirectory() - { - return m_directory; - } - - public long getSize() - { - return m_size; - } - - public void list( List contents ) - { - for( String child : m_children.keySet() ) - { - contents.add( child ); - } - } - - public void insertChild( FileInZip child ) - { - String localPath = FileSystem.toLocal( child.getPath(), m_path ); - m_children.put( localPath, child ); - } +{ + private class FileInZip + { + private String m_path; + private boolean m_directory; + private long m_size; + private Map m_children; + + public FileInZip( String path, boolean directory, long size ) + { + m_path = path; + m_directory = directory; + m_size = m_directory ? 0 : size; + m_children = new LinkedHashMap(); + } + + public String getPath() + { + return m_path; + } + + public boolean isDirectory() + { + return m_directory; + } + + public long getSize() + { + return m_size; + } + + public void list( List contents ) + { + for( String child : m_children.keySet() ) + { + contents.add( child ); + } + } + + public void insertChild( FileInZip child ) + { + String localPath = FileSystem.toLocal( child.getPath(), m_path ); + m_children.put( localPath, child ); + } - public FileInZip getFile( String path ) - { - // If we've reached the target, return this - if( path.equals( m_path ) ) - { - return this; - } - - // Otherwise, get the next component of the path - String localPath = FileSystem.toLocal( path, m_path ); - int slash = localPath.indexOf("/"); - if( slash >= 0 ) - { - localPath = localPath.substring( 0, slash ); - } + public FileInZip getFile( String path ) + { + // If we've reached the target, return this + if( path.equals( m_path ) ) + { + return this; + } + + // Otherwise, get the next component of the path + String localPath = FileSystem.toLocal( path, m_path ); + int slash = localPath.indexOf("/"); + if( slash >= 0 ) + { + localPath = localPath.substring( 0, slash ); + } - // And recurse down using it - FileInZip subFile = m_children.get( localPath ); - if( subFile != null ) - { - return subFile.getFile( path ); - } - - return null; - } - - public FileInZip getParent( String path ) - { - if( path.length() == 0 ) - { - return null; - } - - FileInZip file = getFile( FileSystem.getDirectory( path ) ); - if( file.isDirectory() ) - { - return file; - } - return null; - } - } - - private ZipFile m_zipFile; - private FileInZip m_root; - private String m_rootPath; + // And recurse down using it + FileInZip subFile = m_children.get( localPath ); + if( subFile != null ) + { + return subFile.getFile( path ); + } + + return null; + } + + public FileInZip getParent( String path ) + { + if( path.length() == 0 ) + { + return null; + } + + FileInZip file = getFile( FileSystem.getDirectory( path ) ); + if( file.isDirectory() ) + { + return file; + } + return null; + } + } + + private ZipFile m_zipFile; + private FileInZip m_root; + private String m_rootPath; - public JarMount( File jarFile, String subPath ) throws IOException - { - if( !jarFile.exists() || jarFile.isDirectory() ) - { - throw new FileNotFoundException(); - } - - // Open the zip file - try - { - m_zipFile = new ZipFile( jarFile ); - } - catch( Exception e ) - { - throw new IOException( "Error loading zip file" ); - } - - if( m_zipFile.getEntry( subPath ) == null ) - { - m_zipFile.close(); - throw new IOException( "Zip does not contain path" ); - } - - // Read in all the entries - Enumeration zipEntries = m_zipFile.entries(); - while( zipEntries.hasMoreElements() ) - { - ZipEntry entry = zipEntries.nextElement(); - String entryName = entry.getName(); - if( entryName.startsWith( subPath ) ) - { - entryName = FileSystem.toLocal( entryName, subPath ); - if( m_root == null ) - { - if( entryName.equals( "" ) ) - { - m_root = new FileInZip( entryName, entry.isDirectory(), entry.getSize() ); - m_rootPath = subPath; - if( !m_root.isDirectory() ) - { - break; - } - } - else - { - // TODO: handle this case. The code currently assumes we find the root before anything else - } - } - else - { - FileInZip parent = m_root.getParent( entryName ); - if( parent != null ) - { - parent.insertChild( new FileInZip( entryName, entry.isDirectory(), entry.getSize() ) ); - } - else - { - // TODO: handle this case. The code currently assumes we find folders before their contents - } - } - } - } - } - - // IMount implementation - - @Override - public boolean exists( String path ) throws IOException - { - FileInZip file = m_root.getFile( path ); + public JarMount( File jarFile, String subPath ) throws IOException + { + if( !jarFile.exists() || jarFile.isDirectory() ) + { + throw new FileNotFoundException(); + } + + // Open the zip file + try + { + m_zipFile = new ZipFile( jarFile ); + } + catch( Exception e ) + { + throw new IOException( "Error loading zip file" ); + } + + if( m_zipFile.getEntry( subPath ) == null ) + { + m_zipFile.close(); + throw new IOException( "Zip does not contain path" ); + } + + // Read in all the entries + Enumeration zipEntries = m_zipFile.entries(); + while( zipEntries.hasMoreElements() ) + { + ZipEntry entry = zipEntries.nextElement(); + String entryName = entry.getName(); + if( entryName.startsWith( subPath ) ) + { + entryName = FileSystem.toLocal( entryName, subPath ); + if( m_root == null ) + { + if( entryName.equals( "" ) ) + { + m_root = new FileInZip( entryName, entry.isDirectory(), entry.getSize() ); + m_rootPath = subPath; + if( !m_root.isDirectory() ) + { + break; + } + } + else + { + // TODO: handle this case. The code currently assumes we find the root before anything else + } + } + else + { + FileInZip parent = m_root.getParent( entryName ); + if( parent != null ) + { + parent.insertChild( new FileInZip( entryName, entry.isDirectory(), entry.getSize() ) ); + } + else + { + // TODO: handle this case. The code currently assumes we find folders before their contents + } + } + } + } + } + + // IMount implementation + + @Override + public boolean exists( String path ) throws IOException + { + FileInZip file = m_root.getFile( path ); return file != null; } - - @Override - public boolean isDirectory( String path ) throws IOException - { - FileInZip file = m_root.getFile( path ); - if( file != null ) - { - return file.isDirectory(); - } - return false; - } - - @Override - public void list( String path, List contents ) throws IOException - { - FileInZip file = m_root.getFile( path ); - if( file != null && file.isDirectory() ) - { - file.list( contents ); - } - else - { - throw new IOException( "Not a directory" ); - } - } - - @Override - public long getSize( String path ) throws IOException - { - FileInZip file = m_root.getFile( path ); - if( file != null ) - { - return file.getSize(); - } - throw new IOException( "No such file" ); - } + + @Override + public boolean isDirectory( String path ) throws IOException + { + FileInZip file = m_root.getFile( path ); + if( file != null ) + { + return file.isDirectory(); + } + return false; + } + + @Override + public void list( String path, List contents ) throws IOException + { + FileInZip file = m_root.getFile( path ); + if( file != null && file.isDirectory() ) + { + file.list( contents ); + } + else + { + throw new IOException( "Not a directory" ); + } + } + + @Override + public long getSize( String path ) throws IOException + { + FileInZip file = m_root.getFile( path ); + if( file != null ) + { + return file.getSize(); + } + throw new IOException( "No such file" ); + } - @Override - public InputStream openForRead( String path ) throws IOException - { - FileInZip file = m_root.getFile( path ); - if( file != null && !file.isDirectory() ) - { - try - { - String fullPath = m_rootPath; - if( path.length() > 0 ) - { - fullPath = fullPath + "/" + path; - } - ZipEntry entry = m_zipFile.getEntry( fullPath ); - if( entry != null ) - { - return m_zipFile.getInputStream( entry ); - } - } - catch( Exception e ) - { - // treat errors as non-existance of file - } - } - throw new IOException( "No such file" ); - } + @Override + public InputStream openForRead( String path ) throws IOException + { + FileInZip file = m_root.getFile( path ); + if( file != null && !file.isDirectory() ) + { + try + { + String fullPath = m_rootPath; + if( path.length() > 0 ) + { + fullPath = fullPath + "/" + path; + } + ZipEntry entry = m_zipFile.getEntry( fullPath ); + if( entry != null ) + { + return m_zipFile.getInputStream( entry ); + } + } + catch( Exception e ) + { + // treat errors as non-existance of file + } + } + throw new IOException( "No such file" ); + } } diff --git a/src/main/java/dan200/computercraft/core/filesystem/SubMount.java b/src/main/java/dan200/computercraft/core/filesystem/SubMount.java index ac650a0b9..fecdbd7dd 100644 --- a/src/main/java/dan200/computercraft/core/filesystem/SubMount.java +++ b/src/main/java/dan200/computercraft/core/filesystem/SubMount.java @@ -13,57 +13,57 @@ import java.util.List; public class SubMount implements IMount -{ - private IMount m_parent; - private String m_subPath; - - public SubMount( IMount parent, String subPath ) - { - m_parent = parent; - m_subPath = subPath; - } - - // IMount implementation - - @Override - public boolean exists( String path ) throws IOException - { - return m_parent.exists( getFullPath( path ) ); - } - - @Override - public boolean isDirectory( String path ) throws IOException - { - return m_parent.isDirectory( getFullPath( path ) ); - } - - @Override - public void list( String path, List contents ) throws IOException - { - m_parent.list( getFullPath( path ), contents ); - } - - @Override - public long getSize( String path ) throws IOException - { - return m_parent.getSize( getFullPath( path ) ); - } +{ + private IMount m_parent; + private String m_subPath; + + public SubMount( IMount parent, String subPath ) + { + m_parent = parent; + m_subPath = subPath; + } + + // IMount implementation + + @Override + public boolean exists( String path ) throws IOException + { + return m_parent.exists( getFullPath( path ) ); + } + + @Override + public boolean isDirectory( String path ) throws IOException + { + return m_parent.isDirectory( getFullPath( path ) ); + } + + @Override + public void list( String path, List contents ) throws IOException + { + m_parent.list( getFullPath( path ), contents ); + } + + @Override + public long getSize( String path ) throws IOException + { + return m_parent.getSize( getFullPath( path ) ); + } - @Override - public InputStream openForRead( String path ) throws IOException - { - return m_parent.openForRead( getFullPath( path ) ); - } - - private String getFullPath( String path ) - { - if( path.length() == 0 ) - { - return m_subPath; - } - else - { - return m_subPath + "/" + path; - } - } + @Override + public InputStream openForRead( String path ) throws IOException + { + return m_parent.openForRead( getFullPath( path ) ); + } + + private String getFullPath( String path ) + { + if( path.length() == 0 ) + { + return m_subPath; + } + else + { + return m_subPath + "/" + path; + } + } } diff --git a/src/main/java/dan200/computercraft/core/lua/ILuaMachine.java b/src/main/java/dan200/computercraft/core/lua/ILuaMachine.java index 3f0e7a322..45a5f3644 100644 --- a/src/main/java/dan200/computercraft/core/lua/ILuaMachine.java +++ b/src/main/java/dan200/computercraft/core/lua/ILuaMachine.java @@ -12,17 +12,17 @@ public interface ILuaMachine { - public void addAPI( ILuaAPI api ); - - public void loadBios( InputStream bios ); - public void handleEvent( String eventName, Object[] arguments ); - public void softAbort( String abortMessage ); - public void hardAbort( String abortMessage ); - - public boolean saveState( OutputStream output ); - public boolean restoreState( InputStream input ); - - public boolean isFinished(); - - public void unload(); + public void addAPI( ILuaAPI api ); + + public void loadBios( InputStream bios ); + public void handleEvent( String eventName, Object[] arguments ); + public void softAbort( String abortMessage ); + public void hardAbort( String abortMessage ); + + public boolean saveState( OutputStream output ); + public boolean restoreState( InputStream input ); + + public boolean isFinished(); + + public void unload(); } diff --git a/src/main/java/dan200/computercraft/core/lua/LuaJLuaMachine.java b/src/main/java/dan200/computercraft/core/lua/LuaJLuaMachine.java index 7363f14bb..16cefb4b8 100644 --- a/src/main/java/dan200/computercraft/core/lua/LuaJLuaMachine.java +++ b/src/main/java/dan200/computercraft/core/lua/LuaJLuaMachine.java @@ -31,78 +31,78 @@ public class LuaJLuaMachine implements ILuaMachine { private Computer m_computer; - private LuaValue m_globals; - private LuaValue m_loadString; - private LuaValue m_assert; - private LuaValue m_coroutine_create; - private LuaValue m_coroutine_resume; - private LuaValue m_coroutine_yield; - - private LuaValue m_mainRoutine; - private String m_eventFilter; - private String m_softAbortMessage; - private String m_hardAbortMessage; + private LuaValue m_globals; + private LuaValue m_loadString; + private LuaValue m_assert; + private LuaValue m_coroutine_create; + private LuaValue m_coroutine_resume; + private LuaValue m_coroutine_yield; + + private LuaValue m_mainRoutine; + private String m_eventFilter; + private String m_softAbortMessage; + private String m_hardAbortMessage; private Map m_valuesInProgress; private Map m_objectsInProgress; - public LuaJLuaMachine( Computer computer ) - { + public LuaJLuaMachine( Computer computer ) + { m_computer = computer; - // Create an environment to run in - m_globals = JsePlatform.debugGlobals(); - m_loadString = m_globals.get("loadstring"); - m_assert = m_globals.get("assert"); + // Create an environment to run in + m_globals = JsePlatform.debugGlobals(); + m_loadString = m_globals.get("loadstring"); + m_assert = m_globals.get("assert"); - LuaValue coroutine = m_globals.get("coroutine"); - final LuaValue native_coroutine_create = coroutine.get("create"); - - LuaValue debug = m_globals.get("debug"); - final LuaValue debug_sethook = debug.get("sethook"); - - coroutine.set("create", new OneArgFunction() { - @Override - public LuaValue call( LuaValue value ) - { - final LuaThread thread = native_coroutine_create.call( value ).checkthread(); - debug_sethook.invoke( new LuaValue[] { - thread, - new ZeroArgFunction() { - @Override - public LuaValue call() { - String hardAbortMessage = m_hardAbortMessage; - if( hardAbortMessage != null ) - { - LuaThread.yield(LuaValue.NIL); - } - return LuaValue.NIL; - } - }, - LuaValue.NIL, - LuaValue.valueOf(100000) - } ); - return thread; - } - }); - - m_coroutine_create = coroutine.get("create"); - m_coroutine_resume = coroutine.get("resume"); - m_coroutine_yield = coroutine.get("yield"); - - // Remove globals we don't want to expose - m_globals.set( "collectgarbage", LuaValue.NIL ); - m_globals.set( "dofile", LuaValue.NIL ); - m_globals.set( "loadfile", LuaValue.NIL ); - m_globals.set( "module", LuaValue.NIL ); - m_globals.set( "require", LuaValue.NIL ); - m_globals.set( "package", LuaValue.NIL ); - m_globals.set( "io", LuaValue.NIL ); - m_globals.set( "os", LuaValue.NIL ); - m_globals.set( "print", LuaValue.NIL ); - m_globals.set( "luajava", LuaValue.NIL ); - m_globals.set( "debug", LuaValue.NIL ); - m_globals.set( "newproxy", LuaValue.NIL ); + LuaValue coroutine = m_globals.get("coroutine"); + final LuaValue native_coroutine_create = coroutine.get("create"); + + LuaValue debug = m_globals.get("debug"); + final LuaValue debug_sethook = debug.get("sethook"); + + coroutine.set("create", new OneArgFunction() { + @Override + public LuaValue call( LuaValue value ) + { + final LuaThread thread = native_coroutine_create.call( value ).checkthread(); + debug_sethook.invoke( new LuaValue[] { + thread, + new ZeroArgFunction() { + @Override + public LuaValue call() { + String hardAbortMessage = m_hardAbortMessage; + if( hardAbortMessage != null ) + { + LuaThread.yield(LuaValue.NIL); + } + return LuaValue.NIL; + } + }, + LuaValue.NIL, + LuaValue.valueOf(100000) + } ); + return thread; + } + }); + + m_coroutine_create = coroutine.get("create"); + m_coroutine_resume = coroutine.get("resume"); + m_coroutine_yield = coroutine.get("yield"); + + // Remove globals we don't want to expose + m_globals.set( "collectgarbage", LuaValue.NIL ); + m_globals.set( "dofile", LuaValue.NIL ); + m_globals.set( "loadfile", LuaValue.NIL ); + m_globals.set( "module", LuaValue.NIL ); + m_globals.set( "require", LuaValue.NIL ); + m_globals.set( "package", LuaValue.NIL ); + m_globals.set( "io", LuaValue.NIL ); + m_globals.set( "os", LuaValue.NIL ); + m_globals.set( "print", LuaValue.NIL ); + m_globals.set( "luajava", LuaValue.NIL ); + m_globals.set( "debug", LuaValue.NIL ); + m_globals.set( "newproxy", LuaValue.NIL ); m_globals.set( "__inext", LuaValue.NIL ); // Add version globals @@ -114,41 +114,41 @@ public LuaValue call() { m_globals.set( "_CC_DISABLE_LUA51_FEATURES", toValue( true ) ); } - // Our main function will go here - m_mainRoutine = null; - m_eventFilter = null; + // Our main function will go here + m_mainRoutine = null; + m_eventFilter = null; - m_softAbortMessage = null; - m_hardAbortMessage = null; - } - - @Override - public void addAPI( ILuaAPI api ) - { - // Add the methods of an API to the global table - LuaTable table = wrapLuaObject( api ); - String[] names = api.getNames(); - for( int i=0; i= 1 && results[0].equals( "terminate" ) ) - { - throw new LuaException( "Terminated", 0 ); - } - return results; - } - - @Override - public Object[] pullEventRaw( String filter ) throws InterruptedException - { - return yield( new Object[] { filter } ); - } - - @Override - public Object[] yield( Object[] yieldArgs ) throws InterruptedException - { - try - { - LuaValue[] yieldValues = toValues( yieldArgs, 0 ); - Varargs results = m_coroutine_yield.invoke( LuaValue.varargsOf( yieldValues ) ); - return toObjects( results, 1 ); - } - catch( OrphanedThread e ) - { - throw new InterruptedException(); - } - } + + private LuaTable wrapLuaObject( ILuaObject object ) + { + LuaTable table = new LuaTable(); + String[] methods = object.getMethodNames(); + for(int i=0; i= 1 && results[0].equals( "terminate" ) ) + { + throw new LuaException( "Terminated", 0 ); + } + return results; + } + + @Override + public Object[] pullEventRaw( String filter ) throws InterruptedException + { + return yield( new Object[] { filter } ); + } + + @Override + public Object[] yield( Object[] yieldArgs ) throws InterruptedException + { + try + { + LuaValue[] yieldValues = toValues( yieldArgs, 0 ); + Varargs results = m_coroutine_yield.invoke( LuaValue.varargsOf( yieldValues ) ); + return toObjects( results, 1 ); + } + catch( OrphanedThread e ) + { + throw new InterruptedException(); + } + } @Override public long issueMainThreadTask( final ILuaTask task ) throws LuaException @@ -471,49 +471,49 @@ public Object[] executeMainThreadTask( final ILuaTask task ) throws LuaException } } - }, method, arguments ); - } - catch( InterruptedException e ) - { - throw new OrphanedThread(); - } - catch( LuaException e ) - { - throw new LuaError( e.getMessage(), e.getLevel() ); - } + }, method, arguments ); + } + catch( InterruptedException e ) + { + throw new OrphanedThread(); + } + catch( LuaException e ) + { + throw new LuaError( e.getMessage(), e.getLevel() ); + } catch( Throwable t ) { throw new LuaError( "Java Exception Thrown: " + t.toString(), 0 ); } - return LuaValue.varargsOf( toValues( results, 0 ) ); - } - } ); - } - } - return table; - } + return LuaValue.varargsOf( toValues( results, 0 ) ); + } + } ); + } + } + return table; + } private LuaValue toValue( Object object ) - { - if( object == null ) + { + if( object == null ) { - return LuaValue.NIL; - } + return LuaValue.NIL; + } else if( object instanceof Number ) { - double d = ((Number)object).doubleValue(); - return LuaValue.valueOf( d ); - } + double d = ((Number)object).doubleValue(); + return LuaValue.valueOf( d ); + } else if( object instanceof Boolean ) { - boolean b = ((Boolean)object).booleanValue(); - return LuaValue.valueOf( b ); - } + boolean b = ((Boolean)object).booleanValue(); + return LuaValue.valueOf( b ); + } else if( object instanceof String ) { - String s = object.toString(); + String s = object.toString(); return LuaValue.valueOf( s ); - } + } else if( object instanceof Map ) { // Table: @@ -555,66 +555,66 @@ else if( m_valuesInProgress.containsKey( object ) ) m_valuesInProgress = null; } } - } + } else if( object instanceof ILuaObject ) { - LuaValue table = wrapLuaObject( (ILuaObject)object ); - return table; - } + LuaValue table = wrapLuaObject( (ILuaObject)object ); + return table; + } else { - return LuaValue.NIL; - } - } + return LuaValue.NIL; + } + } - private LuaValue[] toValues( Object[] objects, int leaveEmpty ) - { - if( objects == null || objects.length == 0 ) - { - return new LuaValue[ leaveEmpty ]; - } - - LuaValue[] values = new LuaValue[objects.length + leaveEmpty]; - for( int i=0; i= 0 && y < m_height ) + if( y >= 0 && y < m_height ) { m_text[ y ].fill( ' ' ); m_textColour[ y ].fill( base16.charAt( m_cursorColour ) ); m_backgroundColour[ y ].fill( base16.charAt( m_cursorBackgroundColour ) ); m_changed = true; } - } - - public TextBuffer getLine( int y ) + } + + public TextBuffer getLine( int y ) { - if( y >= 0 && y < m_height ) - { - return m_text[ y ]; - } + if( y >= 0 && y < m_height ) + { + return m_text[ y ]; + } return null; - } + } - public void setLine( int y, String text, String textColour, String backgroundColour ) + public void setLine( int y, String text, String textColour, String backgroundColour ) { m_text[y].write( text ); m_textColour[y].write( textColour ); m_backgroundColour[y].write( backgroundColour ); - m_changed = true; - } - - public TextBuffer getTextColourLine( int y ) + m_changed = true; + } + + public TextBuffer getTextColourLine( int y ) { - if( y>=0 && y=0 && y= 0 ) @@ -108,27 +108,27 @@ private void setupComputerAfterPlacement( ItemStack stack, IComputerTile compute { computer.setLabel( label ); } - } + } @Override public String getUnlocalizedName( ItemStack stack ) { - switch( getFamily( stack ) ) - { - case Normal: + switch( getFamily( stack ) ) + { + case Normal: default: - { - return "tile.computercraft:computer"; - } - case Advanced: - { - return "tile.computercraft:advanced_computer"; - } + { + return "tile.computercraft:computer"; + } + case Advanced: + { + return "tile.computercraft:advanced_computer"; + } case Command: { return "tile.computercraft:command_computer"; } - } + } } // IComputerItem implementation diff --git a/src/main/java/dan200/computercraft/shared/media/items/ItemDiskExpanded.java b/src/main/java/dan200/computercraft/shared/media/items/ItemDiskExpanded.java index fa56c27c5..a3643e5c2 100644 --- a/src/main/java/dan200/computercraft/shared/media/items/ItemDiskExpanded.java +++ b/src/main/java/dan200/computercraft/shared/media/items/ItemDiskExpanded.java @@ -12,56 +12,56 @@ import net.minecraft.nbt.NBTTagCompound; public class ItemDiskExpanded extends ItemDiskLegacy -{ +{ public ItemDiskExpanded() { } public static ItemStack createFromIDAndColour( int id, String label, int colour ) { - ItemStack stack = new ItemStack( ComputerCraft.Items.diskExpanded, 1, 0 ); - - NBTTagCompound nbt = stack.getTagCompound(); + ItemStack stack = new ItemStack( ComputerCraft.Items.diskExpanded, 1, 0 ); + + NBTTagCompound nbt = stack.getTagCompound(); if( nbt == null ) { nbt = new NBTTagCompound(); stack.setTagCompound(nbt); } nbt.setInteger( "color", colour ); - ComputerCraft.Items.diskExpanded.setDiskID( stack, id ); + ComputerCraft.Items.diskExpanded.setDiskID( stack, id ); ComputerCraft.Items.diskExpanded.setLabel( stack, label ); return stack; } - @Override - public int getDiskID( ItemStack stack ) - { - NBTTagCompound nbt = stack.getTagCompound(); - if( nbt != null && nbt.hasKey( "diskID" ) ) - { - return nbt.getInteger( "diskID" ); - } - return -1; - } - - @Override - protected void setDiskID( ItemStack stack, int id ) - { - if( id >= 0 ) - { - NBTTagCompound nbt = stack.getTagCompound(); - if( nbt == null ) - { - nbt = new NBTTagCompound(); - stack.setTagCompound( nbt ); - } - nbt.setInteger( "diskID", id ); - } - } - - public int getColor( ItemStack stack ) - { + @Override + public int getDiskID( ItemStack stack ) + { NBTTagCompound nbt = stack.getTagCompound(); - return nbt != null && nbt.hasKey("color") ? nbt.getInteger("color") : Colour.values()[ Math.min(15, stack.getItemDamage()) ].getHex(); - } + if( nbt != null && nbt.hasKey( "diskID" ) ) + { + return nbt.getInteger( "diskID" ); + } + return -1; + } + + @Override + protected void setDiskID( ItemStack stack, int id ) + { + if( id >= 0 ) + { + NBTTagCompound nbt = stack.getTagCompound(); + if( nbt == null ) + { + nbt = new NBTTagCompound(); + stack.setTagCompound( nbt ); + } + nbt.setInteger( "diskID", id ); + } + } + + public int getColor( ItemStack stack ) + { + NBTTagCompound nbt = stack.getTagCompound(); + return nbt != null && nbt.hasKey("color") ? nbt.getInteger("color") : Colour.values()[ Math.min(15, stack.getItemDamage()) ].getHex(); + } } diff --git a/src/main/java/dan200/computercraft/shared/media/items/ItemDiskLegacy.java b/src/main/java/dan200/computercraft/shared/media/items/ItemDiskLegacy.java index b104fca91..348faa531 100644 --- a/src/main/java/dan200/computercraft/shared/media/items/ItemDiskLegacy.java +++ b/src/main/java/dan200/computercraft/shared/media/items/ItemDiskLegacy.java @@ -23,60 +23,60 @@ import java.util.List; public class ItemDiskLegacy extends Item - implements IMedia + implements IMedia { public ItemDiskLegacy() { setMaxStackSize( 1 ); - setHasSubtypes( true ); - setUnlocalizedName( "computercraft:disk" ); + setHasSubtypes( true ); + setUnlocalizedName( "computercraft:disk" ); setCreativeTab( ComputerCraft.mainCreativeTab ); } - @Override + @Override public void getSubItems( Item itemID, CreativeTabs tabs, List list ) { - for( int colour=0; colour<16; ++colour ) - { + for( int colour=0; colour<16; ++colour ) + { ItemStack stack = createFromIDAndColour( -1, null, Colour.values()[ colour ].getHex() ); if( stack.getItem() == this ) { - list.add( stack ); + list.add( stack ); } - } + } } - + public static ItemStack createFromIDAndColour( int id, String label, int colour ) { - if( colour != Colour.Blue.getHex() ) - { - return ItemDiskExpanded.createFromIDAndColour( id, label, colour ); - } - - ItemStack stack = new ItemStack( ComputerCraft.Items.disk, 1 ); - ComputerCraft.Items.disk.setDiskID( stack, id ); + if( colour != Colour.Blue.getHex() ) + { + return ItemDiskExpanded.createFromIDAndColour( id, label, colour ); + } + + ItemStack stack = new ItemStack( ComputerCraft.Items.disk, 1 ); + ComputerCraft.Items.disk.setDiskID( stack, id ); ComputerCraft.Items.disk.setLabel( stack, label ); - return stack; + return stack; } - public int getDiskID( ItemStack stack ) - { - int damage = stack.getItemDamage(); - if( damage > 0 ) - { - return damage; - } - return -1; - } + public int getDiskID( ItemStack stack ) + { + int damage = stack.getItemDamage(); + if( damage > 0 ) + { + return damage; + } + return -1; + } - protected void setDiskID( ItemStack stack, int id ) - { - if( id > 0 ) { - stack.setItemDamage( id ); - } else { - stack.setItemDamage( 0 ); - } - } + protected void setDiskID( ItemStack stack, int id ) + { + if( id > 0 ) { + stack.setItemDamage( id ); + } else { + stack.setItemDamage( 0 ); + } + } @Override public void addInformation( ItemStack stack, EntityPlayer player, List list, boolean debug ) @@ -94,18 +94,18 @@ public void addInformation( ItemStack stack, EntityPlayer player, List list, boo // IMedia implementation @Override - public String getLabel( ItemStack stack ) - { + public String getLabel( ItemStack stack ) + { if( stack.hasDisplayName() ) { return stack.getDisplayName(); } return null; - } - + } + @Override - public boolean setLabel( ItemStack stack, String label ) - { + public boolean setLabel( ItemStack stack, String label ) + { if( label != null ) { stack.setStackDisplayName( label ); @@ -115,38 +115,38 @@ public boolean setLabel( ItemStack stack, String label ) stack.clearCustomName(); } return true; - } - + } + @Override - public String getAudioTitle( ItemStack stack ) - { - return null; - } - + public String getAudioTitle( ItemStack stack ) + { + return null; + } + @Override - public SoundEvent getAudio( ItemStack stack ) - { - return null; - } + public SoundEvent getAudio( ItemStack stack ) + { + return null; + } @Override public IMount createDataMount( ItemStack stack, World world ) { - int diskID = getDiskID( stack ); - if( diskID < 0 ) - { - diskID = ComputerCraft.createUniqueNumberedSaveDir( world, "computer/disk" ); - setDiskID( stack, diskID ); - } - return ComputerCraftAPI.createSaveDirMount( world, "computer/disk/" + diskID, ComputerCraft.floppySpaceLimit ); + int diskID = getDiskID( stack ); + if( diskID < 0 ) + { + diskID = ComputerCraft.createUniqueNumberedSaveDir( world, "computer/disk" ); + setDiskID( stack, diskID ); + } + return ComputerCraftAPI.createSaveDirMount( world, "computer/disk/" + diskID, ComputerCraft.floppySpaceLimit ); } - public int getColor( ItemStack stack ) - { - return Colour.Blue.getHex(); - } + public int getColor( ItemStack stack ) + { + return Colour.Blue.getHex(); + } - @Override + @Override public boolean doesSneakBypassUse( ItemStack stack, IBlockAccess world, BlockPos pos, EntityPlayer player ) { return true; diff --git a/src/main/java/dan200/computercraft/shared/media/items/ItemPrintout.java b/src/main/java/dan200/computercraft/shared/media/items/ItemPrintout.java index d18ba6300..6aed1d791 100644 --- a/src/main/java/dan200/computercraft/shared/media/items/ItemPrintout.java +++ b/src/main/java/dan200/computercraft/shared/media/items/ItemPrintout.java @@ -20,74 +20,74 @@ import java.util.List; public class ItemPrintout extends Item -{ - public static final int LINES_PER_PAGE = 21; - public static final int LINE_MAX_LENGTH = 25; - public static final int MAX_PAGES = 16; - - public enum Type - { - Single, - Multiple, - Book - } +{ + public static final int LINES_PER_PAGE = 21; + public static final int LINE_MAX_LENGTH = 25; + public static final int MAX_PAGES = 16; + + public enum Type + { + Single, + Multiple, + Book + } public ItemPrintout() { setMaxStackSize( 1 ); - setHasSubtypes( true ); - setUnlocalizedName( "computercraft:page" ); + setHasSubtypes( true ); + setUnlocalizedName( "computercraft:page" ); setCreativeTab( ComputerCraft.mainCreativeTab ); } - - @Override + + @Override public void getSubItems( Item itemID, CreativeTabs tabs, List list ) { - list.add( createSingleFromTitleAndText( null, new String[ LINES_PER_PAGE ], new String[ LINES_PER_PAGE ] ) ); - list.add( createMultipleFromTitleAndText( null, new String[ 2*LINES_PER_PAGE ], new String[ 2*LINES_PER_PAGE ] ) ); - list.add( createBookFromTitleAndText( null, new String[ 2*LINES_PER_PAGE ], new String[ 2*LINES_PER_PAGE ] ) ); + list.add( createSingleFromTitleAndText( null, new String[ LINES_PER_PAGE ], new String[ LINES_PER_PAGE ] ) ); + list.add( createMultipleFromTitleAndText( null, new String[ 2*LINES_PER_PAGE ], new String[ 2*LINES_PER_PAGE ] ) ); + list.add( createBookFromTitleAndText( null, new String[ 2*LINES_PER_PAGE ], new String[ 2*LINES_PER_PAGE ] ) ); } @Override public void addInformation( ItemStack itemstack, EntityPlayer par2EntityPlayer, List list, boolean flag ) { - String title = getTitle( itemstack ); - if( title != null && title.length() > 0 ) - { - list.add( title ); - } + String title = getTitle( itemstack ); + if( title != null && title.length() > 0 ) + { + list.add( title ); + } } @Override public String getUnlocalizedName( ItemStack stack ) { Type type = getType( stack ); - switch( type ) - { - case Single: + switch( type ) + { + case Single: default: - { - return "item.computercraft:page"; - } - case Multiple: - { - return "item.computercraft:pages"; - } - case Book: - { + { + return "item.computercraft:page"; + } + case Multiple: + { + return "item.computercraft:pages"; + } + case Book: + { return "item.computercraft:book"; - } - } + } + } } @Override public ActionResult onItemRightClick( ItemStack stack, World world, EntityPlayer player, EnumHand hand ) { - if( !world.isRemote ) - { - ComputerCraft.openPrintoutGUI( player ); + if( !world.isRemote ) + { + ComputerCraft.openPrintoutGUI( player ); return new ActionResult( EnumActionResult.SUCCESS, stack ); - } + } return new ActionResult( EnumActionResult.PASS, stack ); } @@ -116,14 +116,14 @@ private static ItemStack createFromTitleAndText( Type type, String title, String } // Create stack - ItemStack stack = new ItemStack( ComputerCraft.Items.printout, 1, damage ); + ItemStack stack = new ItemStack( ComputerCraft.Items.printout, 1, damage ); // Build NBT - NBTTagCompound nbt = new NBTTagCompound(); - if( title != null ) - { - nbt.setString( "title", title ); - } + NBTTagCompound nbt = new NBTTagCompound(); + if( title != null ) + { + nbt.setString( "title", title ); + } if( text != null ) { nbt.setInteger( "pages", text.length / LINES_PER_PAGE ); @@ -151,20 +151,20 @@ private static ItemStack createFromTitleAndText( Type type, String title, String return stack; } - public static ItemStack createSingleFromTitleAndText( String title, String[] text, String[] colours ) - { - return createFromTitleAndText( Type.Single, title, text, colours ); - } - - public static ItemStack createMultipleFromTitleAndText( String title, String[] text, String[] colours ) - { - return createFromTitleAndText( Type.Multiple, title, text, colours ); - } + public static ItemStack createSingleFromTitleAndText( String title, String[] text, String[] colours ) + { + return createFromTitleAndText( Type.Single, title, text, colours ); + } + + public static ItemStack createMultipleFromTitleAndText( String title, String[] text, String[] colours ) + { + return createFromTitleAndText( Type.Multiple, title, text, colours ); + } - public static ItemStack createBookFromTitleAndText( String title, String[] text, String[] colours ) - { - return createFromTitleAndText( Type.Book, title, text, colours ); - } + public static ItemStack createBookFromTitleAndText( String title, String[] text, String[] colours ) + { + return createFromTitleAndText( Type.Book, title, text, colours ); + } public static Type getType( ItemStack stack ) { @@ -187,61 +187,61 @@ public static Type getType( ItemStack stack ) } } - public static String getTitle( ItemStack stack ) - { - NBTTagCompound nbt = stack.getTagCompound(); - if( nbt != null && nbt.hasKey( "title" ) ) - { - return nbt.getString( "title" ); - } - return null; - } - - public static int getPageCount( ItemStack stack ) - { - NBTTagCompound nbt = stack.getTagCompound(); - if( nbt != null && nbt.hasKey( "pages" ) ) - { - return nbt.getInteger( "pages" ); - } - return 1; - } - - public static String[] getText( ItemStack stack ) - { - NBTTagCompound nbt = stack.getTagCompound(); - int numLines = getPageCount( stack ) * LINES_PER_PAGE; - String[] lines = new String[numLines]; - for( int i=0; i 0 ) - { - list.add( label ); - } + String label = getTitle( stack ); + if( label != null && label.length() > 0 ) + { + list.add( label ); + } } - @Override + @Override public boolean doesSneakBypassUse( ItemStack stack, IBlockAccess world, BlockPos pos, EntityPlayer player ) { return true; } - // IMedia implementation + // IMedia implementation @Override - public String getLabel( ItemStack stack ) - { - return getTitle( stack ); - } - + public String getLabel( ItemStack stack ) + { + return getTitle( stack ); + } + @Override - public boolean setLabel( ItemStack stack, String label ) - { - return false; - } - + public boolean setLabel( ItemStack stack, String label ) + { + return false; + } + @Override - public String getAudioTitle( ItemStack stack ) - { - return null; - } - + public String getAudioTitle( ItemStack stack ) + { + return null; + } + @Override - public SoundEvent getAudio( ItemStack stack ) - { - return null; - } + public SoundEvent getAudio( ItemStack stack ) + { + return null; + } @Override public IMount createDataMount( ItemStack stack, World world ) @@ -112,30 +112,30 @@ else if( rootTreasure.exists( "deprecated/" + subPath ) ) public static ItemStack create( String subPath, int colourIndex ) { - NBTTagCompound nbt = new NBTTagCompound(); - nbt.setString( "subPath", subPath ); - - int slash = subPath.indexOf( "/" ); - if( slash >= 0 ) - { - String author = subPath.substring( 0, slash ); - String title = subPath.substring( slash + 1 ); - nbt.setString( "title", "\"" + title + "\" by " + author ); - } - else - { - nbt.setString( "title", "untitled" ); - } - nbt.setInteger( "colour", Colour.values()[ colourIndex ].getHex() ); - - ItemStack result = new ItemStack( ComputerCraft.Items.treasureDisk, 1, 0 ); - result.setTagCompound( nbt ); - return result; + NBTTagCompound nbt = new NBTTagCompound(); + nbt.setString( "subPath", subPath ); + + int slash = subPath.indexOf( "/" ); + if( slash >= 0 ) + { + String author = subPath.substring( 0, slash ); + String title = subPath.substring( slash + 1 ); + nbt.setString( "title", "\"" + title + "\" by " + author ); + } + else + { + nbt.setString( "title", "untitled" ); + } + nbt.setInteger( "colour", Colour.values()[ colourIndex ].getHex() ); + + ItemStack result = new ItemStack( ComputerCraft.Items.treasureDisk, 1, 0 ); + result.setTagCompound( nbt ); + return result; } private static IMount getTreasureMount() { - return ComputerCraft.createResourceMount( ComputerCraft.class, "computercraft", "lua/treasure" ); + return ComputerCraft.createResourceMount( ComputerCraft.class, "computercraft", "lua/treasure" ); } // private stuff @@ -145,9 +145,9 @@ public String getTitle( ItemStack stack ) NBTTagCompound nbt = stack.getTagCompound(); if( nbt != null && nbt.hasKey( "title" ) ) { - return nbt.getString( "title" ); + return nbt.getString( "title" ); } - return "'alongtimeago' by dan200"; + return "'alongtimeago' by dan200"; } public String getSubPath( ItemStack stack ) @@ -155,9 +155,9 @@ public String getSubPath( ItemStack stack ) NBTTagCompound nbt = stack.getTagCompound(); if( nbt != null && nbt.hasKey( "subPath" ) ) { - return nbt.getString( "subPath" ); + return nbt.getString( "subPath" ); } - return "dan200/alongtimeago"; + return "dan200/alongtimeago"; } public int getColour( ItemStack stack ) @@ -165,8 +165,8 @@ public int getColour( ItemStack stack ) NBTTagCompound nbt = stack.getTagCompound(); if( nbt != null && nbt.hasKey( "colour" ) ) { - return nbt.getInteger( "colour" ); + return nbt.getInteger( "colour" ); } - return Colour.Blue.getHex(); + return Colour.Blue.getHex(); } } diff --git a/src/main/java/dan200/computercraft/shared/media/items/RecordMedia.java b/src/main/java/dan200/computercraft/shared/media/items/RecordMedia.java index 1054db403..e770268dc 100644 --- a/src/main/java/dan200/computercraft/shared/media/items/RecordMedia.java +++ b/src/main/java/dan200/computercraft/shared/media/items/RecordMedia.java @@ -17,38 +17,38 @@ // An implementation of IMedia for ItemRecord's public class RecordMedia implements IMedia { - public RecordMedia() - { - } - - @Override - public String getLabel( ItemStack stack ) - { - return getAudioTitle( stack ); - } - - @Override - public boolean setLabel( ItemStack stack, String label ) - { - return false; - } - - @Override - public String getAudioTitle( ItemStack stack ) - { - return ComputerCraft.getRecordInfo( stack ); - } - - @Override - public SoundEvent getAudio( ItemStack stack ) - { - ItemRecord itemRecord = (ItemRecord)stack.getItem(); - return itemRecord.getSound(); - } + public RecordMedia() + { + } + + @Override + public String getLabel( ItemStack stack ) + { + return getAudioTitle( stack ); + } - @Override + @Override + public boolean setLabel( ItemStack stack, String label ) + { + return false; + } + + @Override + public String getAudioTitle( ItemStack stack ) + { + return ComputerCraft.getRecordInfo( stack ); + } + + @Override + public SoundEvent getAudio( ItemStack stack ) + { + ItemRecord itemRecord = (ItemRecord)stack.getItem(); + return itemRecord.getSound(); + } + + @Override public IMount createDataMount( ItemStack stack, World world ) { - return null; + return null; } } diff --git a/src/main/java/dan200/computercraft/shared/media/recipes/DiskRecipe.java b/src/main/java/dan200/computercraft/shared/media/recipes/DiskRecipe.java index 7e11aa030..5d0cad320 100644 --- a/src/main/java/dan200/computercraft/shared/media/recipes/DiskRecipe.java +++ b/src/main/java/dan200/computercraft/shared/media/recipes/DiskRecipe.java @@ -45,28 +45,28 @@ public boolean matches( InventoryCrafting inventory, World world ) } else if( var6.getItem() == Items.DYE ) { - dyeFound = true; + dyeFound = true; } else if( var6.getItem() == Items.PAPER ) { - if(paperFound || diskFound) - { - return false; - } - paperFound = true; + if(paperFound || diskFound) + { + return false; + } + paperFound = true; } else if (var6.getItem() == Items.REDSTONE) { - if (redstoneFound || diskFound) - { - return false; - } + if (redstoneFound || diskFound) + { + return false; + } - redstoneFound = true; + redstoneFound = true; } else { - return false; + return false; } } } @@ -105,7 +105,7 @@ public ItemStack getCraftingResult(InventoryCrafting par1InventoryCrafting) } else if (var8.getItem() == Items.DYE) { - dyeFound = true; + dyeFound = true; float[] var14 = Colour.values()[ var8.getItemDamage() & 0xf ].getRGB(); int var16 = (int)(var14[0] * 255.0F); int var15 = (int)(var14[1] * 255.0F); @@ -118,14 +118,14 @@ else if (var8.getItem() == Items.DYE) } else if (!(var8.getItem() != Items.PAPER || var8.getItem() != Items.REDSTONE)) { - return null; + return null; } } } if( !dyeFound ) { - return ItemDiskLegacy.createFromIDAndColour( diskID, diskLabel, Colour.Blue.getHex() ); + return ItemDiskLegacy.createFromIDAndColour( diskID, diskLabel, Colour.Blue.getHex() ); } var7 = var3[0] / var5; diff --git a/src/main/java/dan200/computercraft/shared/media/recipes/PrintoutRecipe.java b/src/main/java/dan200/computercraft/shared/media/recipes/PrintoutRecipe.java index 7eeb79cf3..36638e011 100644 --- a/src/main/java/dan200/computercraft/shared/media/recipes/PrintoutRecipe.java +++ b/src/main/java/dan200/computercraft/shared/media/recipes/PrintoutRecipe.java @@ -20,130 +20,130 @@ public PrintoutRecipe( ) { } - @Override - public int getRecipeSize() - { - return 3; - } - - @Override + @Override + public int getRecipeSize() + { + return 3; + } + + @Override public ItemStack getRecipeOutput() { return ItemPrintout.createMultipleFromTitleAndText( null, null, null ); } - @Override + @Override public boolean matches( InventoryCrafting _inventory, World world ) { - return (getCraftingResult( _inventory ) != null); + return (getCraftingResult( _inventory ) != null); } - @Override + @Override public ItemStack getCraftingResult( InventoryCrafting inventory ) { - // See if we match the recipe, and extract the input disk ID and dye colour - int numPages = 0; - int numPrintouts = 0; - ItemStack[] printouts = null; - boolean stringFound = false; - boolean leatherFound = false; - boolean printoutFound = false; - for( int y=0; y= (leatherFound ? 1 : 2) ) - { - String[] text = new String[ numPages * ItemPrintout.LINES_PER_PAGE ]; - String[] colours = new String[ numPages * ItemPrintout.LINES_PER_PAGE ]; - int line = 0; - - for( int printout=0; printout= (leatherFound ? 1 : 2) ) + { + String[] text = new String[ numPages * ItemPrintout.LINES_PER_PAGE ]; + String[] colours = new String[ numPages * ItemPrintout.LINES_PER_PAGE ]; + int line = 0; + + for( int printout=0; printout 66.5F ) - { + break; + } + case Monitor: + case AdvancedMonitor: + { + if( tile != null && tile instanceof TileMonitor ) + { + int direction = DirectionUtil.fromEntityRot( player ).getIndex(); + if( player.rotationPitch > 66.5F ) + { direction += 12; - } - else if( player.rotationPitch < -66.5F ) - { + } + else if( player.rotationPitch < -66.5F ) + { direction += 6; - } + } - TileMonitor monitor = (TileMonitor)tile; + TileMonitor monitor = (TileMonitor)tile; if( world.isRemote ) { monitor.setDir( direction ); @@ -578,9 +578,9 @@ else if( player.rotationPitch < -66.5F ) monitor.contract(); monitor.expand(); } - } - break; - } - } + } + break; + } + } } } diff --git a/src/main/java/dan200/computercraft/shared/peripheral/common/ItemAdvancedModem.java b/src/main/java/dan200/computercraft/shared/peripheral/common/ItemAdvancedModem.java index 1849e9174..dd40f9a6f 100644 --- a/src/main/java/dan200/computercraft/shared/peripheral/common/ItemAdvancedModem.java +++ b/src/main/java/dan200/computercraft/shared/peripheral/common/ItemAdvancedModem.java @@ -17,7 +17,7 @@ public class ItemAdvancedModem extends ItemPeripheralBase { - public ItemAdvancedModem( Block block ) + public ItemAdvancedModem( Block block ) { super( block ); setUnlocalizedName( "computercraft:advanced_modem" ); @@ -50,7 +50,7 @@ public ItemStack create( PeripheralType type, String label, int quantity ) @Override public void getSubItems( Item itemID, CreativeTabs tabs, List list ) { - list.add( PeripheralItemFactory.create( PeripheralType.AdvancedModem, null, 1 ) ); + list.add( PeripheralItemFactory.create( PeripheralType.AdvancedModem, null, 1 ) ); } @Override diff --git a/src/main/java/dan200/computercraft/shared/peripheral/common/ItemCable.java b/src/main/java/dan200/computercraft/shared/peripheral/common/ItemCable.java index 0606513b4..a0b2ebbd6 100644 --- a/src/main/java/dan200/computercraft/shared/peripheral/common/ItemCable.java +++ b/src/main/java/dan200/computercraft/shared/peripheral/common/ItemCable.java @@ -28,7 +28,7 @@ public class ItemCable extends ItemPeripheralBase { - public ItemCable( Block block ) + public ItemCable( Block block ) { super( block ); setUnlocalizedName( "computercraft:cable" ); @@ -62,100 +62,100 @@ public ItemStack create( PeripheralType type, String label, int quantity ) return stack; } - @Override + @Override public void getSubItems( Item itemID, CreativeTabs tabs, List list ) { list.add( PeripheralItemFactory.create( PeripheralType.WiredModem, null, 1 ) ); list.add( PeripheralItemFactory.create( PeripheralType.Cable, null, 1 ) ); } - @Override + @Override public EnumActionResult onItemUse( ItemStack stack, EntityPlayer player, World world, BlockPos pos, EnumHand hand, EnumFacing side, float fx, float fy, float fz ) { - if( !canPlaceBlockOnSide( world, pos, side, player, stack ) ) - { - return EnumActionResult.FAIL; - } + if( !canPlaceBlockOnSide( world, pos, side, player, stack ) ) + { + return EnumActionResult.FAIL; + } // Try to add a cable to a modem - PeripheralType type = getPeripheralType( stack ); - Block existing = world.getBlockState( pos ).getBlock(); + PeripheralType type = getPeripheralType( stack ); + Block existing = world.getBlockState( pos ).getBlock(); IBlockState existingState = world.getBlockState( pos ); - if( existing == ComputerCraft.Blocks.cable ) - { - PeripheralType existingType = ComputerCraft.Blocks.cable.getPeripheralType( world, pos ); - if( existingType == PeripheralType.WiredModem && type == PeripheralType.Cable ) - { - if( stack.stackSize > 0 ) - { - world.setBlockState( pos, existingState.withProperty( BlockCable.Properties.CABLE, true ), 3 ); + if( existing == ComputerCraft.Blocks.cable ) + { + PeripheralType existingType = ComputerCraft.Blocks.cable.getPeripheralType( world, pos ); + if( existingType == PeripheralType.WiredModem && type == PeripheralType.Cable ) + { + if( stack.stackSize > 0 ) + { + world.setBlockState( pos, existingState.withProperty( BlockCable.Properties.CABLE, true ), 3 ); world.playSound( null, pos.getX() + 0.5, pos.getY() + 0.5, pos.getZ() + 0.5, ComputerCraft.Blocks.cable.getSoundType().getBreakSound(), SoundCategory.BLOCKS, (ComputerCraft.Blocks.cable.getSoundType().getVolume() + 1.0F ) / 2.0F, ComputerCraft.Blocks.cable.getSoundType().getPitch() * 0.8F); - stack.stackSize--; - - TileEntity tile = world.getTileEntity( pos ); - if( tile != null && tile instanceof TileCable ) - { - TileCable cable = (TileCable)tile; - cable.networkChanged(); - } - return EnumActionResult.SUCCESS; - } - return EnumActionResult.FAIL; - } - } + stack.stackSize--; + + TileEntity tile = world.getTileEntity( pos ); + if( tile != null && tile instanceof TileCable ) + { + TileCable cable = (TileCable)tile; + cable.networkChanged(); + } + return EnumActionResult.SUCCESS; + } + return EnumActionResult.FAIL; + } + } // Try to add on the side of something - if( !existing.isAir( existingState, world, pos ) && (type == PeripheralType.Cable || existing.isSideSolid( existingState, world, pos, side )) ) - { + if( !existing.isAir( existingState, world, pos ) && (type == PeripheralType.Cable || existing.isSideSolid( existingState, world, pos, side )) ) + { BlockPos offset = pos.offset( side ); - Block offsetExisting = world.getBlockState( offset ).getBlock(); + Block offsetExisting = world.getBlockState( offset ).getBlock(); IBlockState offsetExistingState = world.getBlockState( offset ); - if( offsetExisting == ComputerCraft.Blocks.cable ) - { + if( offsetExisting == ComputerCraft.Blocks.cable ) + { // Try to add a modem to a cable PeripheralType offsetExistingType = ComputerCraft.Blocks.cable.getPeripheralType( world, offset ); - if( offsetExistingType == PeripheralType.Cable && type == PeripheralType.WiredModem ) - { - if( stack.stackSize > 0 ) - { + if( offsetExistingType == PeripheralType.Cable && type == PeripheralType.WiredModem ) + { + if( stack.stackSize > 0 ) + { world.setBlockState( offset, offsetExistingState.withProperty( BlockCable.Properties.MODEM, BlockCableModemVariant.fromFacing( side.getOpposite() ) ), 3 ); world.playSound( null, offset.getX() + 0.5, offset.getY() + 0.5, offset.getZ() + 0.5, ComputerCraft.Blocks.cable.getSoundType().getBreakSound(), SoundCategory.BLOCKS, (ComputerCraft.Blocks.cable.getSoundType().getVolume() + 1.0F ) / 2.0F, ComputerCraft.Blocks.cable.getSoundType().getPitch() * 0.8F); - stack.stackSize--; + stack.stackSize--; - TileEntity tile = world.getTileEntity( offset ); - if( tile != null && tile instanceof TileCable ) - { - TileCable cable = (TileCable)tile; - cable.networkChanged(); - } - return EnumActionResult.SUCCESS; - } - return EnumActionResult.FAIL; - } + TileEntity tile = world.getTileEntity( offset ); + if( tile != null && tile instanceof TileCable ) + { + TileCable cable = (TileCable)tile; + cable.networkChanged(); + } + return EnumActionResult.SUCCESS; + } + return EnumActionResult.FAIL; + } // Try to add a cable to a modem if( offsetExistingType == PeripheralType.WiredModem && type == PeripheralType.Cable ) - { - if( stack.stackSize > 0 ) - { + { + if( stack.stackSize > 0 ) + { world.setBlockState( offset, offsetExistingState.withProperty( BlockCable.Properties.CABLE, true ), 3 ); - world.playSound( null, offset.getX() + 0.5, offset.getY() + 0.5, offset.getZ() + 0.5, ComputerCraft.Blocks.cable.getSoundType().getBreakSound(), SoundCategory.BLOCKS, (ComputerCraft.Blocks.cable.getSoundType().getVolume() + 1.0F ) / 2.0F, ComputerCraft.Blocks.cable.getSoundType().getPitch() * 0.8F); - stack.stackSize--; + world.playSound( null, offset.getX() + 0.5, offset.getY() + 0.5, offset.getZ() + 0.5, ComputerCraft.Blocks.cable.getSoundType().getBreakSound(), SoundCategory.BLOCKS, (ComputerCraft.Blocks.cable.getSoundType().getVolume() + 1.0F ) / 2.0F, ComputerCraft.Blocks.cable.getSoundType().getPitch() * 0.8F); + stack.stackSize--; - TileEntity tile = world.getTileEntity( offset ); - if( tile != null && tile instanceof TileCable ) - { - TileCable cable = (TileCable)tile; - cable.networkChanged(); - } - return EnumActionResult.SUCCESS; - } - return EnumActionResult.FAIL; - } - } - } - - return super.onItemUse( stack, player, world, pos, hand, side, fx, fy, fz ); + TileEntity tile = world.getTileEntity( offset ); + if( tile != null && tile instanceof TileCable ) + { + TileCable cable = (TileCable)tile; + cable.networkChanged(); + } + return EnumActionResult.SUCCESS; + } + return EnumActionResult.FAIL; + } + } + } + + return super.onItemUse( stack, player, world, pos, hand, side, fx, fy, fz ); } @Override diff --git a/src/main/java/dan200/computercraft/shared/peripheral/common/ItemPeripheral.java b/src/main/java/dan200/computercraft/shared/peripheral/common/ItemPeripheral.java index 7d87115e8..5e5660795 100644 --- a/src/main/java/dan200/computercraft/shared/peripheral/common/ItemPeripheral.java +++ b/src/main/java/dan200/computercraft/shared/peripheral/common/ItemPeripheral.java @@ -17,7 +17,7 @@ public class ItemPeripheral extends ItemPeripheralBase { - public ItemPeripheral( Block block ) + public ItemPeripheral( Block block ) { super( block ); setUnlocalizedName( "computercraft:peripheral" ); @@ -70,7 +70,7 @@ public ItemStack create( PeripheralType type, String label, int quantity ) @Override public void getSubItems( Item itemID, CreativeTabs tabs, List list ) { - list.add( PeripheralItemFactory.create( PeripheralType.DiskDrive, null, 1 ) ); + list.add( PeripheralItemFactory.create( PeripheralType.DiskDrive, null, 1 ) ); list.add( PeripheralItemFactory.create( PeripheralType.Printer, null, 1 ) ); list.add( PeripheralItemFactory.create( PeripheralType.Monitor, null, 1 ) ); list.add( PeripheralItemFactory.create( PeripheralType.AdvancedMonitor, null, 1 ) ); diff --git a/src/main/java/dan200/computercraft/shared/peripheral/common/TilePeripheralBase.java b/src/main/java/dan200/computercraft/shared/peripheral/common/TilePeripheralBase.java index baf55ec30..2544d0af6 100644 --- a/src/main/java/dan200/computercraft/shared/peripheral/common/TilePeripheralBase.java +++ b/src/main/java/dan200/computercraft/shared/peripheral/common/TilePeripheralBase.java @@ -18,21 +18,21 @@ import java.util.List; public abstract class TilePeripheralBase extends TileGeneric - implements IPeripheralTile, IDirectionalTile, ITickable + implements IPeripheralTile, IDirectionalTile, ITickable { // Statics - private EnumFacing m_dir; - private int m_anim; - private boolean m_changed; + private EnumFacing m_dir; + private int m_anim; + private boolean m_changed; private String m_label; public TilePeripheralBase() { - m_dir = EnumFacing.NORTH; - m_anim = 0; - m_changed = false; + m_dir = EnumFacing.NORTH; + m_anim = 0; + m_changed = false; m_label = null; } @@ -99,63 +99,63 @@ public EnumFacing getDirection() @Override public void setDirection( EnumFacing dir ) { - if( dir != m_dir ) - { - m_dir = dir; - m_changed = true; - } + if( dir != m_dir ) + { + m_dir = dir; + m_changed = true; + } } public synchronized int getAnim() { - return m_anim; + return m_anim; } public synchronized void setAnim( int anim ) { - if( anim != m_anim ) - { - m_anim = anim; - m_changed = true; - } + if( anim != m_anim ) + { + m_anim = anim; + m_changed = true; + } } - @Override + @Override public synchronized void update() { - if( m_changed ) - { + if( m_changed ) + { updateBlock(); - m_changed = false; - } + m_changed = false; + } } - @Override + @Override public void readFromNBT( NBTTagCompound nbttagcompound ) { - // Read properties + // Read properties super.readFromNBT(nbttagcompound); if( nbttagcompound.hasKey( "dir" ) ) { - m_dir = EnumFacing.getFront( nbttagcompound.getInteger( "dir" ) ); - } + m_dir = EnumFacing.getFront( nbttagcompound.getInteger( "dir" ) ); + } if( nbttagcompound.hasKey( "anim" ) ) { - m_anim = nbttagcompound.getInteger( "anim" ); - } + m_anim = nbttagcompound.getInteger( "anim" ); + } if( nbttagcompound.hasKey( "label" ) ) { m_label = nbttagcompound.getString( "label" ); } } - @Override + @Override public NBTTagCompound writeToNBT( NBTTagCompound nbttagcompound ) { - // Write properties + // Write properties nbttagcompound = super.writeToNBT( nbttagcompound ); - nbttagcompound.setInteger( "dir", m_dir.getIndex() ); - nbttagcompound.setInteger( "anim", m_anim ); + nbttagcompound.setInteger( "dir", m_dir.getIndex() ); + nbttagcompound.setInteger( "anim", m_anim ); if( m_label != null ) { nbttagcompound.setString( "label", m_label ); diff --git a/src/main/java/dan200/computercraft/shared/peripheral/diskdrive/ContainerDiskDrive.java b/src/main/java/dan200/computercraft/shared/peripheral/diskdrive/ContainerDiskDrive.java index d74fb8716..7c9139343 100644 --- a/src/main/java/dan200/computercraft/shared/peripheral/diskdrive/ContainerDiskDrive.java +++ b/src/main/java/dan200/computercraft/shared/peripheral/diskdrive/ContainerDiskDrive.java @@ -20,18 +20,18 @@ public ContainerDiskDrive( IInventory playerInventory, TileDiskDrive diskDrive ) { m_diskDrive = diskDrive; addSlotToContainer(new Slot( m_diskDrive, 0, 8 + 4 * 18, 35)); - + for(int j = 0; j < 3; j++) { for(int i1 = 0; i1 < 9; i1++) { - addSlotToContainer(new Slot(playerInventory, i1 + j * 9 + 9, 8 + i1 * 18, 84 + j * 18)); + addSlotToContainer(new Slot(playerInventory, i1 + j * 9 + 9, 8 + i1 * 18, 84 + j * 18)); } } for(int k = 0; k < 9; k++) { - addSlotToContainer(new Slot(playerInventory, k, 8 + k * 18, 142)); + addSlotToContainer(new Slot(playerInventory, k, 8 + k * 18, 142)); } } diff --git a/src/main/java/dan200/computercraft/shared/peripheral/diskdrive/TileDiskDrive.java b/src/main/java/dan200/computercraft/shared/peripheral/diskdrive/TileDiskDrive.java index 6b1c576f3..65f0be7da 100644 --- a/src/main/java/dan200/computercraft/shared/peripheral/diskdrive/TileDiskDrive.java +++ b/src/main/java/dan200/computercraft/shared/peripheral/diskdrive/TileDiskDrive.java @@ -64,11 +64,11 @@ public TileDiskDrive() m_computers = new HashMap(); m_diskStack = null; - m_diskMount = null; + m_diskMount = null; m_recordQueued = false; m_recordPlaying = false; - m_restartRecord = false; + m_restartRecord = false; } @Override @@ -77,10 +77,10 @@ public void destroy() ejectContents( true ); synchronized( this ) { - if( m_recordPlaying ) - { - sendBlockEvent( BLOCKEVENT_STOP_RECORD ); - } + if( m_recordPlaying ) + { + sendBlockEvent( BLOCKEVENT_STOP_RECORD ); + } } } @@ -139,9 +139,9 @@ public void readFromNBT(NBTTagCompound nbttagcompound) super.readFromNBT(nbttagcompound); if( nbttagcompound.hasKey( "item" ) ) { - NBTTagCompound item = nbttagcompound.getCompoundTag( "item" ); - m_diskStack = ItemStack.loadItemStackFromNBT( item ); - m_diskMount = null; + NBTTagCompound item = nbttagcompound.getCompoundTag( "item" ); + m_diskStack = ItemStack.loadItemStackFromNBT( item ); + m_diskMount = null; } } @@ -149,10 +149,10 @@ public void readFromNBT(NBTTagCompound nbttagcompound) public NBTTagCompound writeToNBT(NBTTagCompound nbttagcompound) { nbttagcompound = super.writeToNBT(nbttagcompound); - if( m_diskStack != null ) - { + if( m_diskStack != null ) + { NBTTagCompound item = new NBTTagCompound(); - m_diskStack.writeToNBT( item ); + m_diskStack.writeToNBT( item ); nbttagcompound.setTag( "item", item ); } return nbttagcompound; @@ -163,43 +163,43 @@ public void update() { super.update(); - // Ejection - synchronized( this ) - { - if( m_ejectQueued ) - { - ejectContents( false ); - m_ejectQueued = false; - } - } - - // Music - synchronized( this ) - { - if( m_recordPlaying != m_recordQueued || m_restartRecord ) - { - m_restartRecord = false; - if( m_recordQueued ) - { - IMedia contents = getDiskMedia(); - SoundEvent record = (contents != null) ? contents.getAudio( m_diskStack ) : null; - if( record != null ) - { - m_recordPlaying = true; + // Ejection + synchronized( this ) + { + if( m_ejectQueued ) + { + ejectContents( false ); + m_ejectQueued = false; + } + } + + // Music + synchronized( this ) + { + if( m_recordPlaying != m_recordQueued || m_restartRecord ) + { + m_restartRecord = false; + if( m_recordQueued ) + { + IMedia contents = getDiskMedia(); + SoundEvent record = (contents != null) ? contents.getAudio( m_diskStack ) : null; + if( record != null ) + { + m_recordPlaying = true; sendBlockEvent( BLOCKEVENT_PLAY_RECORD ); - } - else - { - m_recordQueued = false; - } - } - else - { + } + else + { + m_recordQueued = false; + } + } + else + { sendBlockEvent( BLOCKEVENT_STOP_RECORD ); - m_recordPlaying = false; - } - } - } + m_recordPlaying = false; + } + } + } } // IInventory implementation @@ -219,10 +219,10 @@ public ItemStack getStackInSlot(int i) @Override public ItemStack removeStackFromSlot(int i) { - ItemStack result = m_diskStack; - m_diskStack = null; + ItemStack result = m_diskStack; + m_diskStack = null; m_diskMount = null; - + return result; } @@ -231,87 +231,87 @@ public ItemStack decrStackSize(int i, int j) { if (m_diskStack == null) { - return null; + return null; } - if (m_diskStack.stackSize <= j) - { - ItemStack disk = m_diskStack; - setInventorySlotContents( 0, null ); - return disk; - } - - ItemStack part = m_diskStack.splitStack(j); - if (m_diskStack.stackSize == 0) - { - setInventorySlotContents( 0, null ); - } - else - { - setInventorySlotContents( 0, m_diskStack ); - } - return part; + if (m_diskStack.stackSize <= j) + { + ItemStack disk = m_diskStack; + setInventorySlotContents( 0, null ); + return disk; + } + + ItemStack part = m_diskStack.splitStack(j); + if (m_diskStack.stackSize == 0) + { + setInventorySlotContents( 0, null ); + } + else + { + setInventorySlotContents( 0, m_diskStack ); + } + return part; } @Override public void setInventorySlotContents( int i, ItemStack itemStack ) - { - if( worldObj.isRemote ) - { - m_diskStack = itemStack; + { + if( worldObj.isRemote ) + { + m_diskStack = itemStack; m_diskMount = null; - markDirty(); - return; - } + markDirty(); + return; + } - synchronized( this ) - { - if( InventoryUtil.areItemsStackable( itemStack, m_diskStack ) ) - { - m_diskStack = itemStack; - return; - } - - // Unmount old disk - if( m_diskStack != null ) - { - Set computers = m_computers.keySet(); - Iterator it = computers.iterator(); - while( it.hasNext() ) - { - IComputerAccess computer = it.next(); - unmountDisk( computer ); - } - } - - // Stop music - if( m_recordPlaying ) - { + synchronized( this ) + { + if( InventoryUtil.areItemsStackable( itemStack, m_diskStack ) ) + { + m_diskStack = itemStack; + return; + } + + // Unmount old disk + if( m_diskStack != null ) + { + Set computers = m_computers.keySet(); + Iterator it = computers.iterator(); + while( it.hasNext() ) + { + IComputerAccess computer = it.next(); + unmountDisk( computer ); + } + } + + // Stop music + if( m_recordPlaying ) + { sendBlockEvent( BLOCKEVENT_STOP_RECORD ); - m_recordPlaying = false; - m_recordQueued = false; - } - - // Swap disk over - m_diskStack = itemStack; + m_recordPlaying = false; + m_recordQueued = false; + } + + // Swap disk over + m_diskStack = itemStack; m_diskMount = null; - markDirty(); + markDirty(); - // Update contents - updateAnim(); + // Update contents + updateAnim(); - // Mount new disk - if( m_diskStack != null ) - { - Set computers = m_computers.keySet(); - Iterator it = computers.iterator(); - while( it.hasNext() ) - { - IComputerAccess computer = it.next(); - mountDisk( computer ); - } - } - } + // Mount new disk + if( m_diskStack != null ) + { + Set computers = m_computers.keySet(); + Iterator it = computers.iterator(); + while( it.hasNext() ) + { + IComputerAccess computer = it.next(); + mountDisk( computer ); + } + } + } } @Override @@ -354,14 +354,14 @@ public int getInventoryStackLimit() } @Override - public void openInventory( EntityPlayer player ) - { - } - + public void openInventory( EntityPlayer player ) + { + } + @Override - public void closeInventory( EntityPlayer player ) - { - } + public void closeInventory( EntityPlayer player ) + { + } @Override public boolean isItemValidForSlot(int i, ItemStack itemstack) @@ -401,7 +401,7 @@ public void setField(int id, int value) { } - // IPeripheralTile implementation + // IPeripheralTile implementation @Override public IPeripheral getPeripheral( EnumFacing side ) @@ -495,121 +495,121 @@ public void ejectDisk() } // private methods - - private synchronized void mountDisk( IComputerAccess computer ) - { - if( m_diskStack != null ) - { - MountInfo info = m_computers.get( computer ); - IMedia contents = getDiskMedia(); - if( contents != null ) - { - if( m_diskMount == null ) - { - m_diskMount = contents.createDataMount( m_diskStack, worldObj ); - } - if( m_diskMount != null ) - { - if( m_diskMount instanceof IWritableMount) - { - // Try mounting at the lowest numbered "disk" name we can - int n = 1; - while( info.mountPath == null ) - { - info.mountPath = computer.mountWritable( (n==1) ? "disk" : ("disk" + n), (IWritableMount)m_diskMount ); - n++; - } - } - else - { - // Try mounting at the lowest numbered "disk" name we can - int n = 1; - while( info.mountPath == null ) - { - info.mountPath = computer.mount( (n==1) ? "disk" : ("disk" + n), m_diskMount ); - n++; - } - } - } - else - { - info.mountPath = null; - } - } - computer.queueEvent( "disk", new Object[] { computer.getAttachmentName() } ); - } - } + + private synchronized void mountDisk( IComputerAccess computer ) + { + if( m_diskStack != null ) + { + MountInfo info = m_computers.get( computer ); + IMedia contents = getDiskMedia(); + if( contents != null ) + { + if( m_diskMount == null ) + { + m_diskMount = contents.createDataMount( m_diskStack, worldObj ); + } + if( m_diskMount != null ) + { + if( m_diskMount instanceof IWritableMount) + { + // Try mounting at the lowest numbered "disk" name we can + int n = 1; + while( info.mountPath == null ) + { + info.mountPath = computer.mountWritable( (n==1) ? "disk" : ("disk" + n), (IWritableMount)m_diskMount ); + n++; + } + } + else + { + // Try mounting at the lowest numbered "disk" name we can + int n = 1; + while( info.mountPath == null ) + { + info.mountPath = computer.mount( (n==1) ? "disk" : ("disk" + n), m_diskMount ); + n++; + } + } + } + else + { + info.mountPath = null; + } + } + computer.queueEvent( "disk", new Object[] { computer.getAttachmentName() } ); + } + } - private synchronized void unmountDisk( IComputerAccess computer ) - { - if( m_diskStack != null ) - { - MountInfo info = m_computers.get( computer ); - assert( info != null ); - if( info.mountPath != null ) - { - computer.unmount( info.mountPath ); - info.mountPath = null; - } - computer.queueEvent( "disk_eject", new Object[] { computer.getAttachmentName() } ); - } - } + private synchronized void unmountDisk( IComputerAccess computer ) + { + if( m_diskStack != null ) + { + MountInfo info = m_computers.get( computer ); + assert( info != null ); + if( info.mountPath != null ) + { + computer.unmount( info.mountPath ); + info.mountPath = null; + } + computer.queueEvent( "disk_eject", new Object[] { computer.getAttachmentName() } ); + } + } - private synchronized void updateAnim() - { - if( m_diskStack != null ) - { - IMedia contents = getDiskMedia(); - if( contents != null ) { - setAnim( 2 ); - } else { - setAnim( 1 ); - } - } - else - { - setAnim( 0 ); - } - } - + private synchronized void updateAnim() + { + if( m_diskStack != null ) + { + IMedia contents = getDiskMedia(); + if( contents != null ) { + setAnim( 2 ); + } else { + setAnim( 1 ); + } + } + else + { + setAnim( 0 ); + } + } + private synchronized void ejectContents( boolean destroyed ) { - if( worldObj.isRemote ) - { - return; - } - - if( m_diskStack != null ) - { - // Remove the disks from the inventory - ItemStack disks = m_diskStack; - setInventorySlotContents( 0, null ); + if( worldObj.isRemote ) + { + return; + } + + if( m_diskStack != null ) + { + // Remove the disks from the inventory + ItemStack disks = m_diskStack; + setInventorySlotContents( 0, null ); - // Spawn the item in the world - int xOff = 0; - int zOff = 0; - if( !destroyed ) - { - EnumFacing dir = getDirection(); + // Spawn the item in the world + int xOff = 0; + int zOff = 0; + if( !destroyed ) + { + EnumFacing dir = getDirection(); xOff = dir.getFrontOffsetX(); zOff = dir.getFrontOffsetZ(); - } + } BlockPos pos = getPos(); - double x = (double)pos.getX() + 0.5 + ((double)xOff * 0.5); - double y = (double)pos.getY() + 0.75; - double z = (double)pos.getZ() + 0.5 + ((double)zOff * 0.5); - EntityItem entityitem = new EntityItem( worldObj, x, y, z, disks ); - entityitem.motionX = (double)xOff * 0.15; - entityitem.motionY = 0.0; - entityitem.motionZ = (double)zOff * 0.15; - - worldObj.spawnEntityInWorld(entityitem); - if( !destroyed ) - { - worldObj.playBroadcastSound(1000, getPos(), 0); - } - } + double x = (double)pos.getX() + 0.5 + ((double)xOff * 0.5); + double y = (double)pos.getY() + 0.75; + double z = (double)pos.getZ() + 0.5 + ((double)zOff * 0.5); + EntityItem entityitem = new EntityItem( worldObj, x, y, z, disks ); + entityitem.motionX = (double)xOff * 0.15; + entityitem.motionY = 0.0; + entityitem.motionZ = (double)zOff * 0.15; + + worldObj.spawnEntityInWorld(entityitem); + if( !destroyed ) + { + worldObj.playBroadcastSound(1000, getPos(), 0); + } + } } @Override @@ -666,8 +666,8 @@ public boolean shouldRefresh( World world, BlockPos pos, IBlockState oldState, I // Private methods - private void playRecord() - { + private void playRecord() + { IMedia contents = getDiskMedia(); SoundEvent record = (contents != null) ? contents.getAudio( m_diskStack ) : null; if( record != null ) @@ -678,7 +678,7 @@ private void playRecord() { ComputerCraft.playRecord( null, null, worldObj, getPos() ); } - } + } private void stopRecord() { diff --git a/src/main/java/dan200/computercraft/shared/peripheral/modem/INetwork.java b/src/main/java/dan200/computercraft/shared/peripheral/modem/INetwork.java index 267477b8d..91fbcb394 100644 --- a/src/main/java/dan200/computercraft/shared/peripheral/modem/INetwork.java +++ b/src/main/java/dan200/computercraft/shared/peripheral/modem/INetwork.java @@ -11,8 +11,8 @@ public interface INetwork { - public void addReceiver( IReceiver receiver ); - public void removeReceiver( IReceiver receiver ); - public void transmit( int channel, int replyChannel, Object payload, World world, Vec3d pos, double range, boolean interdimensional, Object senderObject ); - public boolean isWireless(); + public void addReceiver( IReceiver receiver ); + public void removeReceiver( IReceiver receiver ); + public void transmit( int channel, int replyChannel, Object payload, World world, Vec3d pos, double range, boolean interdimensional, Object senderObject ); + public boolean isWireless(); } diff --git a/src/main/java/dan200/computercraft/shared/peripheral/modem/IReceiver.java b/src/main/java/dan200/computercraft/shared/peripheral/modem/IReceiver.java index 7e3fce65f..869c1ea15 100644 --- a/src/main/java/dan200/computercraft/shared/peripheral/modem/IReceiver.java +++ b/src/main/java/dan200/computercraft/shared/peripheral/modem/IReceiver.java @@ -10,11 +10,11 @@ public interface IReceiver { - public int getChannel(); + public int getChannel(); public World getWorld(); - public Vec3d getWorldPosition(); + public Vec3d getWorldPosition(); public boolean isInterdimensional(); - public double getReceiveRange(); - public void receiveSameDimension( int replyChannel, Object payload, double distance, Object senderObject ); + public double getReceiveRange(); + public void receiveSameDimension( int replyChannel, Object payload, double distance, Object senderObject ); public void receiveDifferentDimension( int replyChannel, Object payload, Object senderObject ); } diff --git a/src/main/java/dan200/computercraft/shared/peripheral/modem/ModemPeripheral.java b/src/main/java/dan200/computercraft/shared/peripheral/modem/ModemPeripheral.java index a16a5de02..c3c92781a 100644 --- a/src/main/java/dan200/computercraft/shared/peripheral/modem/ModemPeripheral.java +++ b/src/main/java/dan200/computercraft/shared/peripheral/modem/ModemPeripheral.java @@ -18,26 +18,26 @@ import java.util.Map; public abstract class ModemPeripheral - implements IPeripheral -{ - private static class SingleChannelReceiver implements IReceiver - { - private ModemPeripheral m_owner; - private int m_channel; - - public SingleChannelReceiver( ModemPeripheral owner, int channel ) - { - m_owner = owner; - m_channel = channel; - } - - // IReceiver implementation - - @Override - public int getChannel() - { - return m_channel; - } + implements IPeripheral +{ + private static class SingleChannelReceiver implements IReceiver + { + private ModemPeripheral m_owner; + private int m_channel; + + public SingleChannelReceiver( ModemPeripheral owner, int channel ) + { + m_owner = owner; + m_channel = channel; + } + + // IReceiver implementation + + @Override + public int getChannel() + { + return m_channel; + } @Override public World getWorld() @@ -45,17 +45,17 @@ public World getWorld() return m_owner.getWorld(); } - @Override - public Vec3d getWorldPosition() - { - return m_owner.getWorldPosition(); - } - - @Override - public boolean isInterdimensional() - { - return m_owner.isInterdimensional(); - } + @Override + public Vec3d getWorldPosition() + { + return m_owner.getWorldPosition(); + } + + @Override + public boolean isInterdimensional() + { + return m_owner.isInterdimensional(); + } @Override public double getReceiveRange() @@ -64,13 +64,13 @@ public double getReceiveRange() } @Override - public void receiveSameDimension( int replyChannel, Object payload, double distance, Object senderObject ) - { - if( senderObject != m_owner ) - { - m_owner.receiveSameDimension( m_channel, replyChannel, payload, distance ); - } - } + public void receiveSameDimension( int replyChannel, Object payload, double distance, Object senderObject ) + { + if( senderObject != m_owner ) + { + m_owner.receiveSameDimension( m_channel, replyChannel, payload, distance ); + } + } @Override public void receiveDifferentDimension( int replyChannel, Object payload, Object senderObject ) @@ -80,14 +80,14 @@ public void receiveDifferentDimension( int replyChannel, Object payload, Object m_owner.receiveDifferentDimension( m_channel, replyChannel, payload ); } } - } - - private INetwork m_network; - private IComputerAccess m_computer; - private Map m_channels; + } + + private INetwork m_network; + private IComputerAccess m_computer; + private Map m_channels; - private boolean m_open; - private boolean m_changed; + private boolean m_open; + private boolean m_changed; public ModemPeripheral() { @@ -146,12 +146,12 @@ public synchronized void destroy() public synchronized boolean pollChanged() { - if( m_changed ) - { - m_changed = false; - return true; - } - return false; + if( m_changed ) + { + m_changed = false; + return true; + } + return false; } protected abstract double getTransmitRange(); @@ -159,32 +159,32 @@ public synchronized boolean pollChanged() protected abstract boolean isInterdimensional(); public synchronized boolean isActive() - { - return (m_computer != null) && m_open; - } + { + return (m_computer != null) && m_open; + } - public synchronized Vec3d getWorldPosition() - { - return getPosition(); - } - - public synchronized double getReceiveRange() - { - return getTransmitRange(); - } - - public void receiveSameDimension( int channel, int replyChannel, Object payload, double distance ) - { - synchronized (m_channels) - { - if( m_computer != null && m_channels.containsKey( channel ) ) - { - m_computer.queueEvent( "modem_message", new Object[] { - m_computer.getAttachmentName(), channel, replyChannel, payload, distance - } ); - } - } - } + public synchronized Vec3d getWorldPosition() + { + return getPosition(); + } + + public synchronized double getReceiveRange() + { + return getTransmitRange(); + } + + public void receiveSameDimension( int channel, int replyChannel, Object payload, double distance ) + { + synchronized (m_channels) + { + if( m_computer != null && m_channels.containsKey( channel ) ) + { + m_computer.queueEvent( "modem_message", new Object[] { + m_computer.getAttachmentName(), channel, replyChannel, payload, distance + } ); + } + } + } public void receiveDifferentDimension( int channel, int replyChannel, Object payload ) { @@ -201,115 +201,115 @@ public void receiveDifferentDimension( int channel, int replyChannel, Object pay protected abstract INetwork getNetwork(); - // IPeripheral implementation + // IPeripheral implementation - @Override + @Override public String getType() { - return "modem"; + return "modem"; } - - @Override + + @Override public String[] getMethodNames() { - return new String[] { - "open", - "isOpen", - "close", - "closeAll", - "transmit", - "isWireless", - }; + return new String[] { + "open", + "isOpen", + "close", + "closeAll", + "transmit", + "isWireless", + }; } private static int parseChannel( Object[] arguments, int index ) throws LuaException { - if( arguments.length <= index || !(arguments[index] instanceof Double) ) - { - throw new LuaException( "Expected number" ); - } - int channel = (int)((Double)arguments[index]).doubleValue(); - if( channel < 0 || channel > 65535 ) - { - throw new LuaException( "Expected number in range 0-65535" ); - } - return channel; + if( arguments.length <= index || !(arguments[index] instanceof Double) ) + { + throw new LuaException( "Expected number" ); + } + int channel = (int)((Double)arguments[index]).doubleValue(); + if( channel < 0 || channel > 65535 ) + { + throw new LuaException( "Expected number in range 0-65535" ); + } + return channel; } - @Override + @Override public Object[] callMethod( IComputerAccess computer, ILuaContext context, int method, Object[] arguments ) throws LuaException, InterruptedException { - switch( method ) - { - case 0: - { - // open - int channel = parseChannel( arguments, 0 ); - synchronized( this ) - { - if( !m_channels.containsKey( channel ) ) - { - if( m_channels.size() >= 128 ) - { - throw new LuaException( "Too many open channels" ); - } - - IReceiver receiver = new SingleChannelReceiver( this, channel ); - m_channels.put( channel, receiver ); + switch( method ) + { + case 0: + { + // open + int channel = parseChannel( arguments, 0 ); + synchronized( this ) + { + if( !m_channels.containsKey( channel ) ) + { + if( m_channels.size() >= 128 ) + { + throw new LuaException( "Too many open channels" ); + } + + IReceiver receiver = new SingleChannelReceiver( this, channel ); + m_channels.put( channel, receiver ); if( m_network != null ) { - m_network.addReceiver( receiver ); + m_network.addReceiver( receiver ); } - if( !m_open ) - { - m_open = true; - m_changed = true; - } - } - } - return null; - } - case 1: - { - // isOpen - int channel = parseChannel( arguments, 0 ); - synchronized( this ) - { - boolean open = m_channels.containsKey( channel ); - return new Object[] { open }; - } - } - case 2: - { - // close - int channel = parseChannel( arguments, 0 ); - synchronized( this ) - { - if( m_channels.containsKey( channel ) ) - { - IReceiver receiver = m_channels.get( channel ); + if( !m_open ) + { + m_open = true; + m_changed = true; + } + } + } + return null; + } + case 1: + { + // isOpen + int channel = parseChannel( arguments, 0 ); + synchronized( this ) + { + boolean open = m_channels.containsKey( channel ); + return new Object[] { open }; + } + } + case 2: + { + // close + int channel = parseChannel( arguments, 0 ); + synchronized( this ) + { + if( m_channels.containsKey( channel ) ) + { + IReceiver receiver = m_channels.get( channel ); if( m_network != null ) { - m_network.removeReceiver( receiver ); + m_network.removeReceiver( receiver ); } - m_channels.remove( channel ); - - if( m_channels.size() == 0 ) - { - m_open = false; - m_changed = true; - } - } - } - return null; - } - case 3: - { - // closeAll - synchronized( this ) - { - if( m_channels.size() > 0 ) - { + m_channels.remove( channel ); + + if( m_channels.size() == 0 ) + { + m_open = false; + m_changed = true; + } + } + } + return null; + } + case 3: + { + // closeAll + synchronized( this ) + { + if( m_channels.size() > 0 ) + { if( m_network != null ) { Iterator it = m_channels.values().iterator(); @@ -318,37 +318,37 @@ public Object[] callMethod( IComputerAccess computer, ILuaContext context, int m m_network.removeReceiver( it.next() ); } } - m_channels.clear(); - - if( m_open ) - { - m_open = false; - m_changed = true; - } - } - } - return null; - } - case 4: - { - // transmit - int channel = parseChannel( arguments, 0 ); - int replyChannel = parseChannel( arguments, 1 ); - Object payload = (arguments.length >= 3) ? arguments[2] : null; - synchronized( this ) - { + m_channels.clear(); + + if( m_open ) + { + m_open = false; + m_changed = true; + } + } + } + return null; + } + case 4: + { + // transmit + int channel = parseChannel( arguments, 0 ); + int replyChannel = parseChannel( arguments, 1 ); + Object payload = (arguments.length >= 3) ? arguments[2] : null; + synchronized( this ) + { World world = getWorld(); - Vec3d position = getPosition(); + Vec3d position = getPosition(); if( world != null && position != null && m_network != null) { - m_network.transmit( channel, replyChannel, payload, world, position, getTransmitRange(), isInterdimensional(), this ); + m_network.transmit( channel, replyChannel, payload, world, position, getTransmitRange(), isInterdimensional(), this ); } - } - return null; - } - case 5: - { - // isWireless + } + return null; + } + case 5: + { + // isWireless synchronized( this ) { if( m_network != null ) @@ -357,43 +357,43 @@ public Object[] callMethod( IComputerAccess computer, ILuaContext context, int m } } return new Object[] { false }; - } - default: - { - return null; - } - } + } + default: + { + return null; + } + } } - @Override + @Override public synchronized void attach( IComputerAccess computer ) { - m_computer = computer; - setNetwork( getNetwork() ); - m_open = !m_channels.isEmpty(); + m_computer = computer; + setNetwork( getNetwork() ); + m_open = !m_channels.isEmpty(); } - @Override + @Override public synchronized void detach( IComputerAccess computer ) { - if( m_network != null ) - { - Iterator it = m_channels.values().iterator(); - while( it.hasNext() ) - { - m_network.removeReceiver( it.next() ); - } - m_channels.clear(); - m_network = null; - } + if( m_network != null ) + { + Iterator it = m_channels.values().iterator(); + while( it.hasNext() ) + { + m_network.removeReceiver( it.next() ); + } + m_channels.clear(); + m_network = null; + } - m_computer = null; - - if( m_open ) - { - m_open = false; - m_changed = true; - } + m_computer = null; + + if( m_open ) + { + m_open = false; + m_changed = true; + } } @Override @@ -401,6 +401,6 @@ public synchronized void detach( IComputerAccess computer ) public IComputerAccess getComputer() { - return m_computer; + return m_computer; } } diff --git a/src/main/java/dan200/computercraft/shared/peripheral/modem/TileAdvancedModem.java b/src/main/java/dan200/computercraft/shared/peripheral/modem/TileAdvancedModem.java index 4ff2186a3..c8c5dfb52 100644 --- a/src/main/java/dan200/computercraft/shared/peripheral/modem/TileAdvancedModem.java +++ b/src/main/java/dan200/computercraft/shared/peripheral/modem/TileAdvancedModem.java @@ -18,15 +18,15 @@ public class TileAdvancedModem extends TileModemBase { // Statics - private static class Peripheral extends WirelessModemPeripheral - { - private TileModemBase m_entity; + private static class Peripheral extends WirelessModemPeripheral + { + private TileModemBase m_entity; - public Peripheral( TileModemBase entity ) - { + public Peripheral( TileModemBase entity ) + { super( true ); - m_entity = entity; - } + m_entity = entity; + } @Override public World getWorld() @@ -34,12 +34,12 @@ public World getWorld() return m_entity.getWorld(); } - @Override - protected Vec3d getPosition() - { + @Override + protected Vec3d getPosition() + { BlockPos pos = m_entity.getPos().offset( m_entity.getDirection() ); - return new Vec3d( (double)pos.getX(), (double)pos.getY(), (double)pos.getZ() ); - } + return new Vec3d( (double)pos.getX(), (double)pos.getY(), (double)pos.getZ() ); + } @Override public boolean equals( IPeripheral other ) @@ -79,6 +79,6 @@ public void setDirection( EnumFacing dir ) @Override protected ModemPeripheral createPeripheral() { - return new Peripheral( this ); + return new Peripheral( this ); } } diff --git a/src/main/java/dan200/computercraft/shared/peripheral/modem/TileCable.java b/src/main/java/dan200/computercraft/shared/peripheral/modem/TileCable.java index 808762b07..4dce114bc 100644 --- a/src/main/java/dan200/computercraft/shared/peripheral/modem/TileCable.java +++ b/src/main/java/dan200/computercraft/shared/peripheral/modem/TileCable.java @@ -35,24 +35,24 @@ import java.util.*; public class TileCable extends TileModemBase - implements INetwork + implements INetwork { // Statics - private static class Peripheral extends ModemPeripheral - { - private TileCable m_entity; - - public Peripheral( TileCable entity ) - { - m_entity = entity; - } + private static class Peripheral extends ModemPeripheral + { + private TileCable m_entity; + + public Peripheral( TileCable entity ) + { + m_entity = entity; + } - @Override - protected boolean isInterdimensional() - { - return false; - } + @Override + protected boolean isInterdimensional() + { + return false; + } @Override protected double getTransmitRange() @@ -61,10 +61,10 @@ protected double getTransmitRange() } @Override - protected INetwork getNetwork() - { - return m_entity; - } + protected INetwork getNetwork() + { + return m_entity; + } @Override protected World getWorld() @@ -72,13 +72,13 @@ protected World getWorld() return m_entity.getWorld(); } - @Override - protected Vec3d getPosition() - { - EnumFacing direction = m_entity.getDirection(); + @Override + protected Vec3d getPosition() + { + EnumFacing direction = m_entity.getDirection(); BlockPos pos = m_entity.getPos().offset( direction ); - return new Vec3d( (double)pos.getX() + 0.5, (double)pos.getY() + 0.5, (double)pos.getZ() + 0.5 ); - } + return new Vec3d( (double)pos.getX() + 0.5, (double)pos.getY() + 0.5, (double)pos.getZ() + 0.5 ); + } @Override public String[] getMethodNames() @@ -222,44 +222,44 @@ public boolean equals( IPeripheral other ) // Members - private Map> m_receivers; - private Queue m_transmitQueue; - + private Map> m_receivers; + private Queue m_transmitQueue; + private boolean m_peripheralAccessAllowed; private int m_attachedPeripheralID; - private Map m_peripheralsByName; - private Map m_peripheralWrappersByName; - private boolean m_peripheralsKnown; + private Map m_peripheralsByName; + private Map m_peripheralWrappersByName; + private boolean m_peripheralsKnown; private boolean m_destroyed; private int m_lastSearchID; - + public TileCable() { - m_receivers = new HashMap>(); - m_transmitQueue = new LinkedList(); - - m_peripheralAccessAllowed = false; - m_attachedPeripheralID = -1; - - m_peripheralsByName = new HashMap(); - m_peripheralWrappersByName = new HashMap(); - m_peripheralsKnown = false; - m_destroyed = false; - - m_lastSearchID = 0; + m_receivers = new HashMap>(); + m_transmitQueue = new LinkedList(); + + m_peripheralAccessAllowed = false; + m_attachedPeripheralID = -1; + + m_peripheralsByName = new HashMap(); + m_peripheralWrappersByName = new HashMap(); + m_peripheralsKnown = false; + m_destroyed = false; + + m_lastSearchID = 0; } @Override public void destroy() { - if( !m_destroyed ) - { - m_destroyed = true; - networkChanged(); - } - super.destroy(); + if( !m_destroyed ) + { + m_destroyed = true; + networkChanged(); + } + super.destroy(); } @Override @@ -483,41 +483,41 @@ public boolean onActivate( EntityPlayer player, EnumFacing side, float hitX, flo @Override public void readFromNBT(NBTTagCompound nbttagcompound) { - // Read properties + // Read properties super.readFromNBT(nbttagcompound); - m_peripheralAccessAllowed = nbttagcompound.getBoolean( "peripheralAccess" ); - m_attachedPeripheralID = nbttagcompound.getInteger( "peripheralID" ); + m_peripheralAccessAllowed = nbttagcompound.getBoolean( "peripheralAccess" ); + m_attachedPeripheralID = nbttagcompound.getInteger( "peripheralID" ); } - @Override + @Override public NBTTagCompound writeToNBT(NBTTagCompound nbttagcompound) { - // Write properties + // Write properties nbttagcompound = super.writeToNBT(nbttagcompound); - nbttagcompound.setBoolean( "peripheralAccess", m_peripheralAccessAllowed ); - nbttagcompound.setInteger( "peripheralID", m_attachedPeripheralID ); + nbttagcompound.setBoolean( "peripheralAccess", m_peripheralAccessAllowed ); + nbttagcompound.setInteger( "peripheralID", m_attachedPeripheralID ); return nbttagcompound; } @Override protected ModemPeripheral createPeripheral() { - return new Peripheral( this ); + return new Peripheral( this ); } @Override - protected void updateAnim() - { - int anim = 0; - if( m_modem.isActive() ) - { - anim += 1; - } - if( m_peripheralAccessAllowed ) - { - anim += 2; - } - setAnim( anim ); + protected void updateAnim() + { + int anim = 0; + if( m_modem.isActive() ) + { + anim += 1; + } + if( m_peripheralAccessAllowed ) + { + anim += 2; + } + setAnim( anim ); } // IPeripheralTile @@ -535,283 +535,283 @@ public IPeripheral getPeripheral( EnumFacing side ) @Override public void update() { - super.update(); - if( !worldObj.isRemote ) - { - synchronized( m_peripheralsByName ) - { - if( !m_peripheralsKnown ) - { - findPeripherals(); - m_peripheralsKnown = true; - } - } - synchronized( m_transmitQueue ) - { - while( m_transmitQueue.peek() != null ) - { - Packet p = m_transmitQueue.remove(); - if( p != null ) - { - dispatchPacket( p ); - } - } - } - } + super.update(); + if( !worldObj.isRemote ) + { + synchronized( m_peripheralsByName ) + { + if( !m_peripheralsKnown ) + { + findPeripherals(); + m_peripheralsKnown = true; + } + } + synchronized( m_transmitQueue ) + { + while( m_transmitQueue.peek() != null ) + { + Packet p = m_transmitQueue.remove(); + if( p != null ) + { + dispatchPacket( p ); + } + } + } + } } // INetwork implementation @Override - public void addReceiver( IReceiver receiver ) - { - synchronized( m_receivers ) - { - int channel = receiver.getChannel(); - Set receivers = m_receivers.get( channel ); - if( receivers == null ) - { - receivers = new HashSet(); - m_receivers.put( channel, receivers ); - } - receivers.add( receiver ); - } - } - + public void addReceiver( IReceiver receiver ) + { + synchronized( m_receivers ) + { + int channel = receiver.getChannel(); + Set receivers = m_receivers.get( channel ); + if( receivers == null ) + { + receivers = new HashSet(); + m_receivers.put( channel, receivers ); + } + receivers.add( receiver ); + } + } + @Override - public void removeReceiver( IReceiver receiver ) - { - synchronized( m_receivers ) - { - int channel = receiver.getChannel(); - Set receivers = m_receivers.get( channel ); - if( receivers != null ) - { - receivers.remove( receiver ); - } - } - } - + public void removeReceiver( IReceiver receiver ) + { + synchronized( m_receivers ) + { + int channel = receiver.getChannel(); + Set receivers = m_receivers.get( channel ); + if( receivers != null ) + { + receivers.remove( receiver ); + } + } + } + @Override - public void transmit( int channel, int replyChannel, Object payload, World world, Vec3d pos, double range, boolean interdimensional, Object senderObject ) - { - Packet p = new Packet(); - p.channel = channel; - p.replyChannel = replyChannel; - p.payload = payload; - p.senderObject = senderObject; - synchronized( m_transmitQueue ) - { - m_transmitQueue.offer(p); - } - } - + public void transmit( int channel, int replyChannel, Object payload, World world, Vec3d pos, double range, boolean interdimensional, Object senderObject ) + { + Packet p = new Packet(); + p.channel = channel; + p.replyChannel = replyChannel; + p.payload = payload; + p.senderObject = senderObject; + synchronized( m_transmitQueue ) + { + m_transmitQueue.offer(p); + } + } + @Override - public boolean isWireless() - { - return false; - } + public boolean isWireless() + { + return false; + } private void attachPeripheral( String periphName, IPeripheral peripheral ) { - if( !m_peripheralWrappersByName.containsKey( periphName ) ) - { - RemotePeripheralWrapper wrapper = new RemotePeripheralWrapper( peripheral, m_modem.getComputer(), periphName ); - m_peripheralWrappersByName.put( periphName, wrapper ); - wrapper.attach(); - } + if( !m_peripheralWrappersByName.containsKey( periphName ) ) + { + RemotePeripheralWrapper wrapper = new RemotePeripheralWrapper( peripheral, m_modem.getComputer(), periphName ); + m_peripheralWrappersByName.put( periphName, wrapper ); + wrapper.attach(); + } } private void detachPeripheral( String periphName ) { - if( m_peripheralWrappersByName.containsKey( periphName ) ) - { - RemotePeripheralWrapper wrapper = m_peripheralWrappersByName.get( periphName ); - m_peripheralWrappersByName.remove( periphName ); - wrapper.detach(); - } + if( m_peripheralWrappersByName.containsKey( periphName ) ) + { + RemotePeripheralWrapper wrapper = m_peripheralWrappersByName.get( periphName ); + m_peripheralWrappersByName.remove( periphName ); + wrapper.detach(); + } } private String getTypeRemote( String remoteName ) { - synchronized( m_peripheralsByName ) - { - RemotePeripheralWrapper wrapper = m_peripheralWrappersByName.get( remoteName ); - if( wrapper != null ) - { - return wrapper.getType(); - } - } - return null; + synchronized( m_peripheralsByName ) + { + RemotePeripheralWrapper wrapper = m_peripheralWrappersByName.get( remoteName ); + if( wrapper != null ) + { + return wrapper.getType(); + } + } + return null; } private String[] getMethodNamesRemote( String remoteName ) { - synchronized( m_peripheralsByName ) - { - RemotePeripheralWrapper wrapper = m_peripheralWrappersByName.get( remoteName ); - if( wrapper != null ) - { - return wrapper.getMethodNames(); - } - } - return null; + synchronized( m_peripheralsByName ) + { + RemotePeripheralWrapper wrapper = m_peripheralWrappersByName.get( remoteName ); + if( wrapper != null ) + { + return wrapper.getMethodNames(); + } + } + return null; } private Object[] callMethodRemote( String remoteName, ILuaContext context, String method, Object[] arguments ) throws LuaException, InterruptedException { - RemotePeripheralWrapper wrapper; - synchronized( m_peripheralsByName ) - { - wrapper = m_peripheralWrappersByName.get( remoteName ); - } - if( wrapper != null ) - { - return wrapper.callMethod( context, method, arguments ); - } - throw new LuaException( "No peripheral: "+remoteName ); - } + RemotePeripheralWrapper wrapper; + synchronized( m_peripheralsByName ) + { + wrapper = m_peripheralWrappersByName.get( remoteName ); + } + if( wrapper != null ) + { + return wrapper.callMethod( context, method, arguments ); + } + throw new LuaException( "No peripheral: "+remoteName ); + } public void networkChanged() { - if( !worldObj.isRemote ) - { - if( !m_destroyed ) - { - // If this modem is alive, rebuild the network - searchNetwork( new ICableVisitor() { - public void visit( TileCable modem, int distance ) - { - synchronized( modem.m_peripheralsByName ) - { - modem.m_peripheralsKnown = false; - } - } - } ); - } - else - { - // If this modem is dead, rebuild the neighbours' networks - for( EnumFacing dir : EnumFacing.values() ) - { + if( !worldObj.isRemote ) + { + if( !m_destroyed ) + { + // If this modem is alive, rebuild the network + searchNetwork( new ICableVisitor() { + public void visit( TileCable modem, int distance ) + { + synchronized( modem.m_peripheralsByName ) + { + modem.m_peripheralsKnown = false; + } + } + } ); + } + else + { + // If this modem is dead, rebuild the neighbours' networks + for( EnumFacing dir : EnumFacing.values() ) + { BlockPos offset = getPos().offset( dir ); - if( offset.getY() >= 0 && offset.getY() < worldObj.getHeight() && BlockCable.isCable( worldObj, offset ) ) - { - TileEntity tile = worldObj.getTileEntity( offset ); - if( tile != null && tile instanceof TileCable ) - { - TileCable modem = (TileCable)tile; - modem.networkChanged(); - } - } - } - } - } + if( offset.getY() >= 0 && offset.getY() < worldObj.getHeight() && BlockCable.isCable( worldObj, offset ) ) + { + TileEntity tile = worldObj.getTileEntity( offset ); + if( tile != null && tile instanceof TileCable ) + { + TileCable modem = (TileCable)tile; + modem.networkChanged(); + } + } + } + } + } } - - // private stuff - - // Packet sending - + + // private stuff + + // Packet sending + private class Packet { - public int channel; - public int replyChannel; - public Object payload; - public Object senderObject; + public int channel; + public int replyChannel; + public Object payload; + public Object senderObject; } private void dispatchPacket( final Packet packet ) { - searchNetwork( new ICableVisitor() { - public void visit( TileCable modem, int distance ) - { - modem.receivePacket( packet, distance ); - } - } ); + searchNetwork( new ICableVisitor() { + public void visit( TileCable modem, int distance ) + { + modem.receivePacket( packet, distance ); + } + } ); } private void receivePacket( Packet packet, int distanceTravelled ) { - synchronized( m_receivers ) - { - Set receivers = m_receivers.get( packet.channel ); - if( receivers != null ) - { - Iterator it = receivers.iterator(); - while( it.hasNext() ) - { - IReceiver receiver = it.next(); - receiver.receiveSameDimension( packet.replyChannel, packet.payload, (double)distanceTravelled, packet.senderObject ); - } - } - } + synchronized( m_receivers ) + { + Set receivers = m_receivers.get( packet.channel ); + if( receivers != null ) + { + Iterator it = receivers.iterator(); + while( it.hasNext() ) + { + IReceiver receiver = it.next(); + receiver.receiveSameDimension( packet.replyChannel, packet.payload, (double)distanceTravelled, packet.senderObject ); + } + } + } } // Remote peripheral control - private static class RemotePeripheralWrapper implements IComputerAccess - { - private IPeripheral m_peripheral; - private IComputerAccess m_computer; - private String m_name; - - private String m_type; - private String[] m_methods; - private Map m_methodMap; - - public RemotePeripheralWrapper( IPeripheral peripheral, IComputerAccess computer, String name ) - { - m_peripheral = peripheral; - m_computer = computer; - m_name = name; + private static class RemotePeripheralWrapper implements IComputerAccess + { + private IPeripheral m_peripheral; + private IComputerAccess m_computer; + private String m_name; + + private String m_type; + private String[] m_methods; + private Map m_methodMap; + + public RemotePeripheralWrapper( IPeripheral peripheral, IComputerAccess computer, String name ) + { + m_peripheral = peripheral; + m_computer = computer; + m_name = name; - m_type = peripheral.getType(); - m_methods = peripheral.getMethodNames(); - assert( m_type != null ); - assert( m_methods != null ); - - m_methodMap = new HashMap(); - for( int i=0; i(); + for( int i=0; i newPeripheralsByName = new HashMap(); - if( getPeripheralType() == PeripheralType.WiredModemWithCable ) - { - searchNetwork( new ICableVisitor() { - public void visit( TileCable modem, int distance ) - { + final TileCable origin = this; + synchronized( m_peripheralsByName ) + { + // Collect the peripherals + final Map newPeripheralsByName = new HashMap(); + if( getPeripheralType() == PeripheralType.WiredModemWithCable ) + { + searchNetwork( new ICableVisitor() { + public void visit( TileCable modem, int distance ) + { if( modem != origin ) { IPeripheral peripheral = modem.getConnectedPeripheral(); @@ -883,162 +883,162 @@ public void visit( TileCable modem, int distance ) newPeripheralsByName.put( periphName, peripheral ); } } - } - } ); - } - //System.out.println( newPeripheralsByName.size()+" peripherals discovered" ); + } + } ); + } + //System.out.println( newPeripheralsByName.size()+" peripherals discovered" ); - // Detach all the old peripherals - Iterator it = m_peripheralsByName.keySet().iterator(); - while( it.hasNext() ) - { - String periphName = it.next(); - if( !newPeripheralsByName.containsKey( periphName ) ) - { - detachPeripheral( periphName ); - it.remove(); - } - } + // Detach all the old peripherals + Iterator it = m_peripheralsByName.keySet().iterator(); + while( it.hasNext() ) + { + String periphName = it.next(); + if( !newPeripheralsByName.containsKey( periphName ) ) + { + detachPeripheral( periphName ); + it.remove(); + } + } - // Attach all the new peripherals - Iterator it2 = newPeripheralsByName.keySet().iterator(); - while( it2.hasNext() ) - { - String periphName = it2.next(); - if( !m_peripheralsByName.containsKey( periphName ) ) - { - IPeripheral peripheral = newPeripheralsByName.get( periphName ); - if( peripheral != null ) - { - m_peripheralsByName.put( periphName, peripheral ); - if( isAttached() ) - { - attachPeripheral( periphName, peripheral ); - } - } - } - } - //System.out.println( m_peripheralsByName.size()+" connected" ); - } + // Attach all the new peripherals + Iterator it2 = newPeripheralsByName.keySet().iterator(); + while( it2.hasNext() ) + { + String periphName = it2.next(); + if( !m_peripheralsByName.containsKey( periphName ) ) + { + IPeripheral peripheral = newPeripheralsByName.get( periphName ); + if( peripheral != null ) + { + m_peripheralsByName.put( periphName, peripheral ); + if( isAttached() ) + { + attachPeripheral( periphName, peripheral ); + } + } + } + } + //System.out.println( m_peripheralsByName.size()+" connected" ); + } } public void togglePeripheralAccess() { - if( !m_peripheralAccessAllowed ) - { - m_peripheralAccessAllowed = true; - if( getConnectedPeripheral() == null ) - { - m_peripheralAccessAllowed = false; - return; - } - } - else - { - m_peripheralAccessAllowed = false; - } - updateAnim(); - networkChanged(); + if( !m_peripheralAccessAllowed ) + { + m_peripheralAccessAllowed = true; + if( getConnectedPeripheral() == null ) + { + m_peripheralAccessAllowed = false; + return; + } + } + else + { + m_peripheralAccessAllowed = false; + } + updateAnim(); + networkChanged(); } public String getConnectedPeripheralName() { - IPeripheral periph = getConnectedPeripheral(); - if( periph != null ) - { - String type = periph.getType(); - if( m_attachedPeripheralID < 0 ) - { - m_attachedPeripheralID = IDAssigner.getNextIDFromFile(new File( + IPeripheral periph = getConnectedPeripheral(); + if( periph != null ) + { + String type = periph.getType(); + if( m_attachedPeripheralID < 0 ) + { + m_attachedPeripheralID = IDAssigner.getNextIDFromFile(new File( ComputerCraft.getWorldDir(worldObj), "computer/lastid_" + type + ".txt" )); - } - return type + "_" + m_attachedPeripheralID; - } - return null; + } + return type + "_" + m_attachedPeripheralID; + } + return null; } private IPeripheral getConnectedPeripheral() { - if( m_peripheralAccessAllowed ) - { - if( getPeripheralType() == PeripheralType.WiredModemWithCable ) - { - EnumFacing facing = getDirection(); + if( m_peripheralAccessAllowed ) + { + if( getPeripheralType() == PeripheralType.WiredModemWithCable ) + { + EnumFacing facing = getDirection(); BlockPos neighbour = getPos().offset( facing ); - return PeripheralUtil.getPeripheral( worldObj, neighbour, facing.getOpposite() ); - } - } - return null; - } + return PeripheralUtil.getPeripheral( worldObj, neighbour, facing.getOpposite() ); + } + } + return null; + } // Generic network search stuff private static interface ICableVisitor { - public void visit( TileCable modem, int distance ); + public void visit( TileCable modem, int distance ); } private static class SearchLoc { - public World world; - public BlockPos pos; - public int distanceTravelled; + public World world; + public BlockPos pos; + public int distanceTravelled; } private static void enqueue( Queue queue, World world, BlockPos pos, int distanceTravelled ) { int y = pos.getY(); - if( y >= 0 && y < world.getHeight() && BlockCable.isCable( world, pos ) ) - { - SearchLoc loc = new SearchLoc(); - loc.world = world; - loc.pos = pos; - loc.distanceTravelled = distanceTravelled; - queue.offer( loc ); - } + if( y >= 0 && y < world.getHeight() && BlockCable.isCable( world, pos ) ) + { + SearchLoc loc = new SearchLoc(); + loc.world = world; + loc.pos = pos; + loc.distanceTravelled = distanceTravelled; + queue.offer( loc ); + } } private static void visitBlock( Queue queue, SearchLoc location, int searchID, ICableVisitor visitor ) { - if( location.distanceTravelled >= 256 ) - { - return; - } - - TileEntity tile = location.world.getTileEntity( location.pos ); - if( tile != null && tile instanceof TileCable ) - { - TileCable modem = (TileCable)tile; - if( !modem.m_destroyed && modem.m_lastSearchID != searchID ) - { - modem.m_lastSearchID = searchID; - visitor.visit( modem, location.distanceTravelled + 1 ); - - enqueue( queue, location.world, location.pos.up(), location.distanceTravelled + 1 ); - enqueue( queue, location.world, location.pos.down(), location.distanceTravelled + 1 ); - enqueue( queue, location.world, location.pos.south(), location.distanceTravelled + 1 ); - enqueue( queue, location.world, location.pos.north(), location.distanceTravelled + 1 ); - enqueue( queue, location.world, location.pos.east(), location.distanceTravelled + 1 ); - enqueue( queue, location.world, location.pos.west(), location.distanceTravelled + 1 ); - } - } + if( location.distanceTravelled >= 256 ) + { + return; + } + + TileEntity tile = location.world.getTileEntity( location.pos ); + if( tile != null && tile instanceof TileCable ) + { + TileCable modem = (TileCable)tile; + if( !modem.m_destroyed && modem.m_lastSearchID != searchID ) + { + modem.m_lastSearchID = searchID; + visitor.visit( modem, location.distanceTravelled + 1 ); + + enqueue( queue, location.world, location.pos.up(), location.distanceTravelled + 1 ); + enqueue( queue, location.world, location.pos.down(), location.distanceTravelled + 1 ); + enqueue( queue, location.world, location.pos.south(), location.distanceTravelled + 1 ); + enqueue( queue, location.world, location.pos.north(), location.distanceTravelled + 1 ); + enqueue( queue, location.world, location.pos.east(), location.distanceTravelled + 1 ); + enqueue( queue, location.world, location.pos.west(), location.distanceTravelled + 1 ); + } + } } private void searchNetwork( ICableVisitor visitor ) { - int searchID = ++s_nextUniqueSearchID; - Queue queue = new LinkedList(); - enqueue( queue, worldObj, getPos(), 1 ); - - int visited = 0; - while( queue.peek() != null ) - { - SearchLoc loc = queue.remove(); - visitBlock( queue, loc, searchID, visitor ); - visited++; - } - //System.out.println( "Visited "+visited+" common" ); + int searchID = ++s_nextUniqueSearchID; + Queue queue = new LinkedList(); + enqueue( queue, worldObj, getPos(), 1 ); + + int visited = 0; + while( queue.peek() != null ) + { + SearchLoc loc = queue.remove(); + visitBlock( queue, loc, searchID, visitor ); + visited++; + } + //System.out.println( "Visited "+visited+" common" ); } } diff --git a/src/main/java/dan200/computercraft/shared/peripheral/modem/TileModemBase.java b/src/main/java/dan200/computercraft/shared/peripheral/modem/TileModemBase.java index e56d4c30b..14f27b369 100644 --- a/src/main/java/dan200/computercraft/shared/peripheral/modem/TileModemBase.java +++ b/src/main/java/dan200/computercraft/shared/peripheral/modem/TileModemBase.java @@ -15,7 +15,7 @@ public abstract class TileModemBase extends TilePeripheralBase { - protected ModemPeripheral m_modem; + protected ModemPeripheral m_modem; protected TileModemBase() { @@ -27,11 +27,11 @@ protected TileModemBase() @Override public synchronized void destroy() { - if( m_modem != null ) - { - m_modem.destroy(); - m_modem = null; - } + if( m_modem != null ) + { + m_modem.destroy(); + m_modem = null; + } } @Override @@ -91,23 +91,23 @@ public AxisAlignedBB getBounds() @Override public void update() { - super.update(); - if( !worldObj.isRemote && m_modem.pollChanged() ) - { - updateAnim(); - } - } - - protected void updateAnim() - { - if( m_modem.isActive() ) - { - setAnim(1); - } - else - { - setAnim(0); - } + super.update(); + if( !worldObj.isRemote && m_modem.pollChanged() ) + { + updateAnim(); + } + } + + protected void updateAnim() + { + if( m_modem.isActive() ) + { + setAnim(1); + } + else + { + setAnim(0); + } } @Override @@ -131,6 +131,6 @@ public IPeripheral getPeripheral( EnumFacing side ) protected boolean isAttached() { - return (m_modem != null) && (m_modem.getComputer() != null); + return (m_modem != null) && (m_modem.getComputer() != null); } } diff --git a/src/main/java/dan200/computercraft/shared/peripheral/modem/TileWirelessModem.java b/src/main/java/dan200/computercraft/shared/peripheral/modem/TileWirelessModem.java index 58958c3d0..e68788dd7 100644 --- a/src/main/java/dan200/computercraft/shared/peripheral/modem/TileWirelessModem.java +++ b/src/main/java/dan200/computercraft/shared/peripheral/modem/TileWirelessModem.java @@ -21,28 +21,28 @@ public class TileWirelessModem extends TileModemBase { // Statics - private static class Peripheral extends WirelessModemPeripheral - { - private TileModemBase m_entity; - - public Peripheral( TileModemBase entity ) - { + private static class Peripheral extends WirelessModemPeripheral + { + private TileModemBase m_entity; + + public Peripheral( TileModemBase entity ) + { super( false ); - m_entity = entity; - } + m_entity = entity; + } - @Override - protected World getWorld() - { - return m_entity.getWorld(); - } - - @Override - protected Vec3d getPosition() - { + @Override + protected World getWorld() + { + return m_entity.getWorld(); + } + + @Override + protected Vec3d getPosition() + { BlockPos pos = m_entity.getPos().offset( m_entity.getDirection() ); - return new Vec3d( (double)pos.getX(), (double)pos.getY(), (double)pos.getZ() ); - } + return new Vec3d( (double)pos.getX(), (double)pos.getY(), (double)pos.getZ() ); + } @Override public boolean equals( IPeripheral other ) @@ -116,7 +116,7 @@ else if( dir == EnumFacing.DOWN ) @Override protected ModemPeripheral createPeripheral() { - return new Peripheral( this ); + return new Peripheral( this ); } @Override diff --git a/src/main/java/dan200/computercraft/shared/peripheral/modem/WirelessModemPeripheral.java b/src/main/java/dan200/computercraft/shared/peripheral/modem/WirelessModemPeripheral.java index eef732ec5..ba1ed8e4a 100644 --- a/src/main/java/dan200/computercraft/shared/peripheral/modem/WirelessModemPeripheral.java +++ b/src/main/java/dan200/computercraft/shared/peripheral/modem/WirelessModemPeripheral.java @@ -25,7 +25,7 @@ protected boolean isInterdimensional() return m_advanced; } - @Override + @Override protected double getTransmitRange() { if( m_advanced ) @@ -54,8 +54,8 @@ protected double getTransmitRange() return 0.0; } } - - @Override + + @Override protected INetwork getNetwork() { return WirelessNetwork.getUniversal(); diff --git a/src/main/java/dan200/computercraft/shared/peripheral/modem/WirelessNetwork.java b/src/main/java/dan200/computercraft/shared/peripheral/modem/WirelessNetwork.java index 51429fd3a..24f462974 100644 --- a/src/main/java/dan200/computercraft/shared/peripheral/modem/WirelessNetwork.java +++ b/src/main/java/dan200/computercraft/shared/peripheral/modem/WirelessNetwork.java @@ -28,55 +28,55 @@ public static void resetNetworks() { s_universalNetwork = null; } - - private Map> m_receivers; - + + private Map> m_receivers; + private WirelessNetwork() { - m_receivers = new HashMap>(); + m_receivers = new HashMap>(); } - @Override - public synchronized void addReceiver( IReceiver receiver ) - { - int channel = receiver.getChannel(); - Set receivers = m_receivers.get( channel ); - if( receivers == null ) - { - receivers = new HashSet(); - m_receivers.put( channel, receivers ); - } - receivers.add( receiver ); - } - - @Override - public synchronized void removeReceiver( IReceiver receiver ) - { - int channel = receiver.getChannel(); - Set receivers = m_receivers.get( channel ); - if( receivers != null ) - { - receivers.remove( receiver ); - } - } - - @Override - public synchronized void transmit( int channel, int replyChannel, Object payload, World world, Vec3d pos, double range, boolean interdimensional, Object senderObject ) - { - Set receivers = m_receivers.get( channel ); - if( receivers != null ) - { - Iterator it = receivers.iterator(); - while( it.hasNext() ) - { - IReceiver receiver = it.next(); - tryTransmit( receiver, replyChannel, payload, world, pos, range, interdimensional, senderObject ); - } - } - } - - private void tryTransmit( IReceiver receiver, int replyChannel, Object payload, World world, Vec3d pos, double range, boolean interdimensional, Object senderObject ) - { + @Override + public synchronized void addReceiver( IReceiver receiver ) + { + int channel = receiver.getChannel(); + Set receivers = m_receivers.get( channel ); + if( receivers == null ) + { + receivers = new HashSet(); + m_receivers.put( channel, receivers ); + } + receivers.add( receiver ); + } + + @Override + public synchronized void removeReceiver( IReceiver receiver ) + { + int channel = receiver.getChannel(); + Set receivers = m_receivers.get( channel ); + if( receivers != null ) + { + receivers.remove( receiver ); + } + } + + @Override + public synchronized void transmit( int channel, int replyChannel, Object payload, World world, Vec3d pos, double range, boolean interdimensional, Object senderObject ) + { + Set receivers = m_receivers.get( channel ); + if( receivers != null ) + { + Iterator it = receivers.iterator(); + while( it.hasNext() ) + { + IReceiver receiver = it.next(); + tryTransmit( receiver, replyChannel, payload, world, pos, range, interdimensional, senderObject ); + } + } + } + + private void tryTransmit( IReceiver receiver, int replyChannel, Object payload, World world, Vec3d pos, double range, boolean interdimensional, Object senderObject ) + { if( receiver.getWorld() == world ) { Vec3d position = receiver.getWorldPosition(); @@ -94,11 +94,11 @@ private void tryTransmit( IReceiver receiver, int replyChannel, Object payload, receiver.receiveDifferentDimension( replyChannel, payload, senderObject ); } } - } + } - @Override - public boolean isWireless() - { - return true; - } + @Override + public boolean isWireless() + { + return true; + } } diff --git a/src/main/java/dan200/computercraft/shared/peripheral/monitor/TileMonitor.java b/src/main/java/dan200/computercraft/shared/peripheral/monitor/TileMonitor.java index a77dd6daf..59c33035f 100644 --- a/src/main/java/dan200/computercraft/shared/peripheral/monitor/TileMonitor.java +++ b/src/main/java/dan200/computercraft/shared/peripheral/monitor/TileMonitor.java @@ -29,38 +29,38 @@ import java.util.Set; public class TileMonitor extends TilePeripheralBase - implements ITerminalTile + implements ITerminalTile { // Statics public static final double RENDER_BORDER = (2.0 / 16.0); - public static final double RENDER_MARGIN = (0.5 / 16.0); - public static final double RENDER_PIXEL_SCALE = (1.0 / 64.0); - - private static final int MAX_WIDTH = 8; - private static final int MAX_HEIGHT = 6; + public static final double RENDER_MARGIN = (0.5 / 16.0); + public static final double RENDER_PIXEL_SCALE = (1.0 / 64.0); + + private static final int MAX_WIDTH = 8; + private static final int MAX_HEIGHT = 6; // Members - private ServerTerminal m_serverTerminal; + private ServerTerminal m_serverTerminal; private ClientTerminal m_clientTerminal; private final Set m_computers; public long m_lastRenderFrame = -1; // For rendering use only public int m_renderDisplayList = -1; // For rendering use only - private boolean m_destroyed; - private boolean m_ignoreMe; + private boolean m_destroyed; + private boolean m_ignoreMe; private boolean m_changed; - private int m_textScale; - private int m_width; - private int m_height; - private int m_xIndex; - private int m_yIndex; + private int m_textScale; + private int m_width; + private int m_height; + private int m_xIndex; + private int m_yIndex; - private int m_dir; - private boolean m_sizeChangedQueued; + private int m_dir; + private boolean m_sizeChangedQueued; public TileMonitor() { @@ -68,34 +68,34 @@ public TileMonitor() m_destroyed = false; m_ignoreMe = false; - m_textScale = 2; - - m_width = 1; - m_height = 1; - m_xIndex = 0; - m_yIndex = 0; - m_changed = false; - - m_dir = 2; + m_textScale = 2; + + m_width = 1; + m_height = 1; + m_xIndex = 0; + m_yIndex = 0; + m_changed = false; + + m_dir = 2; } @Override public void destroy() { - if( !m_destroyed ) - { - m_destroyed = true; - if( !worldObj.isRemote ) - { - contractNeighbours(); - } - } + if( !m_destroyed ) + { + m_destroyed = true; + if( !worldObj.isRemote ) + { + contractNeighbours(); + } + } if( m_renderDisplayList >= 0 ) { ComputerCraft.deleteDisplayLists( m_renderDisplayList, 3 ); m_renderDisplayList = -1; } - } + } @Override public boolean onActivate( EntityPlayer player, EnumFacing side, float hitX, float hitY, float hitZ ) @@ -115,11 +115,11 @@ public boolean onActivate( EntityPlayer player, EnumFacing side, float hitX, flo public NBTTagCompound writeToNBT( NBTTagCompound nbttagcompound ) { nbttagcompound = super.writeToNBT( nbttagcompound); - nbttagcompound.setInteger( "xIndex", m_xIndex ); - nbttagcompound.setInteger( "yIndex", m_yIndex ); - nbttagcompound.setInteger( "width", m_width ); - nbttagcompound.setInteger( "height", m_height ); - nbttagcompound.setInteger( "dir", m_dir ); + nbttagcompound.setInteger( "xIndex", m_xIndex ); + nbttagcompound.setInteger( "yIndex", m_yIndex ); + nbttagcompound.setInteger( "width", m_width ); + nbttagcompound.setInteger( "height", m_height ); + nbttagcompound.setInteger( "dir", m_dir ); return nbttagcompound; } @@ -131,7 +131,7 @@ public void readFromNBT( NBTTagCompound nbttagcompound ) m_yIndex = nbttagcompound.getInteger("yIndex"); m_width = nbttagcompound.getInteger("width"); m_height = nbttagcompound.getInteger("height"); - m_dir = nbttagcompound.getInteger("dir"); + m_dir = nbttagcompound.getInteger("dir"); } @Override @@ -165,18 +165,18 @@ public void update() { m_clientTerminal.update(); } - } - } + } + } - public boolean pollChanged() - { - if( m_changed ) - { - m_changed = false; - return true; - } - return false; - } + public boolean pollChanged() + { + if( m_changed ) + { + m_changed = false; + return true; + } + return false; + } // IPeripheralTile implementation @@ -203,7 +203,7 @@ public void setTextScale( int scale ) } } - // Networking stuff + // Networking stuff @Override public void writeDescription( NBTTagCompound nbttagcompound ) @@ -250,8 +250,8 @@ public final void readDescription( NBTTagCompound nbttagcompound ) // ITerminalTile implementation @Override - public ITerminal getTerminal() - { + public ITerminal getTerminal() + { TileMonitor origin = getOrigin(); if( origin != null ) { @@ -287,9 +287,9 @@ private ITerminal getLocalTerminal() // Sizing and placement stuff public double getTextScale() - { + { return (double)m_textScale * 0.5; - } + } private void rebuildTerminal() { @@ -323,7 +323,7 @@ private void rebuildTerminal() } } } - } + } private void destroyTerminal() { @@ -345,13 +345,13 @@ public EnumFacing getDirection() public int getDir() { - return m_dir; + return m_dir; } public void setDir( int dir ) { - m_dir = dir; - m_changed = true; + m_dir = dir; + m_changed = true; markDirty(); } @@ -362,54 +362,54 @@ public EnumFacing getFront() public EnumFacing getRight() { - int dir = getDir() % 6; - switch( dir ) { - case 2: return EnumFacing.WEST; - case 3: return EnumFacing.EAST; - case 4: return EnumFacing.SOUTH; - case 5: return EnumFacing.NORTH; - } - return EnumFacing.WEST; + int dir = getDir() % 6; + switch( dir ) { + case 2: return EnumFacing.WEST; + case 3: return EnumFacing.EAST; + case 4: return EnumFacing.SOUTH; + case 5: return EnumFacing.NORTH; + } + return EnumFacing.WEST; } private EnumFacing getDown() { - int dir = getDir(); - if (dir <= 5) return EnumFacing.UP; - - switch( dir ) { - // up facing - case 8: return EnumFacing.NORTH; - case 9: return EnumFacing.SOUTH; - case 10: return EnumFacing.WEST; - case 11: return EnumFacing.EAST; - // down facing - case 14: return EnumFacing.SOUTH; - case 15: return EnumFacing.NORTH; - case 16: return EnumFacing.EAST; - case 17: return EnumFacing.WEST; - } - return EnumFacing.NORTH; + int dir = getDir(); + if (dir <= 5) return EnumFacing.UP; + + switch( dir ) { + // up facing + case 8: return EnumFacing.NORTH; + case 9: return EnumFacing.SOUTH; + case 10: return EnumFacing.WEST; + case 11: return EnumFacing.EAST; + // down facing + case 14: return EnumFacing.SOUTH; + case 15: return EnumFacing.NORTH; + case 16: return EnumFacing.EAST; + case 17: return EnumFacing.WEST; + } + return EnumFacing.NORTH; } public int getWidth() { - return m_width; + return m_width; } public int getHeight() { - return m_height; + return m_height; } public int getXIndex() { - return m_xIndex; + return m_xIndex; } public int getYIndex() { - return m_yIndex; + return m_yIndex; } private TileMonitor getSimilarMonitorAt( BlockPos pos ) @@ -420,42 +420,42 @@ private TileMonitor getSimilarMonitorAt( BlockPos pos ) } int y = pos.getY(); - if( worldObj != null && y >= 0 && y < worldObj.getHeight() ) - { - if( worldObj.isBlockLoaded( pos ) ) - { - TileEntity tile = worldObj.getTileEntity( pos ); - if( tile != null && tile instanceof TileMonitor ) - { - TileMonitor monitor = (TileMonitor)tile; - if( monitor.getDir() == getDir() && - monitor.getLocalTerminal().isColour() == getLocalTerminal().isColour() && - !monitor.m_destroyed && !monitor.m_ignoreMe ) - { - return monitor; - } - } - } - - } - return null; + if( worldObj != null && y >= 0 && y < worldObj.getHeight() ) + { + if( worldObj.isBlockLoaded( pos ) ) + { + TileEntity tile = worldObj.getTileEntity( pos ); + if( tile != null && tile instanceof TileMonitor ) + { + TileMonitor monitor = (TileMonitor)tile; + if( monitor.getDir() == getDir() && + monitor.getLocalTerminal().isColour() == getLocalTerminal().isColour() && + !monitor.m_destroyed && !monitor.m_ignoreMe ) + { + return monitor; + } + } + } + + } + return null; } private TileMonitor getNeighbour( int x, int y ) { BlockPos pos = getPos(); - EnumFacing right = getRight(); - EnumFacing down = getDown(); - int xOffset = -m_xIndex + x; - int yOffset = -m_yIndex + y; - return getSimilarMonitorAt( + EnumFacing right = getRight(); + EnumFacing down = getDown(); + int xOffset = -m_xIndex + x; + int yOffset = -m_yIndex + y; + return getSimilarMonitorAt( pos.offset( right, xOffset ).offset( down, yOffset ) - ); + ); } public TileMonitor getOrigin() { - return getNeighbour( 0, 0 ); + return getNeighbour( 0, 0 ); } private void resize( int width, int height ) @@ -464,317 +464,317 @@ private void resize( int width, int height ) BlockPos pos = getPos(); EnumFacing right = getRight(); EnumFacing down = getDown(); - for( int y=0; y 0 ) { - TileMonitor left = getNeighbour( m_xIndex - 1, m_yIndex ); - if( left != null ) { - left.contract( ); - } - } - if( m_xIndex + 1 < m_width ) { - TileMonitor right = getNeighbour( m_xIndex + 1, m_yIndex ); - if( right != null ) { - right.contract(); - } - } - if( m_yIndex > 0 ) { - TileMonitor below = getNeighbour( m_xIndex, m_yIndex - 1 ); - if( below != null ) { - below.contract(); - } - } - if( m_yIndex + 1 < m_height ) { - TileMonitor above = getNeighbour( m_xIndex, m_yIndex + 1 ); - if( above != null ) { - above.contract(); - } - } - m_ignoreMe = false; - } - + + public void contractNeighbours() + { + m_ignoreMe = true; + if( m_xIndex > 0 ) { + TileMonitor left = getNeighbour( m_xIndex - 1, m_yIndex ); + if( left != null ) { + left.contract( ); + } + } + if( m_xIndex + 1 < m_width ) { + TileMonitor right = getNeighbour( m_xIndex + 1, m_yIndex ); + if( right != null ) { + right.contract(); + } + } + if( m_yIndex > 0 ) { + TileMonitor below = getNeighbour( m_xIndex, m_yIndex - 1 ); + if( below != null ) { + below.contract(); + } + } + if( m_yIndex + 1 < m_height ) { + TileMonitor above = getNeighbour( m_xIndex, m_yIndex + 1 ); + if( above != null ) { + above.contract(); + } + } + m_ignoreMe = false; + } + public void contract() { - int height = m_height; - int width = m_width; - - TileMonitor origin = getOrigin(); - if( origin == null ) - { - TileMonitor right = null; - TileMonitor below = null; - if( width > 1 ) { - right = getNeighbour( 1, 0 ); - } - if( height > 1 ) { - below = getNeighbour( 0, 1 ); - } - if( right != null ) { - right.resize( width - 1, 1 ); - } - if( below != null ) { - below.resize( width, height - 1 ); - } - if( right != null ) { - right.expand(); - } - if( below != null ) { - below.expand(); - } - return; - } - - for( int y=0; y 0 ) { - above = origin; - above.resize( width, y ); - } - if( x > 0 ) { - left = origin.getNeighbour( 0, y ); - left.resize( x, 1 ); - } - if( x + 1 < width ) { - right = origin.getNeighbour( x + 1, y ); - right.resize( width - (x + 1), 1 ); - } - if( y + 1 < height ) { - below = origin.getNeighbour( 0, y + 1 ); - below.resize( width, height - (y + 1) ); - } + int height = m_height; + int width = m_width; + + TileMonitor origin = getOrigin(); + if( origin == null ) + { + TileMonitor right = null; + TileMonitor below = null; + if( width > 1 ) { + right = getNeighbour( 1, 0 ); + } + if( height > 1 ) { + below = getNeighbour( 0, 1 ); + } + if( right != null ) { + right.resize( width - 1, 1 ); + } + if( below != null ) { + below.resize( width, height - 1 ); + } + if( right != null ) { + right.expand(); + } + if( below != null ) { + below.expand(); + } + return; + } + + for( int y=0; y 0 ) { + above = origin; + above.resize( width, y ); + } + if( x > 0 ) { + left = origin.getNeighbour( 0, y ); + left.resize( x, 1 ); + } + if( x + 1 < width ) { + right = origin.getNeighbour( x + 1, y ); + right.resize( width - (x + 1), 1 ); + } + if( y + 1 < height ) { + below = origin.getNeighbour( 0, y + 1 ); + below.resize( width, height - (y + 1) ); + } - // Re-expand - if( above != null ) { - above.expand(); - } - if( left != null ) { - left.expand(); - } - if( right != null ) { - right.expand(); - } - if( below != null ) { - below.expand(); - } - return; - } - } - } + // Re-expand + if( above != null ) { + above.expand(); + } + if( left != null ) { + left.expand(); + } + if( right != null ) { + right.expand(); + } + if( below != null ) { + below.expand(); + } + return; + } + } + } } - - public void monitorTouched( float xPos, float yPos, float zPos ) - { - int side = getDir(); - XYPair pair = convertToXY( xPos, yPos, zPos, side ); + + public void monitorTouched( float xPos, float yPos, float zPos ) + { + int side = getDir(); + XYPair pair = convertToXY( xPos, yPos, zPos, side ); pair = new XYPair( pair.x + m_xIndex, pair.y + m_height - m_yIndex - 1 ); - if (pair.x > (m_width - RENDER_BORDER) || pair.y > (m_height - RENDER_BORDER) || pair.x < (RENDER_BORDER) || pair.y < (RENDER_BORDER)) - { - return; - } - - Terminal originTerminal = getTerminal().getTerminal(); - if( originTerminal == null ) - { - return; - } + if (pair.x > (m_width - RENDER_BORDER) || pair.y > (m_height - RENDER_BORDER) || pair.x < (RENDER_BORDER) || pair.y < (RENDER_BORDER)) + { + return; + } + + Terminal originTerminal = getTerminal().getTerminal(); + if( originTerminal == null ) + { + return; + } if( !getTerminal().isColour() ) { return; } - - double xCharWidth = ((double)m_width - ((RENDER_BORDER + RENDER_MARGIN) * 2.0)) / ((double)originTerminal.getWidth()); - double yCharHeight = ((double)m_height - ((RENDER_BORDER + RENDER_MARGIN) * 2.0)) / ((double)originTerminal.getHeight()); - - int xCharPos = (int)Math.min((double)originTerminal.getWidth(), Math.max(((pair.x - RENDER_BORDER - RENDER_MARGIN) / xCharWidth) + 1.0, 1.0)); - int yCharPos = (int)Math.min((double)originTerminal.getHeight(), Math.max(((pair.y - RENDER_BORDER - RENDER_MARGIN) / yCharHeight) + 1.0, 1.0)); - - for( int y=0; y 0); - } + if( m_printer.getWorld().isRemote ) + { + m_lastPrinting = (j > 0); + } } - @Override + @Override public boolean canInteractWith( EntityPlayer player ) { return m_printer.isUseableByPlayer( player ); } - @Override - public ItemStack transferStackInSlot(EntityPlayer par1EntityPlayer, int i) + @Override + public ItemStack transferStackInSlot(EntityPlayer par1EntityPlayer, int i) { ItemStack itemstack = null; Slot slot = (Slot)inventorySlots.get(i); @@ -113,7 +113,7 @@ public ItemStack transferStackInSlot(EntityPlayer par1EntityPlayer, int i) itemstack = itemstack1.copy(); if( i < 13 ) { - // Transfer from printer to inventory + // Transfer from printer to inventory if(!mergeItemStack(itemstack1, 13, 49, true)) { return null; @@ -121,22 +121,22 @@ public ItemStack transferStackInSlot(EntityPlayer par1EntityPlayer, int i) } else { - // Transfer from inventory to printer - if( itemstack1.getItem() == Items.DYE ) - { - if( !mergeItemStack(itemstack1, 0, 1, false) ) - { - return null; - } - } - else //if is paper - { - if( !mergeItemStack(itemstack1, 1, 13, false) ) - { - return null; - } - } - } + // Transfer from inventory to printer + if( itemstack1.getItem() == Items.DYE ) + { + if( !mergeItemStack(itemstack1, 0, 1, false) ) + { + return null; + } + } + else //if is paper + { + if( !mergeItemStack(itemstack1, 1, 13, false) ) + { + return null; + } + } + } if(itemstack1.stackSize == 0) { diff --git a/src/main/java/dan200/computercraft/shared/peripheral/printer/TilePrinter.java b/src/main/java/dan200/computercraft/shared/peripheral/printer/TilePrinter.java index 87676cb2b..df98be35b 100644 --- a/src/main/java/dan200/computercraft/shared/peripheral/printer/TilePrinter.java +++ b/src/main/java/dan200/computercraft/shared/peripheral/printer/TilePrinter.java @@ -43,7 +43,7 @@ public class TilePrinter extends TilePeripheralBase private final ItemStack[] m_inventory; private final Terminal m_page; private String m_pageTitle; - private boolean m_printing; + private boolean m_printing; public TilePrinter() { @@ -77,60 +77,60 @@ public boolean onActivate( EntityPlayer player, EnumFacing side, float hitX, flo public void readFromNBT(NBTTagCompound nbttagcompound) { super.readFromNBT(nbttagcompound); - - // Read page - synchronized( m_page ) - { - m_printing = nbttagcompound.getBoolean( "printing" ); - m_pageTitle = nbttagcompound.getString( "pageTitle" ); + + // Read page + synchronized( m_page ) + { + m_printing = nbttagcompound.getBoolean( "printing" ); + m_pageTitle = nbttagcompound.getString( "pageTitle" ); m_page.readFromNBT( nbttagcompound ); - } - - // Read inventory - synchronized( m_inventory ) - { - NBTTagList nbttaglist = nbttagcompound.getTagList( "Items", Constants.NBT.TAG_COMPOUND ); - for( int i=0; i= 0 && j < m_inventory.length) - { - m_inventory[j] = ItemStack.loadItemStackFromNBT(itemTag); - } - } - } + } + + // Read inventory + synchronized( m_inventory ) + { + NBTTagList nbttaglist = nbttagcompound.getTagList( "Items", Constants.NBT.TAG_COMPOUND ); + for( int i=0; i= 0 && j < m_inventory.length) + { + m_inventory[j] = ItemStack.loadItemStackFromNBT(itemTag); + } + } + } } - @Override + @Override public NBTTagCompound writeToNBT(NBTTagCompound nbttagcompound) { nbttagcompound = super.writeToNBT(nbttagcompound); - // Write page - synchronized( m_page ) - { - nbttagcompound.setBoolean( "printing", m_printing ); - nbttagcompound.setString( "pageTitle", m_pageTitle ); + // Write page + synchronized( m_page ) + { + nbttagcompound.setBoolean( "printing", m_printing ); + nbttagcompound.setString( "pageTitle", m_pageTitle ); m_page.writeToNBT( nbttagcompound ); - } - - // Write inventory - synchronized( m_inventory ) - { - NBTTagList nbttaglist = new NBTTagList(); - for(int i=0; i 0 ) - { - return true; - } - return false; - } - } - - private boolean inputPage() - { - synchronized( m_inventory ) - { - ItemStack inkStack = m_inventory[0]; - if( inkStack == null || !isInk(inkStack) ) - { - return false; - } - - for( int i=1; i<7; ++i ) - { - ItemStack paperStack = m_inventory[i]; - if( paperStack != null && isPaper(paperStack) ) - { - // Decrement ink - inkStack.stackSize--; - if( inkStack.stackSize <= 0 ) - { - m_inventory[0] = null; - } - - // Decrement paper - paperStack.stackSize--; - if( paperStack.stackSize <= 0 ) - { - m_inventory[i] = null; - updateAnim(); - } - - // Setup the new page - int colour = inkStack.getItemDamage(); - if( colour >= 0 && colour < 16 ) { - m_page.setTextColour( 15 - colour ); - } else { - m_page.setTextColour( 15 ); - } - - m_page.clear(); - if( paperStack.getItem() instanceof ItemPrintout ) - { - m_pageTitle = ItemPrintout.getTitle( paperStack ); - String[] text = ItemPrintout.getText( paperStack ); - String[] textColour = ItemPrintout.getColours( paperStack ); - for( int y=0; y 0 ) + { + return true; + } + return false; + } + } + + private boolean inputPage() + { + synchronized( m_inventory ) + { + ItemStack inkStack = m_inventory[0]; + if( inkStack == null || !isInk(inkStack) ) + { + return false; + } + + for( int i=1; i<7; ++i ) + { + ItemStack paperStack = m_inventory[i]; + if( paperStack != null && isPaper(paperStack) ) + { + // Decrement ink + inkStack.stackSize--; + if( inkStack.stackSize <= 0 ) + { + m_inventory[0] = null; + } + + // Decrement paper + paperStack.stackSize--; + if( paperStack.stackSize <= 0 ) + { + m_inventory[i] = null; + updateAnim(); + } + + // Setup the new page + int colour = inkStack.getItemDamage(); + if( colour >= 0 && colour < 16 ) { + m_page.setTextColour( 15 - colour ); + } else { + m_page.setTextColour( 15 ); + } + + m_page.clear(); + if( paperStack.getItem() instanceof ItemPrintout ) + { + m_pageTitle = ItemPrintout.getTitle( paperStack ); + String[] text = ItemPrintout.getText( paperStack ); + String[] textColour = ItemPrintout.getColours( paperStack ); + for( int y=0; y m_legacyTurtleUpgrades; +{ + private Map m_legacyTurtleUpgrades; private Map m_turtleUpgrades; - private Map m_dropConsumers; + private Map m_dropConsumers; - public CCTurtleProxyCommon() - { + public CCTurtleProxyCommon() + { m_legacyTurtleUpgrades = new HashMap(); - m_turtleUpgrades = new HashMap(); - m_dropConsumers = new WeakHashMap(); - } - - // ICCTurtleProxy implementation - - @Override - public void preInit() - { - registerItems(); - } - - @Override - public void init() - { - registerForgeHandlers(); - registerTileEntities(); - } + m_turtleUpgrades = new HashMap(); + m_dropConsumers = new WeakHashMap(); + } + + // ICCTurtleProxy implementation + + @Override + public void preInit() + { + registerItems(); + } + + @Override + public void init() + { + registerForgeHandlers(); + registerTileEntities(); + } - @Override - public void registerTurtleUpgrade( ITurtleUpgrade upgrade ) - { - // Check conditions - int id = upgrade.getLegacyUpgradeID(); - if( id >= 0 && id < 64 ) - { - throw new RuntimeException( "Error registering '"+upgrade.getUnlocalisedAdjective()+" Turtle'. Legacy UpgradeID '"+id+"' is reserved by ComputerCraft" ); - } - - // Register - registerTurtleUpgradeInternal( upgrade ); - } + @Override + public void registerTurtleUpgrade( ITurtleUpgrade upgrade ) + { + // Check conditions + int id = upgrade.getLegacyUpgradeID(); + if( id >= 0 && id < 64 ) + { + throw new RuntimeException( "Error registering '"+upgrade.getUnlocalisedAdjective()+" Turtle'. Legacy UpgradeID '"+id+"' is reserved by ComputerCraft" ); + } + + // Register + registerTurtleUpgradeInternal( upgrade ); + } @Override public ITurtleUpgrade getTurtleUpgrade( String id ) @@ -91,16 +91,16 @@ public ITurtleUpgrade getTurtleUpgrade( String id ) } @Override - public ITurtleUpgrade getTurtleUpgrade( int legacyId ) - { - return m_legacyTurtleUpgrades.get( legacyId ); - } - - @Override - public ITurtleUpgrade getTurtleUpgrade( ItemStack stack ) - { - for( ITurtleUpgrade upgrade : m_turtleUpgrades.values() ) - { + public ITurtleUpgrade getTurtleUpgrade( int legacyId ) + { + return m_legacyTurtleUpgrades.get( legacyId ); + } + + @Override + public ITurtleUpgrade getTurtleUpgrade( ItemStack stack ) + { + for( ITurtleUpgrade upgrade : m_turtleUpgrades.values() ) + { try { ItemStack upgradeStack = upgrade.getCraftingItem(); @@ -113,9 +113,9 @@ public ITurtleUpgrade getTurtleUpgrade( ItemStack stack ) { continue; } - } - return null; - } + } + return null; + } public static boolean isUpgradeVanilla( ITurtleUpgrade upgrade ) { @@ -133,8 +133,8 @@ public static boolean isUpgradeSuitableForFamily( ComputerFamily family, ITurtle return true; } } - - private void addAllUpgradedTurtles( ComputerFamily family, List list ) + + private void addAllUpgradedTurtles( ComputerFamily family, List list ) { ItemStack basicStack = TurtleItemFactory.create( -1, null, null, family, null, null, 0, null ); if( basicStack != null ) @@ -161,89 +161,89 @@ private void addUpgradedTurtle( ComputerFamily family, ITurtleUpgrade upgrade, L list.add( stack ); } } - } - - @Override - public void addAllUpgradedTurtles( List list ) - { - addAllUpgradedTurtles( ComputerFamily.Normal, list ); - addAllUpgradedTurtles( ComputerFamily.Advanced, list ); - } - - @Override - public void setEntityDropConsumer( Entity entity, IEntityDropConsumer consumer ) - { - if( !m_dropConsumers.containsKey( entity ) ) - { - boolean captured = ObfuscationReflectionHelper.getPrivateValue( - Entity.class, - entity, - "captureDrops" - ).booleanValue(); - - if( !captured ) - { - ObfuscationReflectionHelper.setPrivateValue( + } + + @Override + public void addAllUpgradedTurtles( List list ) + { + addAllUpgradedTurtles( ComputerFamily.Normal, list ); + addAllUpgradedTurtles( ComputerFamily.Advanced, list ); + } + + @Override + public void setEntityDropConsumer( Entity entity, IEntityDropConsumer consumer ) + { + if( !m_dropConsumers.containsKey( entity ) ) + { + boolean captured = ObfuscationReflectionHelper.getPrivateValue( + Entity.class, + entity, + "captureDrops" + ).booleanValue(); + + if( !captured ) + { + ObfuscationReflectionHelper.setPrivateValue( Entity.class, entity, new Boolean( true ), "captureDrops" ); - - ArrayList items = ObfuscationReflectionHelper.getPrivateValue( + + ArrayList items = ObfuscationReflectionHelper.getPrivateValue( Entity.class, entity, "capturedDrops" ); - - if( items == null || items.size() == 0 ) - { - m_dropConsumers.put( entity, consumer ); - } - } - } - } - - @Override - public void clearEntityDropConsumer( Entity entity ) - { - if( m_dropConsumers.containsKey( entity ) ) - { - boolean captured = ObfuscationReflectionHelper.getPrivateValue( + + if( items == null || items.size() == 0 ) + { + m_dropConsumers.put( entity, consumer ); + } + } + } + } + + @Override + public void clearEntityDropConsumer( Entity entity ) + { + if( m_dropConsumers.containsKey( entity ) ) + { + boolean captured = ObfuscationReflectionHelper.getPrivateValue( Entity.class, entity, "captureDrops" ); - - if( captured ) - { - ObfuscationReflectionHelper.setPrivateValue( - Entity.class, - entity, - new Boolean( false ), - "captureDrops" - ); - - ArrayList items = ObfuscationReflectionHelper.getPrivateValue( + + if( captured ) + { + ObfuscationReflectionHelper.setPrivateValue( + Entity.class, + entity, + new Boolean( false ), + "captureDrops" + ); + + ArrayList items = ObfuscationReflectionHelper.getPrivateValue( Entity.class, entity, "capturedDrops" ); - - if( items != null ) - { - dispatchEntityDrops( entity, items ); - items.clear(); - } - } - m_dropConsumers.remove( entity ); - } - } + + if( items != null ) + { + dispatchEntityDrops( entity, items ); + items.clear(); + } + } + m_dropConsumers.remove( entity ); + } + } private void registerTurtleUpgradeInternal( ITurtleUpgrade upgrade ) - { - // Check conditions - int legacyID = upgrade.getLegacyUpgradeID(); + { + // Check conditions + int legacyID = upgrade.getLegacyUpgradeID(); if( legacyID >= 0 ) { if( legacyID >= Short.MAX_VALUE ) @@ -273,13 +273,13 @@ private void registerTurtleUpgradeInternal( ITurtleUpgrade upgrade ) m_turtleUpgrades.put( id, upgrade ); // Add a bunch of impostor recipes - if( isUpgradeVanilla( upgrade ) ) - { - // Add fake recipes to fool NEI - List recipeList = CraftingManager.getInstance().getRecipeList(); - ItemStack craftingItem = upgrade.getCraftingItem(); + if( isUpgradeVanilla( upgrade ) ) + { + // Add fake recipes to fool NEI + List recipeList = CraftingManager.getInstance().getRecipeList(); + ItemStack craftingItem = upgrade.getCraftingItem(); - // A turtle just containing this upgrade + // A turtle just containing this upgrade for( ComputerFamily family : ComputerFamily.values() ) { if( !isUpgradeSuitableForFamily( family, upgrade ) ) @@ -318,22 +318,22 @@ private void registerTurtleUpgradeInternal( ITurtleUpgrade upgrade ) } } } - } - } - - private void registerItems() - { + } + } + + private void registerItems() + { // Blocks - // Turtle + // Turtle ComputerCraft.Blocks.turtle = BlockTurtle.createTurtleBlock(); - GameRegistry.registerBlock( ComputerCraft.Blocks.turtle, ItemTurtleLegacy.class, "CC-Turtle" ); + GameRegistry.registerBlock( ComputerCraft.Blocks.turtle, ItemTurtleLegacy.class, "CC-Turtle" ); ComputerCraft.Blocks.turtleExpanded = BlockTurtle.createTurtleBlock(); - GameRegistry.registerBlock( ComputerCraft.Blocks.turtleExpanded, ItemTurtleNormal.class, "CC-TurtleExpanded" ); + GameRegistry.registerBlock( ComputerCraft.Blocks.turtleExpanded, ItemTurtleNormal.class, "CC-TurtleExpanded" ); // Advanced Turtle ComputerCraft.Blocks.turtleAdvanced = BlockTurtle.createTurtleBlock(); - GameRegistry.registerBlock( ComputerCraft.Blocks.turtleAdvanced, ItemTurtleAdvanced.class, "CC-TurtleAdvanced" ); + GameRegistry.registerBlock( ComputerCraft.Blocks.turtleAdvanced, ItemTurtleAdvanced.class, "CC-TurtleAdvanced" ); // Recipe types RecipeSorter.register( "computercraft:turtle", TurtleRecipe.class, RecipeSorter.Category.SHAPED, "after:minecraft:shapeless" ); @@ -403,47 +403,47 @@ gold, new ItemStack( Blocks.CHEST, 1 ), gold, registerTurtleUpgradeInternal( ComputerCraft.Upgrades.advancedModem ); } - private void registerTileEntities() - { - // TileEntities - GameRegistry.registerTileEntity( TileTurtle.class, "turtle" ); - GameRegistry.registerTileEntity( TileTurtleExpanded.class, "turtleex" ); - GameRegistry.registerTileEntity( TileTurtleAdvanced.class, "turtleadv" ); - } - - private void registerForgeHandlers() - { - ForgeHandlers handlers = new ForgeHandlers(); - MinecraftForge.EVENT_BUS.register( handlers ); - } - - public class ForgeHandlers - { - private ForgeHandlers() - { - } + private void registerTileEntities() + { + // TileEntities + GameRegistry.registerTileEntity( TileTurtle.class, "turtle" ); + GameRegistry.registerTileEntity( TileTurtleExpanded.class, "turtleex" ); + GameRegistry.registerTileEntity( TileTurtleAdvanced.class, "turtleadv" ); + } + + private void registerForgeHandlers() + { + ForgeHandlers handlers = new ForgeHandlers(); + MinecraftForge.EVENT_BUS.register( handlers ); + } + + public class ForgeHandlers + { + private ForgeHandlers() + { + } - // Forge event responses - @SubscribeEvent - public void onEntityLivingDrops( LivingDropsEvent event ) - { - dispatchEntityDrops( event.getEntity(), event.getDrops() ); - } + // Forge event responses + @SubscribeEvent + public void onEntityLivingDrops( LivingDropsEvent event ) + { + dispatchEntityDrops( event.getEntity(), event.getDrops() ); + } } private void dispatchEntityDrops( Entity entity, java.util.List drops ) { - IEntityDropConsumer consumer = m_dropConsumers.get( entity ); - if( consumer != null ) - { - // All checks have passed, lets dispatch the drops - Iterator it = drops.iterator(); - while( it.hasNext() ) - { - EntityItem entityItem = (EntityItem)it.next(); - consumer.consumeDrop( entity, entityItem.getEntityItem() ); - } - drops.clear(); - } + IEntityDropConsumer consumer = m_dropConsumers.get( entity ); + if( consumer != null ) + { + // All checks have passed, lets dispatch the drops + Iterator it = drops.iterator(); + while( it.hasNext() ) + { + EntityItem entityItem = (EntityItem)it.next(); + consumer.consumeDrop( entity, entityItem.getEntityItem() ); + } + drops.clear(); + } } } diff --git a/src/main/java/dan200/computercraft/shared/proxy/ComputerCraftProxyCommon.java b/src/main/java/dan200/computercraft/shared/proxy/ComputerCraftProxyCommon.java index 67322c506..bf968244e 100644 --- a/src/main/java/dan200/computercraft/shared/proxy/ComputerCraftProxyCommon.java +++ b/src/main/java/dan200/computercraft/shared/proxy/ComputerCraftProxyCommon.java @@ -85,30 +85,30 @@ public abstract class ComputerCraftProxyCommon implements IComputerCraftProxy { - public ComputerCraftProxyCommon() - { - } - - // IComputerCraftProxy implementation + public ComputerCraftProxyCommon() + { + } + + // IComputerCraftProxy implementation - @Override - public void preInit() - { - registerItems(); - } - - @Override - public void init() - { - registerTileEntities(); - registerForgeHandlers(); - } - - @Override - public abstract boolean isClient(); - - @Override - public abstract boolean getGlobalCursorBlink(); + @Override + public void preInit() + { + registerItems(); + } + + @Override + public void init() + { + registerTileEntities(); + registerForgeHandlers(); + } + + @Override + public abstract boolean isClient(); + + @Override + public abstract boolean getGlobalCursorBlink(); @Override public abstract long getRenderFrame(); @@ -119,45 +119,45 @@ public void deleteDisplayLists( int list, int range ) } @Override - public abstract Object getFixedWidthFontRenderer(); - - @Override - public String getRecordInfo( ItemStack recordStack ) - { - Item item = recordStack.getItem(); - if( item instanceof ItemRecord ) - { - ItemRecord record = (ItemRecord)item; - return record.getRecordNameLocal(); - } - return null; - } - - @Override - public abstract void playRecord( SoundEvent record, String recordInfo, World world, BlockPos pos ); - - @Override - public abstract Object getDiskDriveGUI( InventoryPlayer inventory, TileDiskDrive drive ); - - @Override - public abstract Object getComputerGUI( TileComputer computer ); + public abstract Object getFixedWidthFontRenderer(); + + @Override + public String getRecordInfo( ItemStack recordStack ) + { + Item item = recordStack.getItem(); + if( item instanceof ItemRecord ) + { + ItemRecord record = (ItemRecord)item; + return record.getRecordNameLocal(); + } + return null; + } + + @Override + public abstract void playRecord( SoundEvent record, String recordInfo, World world, BlockPos pos ); + + @Override + public abstract Object getDiskDriveGUI( InventoryPlayer inventory, TileDiskDrive drive ); + + @Override + public abstract Object getComputerGUI( TileComputer computer ); - @Override - public abstract Object getPrinterGUI( InventoryPlayer inventory, TilePrinter printer ); + @Override + public abstract Object getPrinterGUI( InventoryPlayer inventory, TilePrinter printer ); @Override public abstract Object getTurtleGUI( InventoryPlayer inventory, TileTurtle turtle ); - @Override - public abstract Object getPrintoutGUI( InventoryPlayer inventory ); + @Override + public abstract Object getPrintoutGUI( InventoryPlayer inventory ); @Override public abstract Object getPocketComputerGUI( InventoryPlayer inventory ); - public abstract File getWorldDir( World world ); - - @Override - public void handlePacket( final ComputerCraftPacket packet, final EntityPlayer player ) + public abstract File getWorldDir( World world ); + + @Override + public void handlePacket( final ComputerCraftPacket packet, final EntityPlayer player ) { IThreadListener listener = player.getServer(); if( listener != null ) @@ -182,11 +182,11 @@ public void run() private void processPacket( ComputerCraftPacket packet, EntityPlayer player ) { - switch( packet.m_packetType ) - { - /////////////////////////////////// - // Packets from Client to Server // - /////////////////////////////////// + switch( packet.m_packetType ) + { + /////////////////////////////////// + // Packets from Client to Server // + /////////////////////////////////// case ComputerCraftPacket.TurnOn: case ComputerCraftPacket.Shutdown: case ComputerCraftPacket.Reboot: @@ -221,18 +221,18 @@ private void processPacket( ComputerCraftPacket packet, EntityPlayer player ) } break; } - } - } + } + } - private void registerItems() - { - // Creative tab - ComputerCraft.mainCreativeTab = new CreativeTabMain( CreativeTabs.getNextID() ); + private void registerItems() + { + // Creative tab + ComputerCraft.mainCreativeTab = new CreativeTabMain( CreativeTabs.getNextID() ); // Blocks - // Computer - ComputerCraft.Blocks.computer = new BlockComputer(); - GameRegistry.registerBlock( ComputerCraft.Blocks.computer, ItemComputer.class, "CC-Computer" ); + // Computer + ComputerCraft.Blocks.computer = new BlockComputer(); + GameRegistry.registerBlock( ComputerCraft.Blocks.computer, ItemComputer.class, "CC-Computer" ); // Peripheral ComputerCraft.Blocks.peripheral = new BlockPeripheral(); @@ -278,80 +278,80 @@ private void registerItems() RecipeSorter.register( "computercraft:pocket_computer_upgrade", PocketComputerUpgradeRecipe.class, RecipeSorter.Category.SHAPELESS, "after:minecraft:shapeless" ); // Recipes - // Computer - ItemStack computer = ComputerItemFactory.create( -1, null, ComputerFamily.Normal ); - GameRegistry.addRecipe( computer, - "XXX", "XYX", "XZX", - 'X', Blocks.STONE, - 'Y', Items.REDSTONE, - 'Z', Blocks.GLASS_PANE - ); + // Computer + ItemStack computer = ComputerItemFactory.create( -1, null, ComputerFamily.Normal ); + GameRegistry.addRecipe( computer, + "XXX", "XYX", "XZX", + 'X', Blocks.STONE, + 'Y', Items.REDSTONE, + 'Z', Blocks.GLASS_PANE + ); // Advanced Computer - ItemStack advancedComputer = ComputerItemFactory.create( -1, null, ComputerFamily.Advanced ); - GameRegistry.addRecipe( advancedComputer, - "XXX", "XYX", "XZX", - 'X', Items.GOLD_INGOT, - 'Y', Items.REDSTONE, - 'Z', Blocks.GLASS_PANE - ); + ItemStack advancedComputer = ComputerItemFactory.create( -1, null, ComputerFamily.Advanced ); + GameRegistry.addRecipe( advancedComputer, + "XXX", "XYX", "XZX", + 'X', Items.GOLD_INGOT, + 'Y', Items.REDSTONE, + 'Z', Blocks.GLASS_PANE + ); // Disk Drive - ItemStack diskDrive = PeripheralItemFactory.create( PeripheralType.DiskDrive, null, 1 ); - GameRegistry.addRecipe( diskDrive, - "XXX", "XYX", "XYX", - 'X', Blocks.STONE, - 'Y', Items.REDSTONE - ); - - // Wireless Modem - ItemStack wirelessModem = PeripheralItemFactory.create( PeripheralType.WirelessModem, null, 1 ); - GameRegistry.addRecipe( wirelessModem, - "XXX", "XYX", "XXX", - 'X', Blocks.STONE, - 'Y', Items.ENDER_PEARL - ); - - // Monitor - ItemStack monitor = PeripheralItemFactory.create( PeripheralType.Monitor, null, 1 ); - GameRegistry.addRecipe( monitor, - "XXX", "XYX", "XXX", - 'X', Blocks.STONE, - 'Y', Blocks.GLASS_PANE - ); - - // PrinterEmpty - ItemStack printer = PeripheralItemFactory.create( PeripheralType.Printer, null, 1 ); - GameRegistry.addRecipe( printer, - "XXX", "XYX", "XZX", - 'X', Blocks.STONE, - 'Y', Items.REDSTONE, - 'Z', new ItemStack( Items.DYE, 1, 0 ) // 0 = Black - ); + ItemStack diskDrive = PeripheralItemFactory.create( PeripheralType.DiskDrive, null, 1 ); + GameRegistry.addRecipe( diskDrive, + "XXX", "XYX", "XYX", + 'X', Blocks.STONE, + 'Y', Items.REDSTONE + ); + + // Wireless Modem + ItemStack wirelessModem = PeripheralItemFactory.create( PeripheralType.WirelessModem, null, 1 ); + GameRegistry.addRecipe( wirelessModem, + "XXX", "XYX", "XXX", + 'X', Blocks.STONE, + 'Y', Items.ENDER_PEARL + ); + + // Monitor + ItemStack monitor = PeripheralItemFactory.create( PeripheralType.Monitor, null, 1 ); + GameRegistry.addRecipe( monitor, + "XXX", "XYX", "XXX", + 'X', Blocks.STONE, + 'Y', Blocks.GLASS_PANE + ); + + // PrinterEmpty + ItemStack printer = PeripheralItemFactory.create( PeripheralType.Printer, null, 1 ); + GameRegistry.addRecipe( printer, + "XXX", "XYX", "XZX", + 'X', Blocks.STONE, + 'Y', Items.REDSTONE, + 'Z', new ItemStack( Items.DYE, 1, 0 ) // 0 = Black + ); - // Advanced Monitor - ItemStack advancedMonitors = PeripheralItemFactory.create( PeripheralType.AdvancedMonitor, null, 4 ); - GameRegistry.addRecipe( advancedMonitors, - "XXX", "XYX", "XXX", - 'X', Items.GOLD_INGOT, - 'Y', Blocks.GLASS_PANE - ); + // Advanced Monitor + ItemStack advancedMonitors = PeripheralItemFactory.create( PeripheralType.AdvancedMonitor, null, 4 ); + GameRegistry.addRecipe( advancedMonitors, + "XXX", "XYX", "XXX", + 'X', Items.GOLD_INGOT, + 'Y', Blocks.GLASS_PANE + ); - // Networking Cable - ItemStack cable = PeripheralItemFactory.create( PeripheralType.Cable, null, 6 ); - GameRegistry.addRecipe( cable, - " X ", "XYX", " X ", - 'X', Blocks.STONE, - 'Y', Items.REDSTONE - ); - - // Wired Modem - ItemStack wiredModem = PeripheralItemFactory.create( PeripheralType.WiredModem, null, 1 ); - GameRegistry.addRecipe( wiredModem, - "XXX", "XYX", "XXX", - 'X', Blocks.STONE, - 'Y', Items.REDSTONE - ); + // Networking Cable + ItemStack cable = PeripheralItemFactory.create( PeripheralType.Cable, null, 6 ); + GameRegistry.addRecipe( cable, + " X ", "XYX", " X ", + 'X', Blocks.STONE, + 'Y', Items.REDSTONE + ); + + // Wired Modem + ItemStack wiredModem = PeripheralItemFactory.create( PeripheralType.WiredModem, null, 1 ); + GameRegistry.addRecipe( wiredModem, + "XXX", "XYX", "XXX", + 'X', Blocks.STONE, + 'Y', Items.REDSTONE + ); // Computer ItemStack commandComputer = ComputerItemFactory.create( -1, null, ComputerFamily.Command ); @@ -371,46 +371,46 @@ private void registerItems() ); // Disk - GameRegistry.addRecipe( new DiskRecipe() ); + GameRegistry.addRecipe( new DiskRecipe() ); // Impostor Disk recipes (to fool NEI) - ItemStack paper = new ItemStack( Items.PAPER, 1 ); - ItemStack redstone = new ItemStack( Items.REDSTONE, 1 ); - ItemStack basicDisk = ItemDiskLegacy.createFromIDAndColour( -1, null, Colour.Blue.getHex() ); - GameRegistry.addRecipe( new ImpostorShapelessRecipe( basicDisk, new Object[] { redstone, paper } ) ); + ItemStack paper = new ItemStack( Items.PAPER, 1 ); + ItemStack redstone = new ItemStack( Items.REDSTONE, 1 ); + ItemStack basicDisk = ItemDiskLegacy.createFromIDAndColour( -1, null, Colour.Blue.getHex() ); + GameRegistry.addRecipe( new ImpostorShapelessRecipe( basicDisk, new Object[] { redstone, paper } ) ); - for( int colour=0; colour<16; ++colour ) - { - ItemStack disk = ItemDiskLegacy.createFromIDAndColour( -1, null, Colour.values()[ colour ].getHex() ); - ItemStack dye = new ItemStack( Items.DYE, 1, colour ); - for( int otherColour=0; otherColour<16; ++otherColour ) - { - if( colour != otherColour ) - { - ItemStack otherDisk = ItemDiskLegacy.createFromIDAndColour( -1, null, Colour.values()[ colour ].getHex() ); - GameRegistry.addRecipe( new ImpostorShapelessRecipe( disk, new Object[] { + for( int colour=0; colour<16; ++colour ) + { + ItemStack disk = ItemDiskLegacy.createFromIDAndColour( -1, null, Colour.values()[ colour ].getHex() ); + ItemStack dye = new ItemStack( Items.DYE, 1, colour ); + for( int otherColour=0; otherColour<16; ++otherColour ) + { + if( colour != otherColour ) + { + ItemStack otherDisk = ItemDiskLegacy.createFromIDAndColour( -1, null, Colour.values()[ colour ].getHex() ); + GameRegistry.addRecipe( new ImpostorShapelessRecipe( disk, new Object[] { otherDisk, dye } ) ); - } - } - GameRegistry.addRecipe( new ImpostorShapelessRecipe( disk, new Object[] { + } + } + GameRegistry.addRecipe( new ImpostorShapelessRecipe( disk, new Object[] { redstone, paper, dye } ) ); - } + } - // Printout + // Printout GameRegistry.addRecipe( new PrintoutRecipe() ); - ItemStack singlePrintout = ItemPrintout.createSingleFromTitleAndText( null, null, null ); - ItemStack multiplePrintout = ItemPrintout.createMultipleFromTitleAndText( null, null, null ); - ItemStack bookPrintout = ItemPrintout.createBookFromTitleAndText( null, null, null ); + ItemStack singlePrintout = ItemPrintout.createSingleFromTitleAndText( null, null, null ); + ItemStack multiplePrintout = ItemPrintout.createMultipleFromTitleAndText( null, null, null ); + ItemStack bookPrintout = ItemPrintout.createBookFromTitleAndText( null, null, null ); - // Impostor Printout recipes (to fool NEI) - ItemStack string = new ItemStack( Items.STRING, 1, 0 ); - GameRegistry.addRecipe( new ImpostorShapelessRecipe( multiplePrintout, new Object[] { singlePrintout, singlePrintout, string } ) ); + // Impostor Printout recipes (to fool NEI) + ItemStack string = new ItemStack( Items.STRING, 1, 0 ); + GameRegistry.addRecipe( new ImpostorShapelessRecipe( multiplePrintout, new Object[] { singlePrintout, singlePrintout, string } ) ); - ItemStack leather = new ItemStack( Items.LEATHER, 1, 0 ); - GameRegistry.addRecipe( new ImpostorShapelessRecipe( bookPrintout, new Object[] { leather, singlePrintout, string } ) ); + ItemStack leather = new ItemStack( Items.LEATHER, 1, 0 ); + GameRegistry.addRecipe( new ImpostorShapelessRecipe( bookPrintout, new Object[] { leather, singlePrintout, string } ) ); // Pocket Computer ItemStack pocketComputer = PocketComputerItemFactory.create( -1, null, ComputerFamily.Normal, false ); @@ -443,98 +443,98 @@ private void registerItems() // Skulls (Easter Egg) // Dan - NBTTagCompound tag = new NBTTagCompound(); - tag.setString( "SkullOwner", "dan200" ); - ItemStack danHead = new ItemStack( Items.SKULL, 1, 3 ); - danHead.setTagCompound( tag ); - GameRegistry.addShapelessRecipe( danHead, computer, new ItemStack( Items.SKULL, 1, 1 ) ); + NBTTagCompound tag = new NBTTagCompound(); + tag.setString( "SkullOwner", "dan200" ); + ItemStack danHead = new ItemStack( Items.SKULL, 1, 3 ); + danHead.setTagCompound( tag ); + GameRegistry.addShapelessRecipe( danHead, computer, new ItemStack( Items.SKULL, 1, 1 ) ); // Cloudy - tag = new NBTTagCompound(); - tag.setString( "SkullOwner", "Cloudhunter" ); - ItemStack cloudyHead = new ItemStack( Items.SKULL, 1, 3 ); - cloudyHead.setTagCompound( tag ); - GameRegistry.addShapelessRecipe( cloudyHead, monitor, new ItemStack( Items.SKULL, 1, 1 ) ); - } - - private void registerTileEntities() - { - // Tile Entities - GameRegistry.registerTileEntity( TileComputer.class, "computer" ); - GameRegistry.registerTileEntity( TileDiskDrive.class, "diskdrive" ); - GameRegistry.registerTileEntity( TileWirelessModem.class, "wirelessmodem" ); - GameRegistry.registerTileEntity( TileMonitor.class, "monitor" ); - GameRegistry.registerTileEntity( TilePrinter.class, "ccprinter" ); - GameRegistry.registerTileEntity( TileCable.class, "wiredmodem" ); + tag = new NBTTagCompound(); + tag.setString( "SkullOwner", "Cloudhunter" ); + ItemStack cloudyHead = new ItemStack( Items.SKULL, 1, 3 ); + cloudyHead.setTagCompound( tag ); + GameRegistry.addShapelessRecipe( cloudyHead, monitor, new ItemStack( Items.SKULL, 1, 1 ) ); + } + + private void registerTileEntities() + { + // Tile Entities + GameRegistry.registerTileEntity( TileComputer.class, "computer" ); + GameRegistry.registerTileEntity( TileDiskDrive.class, "diskdrive" ); + GameRegistry.registerTileEntity( TileWirelessModem.class, "wirelessmodem" ); + GameRegistry.registerTileEntity( TileMonitor.class, "monitor" ); + GameRegistry.registerTileEntity( TilePrinter.class, "ccprinter" ); + GameRegistry.registerTileEntity( TileCable.class, "wiredmodem" ); GameRegistry.registerTileEntity( TileCommandComputer.class, "command_computer" ); GameRegistry.registerTileEntity( TileAdvancedModem.class, "advanced_modem" ); - // Register peripheral providers + // Register peripheral providers ComputerCraftAPI.registerPeripheralProvider( new DefaultPeripheralProvider() ); - if( ComputerCraft.enableCommandBlock ) - { - ComputerCraftAPI.registerPeripheralProvider( new CommandBlockPeripheralProvider() ); - } + if( ComputerCraft.enableCommandBlock ) + { + ComputerCraftAPI.registerPeripheralProvider( new CommandBlockPeripheralProvider() ); + } // Register bundled power providers ComputerCraftAPI.registerBundledRedstoneProvider( new DefaultBundledRedstoneProvider() ); // Register media providers ComputerCraftAPI.registerMediaProvider( new DefaultMediaProvider() ); - } - - private void registerForgeHandlers() - { - ForgeHandlers handlers = new ForgeHandlers(); + } + + private void registerForgeHandlers() + { + ForgeHandlers handlers = new ForgeHandlers(); MinecraftForge.EVENT_BUS.register( handlers ); - NetworkRegistry.INSTANCE.registerGuiHandler( ComputerCraft.instance, handlers ); - } - - public class ForgeHandlers implements - IGuiHandler - { - private ForgeHandlers() - { - } + NetworkRegistry.INSTANCE.registerGuiHandler( ComputerCraft.instance, handlers ); + } + + public class ForgeHandlers implements + IGuiHandler + { + private ForgeHandlers() + { + } - // IGuiHandler implementation - - @Override - public Object getServerGuiElement( int id, EntityPlayer player, World world, int x, int y, int z ) - { + // IGuiHandler implementation + + @Override + public Object getServerGuiElement( int id, EntityPlayer player, World world, int x, int y, int z ) + { BlockPos pos = new BlockPos( x, y, z ); - switch( id ) - { - case ComputerCraft.diskDriveGUIID: - { + switch( id ) + { + case ComputerCraft.diskDriveGUIID: + { TileEntity tile = world.getTileEntity( pos ); - if( tile != null && tile instanceof TileDiskDrive ) - { - TileDiskDrive drive = (TileDiskDrive)tile; - return new ContainerDiskDrive( player.inventory, drive ); - } - break; - } - case ComputerCraft.computerGUIID: - { + if( tile != null && tile instanceof TileDiskDrive ) + { + TileDiskDrive drive = (TileDiskDrive)tile; + return new ContainerDiskDrive( player.inventory, drive ); + } + break; + } + case ComputerCraft.computerGUIID: + { TileEntity tile = world.getTileEntity( pos ); - if( tile != null && tile instanceof TileComputer ) - { - TileComputer computer = (TileComputer)tile; - return new ContainerComputer( computer ); - } - break; - } - case ComputerCraft.printerGUIID: - { + if( tile != null && tile instanceof TileComputer ) + { + TileComputer computer = (TileComputer)tile; + return new ContainerComputer( computer ); + } + break; + } + case ComputerCraft.printerGUIID: + { TileEntity tile = world.getTileEntity( pos ); - if( tile != null && tile instanceof TilePrinter ) - { - TilePrinter printer = (TilePrinter)tile; - return new ContainerPrinter( player.inventory, printer ); - } - break; - } + if( tile != null && tile instanceof TilePrinter ) + { + TilePrinter printer = (TilePrinter)tile; + return new ContainerPrinter( player.inventory, printer ); + } + break; + } case ComputerCraft.turtleGUIID: { TileEntity tile = world.getTileEntity( pos ); @@ -554,45 +554,45 @@ public Object getServerGuiElement( int id, EntityPlayer player, World world, int return new ContainerHeldItem( player.inventory ); } } - return null; - } + return null; + } - @Override - public Object getClientGuiElement( int id, EntityPlayer player, World world, int x, int y, int z ) - { + @Override + public Object getClientGuiElement( int id, EntityPlayer player, World world, int x, int y, int z ) + { BlockPos pos = new BlockPos( x, y, z ); - switch( id ) - { - case ComputerCraft.diskDriveGUIID: - { + switch( id ) + { + case ComputerCraft.diskDriveGUIID: + { TileEntity tile = world.getTileEntity( pos ); - if( tile != null && tile instanceof TileDiskDrive ) - { - TileDiskDrive drive = (TileDiskDrive)tile; - return getDiskDriveGUI( player.inventory, drive ); - } - break; - } - case ComputerCraft.computerGUIID: - { + if( tile != null && tile instanceof TileDiskDrive ) + { + TileDiskDrive drive = (TileDiskDrive)tile; + return getDiskDriveGUI( player.inventory, drive ); + } + break; + } + case ComputerCraft.computerGUIID: + { TileEntity tile = world.getTileEntity( pos ); - if( tile != null && tile instanceof TileComputer ) - { - TileComputer computer = (TileComputer)tile; - return getComputerGUI( computer ); - } - break; - } - case ComputerCraft.printerGUIID: - { + if( tile != null && tile instanceof TileComputer ) + { + TileComputer computer = (TileComputer)tile; + return getComputerGUI( computer ); + } + break; + } + case ComputerCraft.printerGUIID: + { TileEntity tile = world.getTileEntity( pos ); - if( tile != null && tile instanceof TilePrinter ) - { - TilePrinter printer = (TilePrinter)tile; - return getPrinterGUI( player.inventory, printer ); - } - break; - } + if( tile != null && tile instanceof TilePrinter ) + { + TilePrinter printer = (TilePrinter)tile; + return getPrinterGUI( player.inventory, printer ); + } + break; + } case ComputerCraft.turtleGUIID: { TileEntity tile = world.getTileEntity( pos ); diff --git a/src/main/java/dan200/computercraft/shared/proxy/ICCTurtleProxy.java b/src/main/java/dan200/computercraft/shared/proxy/ICCTurtleProxy.java index 9edd30f66..6c6b3ca25 100644 --- a/src/main/java/dan200/computercraft/shared/proxy/ICCTurtleProxy.java +++ b/src/main/java/dan200/computercraft/shared/proxy/ICCTurtleProxy.java @@ -15,15 +15,15 @@ public interface ICCTurtleProxy { - public void preInit(); - public void init(); + public void preInit(); + public void init(); - public void registerTurtleUpgrade( ITurtleUpgrade upgrade ); + public void registerTurtleUpgrade( ITurtleUpgrade upgrade ); public ITurtleUpgrade getTurtleUpgrade( String id ); - public ITurtleUpgrade getTurtleUpgrade( int legacyId ); - public ITurtleUpgrade getTurtleUpgrade( ItemStack item ); - public void addAllUpgradedTurtles( List list ); + public ITurtleUpgrade getTurtleUpgrade( int legacyId ); + public ITurtleUpgrade getTurtleUpgrade( ItemStack item ); + public void addAllUpgradedTurtles( List list ); - public void setEntityDropConsumer( Entity entity, IEntityDropConsumer consumer ); - public void clearEntityDropConsumer( Entity entity ); + public void setEntityDropConsumer( Entity entity, IEntityDropConsumer consumer ); + public void clearEntityDropConsumer( Entity entity ); } diff --git a/src/main/java/dan200/computercraft/shared/proxy/IComputerCraftProxy.java b/src/main/java/dan200/computercraft/shared/proxy/IComputerCraftProxy.java index a2ac6aa4b..82e2dc146 100644 --- a/src/main/java/dan200/computercraft/shared/proxy/IComputerCraftProxy.java +++ b/src/main/java/dan200/computercraft/shared/proxy/IComputerCraftProxy.java @@ -22,25 +22,25 @@ public interface IComputerCraftProxy { - public void preInit(); - public void init(); - public boolean isClient(); + public void preInit(); + public void init(); + public boolean isClient(); - public boolean getGlobalCursorBlink(); + public boolean getGlobalCursorBlink(); public long getRenderFrame(); public void deleteDisplayLists( int list, int range ); - public Object getFixedWidthFontRenderer(); + public Object getFixedWidthFontRenderer(); - public String getRecordInfo( ItemStack item ); - public void playRecord( SoundEvent record, String recordInfo, World world, BlockPos pos ); + public String getRecordInfo( ItemStack item ); + public void playRecord( SoundEvent record, String recordInfo, World world, BlockPos pos ); - public Object getDiskDriveGUI( InventoryPlayer inventory, TileDiskDrive drive ); - public Object getComputerGUI( TileComputer computer ); - public Object getPrinterGUI( InventoryPlayer inventory, TilePrinter printer ); + public Object getDiskDriveGUI( InventoryPlayer inventory, TileDiskDrive drive ); + public Object getComputerGUI( TileComputer computer ); + public Object getPrinterGUI( InventoryPlayer inventory, TilePrinter printer ); public Object getTurtleGUI( InventoryPlayer inventory, TileTurtle turtle ); public abstract Object getPrintoutGUI( InventoryPlayer inventory ); public abstract Object getPocketComputerGUI( InventoryPlayer inventory ); - public File getWorldDir( World world ); - public void handlePacket( ComputerCraftPacket packet, EntityPlayer player ); + public File getWorldDir( World world ); + public void handlePacket( ComputerCraftPacket packet, EntityPlayer player ); } diff --git a/src/main/java/dan200/computercraft/shared/turtle/apis/TurtleAPI.java b/src/main/java/dan200/computercraft/shared/turtle/apis/TurtleAPI.java index 910937adf..0fd7f62a7 100644 --- a/src/main/java/dan200/computercraft/shared/turtle/apis/TurtleAPI.java +++ b/src/main/java/dan200/computercraft/shared/turtle/apis/TurtleAPI.java @@ -25,77 +25,77 @@ public class TurtleAPI implements ILuaAPI { private IAPIEnvironment m_environment; - private ITurtleAccess m_turtle; + private ITurtleAccess m_turtle; public TurtleAPI( IAPIEnvironment environment, ITurtleAccess turtle ) { m_environment = environment; - m_turtle = turtle; + m_turtle = turtle; } - // ILuaAPI implementation + // ILuaAPI implementation - @Override + @Override public String[] getNames() { - return new String[] { - "turtle" - }; + return new String[] { + "turtle" + }; } - @Override - public void startup( ) - { - } + @Override + public void startup( ) + { + } - @Override - public void advance( double _dt ) - { - } - - @Override - public void shutdown( ) - { - } - - @Override + @Override + public void advance( double _dt ) + { + } + + @Override + public void shutdown( ) + { + } + + @Override public String[] getMethodNames() { - return new String[] { - "forward", - "back", - "up", - "down", - "turnLeft", - "turnRight", - "dig", - "digUp", - "digDown", - "place", - "placeUp", - "placeDown", - "drop", - "select", - "getItemCount", - "getItemSpace", - "detect", - "detectUp", - "detectDown", - "compare", - "compareUp", - "compareDown", - "attack", - "attackUp", - "attackDown", - "dropUp", - "dropDown", - "suck", - "suckUp", - "suckDown", - "getFuelLevel", - "refuel", - "compareTo", - "transferTo", + return new String[] { + "forward", + "back", + "up", + "down", + "turnLeft", + "turnRight", + "dig", + "digUp", + "digDown", + "place", + "placeUp", + "placeDown", + "drop", + "select", + "getItemCount", + "getItemSpace", + "detect", + "detectUp", + "detectDown", + "compare", + "compareUp", + "compareDown", + "attack", + "attackUp", + "attackDown", + "dropUp", + "dropDown", + "suck", + "suckUp", + "suckDown", + "getFuelLevel", + "refuel", + "compareTo", + "transferTo", "getSelectedSlot", "getFuelLimit", "equipLeft", @@ -104,7 +104,7 @@ public String[] getMethodNames() "inspectUp", "inspectDown", "getItemDetail", - }; + }; } private Object[] tryCommand( ILuaContext context, ITurtleCommand command ) throws LuaException, InterruptedException @@ -128,11 +128,11 @@ private int parseOptionalSlotNumber( Object[] arguments, int index, int fallback { return fallback; } - int slot = ((Number)arguments[index]).intValue(); - if( slot >= 1 && slot <= 16 ) - { + int slot = ((Number)arguments[index]).intValue(); + if( slot >= 1 && slot <= 16 ) + { return slot - 1; - } + } else { throw new LuaException( "Slot number " + slot + " out of range" ); @@ -142,14 +142,14 @@ private int parseOptionalSlotNumber( Object[] arguments, int index, int fallback private int parseCount( Object[] arguments, int index ) throws LuaException { if( arguments.length <= index || !(arguments[index] instanceof Number) ) - { - throw new LuaException( "Expected number" ); - } - int count = ((Number)arguments[index]).intValue(); - if( count >= 0 && count <= 64 ) - { + { + throw new LuaException( "Expected number" ); + } + int count = ((Number)arguments[index]).intValue(); + if( count >= 0 && count <= 64 ) + { return count; - } + } else { throw new LuaException( "Item count " + count + " out of range" ); @@ -180,94 +180,94 @@ else if( arguments[ index ].equals( "right" ) ) } } - @Override + @Override public Object[] callMethod( ILuaContext context, int method, Object[] args ) throws LuaException, InterruptedException { - switch( method ) - { - case 0: - { - // forward - return tryCommand( context, new TurtleMoveCommand( MoveDirection.Forward ) ); - } - case 1: - { - // back + switch( method ) + { + case 0: + { + // forward + return tryCommand( context, new TurtleMoveCommand( MoveDirection.Forward ) ); + } + case 1: + { + // back return tryCommand( context, new TurtleMoveCommand( MoveDirection.Back ) ); - } - case 2: - { - // up - return tryCommand( context, new TurtleMoveCommand( MoveDirection.Up ) ); - } - case 3: - { - // down - return tryCommand( context, new TurtleMoveCommand( MoveDirection.Down ) ); - } - case 4: - { - // turnLeft - return tryCommand( context, new TurtleTurnCommand( TurnDirection.Left ) ); - } - case 5: - { - // turnRight - return tryCommand( context, new TurtleTurnCommand( TurnDirection.Right ) ); - } - case 6: - { - // dig + } + case 2: + { + // up + return tryCommand( context, new TurtleMoveCommand( MoveDirection.Up ) ); + } + case 3: + { + // down + return tryCommand( context, new TurtleMoveCommand( MoveDirection.Down ) ); + } + case 4: + { + // turnLeft + return tryCommand( context, new TurtleTurnCommand( TurnDirection.Left ) ); + } + case 5: + { + // turnRight + return tryCommand( context, new TurtleTurnCommand( TurnDirection.Right ) ); + } + case 6: + { + // dig Optional side = parseSide( args, 0 ); - return tryCommand( context, new TurtleDigCommand( InteractDirection.Forward, side ) ); - } - case 7: - { - // digUp + return tryCommand( context, new TurtleDigCommand( InteractDirection.Forward, side ) ); + } + case 7: + { + // digUp Optional side = parseSide( args, 0 ); return tryCommand( context, new TurtleDigCommand( InteractDirection.Up, side ) ); - } - case 8: - { - // digDown + } + case 8: + { + // digDown Optional side = parseSide( args, 0 ); return tryCommand( context, new TurtleDigCommand( InteractDirection.Down, side ) ); - } - case 9: - { - // place + } + case 9: + { + // place return tryCommand( context, new TurtlePlaceCommand( InteractDirection.Forward, args ) ); - } - case 10: - { - // placeUp + } + case 10: + { + // placeUp return tryCommand( context, new TurtlePlaceCommand( InteractDirection.Up, args ) ); - } - case 11: - { - // placeDown + } + case 11: + { + // placeDown return tryCommand( context, new TurtlePlaceCommand( InteractDirection.Down, args ) ); - } - case 12: - { - // drop + } + case 12: + { + // drop int count = 64; if( args.length > 0 ) { - count = parseCount( args, 0 ); + count = parseCount( args, 0 ); } return tryCommand( context, new TurtleDropCommand( InteractDirection.Forward, count ) ); - } - case 13: - { - // select - int slot = parseSlotNumber( args, 0 ); + } + case 13: + { + // select + int slot = parseSlotNumber( args, 0 ); return tryCommand( context, new TurtleSelectCommand( slot ) ); - } - case 14: - { - // getItemCount - int slot = parseOptionalSlotNumber( args, 0, m_turtle.getSelectedSlot() ); + } + case 14: + { + // getItemCount + int slot = parseOptionalSlotNumber( args, 0, m_turtle.getSelectedSlot() ); ItemStack stack = m_turtle.getInventory().getStackInSlot( slot ); if( stack != null ) { @@ -277,10 +277,10 @@ public Object[] callMethod( ILuaContext context, int method, Object[] args ) thr { return new Object[] { 0 }; } - } - case 15: - { - // getItemSpace + } + case 15: + { + // getItemSpace int slot = parseOptionalSlotNumber( args, 0, m_turtle.getSelectedSlot() ); ItemStack stack = m_turtle.getInventory().getStackInSlot( slot ); if( stack != null ) @@ -290,144 +290,144 @@ public Object[] callMethod( ILuaContext context, int method, Object[] args ) thr }; } return new Object[] { 64 }; - } - case 16: - { - // detect + } + case 16: + { + // detect return tryCommand( context, new TurtleDetectCommand( InteractDirection.Forward ) ); - } - case 17: - { - // detectUp + } + case 17: + { + // detectUp return tryCommand( context, new TurtleDetectCommand( InteractDirection.Up ) ); - } - case 18: - { - // detectDown + } + case 18: + { + // detectDown return tryCommand( context, new TurtleDetectCommand( InteractDirection.Down ) ); - } - case 19: - { - // compare + } + case 19: + { + // compare return tryCommand( context, new TurtleCompareCommand( InteractDirection.Forward ) ); - } - case 20: - { - // compareUp + } + case 20: + { + // compareUp return tryCommand( context, new TurtleCompareCommand( InteractDirection.Up ) ); - } - case 21: - { - // compareDown + } + case 21: + { + // compareDown return tryCommand( context, new TurtleCompareCommand( InteractDirection.Down ) ); - } - case 22: - { - // attack + } + case 22: + { + // attack Optional side = parseSide( args, 0 ); return tryCommand( context, new TurtleAttackCommand( InteractDirection.Forward, side ) ); - } - case 23: - { - // attackUp + } + case 23: + { + // attackUp Optional side = parseSide( args, 0 ); return tryCommand( context, new TurtleAttackCommand( InteractDirection.Up, side ) ); - } - case 24: - { - // attackDown + } + case 24: + { + // attackDown Optional side = parseSide( args, 0 ); return tryCommand( context, new TurtleAttackCommand( InteractDirection.Down, side ) ); - } - case 25: - { - // dropUp + } + case 25: + { + // dropUp int count = 64; if( args.length > 0 ) { count = parseCount( args, 0 ); } return tryCommand( context, new TurtleDropCommand( InteractDirection.Up, count ) ); - } - case 26: - { - // dropDown + } + case 26: + { + // dropDown int count = 64; if( args.length > 0 ) { count = parseCount( args, 0 ); } return tryCommand( context, new TurtleDropCommand( InteractDirection.Down, count ) ); - } - case 27: - { - // suck + } + case 27: + { + // suck int count = 64; if( args.length > 0 ) { count = parseCount( args, 0 ); } - return tryCommand( context, new TurtleSuckCommand( InteractDirection.Forward, count ) ); - } - case 28: - { - // suckUp + return tryCommand( context, new TurtleSuckCommand( InteractDirection.Forward, count ) ); + } + case 28: + { + // suckUp int count = 64; if( args.length > 0 ) { count = parseCount( args, 0 ); } return tryCommand( context, new TurtleSuckCommand( InteractDirection.Up, count ) ); - } - case 29: - { - // suckDown + } + case 29: + { + // suckDown int count = 64; if( args.length > 0 ) { count = parseCount( args, 0 ); } return tryCommand( context, new TurtleSuckCommand( InteractDirection.Down, count ) ); - } - case 30: - { - // getFuelLevel - if( m_turtle.isFuelNeeded() ) - { - return new Object[] { m_turtle.getFuelLevel() }; - } + } + case 30: + { + // getFuelLevel + if( m_turtle.isFuelNeeded() ) + { + return new Object[] { m_turtle.getFuelLevel() }; + } else { - return new Object[] { "unlimited" }; + return new Object[] { "unlimited" }; } - } - case 31: - { - // refuel + } + case 31: + { + // refuel int count = 64; if( args.length > 0 ) { count = parseCount( args, 0 ); } return tryCommand( context, new TurtleRefuelCommand( count ) ); - } - case 32: - { - // compareTo - int slot = parseSlotNumber( args, 0 ); + } + case 32: + { + // compareTo + int slot = parseSlotNumber( args, 0 ); return tryCommand( context, new TurtleCompareToCommand( slot ) ); } - case 33: - { - // transferTo - int slot = parseSlotNumber( args, 0 ); + case 33: + { + // transferTo + int slot = parseSlotNumber( args, 0 ); int count = 64; if( args.length > 1 ) { count = parseCount( args, 1 ); } - return tryCommand( context, new TurtleTransferToCommand( slot, count ) ); - } + return tryCommand( context, new TurtleTransferToCommand( slot, count ) ); + } case 34: { // getSelectedSlot @@ -493,10 +493,10 @@ public Object[] callMethod( ILuaContext context, int method, Object[] args ) thr return new Object[] { null }; } } - default: - { - return null; - } - } + default: + { + return null; + } + } } } diff --git a/src/main/java/dan200/computercraft/shared/turtle/blocks/BlockTurtle.java b/src/main/java/dan200/computercraft/shared/turtle/blocks/BlockTurtle.java index 78ed5c72d..87b7c16cf 100644 --- a/src/main/java/dan200/computercraft/shared/turtle/blocks/BlockTurtle.java +++ b/src/main/java/dan200/computercraft/shared/turtle/blocks/BlockTurtle.java @@ -47,8 +47,8 @@ public static BlockTurtle createTurtleBlock() public BlockTurtle() { super( Material.IRON ); - setHardness( 2.5f ); - setUnlocalizedName( "computercraft:turtle" ); + setHardness( 2.5f ); + setUnlocalizedName( "computercraft:turtle" ); setCreativeTab( ComputerCraft.mainCreativeTab ); setDefaultState( this.blockState.getBaseState() .withProperty( Properties.FACING, EnumFacing.NORTH ) diff --git a/src/main/java/dan200/computercraft/shared/turtle/blocks/TileTurtle.java b/src/main/java/dan200/computercraft/shared/turtle/blocks/TileTurtle.java index 72eaf5277..31f42e4e9 100644 --- a/src/main/java/dan200/computercraft/shared/turtle/blocks/TileTurtle.java +++ b/src/main/java/dan200/computercraft/shared/turtle/blocks/TileTurtle.java @@ -41,7 +41,7 @@ public class TileTurtle extends TileComputerBase { // Statics - public static final int INVENTORY_SIZE = 16; + public static final int INVENTORY_SIZE = 16; public static final int INVENTORY_WIDTH = 4; public static final int INVENTORY_HEIGHT = 4; @@ -55,7 +55,7 @@ public class TileTurtle extends TileComputerBase public TileTurtle() { - m_inventory = new ItemStack[ INVENTORY_SIZE ]; + m_inventory = new ItemStack[ INVENTORY_SIZE ]; m_previousInventory = new ItemStack[ getSizeInventory() ]; m_inventoryChanged = false; m_brain = createBrain(); @@ -424,12 +424,12 @@ public ItemStack getStackInSlot( int slot ) @Override public ItemStack removeStackFromSlot( int slot ) { - synchronized( m_inventory ) - { - ItemStack result = getStackInSlot( slot ); - setInventorySlotContents( slot, null ); - return result; - } + synchronized( m_inventory ) + { + ItemStack result = getStackInSlot( slot ); + setInventorySlotContents( slot, null ); + return result; + } } @Override @@ -440,29 +440,29 @@ public ItemStack decrStackSize( int slot, int count ) return null; } - synchronized( m_inventory ) - { + synchronized( m_inventory ) + { ItemStack stack = getStackInSlot( slot ); - if( stack == null ) - { - return null; - } - - if( stack.stackSize <= count ) - { - setInventorySlotContents( slot, null ); - return stack; - } - - ItemStack part = stack.splitStack( count ); + if( stack == null ) + { + return null; + } + + if( stack.stackSize <= count ) + { + setInventorySlotContents( slot, null ); + return stack; + } + + ItemStack part = stack.splitStack( count ); onInventoryDefinitelyChanged(); - return part; - } + return part; + } } @Override - public void setInventorySlotContents( int i, ItemStack stack ) - { + public void setInventorySlotContents( int i, ItemStack stack ) + { if( i >= 0 && i < INVENTORY_SIZE ) { synchronized( m_inventory ) @@ -474,7 +474,7 @@ public void setInventorySlotContents( int i, ItemStack stack ) } } } - } + } @Override public void clear() @@ -496,7 +496,7 @@ public void clear() } } } - + @Override public String getName() { @@ -547,24 +547,24 @@ public int getInventoryStackLimit() } @Override - public void openInventory( EntityPlayer player ) + public void openInventory( EntityPlayer player ) { } - + @Override - public void closeInventory( EntityPlayer player ) - { - } + public void closeInventory( EntityPlayer player ) + { + } - @Override - public boolean isItemValidForSlot( int slot, ItemStack stack ) - { - return true; - } - - @Override - public void markDirty() - { + @Override + public boolean isItemValidForSlot( int slot, ItemStack stack ) + { + return true; + } + + @Override + public void markDirty() + { super.markDirty(); synchronized( m_inventory ) { @@ -580,7 +580,7 @@ public void markDirty() } } } - } + } @Override public boolean isUseableByPlayer( EntityPlayer player ) @@ -645,8 +645,8 @@ private boolean hasPeripheralUpgradeOnSide( int side ) ITurtleUpgrade upgrade; switch( side ) { - case 4: upgrade = getUpgrade( TurtleSide.Right ); break; - case 5: upgrade = getUpgrade( TurtleSide.Left ); break; + case 4: upgrade = getUpgrade( TurtleSide.Right ); break; + case 5: upgrade = getUpgrade( TurtleSide.Left ); break; default: return false; } if( upgrade != null && upgrade.getType() == TurtleUpgradeType.Peripheral ) diff --git a/src/main/java/dan200/computercraft/shared/turtle/blocks/TileTurtleAdvanced.java b/src/main/java/dan200/computercraft/shared/turtle/blocks/TileTurtleAdvanced.java index 6a87de418..9332a2521 100644 --- a/src/main/java/dan200/computercraft/shared/turtle/blocks/TileTurtleAdvanced.java +++ b/src/main/java/dan200/computercraft/shared/turtle/blocks/TileTurtleAdvanced.java @@ -8,7 +8,7 @@ public class TileTurtleAdvanced extends TileTurtle { - public TileTurtleAdvanced() - { - } + public TileTurtleAdvanced() + { + } } diff --git a/src/main/java/dan200/computercraft/shared/turtle/blocks/TileTurtleExpanded.java b/src/main/java/dan200/computercraft/shared/turtle/blocks/TileTurtleExpanded.java index 5d307b6b0..8218bffe0 100644 --- a/src/main/java/dan200/computercraft/shared/turtle/blocks/TileTurtleExpanded.java +++ b/src/main/java/dan200/computercraft/shared/turtle/blocks/TileTurtleExpanded.java @@ -8,7 +8,7 @@ public class TileTurtleExpanded extends TileTurtle { - public TileTurtleExpanded() - { - } + public TileTurtleExpanded() + { + } } diff --git a/src/main/java/dan200/computercraft/shared/turtle/core/TurtlePlayer.java b/src/main/java/dan200/computercraft/shared/turtle/core/TurtlePlayer.java index 4911c5388..87e3b1b16 100644 --- a/src/main/java/dan200/computercraft/shared/turtle/core/TurtlePlayer.java +++ b/src/main/java/dan200/computercraft/shared/turtle/core/TurtlePlayer.java @@ -27,43 +27,43 @@ public class TurtlePlayer extends FakePlayer "ComputerCraft" ); - public TurtlePlayer( WorldServer world ) - { - super( world, s_profile ); - } + public TurtlePlayer( WorldServer world ) + { + super( world, s_profile ); + } - public void loadInventory( ItemStack currentStack ) - { - // Load up the fake inventory - inventory.currentItem = 0; - inventory.setInventorySlotContents( 0, currentStack ); - } + public void loadInventory( ItemStack currentStack ) + { + // Load up the fake inventory + inventory.currentItem = 0; + inventory.setInventorySlotContents( 0, currentStack ); + } - public ItemStack unloadInventory( ITurtleAccess turtle ) - { - // Get the item we placed with - ItemStack results = inventory.getStackInSlot( 0 ); - inventory.setInventorySlotContents( 0, null ); + public ItemStack unloadInventory( ITurtleAccess turtle ) + { + // Get the item we placed with + ItemStack results = inventory.getStackInSlot( 0 ); + inventory.setInventorySlotContents( 0, null ); - // Store (or drop) anything else we found + // Store (or drop) anything else we found BlockPos dropPosition = turtle.getPosition(); EnumFacing dropDirection = turtle.getDirection().getOpposite(); - for( int i=0; i= 0 ) { @@ -43,9 +43,9 @@ public ItemStack create( int id, String label, Colour colour, ITurtleUpgrade lef { nbt.setString( "leftUpgrade", leftUpgrade.getUpgradeID().toString() ); } - } - if( rightUpgrade != null ) - { + } + if( rightUpgrade != null ) + { int rightUpgradeLegacyID = rightUpgrade.getLegacyUpgradeID(); if( rightUpgradeLegacyID >= 0 ) { @@ -55,15 +55,15 @@ public ItemStack create( int id, String label, Colour colour, ITurtleUpgrade lef { nbt.setString( "rightUpgrade", rightUpgrade.getUpgradeID().toString() ); } - } - if( id >= 0 ) - { - nbt.setInteger( "computerID", id ); - } - if( fuelLevel > 0 ) - { - nbt.setInteger( "fuelLevel", fuelLevel ); - } + } + if( id >= 0 ) + { + nbt.setInteger( "computerID", id ); + } + if( fuelLevel > 0 ) + { + nbt.setInteger( "fuelLevel", fuelLevel ); + } if( colour != null ) { nbt.setInteger( "colourIndex", colour.ordinal() ); @@ -73,15 +73,15 @@ public ItemStack create( int id, String label, Colour colour, ITurtleUpgrade lef nbt.setString( "overlay_mod", overlay.getResourceDomain() ); nbt.setString( "overlay_path", overlay.getResourcePath() ); } - stack.setTagCompound( nbt ); + stack.setTagCompound( nbt ); // Return the stack if( label != null ) { stack.setStackDisplayName( label ); } - return stack; - } + return stack; + } // IComputerItem implementation @@ -96,8 +96,8 @@ public int getComputerID( ItemStack stack ) return nbt.getInteger( "computerID" ); } } - return -1; - } + return -1; + } @Override public ComputerFamily getFamily( int damage ) diff --git a/src/main/java/dan200/computercraft/shared/turtle/recipes/TurtleRecipe.java b/src/main/java/dan200/computercraft/shared/turtle/recipes/TurtleRecipe.java index 91cb97066..dc306d14e 100644 --- a/src/main/java/dan200/computercraft/shared/turtle/recipes/TurtleRecipe.java +++ b/src/main/java/dan200/computercraft/shared/turtle/recipes/TurtleRecipe.java @@ -17,48 +17,48 @@ public class TurtleRecipe implements IRecipe { - private final Item[] m_recipe; - private final ComputerFamily m_family; - + private final Item[] m_recipe; + private final ComputerFamily m_family; + public TurtleRecipe( Item[] recipe, ComputerFamily family ) { - m_recipe = recipe; + m_recipe = recipe; m_family = family; } - @Override - public int getRecipeSize() - { - return 9; - } - - @Override + @Override + public int getRecipeSize() + { + return 9; + } + + @Override public ItemStack getRecipeOutput() { return TurtleItemFactory.create( -1, null, null, m_family, null, null, 0, null ); } - @Override + @Override public boolean matches( InventoryCrafting _inventory, World world ) { - return (getCraftingResult( _inventory ) != null); + return (getCraftingResult( _inventory ) != null); } - @Override + @Override public ItemStack getCraftingResult( InventoryCrafting inventory ) { - // See if we match the recipe, and extract the input computercraft ID - int computerID = -1; + // See if we match the recipe, and extract the input computercraft ID + int computerID = -1; String label = null; - for( int y=0; y<3; ++y ) - { - for( int x=0; x<3; ++x ) - { - ItemStack item = inventory.getStackInRowAndColumn(x, y); - if( item != null && item.getItem() == m_recipe[ x + y*3 ] ) - { - if( item.getItem() instanceof IComputerItem ) - { + for( int y=0; y<3; ++y ) + { + for( int x=0; x<3; ++x ) + { + ItemStack item = inventory.getStackInRowAndColumn(x, y); + if( item != null && item.getItem() == m_recipe[ x + y*3 ] ) + { + if( item.getItem() instanceof IComputerItem ) + { IComputerItem itemComputer = (IComputerItem)item.getItem(); if( m_family == ComputerFamily.Beginners || itemComputer.getFamily( item ) == m_family ) { @@ -69,17 +69,17 @@ public ItemStack getCraftingResult( InventoryCrafting inventory ) { return null; } - } - } - else - { - return null; - } - } - } - - // Build a turtle with the same ID the computer had - // Construct the new stack + } + } + else + { + return null; + } + } + } + + // Build a turtle with the same ID the computer had + // Construct the new stack if( m_family != ComputerFamily.Beginners ) { return TurtleItemFactory.create( computerID, label, null, m_family, null, null, 0, null ); diff --git a/src/main/java/dan200/computercraft/shared/turtle/recipes/TurtleUpgradeRecipe.java b/src/main/java/dan200/computercraft/shared/turtle/recipes/TurtleUpgradeRecipe.java index fb7eb4271..13a9b758d 100644 --- a/src/main/java/dan200/computercraft/shared/turtle/recipes/TurtleUpgradeRecipe.java +++ b/src/main/java/dan200/computercraft/shared/turtle/recipes/TurtleUpgradeRecipe.java @@ -26,116 +26,116 @@ public TurtleUpgradeRecipe() { } - @Override - public int getRecipeSize() - { - return 3; - } - - @Override + @Override + public int getRecipeSize() + { + return 3; + } + + @Override public ItemStack getRecipeOutput() { return TurtleItemFactory.create( -1, null, null, ComputerFamily.Normal, null, null, 0, null ); } - @Override + @Override public boolean matches( InventoryCrafting inventory, World world ) { - return (getCraftingResult( inventory ) != null); + return (getCraftingResult( inventory ) != null); } - @Override + @Override public ItemStack getCraftingResult( InventoryCrafting inventory ) { - // Scan the grid for a row containing a turtle and 1 or 2 items - ItemStack leftItem = null; - ItemStack turtle = null; - ItemStack rightItem = null; + // Scan the grid for a row containing a turtle and 1 or 2 items + ItemStack leftItem = null; + ItemStack turtle = null; + ItemStack rightItem = null; - for( int y=0; y 64 ) - { - throw new LuaException( "Crafting count " + count + " out of range" ); - } - return count; + if( arguments.length < 1 ) + { + return 64; + } + + if( !(arguments[0] instanceof Number) ) + { + throw new LuaException( "Expected number" ); + } + int count = ((Number)arguments[0]).intValue(); + if( count < 0 || count > 64 ) + { + throw new LuaException( "Crafting count " + count + " out of range" ); + } + return count; } - @Override + @Override public Object[] callMethod( IComputerAccess computer, ILuaContext context, int method, Object[] arguments ) throws LuaException, InterruptedException { - switch( method ) - { - case 0: - { - // craft - final int limit = parseCount( arguments ); - return m_turtle.executeCommand( context, new TurtleCraftCommand( limit ) ); - } - default: - { - return null; - } - } + switch( method ) + { + case 0: + { + // craft + final int limit = parseCount( arguments ); + return m_turtle.executeCommand( context, new TurtleCraftCommand( limit ) ); + } + default: + { + return null; + } + } } - @Override + @Override public void attach( IComputerAccess computer ) { } - @Override + @Override public void detach( IComputerAccess computer ) { } diff --git a/src/main/java/dan200/computercraft/shared/turtle/upgrades/TurtleAxe.java b/src/main/java/dan200/computercraft/shared/turtle/upgrades/TurtleAxe.java index b43cf48c8..e9be49357 100644 --- a/src/main/java/dan200/computercraft/shared/turtle/upgrades/TurtleAxe.java +++ b/src/main/java/dan200/computercraft/shared/turtle/upgrades/TurtleAxe.java @@ -17,8 +17,8 @@ public TurtleAxe( ResourceLocation id, int legacyId, String adjective, Item item } @Override - protected float getDamageMultiplier() - { - return 6.0f; - } + protected float getDamageMultiplier() + { + return 6.0f; + } } diff --git a/src/main/java/dan200/computercraft/shared/turtle/upgrades/TurtleCraftingTable.java b/src/main/java/dan200/computercraft/shared/turtle/upgrades/TurtleCraftingTable.java index 68162e61d..5533a8356 100644 --- a/src/main/java/dan200/computercraft/shared/turtle/upgrades/TurtleCraftingTable.java +++ b/src/main/java/dan200/computercraft/shared/turtle/upgrades/TurtleCraftingTable.java @@ -53,35 +53,35 @@ public int getLegacyUpgradeID() return m_legacyID; } - @Override - public String getUnlocalisedAdjective() - { - return "upgrade.minecraft:crafting_table.adjective"; - } - - @Override - public TurtleUpgradeType getType() - { - return TurtleUpgradeType.Peripheral; - } - - @Override - public ItemStack getCraftingItem() - { - return m_item; - } + @Override + public String getUnlocalisedAdjective() + { + return "upgrade.minecraft:crafting_table.adjective"; + } + + @Override + public TurtleUpgradeType getType() + { + return TurtleUpgradeType.Peripheral; + } + + @Override + public ItemStack getCraftingItem() + { + return m_item; + } - @Override - public IPeripheral createPeripheral( ITurtleAccess turtle, TurtleSide side ) - { - return new CraftingTablePeripheral( turtle ); - } + @Override + public IPeripheral createPeripheral( ITurtleAccess turtle, TurtleSide side ) + { + return new CraftingTablePeripheral( turtle ); + } - @Override - public TurtleCommandResult useTool( ITurtleAccess turtle, TurtleSide side, TurtleVerb verb, EnumFacing dir ) - { - return null; - } + @Override + public TurtleCommandResult useTool( ITurtleAccess turtle, TurtleSide side, TurtleVerb verb, EnumFacing dir ) + { + return null; + } @SideOnly( Side.CLIENT ) private void loadModelLocations() diff --git a/src/main/java/dan200/computercraft/shared/turtle/upgrades/TurtleHoe.java b/src/main/java/dan200/computercraft/shared/turtle/upgrades/TurtleHoe.java index 4cac1ca19..ab3b523d9 100644 --- a/src/main/java/dan200/computercraft/shared/turtle/upgrades/TurtleHoe.java +++ b/src/main/java/dan200/computercraft/shared/turtle/upgrades/TurtleHoe.java @@ -29,27 +29,27 @@ public TurtleHoe( ResourceLocation id, int legacyId, String adjective, Item item } @Override - protected boolean canBreakBlock( World world, BlockPos pos ) - { - if( super.canBreakBlock( world, pos ) ) - { + protected boolean canBreakBlock( World world, BlockPos pos ) + { + if( super.canBreakBlock( world, pos ) ) + { IBlockState state = world.getBlockState( pos ); - Block block = state.getBlock(); + Block block = state.getBlock(); Material material = block.getMaterial( state ); - return + return material == Material.PLANTS || material == Material.CACTUS || material == Material.GOURD || material == Material.LEAVES || material == Material.VINE; - } - return false; - } + } + return false; + } @Override - public TurtleCommandResult useTool( ITurtleAccess turtle, TurtleSide side, TurtleVerb verb, EnumFacing direction ) - { - if( verb == TurtleVerb.Dig ) + public TurtleCommandResult useTool( ITurtleAccess turtle, TurtleSide side, TurtleVerb verb, EnumFacing direction ) + { + if( verb == TurtleVerb.Dig ) { ItemStack hoe = m_item.copy(); ItemStack remainder = TurtlePlaceCommand.deploy( hoe, turtle, direction, null, null ); @@ -57,7 +57,7 @@ public TurtleCommandResult useTool( ITurtleAccess turtle, TurtleSide side, Turtl { return TurtleCommandResult.success(); } - } - return super.useTool( turtle, side, verb, direction ); - } + } + return super.useTool( turtle, side, verb, direction ); + } } diff --git a/src/main/java/dan200/computercraft/shared/turtle/upgrades/TurtleInventoryCrafting.java b/src/main/java/dan200/computercraft/shared/turtle/upgrades/TurtleInventoryCrafting.java index 8fd317cb3..3d1191a17 100644 --- a/src/main/java/dan200/computercraft/shared/turtle/upgrades/TurtleInventoryCrafting.java +++ b/src/main/java/dan200/computercraft/shared/turtle/upgrades/TurtleInventoryCrafting.java @@ -22,14 +22,14 @@ public class TurtleInventoryCrafting extends InventoryCrafting { - private ITurtleAccess m_turtle; + private ITurtleAccess m_turtle; private int m_xStart; private int m_yStart; public TurtleInventoryCrafting( ITurtleAccess turtle ) { - super( null, 0, 0 ); - m_turtle = turtle; + super( null, 0, 0 ); + m_turtle = turtle; m_xStart = 0; m_yStart = 0; } @@ -56,7 +56,7 @@ private ItemStack tryCrafting( int xStart, int yStart ) } // Check the actual crafting - return CraftingManager.getInstance().findMatchingRecipe( this, m_turtle.getWorld() ); + return CraftingManager.getInstance().findMatchingRecipe( this, m_turtle.getWorld() ); } public ArrayList doCrafting( World world, int maxCount ) @@ -66,8 +66,8 @@ public ArrayList doCrafting( World world, int maxCount ) return null; } - // Find out what we can craft - ItemStack result = tryCrafting( 0, 0 ); + // Find out what we can craft + ItemStack result = tryCrafting( 0, 0 ); if( result == null ) { result = tryCrafting( 0, 1 ); @@ -82,53 +82,53 @@ public ArrayList doCrafting( World world, int maxCount ) } // Craft it - if( result != null ) - { - // Special case: craft(0) just returns an empty list if crafting was possible + if( result != null ) + { + // Special case: craft(0) just returns an empty list if crafting was possible ArrayList results = new ArrayList(); - if( maxCount == 0 ) - { - return results; - } - - // Find out how many we can craft - int numToCraft = 1; - int size = getSizeInventory(); - if( maxCount > 1 ) - { - int minStackSize = 0; - for( int n=0; n stack.stackSize) ) - { - minStackSize = stack.stackSize; - } - } - - if( minStackSize > 1 ) - { - numToCraft = Math.min( minStackSize, result.getMaxStackSize() / result.stackSize ); - numToCraft = Math.min( numToCraft, maxCount ); - result.stackSize = result.stackSize * numToCraft; - } - } + if( maxCount == 0 ) + { + return results; + } + + // Find out how many we can craft + int numToCraft = 1; + int size = getSizeInventory(); + if( maxCount > 1 ) + { + int minStackSize = 0; + for( int n=0; n stack.stackSize) ) + { + minStackSize = stack.stackSize; + } + } + + if( minStackSize > 1 ) + { + numToCraft = Math.min( minStackSize, result.getMaxStackSize() / result.stackSize ); + numToCraft = Math.min( numToCraft, maxCount ); + result.stackSize = result.stackSize * numToCraft; + } + } // Do post-pickup stuff - TurtlePlayer turtlePlayer = new TurtlePlayer( (WorldServer)world ); + TurtlePlayer turtlePlayer = new TurtlePlayer( (WorldServer)world ); result.onCrafting( world, turtlePlayer, numToCraft ); results.add( result ); - // Consume resources from the inventory + // Consume resources from the inventory ItemStack[] remainingItems = CraftingManager.getInstance().getRemainingItems( this, world ); - for( int n=0; n= replacement.getMaxDamage()) ) @@ -144,20 +144,20 @@ public ArrayList doCrafting( World world, int maxCount ) } } } - } - } + } + } return results; - } - - return null; + } + + return null; } - @Override + @Override public ItemStack getStackInRowAndColumn(int x, int y) { if (x >= 0 && x < getWidth() && y >= 0 && y < getHeight() ) { - return getStackInSlot( x + y * getWidth() ); + return getStackInSlot( x + y * getWidth() ); } return null; } @@ -187,18 +187,18 @@ private int modifyIndex( int index ) } // IInventory implementation - - @Override + + @Override public int getSizeInventory() { return getWidth() * getHeight(); } - @Override + @Override public ItemStack getStackInSlot( int i ) { i = modifyIndex( i ); - return m_turtle.getInventory().getStackInSlot( i ); + return m_turtle.getInventory().getStackInSlot( i ); } @Override @@ -213,52 +213,52 @@ public boolean hasCustomName() return false; } - @Override + @Override public ITextComponent getDisplayName() { return new TextComponentString( "" ); } - @Override + @Override public ItemStack removeStackFromSlot( int i ) { i = modifyIndex( i ); - return m_turtle.getInventory().removeStackFromSlot( i ); + return m_turtle.getInventory().removeStackFromSlot( i ); } - @Override + @Override public ItemStack decrStackSize( int i, int size ) { i = modifyIndex( i ); return m_turtle.getInventory().decrStackSize( i, size ); } - @Override + @Override public void setInventorySlotContents( int i, ItemStack stack ) { i = modifyIndex( i ); m_turtle.getInventory().setInventorySlotContents( i, stack ); } - @Override + @Override public int getInventoryStackLimit() { return m_turtle.getInventory().getInventoryStackLimit(); } - @Override + @Override public void markDirty() { m_turtle.getInventory().markDirty(); } - @Override + @Override public boolean isUseableByPlayer( EntityPlayer player ) { return true; } - @Override + @Override public void openInventory( EntityPlayer player ) { } diff --git a/src/main/java/dan200/computercraft/shared/turtle/upgrades/TurtleModem.java b/src/main/java/dan200/computercraft/shared/turtle/upgrades/TurtleModem.java index 61e4fedc4..776080031 100644 --- a/src/main/java/dan200/computercraft/shared/turtle/upgrades/TurtleModem.java +++ b/src/main/java/dan200/computercraft/shared/turtle/upgrades/TurtleModem.java @@ -30,33 +30,33 @@ public class TurtleModem implements ITurtleUpgrade { - private static class Peripheral extends WirelessModemPeripheral - implements IPeripheral - { - private final ITurtleAccess m_turtle; + private static class Peripheral extends WirelessModemPeripheral + implements IPeripheral + { + private final ITurtleAccess m_turtle; - public Peripheral( ITurtleAccess turtle, boolean advanced ) - { + public Peripheral( ITurtleAccess turtle, boolean advanced ) + { super( advanced ); - m_turtle = turtle; - } + m_turtle = turtle; + } @Override - protected World getWorld() - { - return m_turtle.getWorld(); - } + protected World getWorld() + { + return m_turtle.getWorld(); + } @Override - protected Vec3d getPosition() - { + protected Vec3d getPosition() + { BlockPos turtlePos = m_turtle.getPosition(); return new Vec3d( (double)turtlePos.getX(), (double)turtlePos.getY(), (double)turtlePos.getZ() ); - } + } @Override public boolean equals( IPeripheral other ) @@ -71,7 +71,7 @@ public boolean equals( IPeripheral other ) } private boolean m_advanced; - private ResourceLocation m_id; + private ResourceLocation m_id; private int m_legacyID; @SideOnly( Side.CLIENT ) @@ -87,11 +87,11 @@ public boolean equals( IPeripheral other ) private ModelResourceLocation m_rightOnModel; public TurtleModem( boolean advanced, ResourceLocation id, int legacyId ) - { + { m_advanced = advanced; m_id = id; - m_legacyID = legacyId; - } + m_legacyID = legacyId; + } @Override public ResourceLocation getUpgradeID() @@ -99,15 +99,15 @@ public ResourceLocation getUpgradeID() return m_id; } - @Override - public int getLegacyUpgradeID() - { - return m_legacyID; - } - - @Override - public String getUnlocalisedAdjective() - { + @Override + public int getLegacyUpgradeID() + { + return m_legacyID; + } + + @Override + public String getUnlocalisedAdjective() + { if( m_advanced ) { return "upgrade.computercraft:advanced_modem.adjective"; @@ -116,17 +116,17 @@ public String getUnlocalisedAdjective() { return "upgrade.computercraft:wireless_modem.adjective"; } - } - - @Override - public TurtleUpgradeType getType() - { - return TurtleUpgradeType.Peripheral; - } - - @Override - public ItemStack getCraftingItem() - { + } + + @Override + public TurtleUpgradeType getType() + { + return TurtleUpgradeType.Peripheral; + } + + @Override + public ItemStack getCraftingItem() + { if( m_advanced ) { return PeripheralItemFactory.create( PeripheralType.AdvancedModem, null, 1 ); @@ -135,19 +135,19 @@ public ItemStack getCraftingItem() { return PeripheralItemFactory.create( PeripheralType.WirelessModem, null, 1 ); } - } + } - @Override - public IPeripheral createPeripheral( ITurtleAccess turtle, TurtleSide side ) - { - return new Peripheral( turtle, m_advanced ); - } + @Override + public IPeripheral createPeripheral( ITurtleAccess turtle, TurtleSide side ) + { + return new Peripheral( turtle, m_advanced ); + } - @Override - public TurtleCommandResult useTool( ITurtleAccess turtle, TurtleSide side, TurtleVerb verb, EnumFacing dir ) - { - return null; - } + @Override + public TurtleCommandResult useTool( ITurtleAccess turtle, TurtleSide side, TurtleVerb verb, EnumFacing dir ) + { + return null; + } @SideOnly( Side.CLIENT ) private void loadModelLocations() diff --git a/src/main/java/dan200/computercraft/shared/turtle/upgrades/TurtleShovel.java b/src/main/java/dan200/computercraft/shared/turtle/upgrades/TurtleShovel.java index 76f128022..067ae062d 100644 --- a/src/main/java/dan200/computercraft/shared/turtle/upgrades/TurtleShovel.java +++ b/src/main/java/dan200/computercraft/shared/turtle/upgrades/TurtleShovel.java @@ -21,14 +21,14 @@ public TurtleShovel( ResourceLocation id, int legacyId, String adjective, Item i } @Override - protected boolean canBreakBlock( World world, BlockPos pos ) - { - if( super.canBreakBlock( world, pos ) ) - { + protected boolean canBreakBlock( World world, BlockPos pos ) + { + if( super.canBreakBlock( world, pos ) ) + { IBlockState state = world.getBlockState( pos ); - Block block = state.getBlock(); + Block block = state.getBlock(); Material material = block.getMaterial( state ); - return + return material == Material.GROUND || material == Material.SAND || material == Material.SNOW || @@ -40,7 +40,7 @@ protected boolean canBreakBlock( World world, BlockPos pos ) material == Material.GOURD || material == Material.LEAVES || material == Material.VINE; - } - return false; - } + } + return false; + } } diff --git a/src/main/java/dan200/computercraft/shared/turtle/upgrades/TurtleSword.java b/src/main/java/dan200/computercraft/shared/turtle/upgrades/TurtleSword.java index c8501ad3b..ef10e099e 100644 --- a/src/main/java/dan200/computercraft/shared/turtle/upgrades/TurtleSword.java +++ b/src/main/java/dan200/computercraft/shared/turtle/upgrades/TurtleSword.java @@ -15,32 +15,32 @@ public class TurtleSword extends TurtleTool { - public TurtleSword( ResourceLocation id, int legacyId, String adjective, Item item ) - { - super( id, legacyId, adjective, item ); - } + public TurtleSword( ResourceLocation id, int legacyId, String adjective, Item item ) + { + super( id, legacyId, adjective, item ); + } @Override - protected boolean canBreakBlock( World world, BlockPos pos ) - { - if( super.canBreakBlock( world, pos ) ) - { + protected boolean canBreakBlock( World world, BlockPos pos ) + { + if( super.canBreakBlock( world, pos ) ) + { IBlockState state = world.getBlockState( pos ); - Block block = state.getBlock(); + Block block = state.getBlock(); Material material = block.getMaterial( state ); - return + return material == Material.PLANTS || material == Material.LEAVES || material == Material.VINE || material == Material.CLOTH || material == Material.WEB; - } - return false; - } + } + return false; + } @Override - protected float getDamageMultiplier() - { - return 9.0f; - } + protected float getDamageMultiplier() + { + return 9.0f; + } } diff --git a/src/main/java/dan200/computercraft/shared/turtle/upgrades/TurtleTool.java b/src/main/java/dan200/computercraft/shared/turtle/upgrades/TurtleTool.java index 9fcda47df..90f8a835d 100644 --- a/src/main/java/dan200/computercraft/shared/turtle/upgrades/TurtleTool.java +++ b/src/main/java/dan200/computercraft/shared/turtle/upgrades/TurtleTool.java @@ -41,17 +41,17 @@ public class TurtleTool implements ITurtleUpgrade { private ResourceLocation m_id; - private int m_legacyId; - private String m_adjective; - protected ItemStack m_item; + private int m_legacyId; + private String m_adjective; + protected ItemStack m_item; - public TurtleTool( ResourceLocation id, int legacyID, String adjective, Item item ) - { - m_id = id; + public TurtleTool( ResourceLocation id, int legacyID, String adjective, Item item ) + { + m_id = id; m_legacyId = legacyID; - m_adjective = adjective; - m_item = new ItemStack( item, 1, 0 ); - } + m_adjective = adjective; + m_item = new ItemStack( item, 1, 0 ); + } @Override public ResourceLocation getUpgradeID() @@ -60,34 +60,34 @@ public ResourceLocation getUpgradeID() } @Override - public int getLegacyUpgradeID() - { - return m_legacyId; - } + public int getLegacyUpgradeID() + { + return m_legacyId; + } @Override - public String getUnlocalisedAdjective() - { - return m_adjective; - } + public String getUnlocalisedAdjective() + { + return m_adjective; + } @Override - public TurtleUpgradeType getType() - { - return TurtleUpgradeType.Tool; - } + public TurtleUpgradeType getType() + { + return TurtleUpgradeType.Tool; + } @Override - public ItemStack getCraftingItem() - { - return m_item.copy(); - } + public ItemStack getCraftingItem() + { + return m_item.copy(); + } @Override - public IPeripheral createPeripheral( ITurtleAccess turtle, TurtleSide side ) - { - return null; - } + public IPeripheral createPeripheral( ITurtleAccess turtle, TurtleSide side ) + { + return null; + } @Override @SideOnly( Side.CLIENT ) @@ -133,31 +133,31 @@ public TurtleCommandResult useTool( ITurtleAccess turtle, TurtleSide side, Turtl } protected boolean canBreakBlock( World world, BlockPos pos ) - { + { IBlockState state = world.getBlockState( pos ); - Block block = state.getBlock(); - if( block.isAir( state, world, pos ) || block == Blocks.BEDROCK || block.getBlockHardness( state, world, pos ) <= -1.0F ) - { - return false; - } - return true; - } - - protected boolean canHarvestBlock( World world, BlockPos pos ) - { + Block block = state.getBlock(); + if( block.isAir( state, world, pos ) || block == Blocks.BEDROCK || block.getBlockHardness( state, world, pos ) <= -1.0F ) + { + return false; + } + return true; + } + + protected boolean canHarvestBlock( World world, BlockPos pos ) + { Block block = world.getBlockState( pos ).getBlock(); - TurtlePlayer turtlePlayer = new TurtlePlayer( (WorldServer)world ); - turtlePlayer.loadInventory( m_item.copy() ); - return ForgeHooks.canHarvestBlock( block, turtlePlayer, world, pos ); - } - - protected float getDamageMultiplier() - { - return 3.0f; - } - - private TurtleCommandResult attack( final ITurtleAccess turtle, EnumFacing direction ) - { + TurtlePlayer turtlePlayer = new TurtlePlayer( (WorldServer)world ); + turtlePlayer.loadInventory( m_item.copy() ); + return ForgeHooks.canHarvestBlock( block, turtlePlayer, world, pos ); + } + + protected float getDamageMultiplier() + { + return 3.0f; + } + + private TurtleCommandResult attack( final ITurtleAccess turtle, EnumFacing direction ) + { // Create a fake player, and orient it appropriately final World world = turtle.getWorld(); final BlockPos position = turtle.getPosition(); @@ -230,13 +230,13 @@ public void consumeDrop( Entity entity, ItemStack drop ) } return TurtleCommandResult.failure( "Nothing to attack here" ); - } - - private TurtleCommandResult dig( ITurtleAccess turtle, EnumFacing direction ) - { + } + + private TurtleCommandResult dig( ITurtleAccess turtle, EnumFacing direction ) + { // Get ready to dig - World world = turtle.getWorld(); - BlockPos position = turtle.getPosition(); + World world = turtle.getWorld(); + BlockPos position = turtle.getPosition(); BlockPos newPosition = WorldUtil.moveCoords( position, direction ); if( WorldUtil.isBlockInWorld( world, newPosition ) && @@ -292,15 +292,15 @@ private TurtleCommandResult dig( ITurtleAccess turtle, EnumFacing direction ) brain.saveBlockChange( newPosition, previousState ); } - return TurtleCommandResult.success(); + return TurtleCommandResult.success(); } return TurtleCommandResult.failure( "Nothing to dig here" ); - } + } - private java.util.List getBlockDropped( World world, BlockPos pos ) + private java.util.List getBlockDropped( World world, BlockPos pos ) { - Block block = world.getBlockState( pos ).getBlock(); - return block.getDrops( world, pos, world.getBlockState( pos ), 0 ); + Block block = world.getBlockState( pos ).getBlock(); + return block.getDrops( world, pos, world.getBlockState( pos ), 0 ); } } diff --git a/src/main/java/dan200/computercraft/shared/util/CreativeTabMain.java b/src/main/java/dan200/computercraft/shared/util/CreativeTabMain.java index 8d990d72f..b9e7a914e 100644 --- a/src/main/java/dan200/computercraft/shared/util/CreativeTabMain.java +++ b/src/main/java/dan200/computercraft/shared/util/CreativeTabMain.java @@ -26,6 +26,6 @@ public Item getTabIconItem() @Override public String getTranslatedTabLabel() { - return getTabLabel(); + return getTabLabel(); } } diff --git a/src/main/java/dan200/computercraft/shared/util/CreativeTabTreasure.java b/src/main/java/dan200/computercraft/shared/util/CreativeTabTreasure.java index 57e06fb6c..74a7ac770 100644 --- a/src/main/java/dan200/computercraft/shared/util/CreativeTabTreasure.java +++ b/src/main/java/dan200/computercraft/shared/util/CreativeTabTreasure.java @@ -26,6 +26,6 @@ public Item getTabIconItem() @Override public String getTranslatedTabLabel() { - return getTabLabel(); + return getTabLabel(); } } diff --git a/src/main/java/dan200/computercraft/shared/util/IDAssigner.java b/src/main/java/dan200/computercraft/shared/util/IDAssigner.java index 7812f753a..15d665bfe 100644 --- a/src/main/java/dan200/computercraft/shared/util/IDAssigner.java +++ b/src/main/java/dan200/computercraft/shared/util/IDAssigner.java @@ -4,61 +4,61 @@ public class IDAssigner { - private IDAssigner() - { - } - - public static int getNextIDFromDirectory( File dir ) - { - return getNextID( dir, true ); - } - - public static int getNextIDFromFile( File file ) - { - return getNextID( file, false ); - } - - private static int getNextID( File location, boolean directory ) - { - // Determine where to locate ID file - File lastidFile = null; - if( directory ) - { - location.mkdirs(); - lastidFile = new File( location, "lastid.txt" ); - } - else - { - location.getParentFile().mkdirs(); - lastidFile = location; - } - - // Try to determine the id - int id = 0; - if( !lastidFile.exists() ) - { - // If an ID file doesn't exist, determine it from the file structure - if( directory && location.exists() && location.isDirectory() ) - { - String[] contents = location.list(); - for( int i=0; i= remainder.stackSize ) - { + for( int n=0; n= remainder.stackSize ) + { // Items fit completely in slot - inventory.setInventorySlotContents( slot, remainder ); - inventory.markDirty(); - return null; - } - else + inventory.setInventorySlotContents( slot, remainder ); + inventory.markDirty(); + return null; + } + else { // Items fit partially in slot remainder = remainder.copy(); - inventory.setInventorySlotContents( slot, remainder.splitStack( space ) ); + inventory.setInventorySlotContents( slot, remainder.splitStack( space ) ); } - } - else if( areItemsStackable( slotContents, remainder ) ) - { - // Slot is occupied, but matching - int space = Math.min( slotContents.getMaxStackSize(), inventory.getInventoryStackLimit() ) - slotContents.stackSize; - if( space >= remainder.stackSize ) - { + } + else if( areItemsStackable( slotContents, remainder ) ) + { + // Slot is occupied, but matching + int space = Math.min( slotContents.getMaxStackSize(), inventory.getInventoryStackLimit() ) - slotContents.stackSize; + if( space >= remainder.stackSize ) + { // Items fit completely in slot - slotContents.stackSize += remainder.stackSize; - inventory.setInventorySlotContents( slot, slotContents ); - inventory.markDirty(); - return null; - } - else if( space > 0 ) - { + slotContents.stackSize += remainder.stackSize; + inventory.setInventorySlotContents( slot, slotContents ); + inventory.markDirty(); + return null; + } + else if( space > 0 ) + { // Items fit partially in slot remainder = remainder.copy(); remainder.stackSize -= space; - slotContents.stackSize += space; - inventory.setInventorySlotContents( slot, slotContents ); - } - } - } - } + slotContents.stackSize += space; + inventory.setInventorySlotContents( slot, slotContents ); + } + } + } + } // If the output isn't the input, inform the change - if( remainder != stack ) - { - inventory.markDirty(); - } + if( remainder != stack ) + { + inventory.markDirty(); + } return remainder; } - private static boolean canPlaceItemThroughFace( IInventory inventory, int slot, ItemStack itemstack, EnumFacing face ) - { - if( inventory.isItemValidForSlot( slot, itemstack ) ) - { - if( face != null && inventory instanceof ISidedInventory ) - { - ISidedInventory sided = (ISidedInventory)inventory; - return sided.canInsertItem( slot, itemstack, face ); - } - return true; - } - return false; - } + private static boolean canPlaceItemThroughFace( IInventory inventory, int slot, ItemStack itemstack, EnumFacing face ) + { + if( inventory.isItemValidForSlot( slot, itemstack ) ) + { + if( face != null && inventory instanceof ISidedInventory ) + { + ISidedInventory sided = (ISidedInventory)inventory; + return sided.canInsertItem( slot, itemstack, face ); + } + return true; + } + return false; + } private static ItemStack takeItems( int count, IInventory inventory, int[] slots, EnumFacing face ) { - if( slots == null ) - { - return null; - } + if( slots == null ) + { + return null; + } - // Combine multiple stacks from inventory into one if necessary + // Combine multiple stacks from inventory into one if necessary ItemStack partialStack = null; int countRemaining = count; - for( int n=0; n 0 ) { - ItemStack stack = inventory.getStackInSlot( slot ); + ItemStack stack = inventory.getStackInSlot( slot ); if( stack != null && canTakeItemThroughFace( inventory, slot, stack, face ) ) { if( partialStack == null || areItemsStackable( stack, partialStack ) ) @@ -328,9 +328,9 @@ private static ItemStack takeItems( int count, IInventory inventory, int[] slots } } } - } - } - } + } + } + } // Return the final stack if( partialStack != null ) @@ -338,16 +338,16 @@ private static ItemStack takeItems( int count, IInventory inventory, int[] slots inventory.markDirty(); return partialStack; } - return null; - } + return null; + } - private static boolean canTakeItemThroughFace( IInventory inventory, int slot, ItemStack itemstack, EnumFacing face ) - { - if( face != null && inventory instanceof ISidedInventory ) - { - ISidedInventory sided = (ISidedInventory)inventory; - return sided.canExtractItem( slot, itemstack, face ); - } - return true; - } + private static boolean canTakeItemThroughFace( IInventory inventory, int slot, ItemStack itemstack, EnumFacing face ) + { + if( face != null && inventory instanceof ISidedInventory ) + { + ISidedInventory sided = (ISidedInventory)inventory; + return sided.canExtractItem( slot, itemstack, face ); + } + return true; + } }