Skip to content

Commit

Permalink
Merge branch 'master-MC1.7.10' of github.com:MightyPirates/OpenComput…
Browse files Browse the repository at this point in the history
…ers into OC1.6-MC1.7.10
  • Loading branch information
fnuecke committed Jun 25, 2016
2 parents 636396c + 9a3fd0f commit dfb8e17
Show file tree
Hide file tree
Showing 15 changed files with 120 additions and 49 deletions.
1 change: 1 addition & 0 deletions src/main/resources/assets/opencomputers/loot/network/.prop
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
{fromDir="/data/"}
Original file line number Diff line number Diff line change
Expand Up @@ -19,17 +19,11 @@ end
local exit_code = nil
options.P = options.P or options.r

-- interrupting is important, but not EVERY copy
local greedy = computer.uptime()

local function status(from, to)
if options.v then
io.write(from .. " -> " .. to .. "\n")
end
if computer.uptime() - greedy > 4 then
os.sleep(0) -- allow interrupting
greedy = computer.uptime()
end
os.sleep(0) -- allow interrupting
end

local result, reason
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@ do
options = basic(...)
end

if not options then return end

if computer.freeMemory() < 50000 then
print("Low memory, collecting garbage")
for i=1,20 do os.sleep(0) end
Expand All @@ -29,13 +31,16 @@ if options.setlabel then
end

if options.setboot then
computer.setBootAddress(options.target.dev.address)
local address = options.target.dev.address
if computer.setBootAddress(address) then
write("Boot address set to " .. address)
end
end

if options.reboot then
write("Reboot now? [Y/n] ")
local result = read()
if not result or result == "" or result:sub(1, 1):lower() == "y" then
local result = read() or "n"
if result:sub(1, 1):lower() == "y" then
write("\nRebooting now!\n")
computer.shutdown(true)
end
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -284,7 +284,7 @@ local function displayDirList(dirs)
end
end
end
local tr,cp={},{path=os.getenv("PWD")}
local tr,cp={},{path=shell.getWorkingDirectory()}
for _,dir in ipairs(dirsArg) do
local path = shell.resolve(dir)
if not fs.exists(path) then
Expand Down
14 changes: 7 additions & 7 deletions src/main/resources/assets/opencomputers/loot/openos/bin/rc.lua
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ local function load(name, args)
return nil, reason
end

function unload(name)
function rc.unload(name)
rc.loaded[name] = nil
end

Expand All @@ -60,15 +60,15 @@ local function rawRunCommand(conf, name, cmd, args, ...)
end
return true
elseif type(result[cmd]) == "function" then
res, what = xpcall(result[cmd], debug.traceback, ...)
if res then
result, what = xpcall(result[cmd], debug.traceback, ...)
if result then
return true
end
elseif cmd == "restart" and type(result["stop"]) == "function" and type(result["start"]) == "function" then
res, what = xpcall(result["stop"], debug.traceback, ...)
if res then
res, what = xpcall(result["start"], debug.traceback, ...)
if res then
result, what = xpcall(result["stop"], debug.traceback, ...)
if result then
result, what = xpcall(result["start"], debug.traceback, ...)
if result then
return true
end
end
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,7 @@ function buffer:read(...)
if computer.uptime() > timeout then
error("timeout")
end
local result, reason = self.stream:read(self.bufferSize)
local result, reason = self.stream:read(math.max(1,self.bufferSize))
if result then
self.bufferRead = self.bufferRead .. result
return self
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -61,15 +61,13 @@ end
local delay_data = {}
local delay_tools = setmetatable({},{__mode="v"})

package.delay_data = delay_data

function delay_data.__index(tbl,key)
delay_data.lookup = delay_data.lookup or loadfile("/lib/tools/delayLookup.lua")
return delay_data.lookup(delay_data, tbl, key)
end
delay_data.__pairs = delay_data.__index -- nil key acts like pairs

function delaySearcher(module)
local function delaySearcher(module)
if not delayed[module] then
return "\tno field package.delayed['" .. module .. "']"
end
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -367,7 +367,7 @@ function plib.popen(prog, mode, env)
pm.pco=plib.internal.create(pm.root)

local pfd = require("buffer").new(mode, pipeStream.new(pm))
pfd:setvbuf("no", nil) -- 2nd are to read chunk size
pfd:setvbuf("no", 0) -- 2nd are to read chunk size

-- popen processes start on create (which is LAME :P)
pfd.stream:resume()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,8 @@ sh.internal = {}

-- --[[@@]] are not just comments, but custom annotations for delayload methods.
-- See package.lua and the api wiki for more information
function isWordOf(w, vs) return w and #w == 1 and not w[1].qr and tx.first(vs,{{w[1].txt}}) ~= nil end
function isWord(w,v) return isWordOf(w,{v}) end
local function isWordOf(w, vs) return w and #w == 1 and not w[1].qr and tx.first(vs,{{w[1].txt}}) ~= nil end
local function isWord(w,v) return isWordOf(w,{v}) end
local local_env = {event=event,fs=fs,process=process,shell=shell,term=term,text=text,tx=tx,unicode=unicode,isWordOf=isWordOf,isWord=isWord}

-------------------------------------------------------------------------------
Expand Down Expand Up @@ -424,7 +424,7 @@ function --[[@delayloaded-start@]] sh.internal.buildPipeChain(threads)
local pipe
if i < #threads then
pipe = require("buffer").new("rw", sh.internal.newMemoryStream())
pipe:setvbuf("no")
pipe:setvbuf("no", 0)
-- buffer close flushes the buffer, but we have no buffer
-- also, when the buffer is closed, read and writes don't pass through
-- simply put, we don't want buffer:close
Expand Down Expand Up @@ -461,7 +461,7 @@ function --[[@delayloaded-start@]] sh.internal.glob(glob_pattern)
end

local is_abs = glob_pattern:sub(1, 1) == "/"
local root = is_abs and '' or shell.getWorkingDirectory()
local root = is_abs and '' or shell.getWorkingDirectory():gsub("([^/])$","%1/")
local paths = {is_abs and "/" or ''}
local relative_separator = ''

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ local function cleanPath(path)
if path then
local rpath = shell.resolve(path)
if fs.isDirectory(rpath) then
return fs.canonical(rpath):gsub("/+$", "") .. '/'
return fs.canonical(rpath) .. '/'
end
end
end
Expand Down Expand Up @@ -84,8 +84,7 @@ up_deprecate('name', 'label')
options.source_root = cleanPath(options.from)
options.target_root = cleanPath(options.to)

options.source_dir = (options.fromDir or "") .. '.'
options.target_dir = (options.root or options.toDir or "")
options.target_dir = fs.canonical(options.root or options.toDir or "")

options.update = options.u or options.update

Expand Down Expand Up @@ -167,10 +166,11 @@ if not target then return end
options.target_root = options.target_root or target.path

-- now that source is selected, we can update options
options.label = options.label or source.prop.label
options.setlabel = source.prop.setlabel and not options.nosetlabel
options.setboot = source.prop.setboot and not options.nosetboot
options.reboot = source.prop.reboot and not options.noreboot
options.label = options.label or source.prop.label
options.setlabel = source.prop.setlabel and not options.nosetlabel
options.setboot = source.prop.setboot and not options.nosetboot
options.reboot = source.prop.reboot and not options.noreboot
options.source_dir = fs.canonical(source.prop.fromDir or options.fromDir or "") .. '/.'

local installer_path = options.source_root .. "/.install"
if fs.exists(installer_path) then
Expand Down
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
local cmd, options = ...

local function select_prompt(devs, direction)
local function select_prompt(devs, prompt)
table.sort(devs, function(a, b) return a.path<b.path end)

local choice = devs[1]
if #devs > 1 then
io.write("Select the device to install " .. direction .. '\n')
print(prompt)

for i = 1, #devs do
local src = devs[i]
Expand Down Expand Up @@ -59,7 +59,13 @@ if cmd == 'select' then
os.exit(1)
end

return select_prompt(options.sources, "from"), select_prompt(options.targets, "to")
local source = select_prompt(options.sources, "What do you want to install?")
if #options.sources > 1 and #options.targets > 1 then
print()
end
local target = select_prompt(options.targets, "Where do you want to install to?")

return source, target

elseif cmd == 'install' then
local installer_path = options.source_root .. "/.install"
Expand Down
1 change: 1 addition & 0 deletions src/main/resources/assets/opencomputers/loot/plan9k/.prop
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
{label="Plan9k",reboot=true,setlabel=true,setboot=true}
7 changes: 5 additions & 2 deletions src/main/scala/li/cil/oc/OpenComputers.scala
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import li.cil.oc.common.IMC
import li.cil.oc.common.Proxy
import li.cil.oc.server.command.CommandHandler
import org.apache.logging.log4j.LogManager
import org.apache.logging.log4j.Logger

@Mod(modid = OpenComputers.ID, name = OpenComputers.Name,
version = OpenComputers.Version,
Expand All @@ -21,7 +22,9 @@ object OpenComputers {

final val Version = "@VERSION@"

var log = LogManager.getLogger(Name)
def log = logger.getOrElse(LogManager.getLogger(Name))

var logger: Option[Logger] = None

@SidedProxy(clientSide = "li.cil.oc.client.Proxy", serverSide = "li.cil.oc.server.Proxy")
var proxy: Proxy = null
Expand All @@ -30,7 +33,7 @@ object OpenComputers {

@EventHandler
def preInit(e: FMLPreInitializationEvent) {
log = e.getModLog
logger = Option(e.getModLog)
proxy.preInit(e)
OpenComputers.log.info("Done with pre init phase.")
}
Expand Down
80 changes: 70 additions & 10 deletions src/main/scala/li/cil/oc/server/component/InternetCard.scala
Original file line number Diff line number Diff line change
Expand Up @@ -7,25 +7,26 @@ import java.io.InputStream
import java.io.OutputStreamWriter
import java.net._
import java.nio.ByteBuffer
import java.nio.channels.SelectionKey
import java.nio.channels.Selector
import java.nio.channels.SocketChannel
import java.util
import java.util.concurrent.Callable
import java.util.concurrent.ConcurrentLinkedQueue
import java.util.concurrent.ExecutionException
import java.util.concurrent.Future
import java.util.UUID
import java.util.concurrent._

import li.cil.oc.Constants
import li.cil.oc.OpenComputers
import li.cil.oc.Settings
import li.cil.oc.api.Network
import li.cil.oc.api.driver.DeviceInfo
import li.cil.oc.api.driver.DeviceInfo.DeviceAttribute
import li.cil.oc.api.driver.DeviceInfo.DeviceClass
import li.cil.oc.Settings
import li.cil.oc.api.machine.Arguments
import li.cil.oc.api.machine.Callback
import li.cil.oc.api.machine.Context
import li.cil.oc.api.network._
import li.cil.oc.api.prefab.AbstractValue
import li.cil.oc.api.Network
import li.cil.oc.api.driver.DeviceInfo
import li.cil.oc.api.prefab
import li.cil.oc.api.prefab.AbstractValue
import li.cil.oc.util.ThreadPoolFactory
import net.minecraft.server.MinecraftServer

Expand Down Expand Up @@ -183,6 +184,41 @@ object InternetCard {
def close(): Unit
}

object TCPNotifier extends Thread {
private val selector = Selector.open()
private val toAccept = new ConcurrentLinkedQueue[(SocketChannel, () => Unit)]

override def run(): Unit = {
while (true) {
try {
Stream.continually(toAccept.poll).takeWhile(_ != null).foreach({
case (channel: SocketChannel, action: (() => Unit)) =>
channel.register(selector, SelectionKey.OP_READ, action)
})

selector.select()

import scala.collection.JavaConversions._
val selectedKeys = selector.selectedKeys
selectedKeys.filter(_.isReadable).foreach(key => {
key.cancel()
key.attachment().asInstanceOf[() => Unit].apply()
})
} catch {
case e: IOException =>
OpenComputers.log.error("Error in TCP selector loop.", e)
}
}
}

def add(e: (SocketChannel, () => Unit)) {
toAccept.offer(e)
selector.wakeup()
}
}

TCPNotifier.start()

class TCPSocket extends AbstractValue with Closable {
def this(owner: InternetCard, uri: URI, port: Int) {
this()
Expand All @@ -196,9 +232,25 @@ object InternetCard {
private var address: Future[InetAddress] = null
private var channel: SocketChannel = null
private var isAddressResolved = false
private val id = UUID.randomUUID()

private def setupSelector() {
TCPNotifier.add((channel, () => {
owner match {
case Some(internetCard) =>
internetCard.node.sendToVisible("computer.signal", "internet_ready", internetCard.node.address(), id.toString)
case _ =>
channel.close()
}
}))
}

@Callback(doc = """function():boolean -- Ensures a socket is connected. Errors if the connection failed.""")
def finishConnect(context: Context, args: Arguments): Array[AnyRef] = this.synchronized(result(checkConnected()))
def finishConnect(context: Context, args: Arguments): Array[AnyRef] = {
val r = this.synchronized(result(checkConnected()))
setupSelector()
r
}

@Callback(doc = """function([n:number]):string -- Tries to read data from the socket stream. Returns the read byte array.""")
def read(context: Context, args: Arguments): Array[AnyRef] = this.synchronized {
Expand All @@ -207,7 +259,10 @@ object InternetCard {
val buffer = ByteBuffer.allocate(n)
val read = channel.read(buffer)
if (read == -1) result(Unit)
else result(buffer.array.view(0, read).toArray)
else {
setupSelector()
result(buffer.array.view(0, read).toArray)
}
}
else result(Array.empty[Byte])
}
Expand All @@ -227,6 +282,11 @@ object InternetCard {
null
}

@Callback(direct = true, doc = """function():string -- Returns connection ID.""")
def id(context: Context, args: Arguments): Array[AnyRef] = this.synchronized {
result(id.toString)
}

override def dispose(context: Context): Unit = {
super.dispose(context)
close()
Expand Down
3 changes: 3 additions & 0 deletions src/main/scala/li/cil/oc/server/network/Network.scala
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,9 @@ private class Network private(private val data: mutable.Map[String, Network.Vert
// ----------------------------------------------------------------------- //

def connect(nodeA: MutableNode, nodeB: MutableNode) = {
if (nodeA == null) throw new NullPointerException("nodeA")
if (nodeB == null) throw new NullPointerException("nodeB")

if (nodeA == nodeB) throw new IllegalArgumentException(
"Cannot connect a node to itself.")

Expand Down

0 comments on commit dfb8e17

Please sign in to comment.