diff --git a/console.js b/console.js index c66c5a1..831b42e 100644 --- a/console.js +++ b/console.js @@ -3,12 +3,12 @@ const http = require('http'); function time() { let now = new Date(); - return `${now.getHours().toString().padStart(2,"0")}:${now.getMinutes().toString().padStart(2,0)}:${now.getSeconds().toString().padStart(2,0)}`; + return `${now.getHours().toString().padStart(2, "0")}:${now.getMinutes().toString().padStart(2, 0)}:${now.getSeconds().toString().padStart(2, 0)}`; } -const server = http.createServer((req,res)=>{ +const server = http.createServer((req, res) => { - if (req.method != "POST" ){ + if (req.method != "POST") { res.writeHead(400); return; } @@ -16,13 +16,13 @@ const server = http.createServer((req,res)=>{ let data = ""; req.on('data', chunk => { - data += chunk; + data += chunk; }) req.on('end', () => { - console.log(`[${time()}]${data}`); - res.writeHead(200); - res.end(); + console.log(`[${time()}]${data}`); + res.writeHead(200); + res.end(); }) }); diff --git a/src/kernel/ButtonType.hx b/src/kernel/ButtonType.hx index bc72d98..f38e7b6 100644 --- a/src/kernel/ButtonType.hx +++ b/src/kernel/ButtonType.hx @@ -1,7 +1,7 @@ package kernel; enum ButtonType { - Left; - Middle; - Right; + Left; + Middle; + Right; } diff --git a/src/kernel/Init.hx b/src/kernel/Init.hx index 27cd8dc..e117172 100644 --- a/src/kernel/Init.hx +++ b/src/kernel/Init.hx @@ -6,17 +6,17 @@ import kernel.peripherals.Peripherals.Peripheral; import kernel.net.Net; class Init { - public static function initKernel() { - // Init singeltons here because haxe is confused about the order to create them. - KernelEvents.instance = new KernelEvents(); - Peripheral.instance = new Peripheral(); - - WindowManager.instance = new WindowManager(); - MainTerm.instance = new MainTerm(); - Net.instance = new Net(); + public static function initKernel() { + // Init singeltons here because haxe is confused about the order to create them. + KernelEvents.instance = new KernelEvents(); + Peripheral.instance = new Peripheral(); - Log.init(); - - Debug.printBuildInfo(); - } + WindowManager.instance = new WindowManager(); + MainTerm.instance = new MainTerm(); + Net.instance = new Net(); + + Log.init(); + + Debug.printBuildInfo(); + } } diff --git a/src/kernel/KernelEvents.hx b/src/kernel/KernelEvents.hx index e95c033..5c8b44b 100644 --- a/src/kernel/KernelEvents.hx +++ b/src/kernel/KernelEvents.hx @@ -2,6 +2,7 @@ package kernel; import util.Vec.Vec2; import haxe.Exception; + using tink.CoreApi; import cc.OS; @@ -11,75 +12,87 @@ using lua.Table; /** Class for interacting with the native pullEvent system. **/ -class KernelEvents{ +class KernelEvents { public static var instance:KernelEvents; - - public final onAlarm: Signal; - public final onChar: Signal; - public final onDisk: Signal; - public final onDiskEject: Signal; - public final onHttpCheck: Signal<{url:String,success:Bool,failReason:Any}>; - public final onHttpFailure: Signal<{url:String,failReason:String,handle:Any}>; - public final onHttpSuccess: Signal<{url:String,handle:Any}>; - public final onKey: Signal<{keyCode: Int,isHeld:Bool}>; - public final onKeyUp: Signal; - public final onModemMessage: Signal<{addr: String,channel:Int, replyChannel:Int,message:Dynamic,distance:Int}>; - public final onMonitorResize: Signal; - public final onMonitorTouch: Signal<{addr:String,pos: Vec2}>; - public final onMouseClick: Signal<{button:ButtonType,pos: Vec2}>; - public final onMouseDrag: Signal<{button:ButtonType,pos: Vec2}>; - public final onMouseScroll: Signal<{dir:Int,pos: Vec2}>; - public final onMouseUp: Signal<{button:ButtonType,pos: Vec2}>; - public final onPaste: Signal; - public final onPeripheral: Signal; - public final onPeripheralDetach: Signal; - public final onRednetMessage: Signal<{sender:Int,message:Any,protocol:Any}>; - public final onRedstone: Signal; - public final onSpeakerAudioEmpty: Signal; - public final onTaskComplete: Signal<{id:Int,success:Bool,failedReason:String}>; - public final onTermResize: Signal; - public final onTerminate: Signal; - public final onTimer: Signal; - public final onTurtleInventory: Signal; - public final onWebsocketClose: Signal; - public final onWebsocketFailure: Signal<{url:String,failReason:String}>; - public final onWebsocketMessage: Signal<{url:String,message:String,isBinary:Bool}>; - public final onWebsocketSuccess: Signal<{url:String,handle:Any}>; - private final onAlarmTrigger: SignalTrigger = Signal.trigger(); - private final onCharTrigger: SignalTrigger = Signal.trigger(); - private final onDiskTrigger: SignalTrigger = Signal.trigger(); - private final onDiskEjectTrigger: SignalTrigger = Signal.trigger(); - private final onHttpCheckTrigger: SignalTrigger<{url:String,success:Bool,failReason:Any}> = Signal.trigger(); - private final onHttpFailureTrigger: SignalTrigger<{url:String,failReason:String,handle:Any}> = Signal.trigger(); - private final onHttpSuccessTrigger: SignalTrigger<{url:String,handle:Any}> = Signal.trigger(); - private final onKeyTrigger: SignalTrigger<{keyCode: Int,isHeld:Bool}> = Signal.trigger(); - private final onKeyUpTrigger: SignalTrigger = Signal.trigger(); - private final onModemMessageTrigger: SignalTrigger<{addr: String,channel:Int, replyChannel:Int,message:Dynamic,distance:Int}> = Signal.trigger(); - private final onMonitorResizeTrigger: SignalTrigger = Signal.trigger(); - private final onMonitorTouchTrigger: SignalTrigger<{addr:String,pos: Vec2}> = Signal.trigger(); - private final onMouseClickTrigger: SignalTrigger<{button:ButtonType,pos: Vec2}> = Signal.trigger(); - private final onMouseDragTrigger: SignalTrigger<{button:ButtonType,pos: Vec2}> = Signal.trigger(); - private final onMouseScrollTrigger: SignalTrigger<{dir:Int,pos: Vec2}> = Signal.trigger(); - private final onMouseUpTrigger: SignalTrigger<{button:ButtonType,pos: Vec2}> = Signal.trigger(); - private final onPasteTrigger: SignalTrigger = Signal.trigger(); - private final onPeripheralTrigger: SignalTrigger = Signal.trigger(); - private final onPeripheralDetachTrigger: SignalTrigger = Signal.trigger(); - private final onRednetMessageTrigger: SignalTrigger<{sender:Int,message:Any,protocol:Any}> = Signal.trigger(); - private final onRedstoneTrigger: SignalTrigger = Signal.trigger(); - private final onSpeakerAudioEmptyTrigger: SignalTrigger = Signal.trigger(); - private final onTaskCompleteTrigger: SignalTrigger<{id:Int,success:Bool,failedReason:String}> = Signal.trigger(); - private final onTermResizeTrigger: SignalTrigger = Signal.trigger(); - private final onTerminateTrigger: SignalTrigger = Signal.trigger(); - private final onTimerTrigger: SignalTrigger = Signal.trigger(); - private final onTurtleInventoryTrigger: SignalTrigger = Signal.trigger(); - private final onWebsocketCloseTrigger: SignalTrigger = Signal.trigger(); - private final onWebsocketFailureTrigger: SignalTrigger<{url:String,failReason:String}> = Signal.trigger(); - private final onWebsocketMessageTrigger: SignalTrigger<{url:String,message:String,isBinary:Bool}> = Signal.trigger(); - private final onWebsocketSuccessTrigger: SignalTrigger<{url:String,handle:Any}> = Signal.trigger(); + public final onAlarm:Signal; + public final onChar:Signal; + public final onDisk:Signal; + public final onDiskEject:Signal; + public final onHttpCheck:Signal<{url:String, success:Bool, failReason:Any}>; + public final onHttpFailure:Signal<{url:String, failReason:String, handle:Any}>; + public final onHttpSuccess:Signal<{url:String, handle:Any}>; + public final onKey:Signal<{keyCode:Int, isHeld:Bool}>; + public final onKeyUp:Signal; + public final onModemMessage:Signal<{ + addr:String, + channel:Int, + replyChannel:Int, + message:Dynamic, + distance:Int + }>; + public final onMonitorResize:Signal; + public final onMonitorTouch:Signal<{addr:String, pos:Vec2}>; + public final onMouseClick:Signal<{button:ButtonType, pos:Vec2}>; + public final onMouseDrag:Signal<{button:ButtonType, pos:Vec2}>; + public final onMouseScroll:Signal<{dir:Int, pos:Vec2}>; + public final onMouseUp:Signal<{button:ButtonType, pos:Vec2}>; + public final onPaste:Signal; + public final onPeripheral:Signal; + public final onPeripheralDetach:Signal; + public final onRednetMessage:Signal<{sender:Int, message:Any, protocol:Any}>; + public final onRedstone:Signal; + public final onSpeakerAudioEmpty:Signal; + public final onTaskComplete:Signal<{id:Int, success:Bool, failedReason:String}>; + public final onTermResize:Signal; + public final onTerminate:Signal; + public final onTimer:Signal; + public final onTurtleInventory:Signal; + public final onWebsocketClose:Signal; + public final onWebsocketFailure:Signal<{url:String, failReason:String}>; + public final onWebsocketMessage:Signal<{url:String, message:String, isBinary:Bool}>; + public final onWebsocketSuccess:Signal<{url:String, handle:Any}>; + + private final onAlarmTrigger:SignalTrigger = Signal.trigger(); + private final onCharTrigger:SignalTrigger = Signal.trigger(); + private final onDiskTrigger:SignalTrigger = Signal.trigger(); + private final onDiskEjectTrigger:SignalTrigger = Signal.trigger(); + private final onHttpCheckTrigger:SignalTrigger<{url:String, success:Bool, failReason:Any}> = Signal.trigger(); + private final onHttpFailureTrigger:SignalTrigger<{url:String, failReason:String, handle:Any}> = Signal.trigger(); + private final onHttpSuccessTrigger:SignalTrigger<{url:String, handle:Any}> = Signal.trigger(); + private final onKeyTrigger:SignalTrigger<{keyCode:Int, isHeld:Bool}> = Signal.trigger(); + private final onKeyUpTrigger:SignalTrigger = Signal.trigger(); + private final onModemMessageTrigger:SignalTrigger<{ + addr:String, + channel:Int, + replyChannel:Int, + message:Dynamic, + distance:Int + }> = Signal.trigger(); + private final onMonitorResizeTrigger:SignalTrigger = Signal.trigger(); + private final onMonitorTouchTrigger:SignalTrigger<{addr:String, pos:Vec2}> = Signal.trigger(); + private final onMouseClickTrigger:SignalTrigger<{button:ButtonType, pos:Vec2}> = Signal.trigger(); + private final onMouseDragTrigger:SignalTrigger<{button:ButtonType, pos:Vec2}> = Signal.trigger(); + private final onMouseScrollTrigger:SignalTrigger<{dir:Int, pos:Vec2}> = Signal.trigger(); + private final onMouseUpTrigger:SignalTrigger<{button:ButtonType, pos:Vec2}> = Signal.trigger(); + private final onPasteTrigger:SignalTrigger = Signal.trigger(); + private final onPeripheralTrigger:SignalTrigger = Signal.trigger(); + private final onPeripheralDetachTrigger:SignalTrigger = Signal.trigger(); + private final onRednetMessageTrigger:SignalTrigger<{sender:Int, message:Any, protocol:Any}> = Signal.trigger(); + private final onRedstoneTrigger:SignalTrigger = Signal.trigger(); + private final onSpeakerAudioEmptyTrigger:SignalTrigger = Signal.trigger(); + private final onTaskCompleteTrigger:SignalTrigger<{id:Int, success:Bool, failedReason:String}> = Signal.trigger(); + private final onTermResizeTrigger:SignalTrigger = Signal.trigger(); + private final onTerminateTrigger:SignalTrigger = Signal.trigger(); + private final onTimerTrigger:SignalTrigger = Signal.trigger(); + private final onTurtleInventoryTrigger:SignalTrigger = Signal.trigger(); + private final onWebsocketCloseTrigger:SignalTrigger = Signal.trigger(); + private final onWebsocketFailureTrigger:SignalTrigger<{url:String, failReason:String}> = Signal.trigger(); + private final onWebsocketMessageTrigger:SignalTrigger<{url:String, message:String, isBinary:Bool}> = Signal.trigger(); + private final onWebsocketSuccessTrigger:SignalTrigger<{url:String, handle:Any}> = Signal.trigger(); @:allow(kernel.Init) - private function new () { + private function new() { this.onAlarm = onAlarmTrigger.asSignal(); this.onChar = onCharTrigger.asSignal(); this.onDisk = onDiskTrigger.asSignal(); @@ -117,11 +130,11 @@ class KernelEvents{ Start pulling events. Blocking. **/ public function startEventLoop() { - while (true){ + while (true) { var event:Table = OS.pullEventRaw(); - + var eventName:String = event[1]; - + switch eventName { case "alarm": this.onAlarmTrigger.trigger(event[2]); @@ -132,29 +145,35 @@ class KernelEvents{ case "disk_eject": this.onDiskEjectTrigger.trigger(event[2]); case "http_check": - this.onHttpCheckTrigger.trigger({url: event[2],success: event[3],failReason: event[4]}); + this.onHttpCheckTrigger.trigger({url: event[2], success: event[3], failReason: event[4]}); case "http_failure": - this.onHttpFailureTrigger.trigger({url: event[2],failReason: event[3],handle: event[4]}); + this.onHttpFailureTrigger.trigger({url: event[2], failReason: event[3], handle: event[4]}); case "http_success": - this.onHttpSuccessTrigger.trigger({url: event[2],handle: event[3]}); + this.onHttpSuccessTrigger.trigger({url: event[2], handle: event[3]}); case "key": - this.onKeyTrigger.trigger({keyCode: event[2],isHeld: event[3]}); + this.onKeyTrigger.trigger({keyCode: event[2], isHeld: event[3]}); case "key_up": this.onKeyUpTrigger.trigger(event[2]); case "modem_message": - this.onModemMessageTrigger.trigger({addr: event[2],channel: event[3],replyChannel: event[4],message: event[5],distance: event[6]}); + this.onModemMessageTrigger.trigger({ + addr: event[2], + channel: event[3], + replyChannel: event[4], + message: event[5], + distance: event[6] + }); case "monitor_resize": this.onMonitorResizeTrigger.trigger(event[2]); case "monitor_touch": - this.onMonitorTouchTrigger.trigger({addr: event[2],pos:{x: (event[3]:Int) - 1,y: (event[4]:Int) - 1}}); + this.onMonitorTouchTrigger.trigger({addr: event[2], pos: {x: (event[3] : Int) - 1, y: (event[4] : Int) - 1}}); case "mouse_click": - this.onMouseClickTrigger.trigger({button: ccButtonToEnum(event[2]),pos:{ x: (event[3]:Int) - 1,y: (event[4]:Int) - 1}}); + this.onMouseClickTrigger.trigger({button: ccButtonToEnum(event[2]), pos: {x: (event[3] : Int) - 1, y: (event[4] : Int) - 1}}); case "mouse_drag": - this.onMouseDragTrigger.trigger({button: ccButtonToEnum(event[2]),pos:{x: (event[3]:Int) - 1,y: (event[4]:Int) - 1}}); + this.onMouseDragTrigger.trigger({button: ccButtonToEnum(event[2]), pos: {x: (event[3] : Int) - 1, y: (event[4] : Int) - 1}}); case "mouse_scroll": - this.onMouseScrollTrigger.trigger({dir: event[2],pos:{x:(event[3]:Int) - 1,y: (event[4]:Int) - 1}}); + this.onMouseScrollTrigger.trigger({dir: event[2], pos: {x: (event[3] : Int) - 1, y: (event[4] : Int) - 1}}); case "mouse_up": - this.onMouseUpTrigger.trigger({button: ccButtonToEnum(event[2]),pos:{x: (event[3]:Int) - 1,y: (event[4]:Int) - 1}}); + this.onMouseUpTrigger.trigger({button: ccButtonToEnum(event[2]), pos: {x: (event[3] : Int) - 1, y: (event[4] : Int) - 1}}); case "paste": this.onPasteTrigger.trigger(event[2]); case "peripheral": @@ -162,13 +181,13 @@ class KernelEvents{ case "peripheral_detach": this.onPeripheralDetachTrigger.trigger(event[2]); case "rednet_message": - this.onRednetMessageTrigger.trigger({sender: event[2],message: event[3],protocol: event[4]}); + this.onRednetMessageTrigger.trigger({sender: event[2], message: event[3], protocol: event[4]}); case "redstone": this.onRedstoneTrigger.trigger(null); case "speaker_audio_empty": this.onSpeakerAudioEmptyTrigger.trigger(event[2]); case "task_complete": - this.onTaskCompleteTrigger.trigger({id: event[2],success: event[3],failedReason: event[4]}); + this.onTaskCompleteTrigger.trigger({id: event[2], success: event[3], failedReason: event[4]}); case "term_resize": this.onTermResizeTrigger.trigger(null); case "terminate": @@ -180,18 +199,18 @@ class KernelEvents{ case "websocket_closed": this.onWebsocketCloseTrigger.trigger(event[2]); case "websocket_failure": - this.onWebsocketFailureTrigger.trigger({url: event[2],failReason: event[3]}); + this.onWebsocketFailureTrigger.trigger({url: event[2], failReason: event[3]}); case "websocket_message": - this.onWebsocketMessageTrigger.trigger({url: event[2],message: event[3],isBinary: event[4]}); + this.onWebsocketMessageTrigger.trigger({url: event[2], message: event[3], isBinary: event[4]}); case "websocket_success": - this.onWebsocketSuccessTrigger.trigger({url: event[2],handle: event[3]}); + this.onWebsocketSuccessTrigger.trigger({url: event[2], handle: event[3]}); default: Log.error("Unknown cc event: " + eventName); } } } - private static function ccButtonToEnum(button: Dynamic): ButtonType { + private static function ccButtonToEnum(button:Dynamic):ButtonType { switch button { case 1: return Left; diff --git a/src/kernel/Log.hx b/src/kernel/Log.hx index 45fab11..a486939 100644 --- a/src/kernel/Log.hx +++ b/src/kernel/Log.hx @@ -13,45 +13,45 @@ class Log { private static var context:WindowContext; private static var writer:TermIO; - @:allow(kernel.Init) + @:allow(kernel.Init) private static function init() { Log.context = WindowManager.instance.createNewContext(); Log.writer = new TermIO(Log.context); } - private static function setMainoutout(newOutput: TermWriteable) { + private static function setMainoutout(newOutput:TermWriteable) { writer = new TermIO(newOutput); } - public static function info(msg: Dynamic, ?pos:haxe.PosInfos){ - writer.writeLn("[INFO]["+pos.className+"]: "+Std.string(msg)); + public static function info(msg:Dynamic, ?pos:haxe.PosInfos) { + writer.writeLn("[INFO][" + pos.className + "]: " + Std.string(msg)); #if webconsole - Debug.printWeb("[INFO]["+pos.className+"]: "+Std.string(msg)); + Debug.printWeb("[INFO][" + pos.className + "]: " + Std.string(msg)); #end } - public static function warn(msg: Dynamic, ?pos:haxe.PosInfos){ - writer.writeLn("[WARN]["+pos.className+"]: "+Std.string(msg),Yellow); + public static function warn(msg:Dynamic, ?pos:haxe.PosInfos) { + writer.writeLn("[WARN][" + pos.className + "]: " + Std.string(msg), Yellow); #if webconsole - Debug.printWeb("[WARN]["+pos.className+"]: "+Std.string(msg)); + Debug.printWeb("[WARN][" + pos.className + "]: " + Std.string(msg)); #end } - public static function error(msg: Dynamic,?pos:haxe.PosInfos) { - writer.writeLn("[ERRO]["+pos.className+"]: "+Std.string(msg),Red); + public static function error(msg:Dynamic, ?pos:haxe.PosInfos) { + writer.writeLn("[ERRO][" + pos.className + "]: " + Std.string(msg), Red); #if webconsole - Debug.printWeb("[ERRO]["+pos.className+"]: "+Std.string(msg)); + Debug.printWeb("[ERRO][" + pos.className + "]: " + Std.string(msg)); #end } - public static function debug(msg: Dynamic,?pos:haxe.PosInfos) { - writer.writeLn("[DEBG]["+pos.className+"]: "+Std.string(msg),Gray); + public static function debug(msg:Dynamic, ?pos:haxe.PosInfos) { + writer.writeLn("[DEBG][" + pos.className + "]: " + Std.string(msg), Gray); #if webconsole - Debug.printWeb("[DEBG]["+pos.className+"]: "+Std.string(msg)); + Debug.printWeb("[DEBG][" + pos.className + "]: " + Std.string(msg)); #end } - public static function moveToOutput(addr: String) { - WindowManager.instance.focusContextToOutput(context,addr); + public static function moveToOutput(addr:String) { + WindowManager.instance.focusContextToOutput(context, addr); } } diff --git a/src/kernel/MainTerm.hx b/src/kernel/MainTerm.hx index edefa73..6ffb79a 100644 --- a/src/kernel/MainTerm.hx +++ b/src/kernel/MainTerm.hx @@ -10,8 +10,9 @@ import util.Color; /** Represents the main computer screen. **/ -class MainTerm implements TermWriteable{ - public static var instance:MainTerm; +class MainTerm implements TermWriteable { + public static var instance:MainTerm; + public var onResize(default, null):Signal>; private var onResizeTrigger:SignalTrigger>; @@ -21,72 +22,71 @@ class MainTerm implements TermWriteable{ this.onResizeTrigger = Signal.trigger(); this.onResize = this.onResizeTrigger.asSignal(); - KernelEvents.instance.onTermResize.handle(_ ->{ + KernelEvents.instance.onTermResize.handle(_ -> { onResizeTrigger.trigger(getSize()); }); } - public function write(text:String) { - Term.write(text); - } + Term.write(text); + } public function scroll(y:Int) { - Term.scroll(y); - } + Term.scroll(y); + } public function getCursorPos():Vec2 { var rtn = Term.getCursorPos(); - return { - x: rtn.x - 1, - y: rtn.y - 1 - } + return { + x: rtn.x - 1, + y: rtn.y - 1 + } } public function setCursorPos(x:Int, y:Int) { - Term.setCursorPos(x + 1,y + 1); - } + Term.setCursorPos(x + 1, y + 1); + } public function getCursorBlink():Bool { - // Missing in api + // Missing in api throw new haxe.exceptions.NotImplementedException(); } public function setCursorBlink(blink:Bool) { - Term.setCursorBlink(blink); - } + Term.setCursorBlink(blink); + } public function getSize():Vec2 { var rtn = Term.getSize(); - return { - x: rtn.width, - y: rtn.height, - } + return { + x: rtn.width, + y: rtn.height, + } } public function clear() { - Term.clear(); - } + Term.clear(); + } public function clearLine() { - Term.clearLine(); - } + Term.clearLine(); + } public function getTextColor():Color { return ColorConvert.ccToColor(Term.getTextColor()); } public function setTextColor(colour:Color) { - Term.setTextColor(ColorConvert.colorToCC(colour)); - } + Term.setTextColor(ColorConvert.colorToCC(colour)); + } public function getBackgroundColor():Color { return ColorConvert.ccToColor(Term.getBackgroundColor()); } public function setBackgroundColor(color:Color) { - Term.setBackgroundColor(ColorConvert.colorToCC(color)); - } + Term.setBackgroundColor(ColorConvert.colorToCC(color)); + } public function isColor():Bool { return Term.isColor(); diff --git a/src/kernel/Timer.hx b/src/kernel/Timer.hx index 2657382..8cd4798 100644 --- a/src/kernel/Timer.hx +++ b/src/kernel/Timer.hx @@ -15,12 +15,12 @@ class Timer { /** Create new timer with timeout in seconds. **/ - public function new(timeout: Int, callback: Callback) { + public function new(timeout:Int, callback:Callback) { timerID = OS.startTimer(timeout); this.callback = callback; - timerLink = KernelEvents.instance.onTimer.handle(timerID ->{ - if (this.timerID == timerID){ + timerLink = KernelEvents.instance.onTimer.handle(timerID -> { + if (this.timerID == timerID) { callback.invoke(null); timerLink.cancel(); } diff --git a/src/kernel/net/Net.hx b/src/kernel/net/Net.hx index edc3768..bc7a34d 100644 --- a/src/kernel/net/Net.hx +++ b/src/kernel/net/Net.hx @@ -16,13 +16,13 @@ using util.Extender.LambdaExtender; Class responsible for everything network related. Used to send and recceive packages. **/ -class Net{ +class Net { public static var instance:Net; @:allow(kernel.Init) - private function new () { - KernelEvents.instance.onModemMessage.handle(params ->{ - var pack: Package = { + private function new() { + KernelEvents.instance.onModemMessage.handle(params -> { + var pack:Package = { fromID: params.replyChannel, toID: params.channel, msgID: params.message.msgID, @@ -30,39 +30,38 @@ class Net{ data: params.message.data, }; - handelIncomming(pack,params.addr); + handelIncomming(pack, params.addr); }); allModems = Peripheral.instance.getModems(); open(); discoverNeighbors(); } - + public static inline final BRODCAST_PORT:Int = 65533; public static inline final MESSAGE_TIMEOUT:Int = 3; private var networkID:Int = OS.getComputerID(); - private var responseBus: util.EventBus = new EventBus(); - private var protoHandlers: Map Void> = new Map(); + private var responseBus:util.EventBus = new EventBus(); + private var protoHandlers:MapVoid> = new Map(); private var allModems:Array; - private var routingTable: Map = new Map(); + private var routingTable:Map = new Map(); - private function handelIncomming(pack: Package, ?addr:String) { + private function handelIncomming(pack:Package, ?addr:String) { switch pack.type { case Data(_): routeTo(pack); case DataNoResponse(_): routeTo(pack); case Response | RouteDiscoverResponse: - responseBus.emit(Std.string(pack.msgID),pack); + responseBus.emit(Std.string(pack.msgID), pack); case RouteDiscover: - handleRoute(pack,addr); - + handleRoute(pack, addr); } } - private function newRoutPackage(): Package { - var pack: Package = { + private function newRoutPackage():Package { + var pack:Package = { type: RouteDiscover, toID: BRODCAST_PORT, msgID: generateMessageID(), @@ -77,24 +76,24 @@ class Net{ for (modem in allModems) { var pack = newRoutPackage(); - var timeout: Timer = null; - var responeListner = responseBus.on(Std.string(pack.msgID),pack -> { - addRoute(pack.fromID,modem.addr); + var timeout:Timer = null; + var responeListner = responseBus.on(Std.string(pack.msgID), pack -> { + addRoute(pack.fromID, modem.addr); }); - timeout = new Timer(MESSAGE_TIMEOUT,() -> { + timeout = new Timer(MESSAGE_TIMEOUT, () -> { responseBus.removeListner(responeListner); }); - modem.transmit(BRODCAST_PORT,OS.getComputerID(),pack); + modem.transmit(BRODCAST_PORT, OS.getComputerID(), pack); } } - private function handleRoute(pack: Package, addr: String) { - addRoute(pack.fromID,addr); - + private function handleRoute(pack:Package, addr:String) { + addRoute(pack.fromID, addr); + // Respond to peer - var response: Package = { + var response:Package = { toID: pack.fromID, fromID: OS.getComputerID(), msgID: pack.msgID, @@ -103,20 +102,20 @@ class Net{ } for (reponseModem in allModems.filter(m -> m.addr == addr)) { - reponseModem.transmit(pack.fromID,networkID,response); + reponseModem.transmit(pack.fromID, networkID, response); } } - private function addRoute(toID: Int,addr: String) { - Log.debug("Added new route to "+toID+" via "+addr); - routingTable.set(toID,allModems.find(item -> item.addr == addr)); + private function addRoute(toID:Int, addr:String) { + Log.debug("Added new route to " + toID + " via " + addr); + routingTable.set(toID, allModems.find(item -> item.addr == addr)); } - public function getAllNeighbors(): Array { + public function getAllNeighbors():Array { return routingTable.mapi((index, item) -> index); } - private function generateMessageID(): Int { + private function generateMessageID():Int { return Std.random(2147483647); // TODO: better uniqe number } @@ -133,9 +132,8 @@ class Net{ /** Send a message. Dont care if its reaches its destination nor it has a response. **/ - public function sendAndForget(dest:Int,proto:String,data: Dynamic){ - - var pack: Package = { + public function sendAndForget(dest:Int, proto:String, data:Dynamic) { + var pack:Package = { toID: dest, fromID: networkID, msgID: generateMessageID(), @@ -146,8 +144,8 @@ class Net{ sendRaw(pack); } - public function respondTo(pack: Package,data: Dynamic) { - if (pack.type.match(DataNoResponse(_))){ + public function respondTo(pack:Package, data:Dynamic) { + if (pack.type.match(DataNoResponse(_))) { Log.warn("Responed to a no response package. Ignoring"); return; } @@ -157,8 +155,8 @@ class Net{ sendRaw(response); } - private function routeTo(pack: Package) { - var proto: String = switch pack.type { + private function routeTo(pack:Package) { + var proto:String = switch pack.type { case Data(proto): proto; case DataNoResponse(proto): @@ -167,57 +165,56 @@ class Net{ return; } - if (!protoHandlers.exists(proto) && protoHandlers[proto] != null){ + if (!protoHandlers.exists(proto) && protoHandlers[proto] != null) { return; } protoHandlers[proto](pack); } - private function sendRaw(pack: Package){ - - if (pack.toID == networkID){ + private function sendRaw(pack:Package) { + if (pack.toID == networkID) { // Loopback handelIncomming(pack); - }else{ - if (routingTable.exists(pack.toID)){ - routingTable[pack.toID].transmit(pack.toID,pack.fromID,pack); - }else{ + } else { + if (routingTable.exists(pack.toID)) { + routingTable[pack.toID].transmit(pack.toID, pack.fromID, pack); + } else { // Route not found // TODO: forward package or report not reachable } } } - public function sendAndAwait(dest: Int,proto:String,data: Dynamic): Promise { + public function sendAndAwait(dest:Int, proto:String, data:Dynamic):Promise { return new Promise((resolve, reject) -> { - var pack: Package = { + var pack:Package = { toID: dest, fromID: networkID, msgID: generateMessageID(), type: Data(proto), data: data } - - var timeout: Timer = null; - var responeListner = responseBus.once(Std.string(pack.msgID),p -> { + + var timeout:Timer = null; + var responeListner = responseBus.once(Std.string(pack.msgID), p -> { resolve(p); - if (timeout != null){ + if (timeout != null) { timeout.cancle(); } }); - - timeout = new Timer(MESSAGE_TIMEOUT,() -> { + + timeout = new Timer(MESSAGE_TIMEOUT, () -> { responseBus.removeListner(responeListner); reject(new Exception("Timeout")); }); - + sendRaw(pack); }); } - public function registerProto(proto: String,cb: Package -> Void) { - if (protoHandlers.exists(proto)){ + public function registerProto(proto:String, cb:Package->Void) { + if (protoHandlers.exists(proto)) { // Failed. Handler already exist. // TODO: return error return; @@ -226,7 +223,7 @@ class Net{ protoHandlers[proto] = cb; } - public function removeProto(proto: String) { + public function removeProto(proto:String) { protoHandlers.remove(proto); } } diff --git a/src/kernel/net/Package.hx b/src/kernel/net/Package.hx index 61cb1b6..6ba6a20 100644 --- a/src/kernel/net/Package.hx +++ b/src/kernel/net/Package.hx @@ -1,8 +1,8 @@ package kernel.net; enum PackageTypes { - Data(proto: String); - DataNoResponse(proto: String); + Data(proto:String); + DataNoResponse(proto:String); Response; RouteDiscover(); RouteDiscoverResponse(); @@ -21,7 +21,7 @@ enum PackageTypes { /** Parse package from an `modem_message` event. **/ - public static function fromEvent(params: Array): Package { + public static function fromEvent(params:Array):Package { var payload = params[4]; return { @@ -36,7 +36,7 @@ enum PackageTypes { /** Create package that can be used as a response. **/ - public function createResponse(newData: Dynamic): Package { + public function createResponse(newData:Dynamic):Package { return { toID: fromID, fromID: toID, @@ -49,7 +49,7 @@ enum PackageTypes { /** Wrapper for `Net.instance.respondTo`. **/ - public function respond(data: Dynamic) { - Net.instance.respondTo(this,data); + public function respond(data:Dynamic) { + Net.instance.respondTo(this, data); } -} \ No newline at end of file +} diff --git a/src/kernel/peripherals/Inventory.hx b/src/kernel/peripherals/Inventory.hx deleted file mode 100644 index 731e781..0000000 --- a/src/kernel/peripherals/Inventory.hx +++ /dev/null @@ -1,31 +0,0 @@ -package kernel.peripherals; - -class Item { - -} - -class Inventory { - - - - public function size():Int { - - } - - public function list(): Map { - - } - - public function getItemDetail(slot: Int): Item { - - } - - public function pushItems(toName: String, fromSlot: Int, ?limit:Int, toSlot: Int): Int { - - } - - public function pullItems(fromName: String, fromSlot: Int, ?limit:Int, ?toSlot: Int): Int { - - } - -} diff --git a/src/kernel/peripherals/Modem.hx b/src/kernel/peripherals/Modem.hx index a177cdd..139c806 100644 --- a/src/kernel/peripherals/Modem.hx +++ b/src/kernel/peripherals/Modem.hx @@ -11,20 +11,20 @@ class Modem { public final addr:String; @:allow(kernel.peripherals) - private function new(nativePeripherals: cc.periphs.Modem.Modem,addr: String) { + private function new(nativePeripherals:cc.periphs.Modem.Modem, addr:String) { this.nativ = nativePeripherals; this.addr = addr; } - public function open(chan: Int) { + public function open(chan:Int) { nativ.open(chan); } - public function isOpen(chan: Int): Bool { + public function isOpen(chan:Int):Bool { return nativ.isOpen(chan); } - public function close(chan: Int) { + public function close(chan:Int) { nativ.close(chan); } @@ -32,32 +32,32 @@ class Modem { nativ.closeAll(); } - public function transmit(chan: Int,replyChan: Int,payload: Any) { - nativ.transmit(chan,replyChan,payload); + public function transmit(chan:Int, replyChan:Int, payload:Any) { + nativ.transmit(chan, replyChan, payload); } - public function isWireless(): Bool { + public function isWireless():Bool { return nativ.isWireless(); } public function getNamesRemote():Array { - if (isWireless()){ + if (isWireless()) { throw new Exception("'getNamesRemote' only works with wired modems"); } return nativ.getNamesRemote().toArray(); } - public function isPresentRemote(name: String): Bool { - if (isWireless()){ + public function isPresentRemote(name:String):Bool { + if (isWireless()) { throw new Exception("'isPresentRemote' only works with wired modems"); } return nativ.isPresentRemote(name); } - public function getTypeRemote(name: String): String { - if (isWireless()){ + public function getTypeRemote(name:String):String { + if (isWireless()) { throw new Exception("'getTypeRemote' only works with wired modems"); } @@ -65,7 +65,7 @@ class Modem { } public function hasTypeRemote(name:String, type:String):Bool { - if (isWireless()){ + if (isWireless()) { throw new Exception("'hasTypeRemote' only works with wired modems"); } @@ -74,16 +74,16 @@ class Modem { // return nativ.hasRemoteType(name,type); } - public function getMethodsRemote(name: String): Array { - if (isWireless()){ + public function getMethodsRemote(name:String):Array { + if (isWireless()) { throw new Exception("'getMethodsRemote' only works with wired modems"); } return nativ.getMethodsRemote(name).toArray(); } - public function callRemote(remoteName: String, method:String):Dynamic { - if (isWireless()){ + public function callRemote(remoteName:String, method:String):Dynamic { + if (isWireless()) { throw new Exception("'callRemote' only works with wired modems"); } @@ -91,8 +91,8 @@ class Modem { throw new haxe.exceptions.NotImplementedException(); } - public function getNameLocal(): String { - if (isWireless()){ + public function getNameLocal():String { + if (isWireless()) { throw new Exception("'getNameLocal' only works with wired modems"); } diff --git a/src/kernel/peripherals/Peripherals.hx b/src/kernel/peripherals/Peripherals.hx index 6be9dd9..1e64220 100644 --- a/src/kernel/peripherals/Peripherals.hx +++ b/src/kernel/peripherals/Peripherals.hx @@ -18,42 +18,42 @@ class Peripheral { /** Get all connected screens. **/ - public function getScreens(): Array { + public function getScreens():Array { var allScreens = cc.Peripheral.getNames().toArray().filter(s -> cc.Peripheral.getType(s) == "monitor"); - return allScreens.map(s -> return new Screen((cc.Peripheral.wrap(s):Dynamic),s)); + return allScreens.map(s -> return new Screen((cc.Peripheral.wrap(s) : Dynamic), s)); } - public function getScreen(addr: String): Screen { - if (!getAllPeripheralsAddr().exists(item -> item == addr)){ + public function getScreen(addr:String):Screen { + if (!getAllPeripheralsAddr().exists(item -> item == addr)) { return null; } - return new Screen((cc.Peripheral.wrap(addr):Dynamic),addr); + return new Screen((cc.Peripheral.wrap(addr) : Dynamic), addr); } /** Get all connected modems. **/ - public function getModems(): Array { + public function getModems():Array { var allModems = cc.Peripheral.getNames().toArray().filter(s -> cc.Peripheral.getType(s) == "modem"); - return allModems.map(s -> return new Modem((cc.Peripheral.wrap(s): Dynamic),s)); + return allModems.map(s -> return new Modem((cc.Peripheral.wrap(s) : Dynamic), s)); } /** Get all connected wireless modems. **/ - public function getWirelessModems(): Array { + public function getWirelessModems():Array { return getModems().filter(modem -> return modem.isWireless()); } /** Get all connected wired modems. **/ - public function getWiredModems(): Array { + public function getWiredModems():Array { return getModems().filter(modem -> return !modem.isWireless()); } - public function getAllPeripheralsAddr(): Array { + public function getAllPeripheralsAddr():Array { return cc.Peripheral.getNames().toArray(); } } diff --git a/src/kernel/peripherals/Screen.hx b/src/kernel/peripherals/Screen.hx index fb682c0..f4f24ae 100644 --- a/src/kernel/peripherals/Screen.hx +++ b/src/kernel/peripherals/Screen.hx @@ -7,17 +7,16 @@ import lib.TermWriteable; import util.Vec.Vec2; import util.Color; -class Screen implements TermWriteable{ +class Screen implements TermWriteable { private final nativ:cc.periphs.Monitor.Monitor; private final addr:String; + private final onResizeTrigger:SignalTrigger>; - private final onResizeTrigger: SignalTrigger>; - public var onResize(default,null):Signal>; - + public var onResize(default, null):Signal>; @:allow(kernel.peripherals) - public function new(nativePeripherals: cc.periphs.Monitor.Monitor,addr: String) { + public function new(nativePeripherals:cc.periphs.Monitor.Monitor, addr:String) { this.onResizeTrigger = Signal.trigger(); this.onResize = onResizeTrigger.asSignal(); @@ -25,7 +24,7 @@ class Screen implements TermWriteable{ this.addr = addr; KernelEvents.instance.onMonitorResize.handle(addr -> { - if (addr == this.addr){ + if (addr == this.addr) { onResizeTrigger.trigger(getSize()); } }); @@ -33,45 +32,45 @@ class Screen implements TermWriteable{ setTextScale(0.5); } - public function getAddr(): String { + public function getAddr():String { return this.addr; } - public function getTextScale(): Float { + public function getTextScale():Float { return nativ.getTextScale(); } - public function setTextScale(scale: Float) { + public function setTextScale(scale:Float) { nativ.setTextScale(scale); } public function write(text:String) { - nativ.write(text); - } + nativ.write(text); + } public function scroll(y:Int) { - nativ.scroll(y); - } + nativ.scroll(y); + } public function getCursorPos():Vec2 { var rtn = nativ.getCursorPos(); - return { - x: rtn.x - 1, - y: rtn.y - 1 - } + return { + x: rtn.x - 1, + y: rtn.y - 1 + } } public function setCursorPos(x:Int, y:Int) { - nativ.setCursorPos(x + 1,y + 1); - } + nativ.setCursorPos(x + 1, y + 1); + } public function getCursorBlink():Bool { - return nativ.getCursorBlink(); + return nativ.getCursorBlink(); } public function setCursorBlink(blink:Bool) { - nativ.setCursorBlink(blink); - } + nativ.setCursorBlink(blink); + } public function getSize():Vec2 { // FIXME: this will not compile. Has to be changes upstream @@ -83,28 +82,28 @@ class Screen implements TermWriteable{ } public function clear() { - nativ.clear(); - } + nativ.clear(); + } public function clearLine() { - nativ.clearLine(); - } + nativ.clearLine(); + } public function getTextColor():Color { return ColorConvert.ccToColor(nativ.getTextColor()); } public function setTextColor(colour:Color) { - nativ.setTextColor(ColorConvert.colorToCC(colour)); - } + nativ.setTextColor(ColorConvert.colorToCC(colour)); + } public function getBackgroundColor():Color { return ColorConvert.ccToColor(nativ.getBackgroundColor()); } public function setBackgroundColor(color:Color) { - nativ.setBackgroundColor(ColorConvert.colorToCC(color)); - } + nativ.setBackgroundColor(ColorConvert.colorToCC(color)); + } public function isColor():Bool { return nativ.isColor(); diff --git a/src/kernel/ui/TermBuffer.hx b/src/kernel/ui/TermBuffer.hx index 1c08ab8..1ad7dfa 100644 --- a/src/kernel/ui/TermBuffer.hx +++ b/src/kernel/ui/TermBuffer.hx @@ -13,27 +13,28 @@ import lib.TermWriteable; } class TermBuffer implements TermWriteable { - /** format [y][x]. First index is the line. Second index the char in the line. **/ - private var screenBuffer: Array>; - private var cursorPos: Vec2 = {x: 0, y: 0}; - private var currentTextColor: Color = White; - private var currentBgColor: Color = Black; - private var size: Vec2 = {x: 51,y:19}; // Default size set to default size of the main terminal + private var screenBuffer:Array>; + + private var cursorPos:Vec2 = {x: 0, y: 0}; + private var currentTextColor:Color = White; + private var currentBgColor:Color = Black; + private var size:Vec2 = {x: 51, y: 19}; // Default size set to default size of the main terminal + + public var onResize(default, null):Signal>; - public var onResize(default,null):Signal>; private final onResizeTrigger:SignalTrigger>; - + public function new() { this.onResizeTrigger = Signal.trigger(); this.onResize = onResizeTrigger.asSignal(); initScreenBuffer(size); } - private function setSize(size: Vec2) { - if (this.size != size){ + private function setSize(size:Vec2) { + if (this.size != size) { this.onResizeTrigger.trigger(size); } @@ -41,80 +42,82 @@ class TermBuffer implements TermWriteable { updateScreenBufferSize(size); } - private function updateScreenBufferSize(size: Vec2) { + private function updateScreenBufferSize(size:Vec2) { // TODO } - private function initScreenBuffer(size: Vec2) { + private function initScreenBuffer(size:Vec2) { screenBuffer = new Array(); - for (y in 0...size.y){ + for (y in 0...size.y) { screenBuffer[y] = new Array(); - for (x in 0...size.x){ + for (x in 0...size.x) { screenBuffer[y][x] = { char: " ", textColor: White, bg: Black, } } - } + } } - private function copyBufferToTarget(target: TermWriteable) { - target.setCursorPos(0,0); + private function copyBufferToTarget(target:TermWriteable) { + target.setCursorPos(0, 0); target.setBackgroundColor(Black); target.setTextColor(White); - var tmpFgColor: Color = White; - var tmpBgColor: Color = Black; + var tmpFgColor:Color = White; + var tmpBgColor:Color = Black; - for (y => line in screenBuffer){ - for(x => pixel in line){ - if (tmpFgColor != pixel.textColor){ + for (y => line in screenBuffer) { + for (x => pixel in line) { + if (tmpFgColor != pixel.textColor) { tmpFgColor = pixel.textColor; target.setTextColor(pixel.textColor); } - if (tmpBgColor != pixel.bg){ + if (tmpBgColor != pixel.bg) { tmpBgColor = pixel.bg; target.setBackgroundColor(pixel.bg); } - target.setCursorPos(x,y); + target.setCursorPos(x, y); target.write(pixel.char); } } - target.setCursorPos(cursorPos.x,cursorPos.y); + target.setCursorPos(cursorPos.x, cursorPos.y); target.setTextColor(currentTextColor); target.setBackgroundColor(currentBgColor); } - private function safeWriteScreenBuffer(pos: Vec2,char: String) { - if (screenBuffer.length > pos.y && screenBuffer[pos.y].length > pos.x){ + private function safeWriteScreenBuffer(pos:Vec2, char:String) { + if (screenBuffer.length > pos.y && screenBuffer[pos.y].length > pos.x) { screenBuffer[pos.y][pos.x].char = char; screenBuffer[pos.y][pos.x].bg = currentBgColor; screenBuffer[pos.y][pos.x].textColor = currentTextColor; } } - // // TermWriteable functions - // + // public function write(text:String) { - for (i in 0...text.length){ - safeWriteScreenBuffer({x: cursorPos.x,y: cursorPos.y},text.charAt(i)); - cursorPos = {y: cursorPos.y,x: cursorPos.x + 1}; - } + for (i in 0...text.length) { + safeWriteScreenBuffer({x: cursorPos.x, y: cursorPos.y}, text.charAt(i)); + cursorPos = {y: cursorPos.y, x: cursorPos.x + 1}; + } } public function scroll(y:Int) { - screenBuffer.unshift([for (i in 0...size.x) { - char: " ", - textColor: White, // TODO: maybe replace with current bg/text color. Check nativ implementation - bg: Black - }]); + screenBuffer.unshift([ + for (i in 0...size.x) + { + char: " ", + textColor: White, // TODO: maybe replace with current bg/text color. Check nativ implementation + bg: Black + } + ]); } public function getCursorPos():Vec2 { @@ -145,8 +148,8 @@ class TermBuffer implements TermWriteable { } public function clearLine() { - if (screenBuffer.length > cursorPos.y){ - screenBuffer[cursorPos.y] = [for(x in 0...size.x){textColor: White,char: " ",bg: Black}]; + if (screenBuffer.length > cursorPos.y) { + screenBuffer[cursorPos.y] = [for (x in 0...size.x) {textColor: White, char: " ", bg: Black}]; } } diff --git a/src/kernel/ui/VirtualTermWriter.hx b/src/kernel/ui/VirtualTermWriter.hx index 56807f7..d60ad9e 100644 --- a/src/kernel/ui/VirtualTermWriter.hx +++ b/src/kernel/ui/VirtualTermWriter.hx @@ -7,159 +7,159 @@ import util.Color; import lib.TermWriteable; class VirtualTermWriter implements TermWriteable extends TermBuffer { - private static final defaultSize:Vec2 = {x: 50,y: 50}; + private static final defaultSize:Vec2 = {x: 50, y: 50}; - private var target: TermWriteable; - private var enabled:Bool = false; - private var onResizeLink: CallbackLink; + private var target:TermWriteable; + private var enabled:Bool = false; + private var onResizeLink:CallbackLink; - public function new(?target: TermWriteable) { - setTarget(target); + public function new(?target:TermWriteable) { + setTarget(target); - if (enabled){ - enable(); - } + if (enabled) { + enable(); + } - super(); - } + super(); + } - public function enable() { - if (target != null){ - enabled = true; - super.copyBufferToTarget(target); - } - } + public function enable() { + if (target != null) { + enabled = true; + super.copyBufferToTarget(target); + } + } - public function disable() { - enabled = false; - } + public function disable() { + enabled = false; + } - public inline function isEnabled(): Bool { - return enabled; - } + public inline function isEnabled():Bool { + return enabled; + } - public function setTarget(newTarget: TermWriteable) { - if (newTarget != null){ - super.setSize(newTarget.getSize()); + public function setTarget(newTarget:TermWriteable) { + if (newTarget != null) { + super.setSize(newTarget.getSize()); - // Remove old target event listner - if (onResizeLink != null){ - onResizeLink.cancel(); - } + // Remove old target event listner + if (onResizeLink != null) { + onResizeLink.cancel(); + } - // Add new target event listner - onResizeLink = newTarget.onResize.handle(newSize -> { - setSuperSize(newSize); - }); + // Add new target event listner + onResizeLink = newTarget.onResize.handle(newSize -> { + setSuperSize(newSize); + }); - target = newTarget; - } - } + target = newTarget; + } + } - private function setSuperSize(size: Vec2) { - super.setSize(target.getSize()); - } - - // - // TermWriteable functions. - // + private function setSuperSize(size:Vec2) { + super.setSize(target.getSize()); + } + + // + // TermWriteable functions. + // public override function write(text:String) { - if (isEnabled()){ - target.write(text); - } - - super.write(text); - } + if (isEnabled()) { + target.write(text); + } + + super.write(text); + } public override function scroll(y:Int) { - if (isEnabled()){ - target.scroll(y); - } - super.scroll(y); - } + if (isEnabled()) { + target.scroll(y); + } + super.scroll(y); + } public override function getCursorPos():Vec2 { - if (isEnabled()){ - return target.getCursorPos(); - }else{ - return super.getCursorPos(); - } + if (isEnabled()) { + return target.getCursorPos(); + } else { + return super.getCursorPos(); + } } public override function setCursorPos(x:Int, y:Int) { - if (isEnabled()){ - target.setCursorPos(x,y); - } + if (isEnabled()) { + target.setCursorPos(x, y); + } - super.setCursorPos(x,y); - } + super.setCursorPos(x, y); + } public override function getCursorBlink():Bool { throw new haxe.exceptions.NotImplementedException(); } public override function setCursorBlink(blink:Bool) { - // TODO - } + // TODO + } public override function getSize():Vec2 { - // TODO: make sense ? - if (target != null){ - return target.getSize(); - } + // TODO: make sense ? + if (target != null) { + return target.getSize(); + } - return defaultSize; + return defaultSize; } public override function clear() { - if (isEnabled()){ - target.clear(); - } - - super.clear(); - } + if (isEnabled()) { + target.clear(); + } + + super.clear(); + } public override function clearLine() { - if (isEnabled()){ - target.clearLine(); - } + if (isEnabled()) { + target.clearLine(); + } - super.clearLine(); - } + super.clearLine(); + } public override function getTextColor():Color { - if (isEnabled()){ - return target.getTextColor(); - } + if (isEnabled()) { + return target.getTextColor(); + } - return super.getTextColor(); + return super.getTextColor(); } public override function setTextColor(colour:Color) { - if (isEnabled()){ - target.setTextColor(colour); - } + if (isEnabled()) { + target.setTextColor(colour); + } - super.setTextColor(colour); - } + super.setTextColor(colour); + } public override function getBackgroundColor():Color { - if (isEnabled()){ - return target.getBackgroundColor(); - } + if (isEnabled()) { + return target.getBackgroundColor(); + } - return super.getBackgroundColor(); + return super.getBackgroundColor(); } public override function setBackgroundColor(color:Color) { - if (isEnabled()){ - target.setBackgroundColor(color); - } + if (isEnabled()) { + target.setBackgroundColor(color); + } - super.setBackgroundColor(color); - } + super.setBackgroundColor(color); + } public override function isColor():Bool { throw new haxe.exceptions.NotImplementedException(); } -} \ No newline at end of file +} diff --git a/src/kernel/ui/WindowContext.hx b/src/kernel/ui/WindowContext.hx index ca3170c..ba8b72d 100644 --- a/src/kernel/ui/WindowContext.hx +++ b/src/kernel/ui/WindowContext.hx @@ -8,120 +8,118 @@ import util.Vec.Vec2; import lib.TermWriteable; class WindowContext implements TermWriteable { - private final writer:VirtualTermWriter; + private final writer:VirtualTermWriter; - public var clickSignal(default,null):Signal<{button: ButtonType, pos: Vec2}>; - public var keySignal(default,null):Signal<{keyCode: Int, isHeld: Bool}>; - public var keyUpSignal(default,null):Signal; - public var mouseDragSignal(default,null):Signal<{button: ButtonType, pos: Vec2}>; - public var mouseScrollSignal(default,null):Signal<{dir: Int,pos: Vec2}>; - public var mouseUpSignal(default,null):Signal<{button: ButtonType,pos: Vec2}>; - public var pasteSignal(default,null):Signal ; + public var clickSignal(default, null):Signal<{button:ButtonType, pos:Vec2}>; + public var keySignal(default, null):Signal<{keyCode:Int, isHeld:Bool}>; + public var keyUpSignal(default, null):Signal; + public var mouseDragSignal(default, null):Signal<{button:ButtonType, pos:Vec2}>; + public var mouseScrollSignal(default, null):Signal<{dir:Int, pos:Vec2}>; + public var mouseUpSignal(default, null):Signal<{button:ButtonType, pos:Vec2}>; + public var pasteSignal(default, null):Signal; - @:allow(kernel.ui.WindowManager) private final clickTrigger:SignalTrigger<{button: ButtonType, pos: Vec2}>; - @:allow(kernel.ui.WindowManager) private final keyTrigger:SignalTrigger<{keyCode: Int, isHeld: Bool}>; - @:allow(kernel.ui.WindowManager) private final keyUpTrigger:SignalTrigger; - @:allow(kernel.ui.WindowManager) private final mouseDragTrigger:SignalTrigger<{button: ButtonType, pos: Vec2}>; - @:allow(kernel.ui.WindowManager) private final mouseScrollTrigger:SignalTrigger<{dir: Int,pos: Vec2}>; - @:allow(kernel.ui.WindowManager) private final mouseUpTrigger:SignalTrigger<{button: ButtonType,pos: Vec2}>; - @:allow(kernel.ui.WindowManager) private final pasteTrigger:SignalTrigger; + @:allow(kernel.ui.WindowManager) private final clickTrigger:SignalTrigger<{button:ButtonType, pos:Vec2}>; + @:allow(kernel.ui.WindowManager) private final keyTrigger:SignalTrigger<{keyCode:Int, isHeld:Bool}>; + @:allow(kernel.ui.WindowManager) private final keyUpTrigger:SignalTrigger; + @:allow(kernel.ui.WindowManager) private final mouseDragTrigger:SignalTrigger<{button:ButtonType, pos:Vec2}>; + @:allow(kernel.ui.WindowManager) private final mouseScrollTrigger:SignalTrigger<{dir:Int, pos:Vec2}>; + @:allow(kernel.ui.WindowManager) private final mouseUpTrigger:SignalTrigger<{button:ButtonType, pos:Vec2}>; + @:allow(kernel.ui.WindowManager) private final pasteTrigger:SignalTrigger; + public function new(writer:VirtualTermWriter) { + this.writer = writer; + this.onResize = writer.onResize; - public function new(writer: VirtualTermWriter) { - this.writer = writer; - this.onResize = writer.onResize; + this.clickTrigger = Signal.trigger(); + this.keyTrigger = Signal.trigger(); + this.keyUpTrigger = Signal.trigger(); + this.mouseDragTrigger = Signal.trigger(); + this.mouseScrollTrigger = Signal.trigger(); + this.mouseUpTrigger = Signal.trigger(); + this.pasteTrigger = Signal.trigger(); - this.clickTrigger = Signal.trigger(); - this.keyTrigger = Signal.trigger(); - this.keyUpTrigger = Signal.trigger(); - this.mouseDragTrigger = Signal.trigger(); - this.mouseScrollTrigger = Signal.trigger(); - this.mouseUpTrigger = Signal.trigger(); - this.pasteTrigger = Signal.trigger(); + this.clickSignal = clickTrigger.asSignal(); + this.keySignal = keyTrigger.asSignal(); + this.keyUpSignal = keyUpTrigger.asSignal(); + this.mouseDragSignal = mouseDragTrigger.asSignal(); + this.mouseScrollSignal = mouseScrollTrigger.asSignal(); + this.mouseUpSignal = mouseUpTrigger.asSignal(); + this.pasteSignal = pasteTrigger.asSignal(); + } - this.clickSignal = clickTrigger.asSignal(); - this.keySignal = keyTrigger.asSignal(); - this.keyUpSignal = keyUpTrigger.asSignal(); - this.mouseDragSignal = mouseDragTrigger.asSignal(); - this.mouseScrollSignal = mouseScrollTrigger.asSignal(); - this.mouseUpSignal = mouseUpTrigger.asSignal(); - this.pasteSignal = pasteTrigger.asSignal(); + public var onResize(default, null):Signal>; - } + @:allow(kernel.ui) + private function setTarget(target:TermWriteable) { + writer.setTarget(target); + } - public var onResize(default, null):Signal>; + @:allow(kernel.ui) + private function enable() { + writer.enable(); + } - @:allow(kernel.ui) - private function setTarget(target: TermWriteable) { - writer.setTarget(target); - } + @:allow(kernel.ui) + private function disable() { + writer.disable(); + } - @:allow(kernel.ui) - private function enable() { - writer.enable(); - } - - @:allow(kernel.ui) - private function disable() { - writer.disable(); - } - - @:allow(kernel.ui) - private function isEnabled() { - return writer.isEnabled(); - } + @:allow(kernel.ui) + private function isEnabled() { + return writer.isEnabled(); + } public function write(text:String) { - writer.write(text); - } + writer.write(text); + } public function scroll(y:Int) { - writer.scroll(y); - } + writer.scroll(y); + } public function getCursorPos():Vec2 { return writer.getCursorPos(); } public function setCursorPos(x:Int, y:Int) { - writer.setCursorPos(x,y); - } + writer.setCursorPos(x, y); + } public function getCursorBlink():Bool { return writer.getCursorBlink(); } public function setCursorBlink(blink:Bool) { - writer.setCursorBlink(blink); - } + writer.setCursorBlink(blink); + } public function getSize():Vec2 { return writer.getSize(); } public function clear() { - writer.clear(); - } + writer.clear(); + } public function clearLine() { - writer.clearLine(); - } + writer.clearLine(); + } public function getTextColor():Color { return writer.getTextColor(); } public function setTextColor(colour:Color) { - writer.setTextColor(colour); - } + writer.setTextColor(colour); + } public function getBackgroundColor():Color { return writer.getBackgroundColor(); } public function setBackgroundColor(color:Color) { - writer.setBackgroundColor(color); - } + writer.setBackgroundColor(color); + } public function isColor():Bool { return writer.isColor(); diff --git a/src/kernel/ui/WindowManager.hx b/src/kernel/ui/WindowManager.hx index 452359f..0a014c4 100644 --- a/src/kernel/ui/WindowManager.hx +++ b/src/kernel/ui/WindowManager.hx @@ -4,102 +4,98 @@ import lib.TermWriteable; import kernel.peripherals.Peripherals.Peripheral; class WindowManager { - public static var instance:WindowManager; + public static var instance:WindowManager; - @:allow(kernel.Init) - private function new() { + @:allow(kernel.Init) + private function new() { + KernelEvents.instance.onKey.handle(params -> { + if (currentMainContext != null) { + currentMainContext.keyTrigger.trigger(params); + } + }); - KernelEvents.instance.onKey.handle(params ->{ - if (currentMainContext != null){ - currentMainContext.keyTrigger.trigger(params); - } - }); - - KernelEvents.instance.onKeyUp.handle(keyCode -> { - if (currentMainContext != null){ - currentMainContext.keyUpTrigger.trigger(keyCode); - } - }); + KernelEvents.instance.onKeyUp.handle(keyCode -> { + if (currentMainContext != null) { + currentMainContext.keyUpTrigger.trigger(keyCode); + } + }); - KernelEvents.instance.onMouseClick.handle(params ->{ - if (currentMainContext != null){ - currentMainContext.clickTrigger.trigger(params); - } - }); - - KernelEvents.instance.onMouseDrag.handle(params ->{ - if (currentMainContext != null){ - currentMainContext.mouseDragTrigger.trigger(params); - } - }); + KernelEvents.instance.onMouseClick.handle(params -> { + if (currentMainContext != null) { + currentMainContext.clickTrigger.trigger(params); + } + }); - KernelEvents.instance.onMouseScroll.handle(params ->{ - if (currentMainContext != null){ - currentMainContext.mouseScrollTrigger.trigger(params); - } - }); + KernelEvents.instance.onMouseDrag.handle(params -> { + if (currentMainContext != null) { + currentMainContext.mouseDragTrigger.trigger(params); + } + }); - KernelEvents.instance.onMouseUp.handle(params ->{ - if (currentMainContext != null){ - currentMainContext.mouseUpTrigger.trigger(params); - } - }); + KernelEvents.instance.onMouseScroll.handle(params -> { + if (currentMainContext != null) { + currentMainContext.mouseScrollTrigger.trigger(params); + } + }); - KernelEvents.instance.onPaste.handle(text->{ - if (currentMainContext != null){ - currentMainContext.pasteTrigger.trigger(text); - } - }); + KernelEvents.instance.onMouseUp.handle(params -> { + if (currentMainContext != null) { + currentMainContext.mouseUpTrigger.trigger(params); + } + }); - KernelEvents.instance.onMonitorTouch.handle(params ->{ - // TODO - }); - } + KernelEvents.instance.onPaste.handle(text -> { + if (currentMainContext != null) { + currentMainContext.pasteTrigger.trigger(text); + } + }); - private var currentMainContext:WindowContext; - private final allContexts:Array = new Array(); - private final outputMap:Map = new Map(); + KernelEvents.instance.onMonitorTouch.handle(params -> { + // TODO + }); + } - public function createNewContext(): WindowContext { - var newContext = new WindowContext(new VirtualTermWriter()); + private var currentMainContext:WindowContext; + private final allContexts:Array = new Array(); + private final outputMap:Map = new Map(); - allContexts.push(newContext); + public function createNewContext():WindowContext { + var newContext = new WindowContext(new VirtualTermWriter()); - // newContext.setTarget(MainTerm.instance); - newContext.enable(); - currentMainContext = newContext; + allContexts.push(newContext); - return newContext; - } + // newContext.setTarget(MainTerm.instance); + newContext.enable(); + currentMainContext = newContext; + return newContext; + } - public function getOutputs(): Array { - var arr = Peripheral.instance.getScreens().map(screen -> return screen.getAddr()); - arr.push("main"); - return arr; - } + public function getOutputs():Array { + var arr = Peripheral.instance.getScreens().map(screen -> return screen.getAddr()); + arr.push("main"); + return arr; + } - public function focusContextToOutput(context: WindowContext,output: String) { - var target: TermWriteable; - if (output == "main"){ - target = MainTerm.instance; - }else{ - target = Peripheral.instance.getScreen(output); + public function focusContextToOutput(context:WindowContext, output:String) { + var target:TermWriteable; + if (output == "main") { + target = MainTerm.instance; + } else { + target = Peripheral.instance.getScreen(output); - if (target == null){ - // output target not found - return; - } - } - + if (target == null) { + // output target not found + return; + } + } - if (outputMap.exists(output)){ - outputMap[output].disable(); - } + if (outputMap.exists(output)) { + outputMap[output].disable(); + } - - outputMap[output] = context; - context.setTarget(target); - context.enable(); - } + outputMap[output] = context; + context.setTarget(target); + context.enable(); + } } diff --git a/src/lib/IUserProgramm.hx b/src/lib/IUserProgramm.hx index 022450f..c868bcc 100644 --- a/src/lib/IUserProgramm.hx +++ b/src/lib/IUserProgramm.hx @@ -1,5 +1,5 @@ package lib; interface IUserProgramm { - public function getName(): String; + public function getName():String; } diff --git a/src/lib/TermIO.hx b/src/lib/TermIO.hx index ce122b9..a3c37d9 100644 --- a/src/lib/TermIO.hx +++ b/src/lib/TermIO.hx @@ -1,6 +1,5 @@ package lib; -import util.Vec.Vec2; import util.Color; import lib.TermWriteable; @@ -8,28 +7,28 @@ import lib.TermWriteable; Helpfull class for writing onto a `TermWriteable`. **/ class TermIO { - private var output: TermWriteable; + private var output:TermWriteable; - public function new(output: TermWriteable) { + public function new(output:TermWriteable) { this.output = output; output.clear(); - output.setCursorPos(0,0); + output.setCursorPos(0, 0); } - - public function writeLn(text: String,?textColor: Color){ - if (textColor != null){ + + public function writeLn(text:String, ?textColor:Color) { + if (textColor != null) { output.setTextColor(textColor); } var size = output.getSize(); - for (i in 0...Math.floor(text.length / size.x) + 1){ - output.write(text.substr(i * size.x,size.x)); + for (i in 0...Math.floor(text.length / size.x) + 1) { + output.write(text.substr(i * size.x, size.x)); newLine(); } - if (textColor != null){ + if (textColor != null) { output.setTextColor(White); } } @@ -37,12 +36,11 @@ class TermIO { private function newLine() { var cPos = output.getCursorPos(); - if (cPos.y == output.getSize().y){ + if (cPos.y == output.getSize().y) { output.scroll(1); - output.setCursorPos(0,cPos.y); - }else{ - output.setCursorPos(0,cPos.y + 1); + output.setCursorPos(0, cPos.y); + } else { + output.setCursorPos(0, cPos.y + 1); } - } } diff --git a/src/lib/TermWriteable.hx b/src/lib/TermWriteable.hx index b90da58..f4fb87f 100644 --- a/src/lib/TermWriteable.hx +++ b/src/lib/TermWriteable.hx @@ -6,34 +6,34 @@ import util.Color; import util.Vec.Vec2; /** - Interface describing a terminal. E.g. the main computer screen or a external screen. + Interface describing a terminal. E.g. the main computer screen or a external screen. **/ interface TermWriteable { + public var onResize(default, null):Signal>; - public var onResize(default,null): Signal>; + public function write(text:String):Void; + public function scroll(y:Int):Void; - public function write(text: String): Void; - public function scroll(y: Int): Void; + /** + Even though CC is 1 based we use a 0 based index. + **/ + public function getCursorPos():Vec2; - /** - Even though CC is 1 based we use a 0 based index. - **/ - public function getCursorPos(): Vec2; - - /** - Even though CC is 1 based we use a 0 based index. - **/ - public function setCursorPos(x: Int, y: Int):Void; - public function getCursorBlink(): Bool; - public function setCursorBlink(blink: Bool):Void; - public function getSize(): Vec2; - public function clear(): Void; - public function clearLine(): Void; - public function getTextColor():Color; - public function setTextColor(colour: Color):Void; - public function getBackgroundColor(): Color; - public function setBackgroundColor(color: Color):Void; - public function isColor(): Bool; - // setPaletteColor(...) - // getPaletteColor(colour) + /** + Even though CC is 1 based we use a 0 based index. + **/ + public function setCursorPos(x:Int, y:Int):Void; + + public function getCursorBlink():Bool; + public function setCursorBlink(blink:Bool):Void; + public function getSize():Vec2; + public function clear():Void; + public function clearLine():Void; + public function getTextColor():Color; + public function setTextColor(colour:Color):Void; + public function getBackgroundColor():Color; + public function setBackgroundColor(color:Color):Void; + public function isColor():Bool; + // setPaletteColor(...) + // getPaletteColor(colour) } diff --git a/src/lib/ui/Canvas.hx b/src/lib/ui/Canvas.hx index 34d3a27..df9c074 100644 --- a/src/lib/ui/Canvas.hx +++ b/src/lib/ui/Canvas.hx @@ -8,32 +8,32 @@ abstract Canvas(Array>) to Array> { this = [[]]; } - public inline function set(i:Vec2,pixel:Pixel) { - if (this[i.y] == null){ + public inline function set(i:Vec2, pixel:Pixel) { + if (this[i.y] == null) { this[i.y] = []; } this[i.y][i.x] = pixel; } - public inline function get(i:Vec2): Pixel { + public inline function get(i:Vec2):Pixel { return this[i.y][i.x]; } - public function keyValueIterator(): KeyValueIterator,Pixel>{ + public function keyValueIterator():KeyValueIterator, Pixel> { return new CanvasKeyValueIterator(this); } - public function combine(other: Canvas,offset: Vec2) { + public function combine(other:Canvas, offset:Vec2) { for (key => value in other) { - if (value == null){ + if (value == null) { continue; } var y = offset.y + key.y; var x = offset.x + key.x; - - if (this[y] == null){ + + if (this[y] == null) { this[y] = []; } @@ -41,14 +41,14 @@ abstract Canvas(Array>) to Array> { } } - public function hight(): Int { + public function hight():Int { return this.length; } public function maxWidth() { var max = 0; - for (i in 0...this.length){ - if (this[i].length > max){ + for (i in 0...this.length) { + if (this[i].length > max) { max = this[i].length; } } @@ -57,28 +57,28 @@ abstract Canvas(Array>) to Array> { } } -class CanvasKeyValueIterator{ +class CanvasKeyValueIterator { private final canvas:Array>; - private var index:Vec2 = {x: 0,y: 0}; + private var index:Vec2 = {x: 0, y: 0}; @:allow(lib.ui.Canvas) - private function new(canvas: Array>) { + private function new(canvas:Array>) { this.canvas = canvas; } - public function hasNext():Bool{ + public function hasNext():Bool { return index.y < canvas.length && index.x <= canvas[index.y].length; } - public function next():{key:Vec2, value:Pixel}{ - var oldIndex: Vec2 = this.index; + public function next():{key:Vec2, value:Pixel} { + var oldIndex:Vec2 = this.index; - if (index.x >= canvas[index.y].length){ + if (index.x >= canvas[index.y].length) { // Goto next line - index = {x:0,y: index.y + 1}; - }else{ + index = {x: 0, y: index.y + 1}; + } else { // Goto next pixel in line - index = {x:index.x + 1,y: index.y}; + index = {x: index.x + 1, y: index.y}; } return { diff --git a/src/lib/ui/IElement.hx b/src/lib/ui/IElement.hx index 8c56a9d..7da5e65 100644 --- a/src/lib/ui/IElement.hx +++ b/src/lib/ui/IElement.hx @@ -1,9 +1,10 @@ package lib.ui; using tink.CoreApi; + import util.Vec.Vec2; interface IElement { - public function render(bounds: Vec2): Canvas; - public var changed(default, null):Signal; + public function render(bounds:Vec2):Canvas; + public var changed(default, null):Signal; } diff --git a/src/lib/ui/Observable.hx b/src/lib/ui/Observable.hx index 6413ef7..46b9855 100644 --- a/src/lib/ui/Observable.hx +++ b/src/lib/ui/Observable.hx @@ -3,26 +3,26 @@ package lib.ui; using tink.CoreApi; class Observable { - private var value: T; - private var callbacks: CallbackList = new CallbackList(true); + private var value:T; + private var callbacks:CallbackList = new CallbackList(true); - public function new(value: T) { - this.value = value; - } + public function new(value:T) { + this.value = value; + } - public function set(value: T) { - if (value != this.value){ - this.value = value; - callbacks.invoke(value); - } - } + public function set(value:T) { + if (value != this.value) { + this.value = value; + callbacks.invoke(value); + } + } - public function get(): T { - return value; - } + public function get():T { + return value; + } - public function subscribe(callback: Callback):CallbackLink { - callback.invoke(value); - return callbacks.add(callback); - } + public function subscribe(callback:Callback):CallbackLink { + callback.invoke(value); + return callbacks.add(callback); + } } diff --git a/src/lib/ui/ReactiveUI.hx b/src/lib/ui/ReactiveUI.hx index 9849252..387595e 100644 --- a/src/lib/ui/ReactiveUI.hx +++ b/src/lib/ui/ReactiveUI.hx @@ -8,12 +8,12 @@ import kernel.ui.WindowContext; class ReactiveUI { private final context:WindowContext; private final children:Array; - - public function new(context: WindowContext,children: Array) { + + public function new(context:WindowContext, children:Array) { this.context = context; this.children = children; - for(child in children){ + for (child in children) { child.changed.handle(v -> { render(); }); @@ -23,37 +23,36 @@ class ReactiveUI { public function render() { var size = context.getSize(); - var screen = renderChildren(children,size); + var screen = renderChildren(children, size); writeToContext(screen); } - private function writeToContext(screen: Canvas) { - var currentBg: Color = Black; - var currentFg: Color = White; + private function writeToContext(screen:Canvas) { + var currentBg:Color = Black; + var currentFg:Color = White; var currentLine = 0; context.setBackgroundColor(currentBg); context.setTextColor(currentFg); - context.setCursorPos(0,0); + context.setCursorPos(0, 0); for (key => pixel in screen) { - - if (key.y != currentLine){ + if (key.y != currentLine) { currentLine = key.y; - context.setCursorPos(key.x,key.y); + context.setCursorPos(key.x, key.y); } - if (pixel == null){ + if (pixel == null) { context.write(' '); - }else{ - if (pixel.bg != currentBg){ + } else { + if (pixel.bg != currentBg) { context.setBackgroundColor(pixel.bg); currentBg = pixel.bg; } - if (pixel.textColor != currentFg){ + if (pixel.textColor != currentFg) { context.setTextColor(pixel.textColor); currentFg = pixel.textColor; } @@ -63,13 +62,13 @@ class ReactiveUI { } } - public static function renderChildren(children: Array,bounds: Vec2): Canvas { - var rtn: Canvas = new Canvas(); + public static function renderChildren(children:Array, bounds:Vec2):Canvas { + var rtn:Canvas = new Canvas(); - var writePoint: Vec2 = {x: 0,y: 0}; + var writePoint:Vec2 = {x: 0, y: 0}; for (child in children) { - if (bounds.y - writePoint.y <= 0){ + if (bounds.y - writePoint.y <= 0) { // No more space to render children Log.debug("No more space"); break; @@ -80,9 +79,9 @@ class ReactiveUI { y: bounds.y - writePoint.y }); - rtn.combine(childRender,writePoint); + rtn.combine(childRender, writePoint); - writePoint = {x: 0,y: writePoint.y + childRender.hight() }; + writePoint = {x: 0, y: writePoint.y + childRender.hight()}; } return rtn; diff --git a/src/lib/ui/TextElement.hx b/src/lib/ui/TextElement.hx index 8210e9e..3bd4802 100644 --- a/src/lib/ui/TextElement.hx +++ b/src/lib/ui/TextElement.hx @@ -7,41 +7,41 @@ import util.Vec.Vec2; import util.MathI; class TextElement implements IElement { - public var changed(default, null):Signal; - private var changedTrigger:SignalTrigger; - - private final text: Observable; - private final bg:Color; - private final fg:Color; + public var changed(default, null):Signal; - public function new(text: Observable,?background: Color = Black,?textColor: Color = White) { + private var changedTrigger:SignalTrigger; - setupTrigger(); + private final text:Observable; + private final bg:Color; + private final fg:Color; - this.text = text; - this.bg = background; - this.fg = textColor; + public function new(text:Observable, ?background:Color = Black, ?textColor:Color = White) { + setupTrigger(); - this.text.subscribe(value -> { - this.changedTrigger.trigger(null); - }); - } + this.text = text; + this.bg = background; + this.fg = textColor; - private function setupTrigger() { - changedTrigger = Signal.trigger(); - changed = changedTrigger.asSignal(); - } + this.text.subscribe(value -> { + this.changedTrigger.trigger(null); + }); + } - public function render(bounds: Vec2):Canvas { + private function setupTrigger() { + changedTrigger = Signal.trigger(); + changed = changedTrigger.asSignal(); + } + + public function render(bounds:Vec2):Canvas { var rtn = new Canvas(); - for (i in 0...MathI.min(Math.floor(text.get().length / bounds.x) + 1,bounds.y)){ - var line = (text.get().substr(i * bounds.x,bounds.x)); - for (char in 0...line.length) { - rtn.set({x: char,y: i},{textColor: fg,char: line.charAt(char),bg: bg}); - } + for (i in 0...MathI.min(Math.floor(text.get().length / bounds.x) + 1, bounds.y)) { + var line = (text.get().substr(i * bounds.x, bounds.x)); + for (char in 0...line.length) { + rtn.set({x: char, y: i}, {textColor: fg, char: line.charAt(char), bg: bg}); + } } - return rtn; + return rtn; } -} \ No newline at end of file +} diff --git a/src/util/BuildInfo.hx b/src/util/BuildInfo.hx index df51a60..a9d38b5 100644 --- a/src/util/BuildInfo.hx +++ b/src/util/BuildInfo.hx @@ -9,35 +9,34 @@ class BuildInfo { **/ public static macro function getGitCommitHash():haxe.macro.Expr.ExprOf { #if !display - var process = new sys.io.Process('git', ['rev-parse', 'HEAD']); - if (process.exitCode() != 0) { - var message = process.stderr.readAll().toString(); - var pos = haxe.macro.Context.currentPos(); - haxe.macro.Context.error("Cannot execute `git rev-parse HEAD`. " + message, pos); - } - - // read the output of the process - var commitHash:String = process.stdout.readLine(); - - // Generates a string expression - return macro $v{commitHash}; - #else - // `#if display` is used for code completion. In this case returning an - // empty string is good enough; We don't want to call git on every hint. - var commitHash:String = ""; - return macro $v{commitHash}; + var process = new sys.io.Process('git', ['rev-parse', 'HEAD']); + if (process.exitCode() != 0) { + var message = process.stderr.readAll().toString(); + var pos = haxe.macro.Context.currentPos(); + haxe.macro.Context.error("Cannot execute `git rev-parse HEAD`. " + message, pos); + } + + // read the output of the process + var commitHash:String = process.stdout.readLine(); + + // Generates a string expression + return macro $v{commitHash}; + #else + // `#if display` is used for code completion. In this case returning an + // empty string is good enough; We don't want to call git on every hint. + var commitHash:String = ""; + return macro $v{commitHash}; #end } /** Get the time the file was build. **/ - public static macro function buildTime(): haxe.macro.Expr.ExprOf { + public static macro function buildTime():haxe.macro.Expr.ExprOf { #if !display - return macro $v{Math.floor(Date.now().getTime())}; - #else - return macro $v{0}; + return macro $v{Math.floor(Date.now().getTime())}; + #else + return macro $v{0}; #end } } - \ No newline at end of file diff --git a/src/util/Color.hx b/src/util/Color.hx index 982e2cb..aa9bf19 100644 --- a/src/util/Color.hx +++ b/src/util/Color.hx @@ -25,7 +25,7 @@ enum Color { } class ColorConvert { - public static function colorToCC(color: Color): cc.Colors.Color { + public static function colorToCC(color:Color):cc.Colors.Color { switch color { case White: return Colors.white; @@ -66,7 +66,7 @@ class ColorConvert { }; } - public static function ccToColor(color: cc.Colors.Color): Color { + public static function ccToColor(color:cc.Colors.Color):Color { switch color { case 0: return White; diff --git a/src/util/Debug.hx b/src/util/Debug.hx index 01e4b39..669e256 100644 --- a/src/util/Debug.hx +++ b/src/util/Debug.hx @@ -16,8 +16,8 @@ class Debug { } #if webconsole - public static function printWeb(msg: String) { - HTTP.post("http://127.0.0.1:8080/",msg); + public static function printWeb(msg:String) { + HTTP.post("http://127.0.0.1:8080/", msg); } #end } diff --git a/src/util/EventBus.hx b/src/util/EventBus.hx index ce9839a..6cfcce2 100644 --- a/src/util/EventBus.hx +++ b/src/util/EventBus.hx @@ -10,7 +10,7 @@ class EventBusListner { private final eventName:String; @:allow(util.EventBus) - private function new(link: CallbackLink,eventName: String) { + private function new(link:CallbackLink, eventName:String) { this.link = link; this.eventName = eventName; } @@ -19,43 +19,40 @@ class EventBusListner { /** Generic event handler. **/ -class EventBus{ - private var listner: Map> = new Map(); +class EventBus { + private var listner:Map> = new Map(); - public function new() { + public function new() {} - } - - public function on(eventName: String, callback: Callback):EventBusListner{ - if (!listner.exists(eventName)){ + public function on(eventName:String, callback:Callback):EventBusListner { + if (!listner.exists(eventName)) { listner[eventName] = Signal.trigger(); } var link = listner[eventName].asSignal().handle(callback); - return new EventBusListner(link,eventName); + return new EventBusListner(link, eventName); } - public function once(eventName: String,callback: Callback):EventBusListner { - if (!listner.exists(eventName)){ + public function once(eventName:String, callback:Callback):EventBusListner { + if (!listner.exists(eventName)) { listner[eventName] = Signal.trigger(); } var link = listner[eventName].asSignal().handle(callback); - return new EventBusListner(link,eventName); + return new EventBusListner(link, eventName); } - public function emit(eventName: String, data: T) { - if (listner.exists(eventName)){ + public function emit(eventName:String, data:T) { + if (listner.exists(eventName)) { var trigger = listner[eventName]; trigger.trigger(data); } } - public function removeListner(id: EventBusListner) { + public function removeListner(id:EventBusListner) { if (!listner.exists(id.eventName)) { return; } id.link.cancel(); } - -} \ No newline at end of file +} diff --git a/src/util/Extender.hx b/src/util/Extender.hx index 7a7a7f5..0fa7a28 100644 --- a/src/util/Extender.hx +++ b/src/util/Extender.hx @@ -7,16 +7,16 @@ class LambdaExtender { Returns the first element if there are exectly one element present. Throws exception if not. **/ - static public function single(it : Iterable): T { - var elem: T = null; + static public function single(it:Iterable):T { + var elem:T = null; for (t in it) { - if (elem != null){ + if (elem != null) { throw new Exception("Multiple elements found"); } elem = t; } - if (elem == null){ + if (elem == null) { throw new Exception("No element found"); } @@ -26,16 +26,16 @@ class LambdaExtender { /** Like `single` but when no element was found return the default value. **/ - static public function singleOrDefault(it : Iterable, defaultValue: T): T { - var elem: T = null; + static public function singleOrDefault(it:Iterable, defaultValue:T):T { + var elem:T = null; for (t in it) { - if (elem != null){ + if (elem != null) { throw new Exception("Multiple elements found"); } elem = t; } - if (elem == null){ + if (elem == null) { return defaultValue; } @@ -46,7 +46,7 @@ class LambdaExtender { Returns the first element. Throws execption if no first element found. **/ - static public function first(it : Iterable): T { + static public function first(it:Iterable):T { for (t in it) { return t; } @@ -57,10 +57,10 @@ class LambdaExtender { /** Like `first` only if no first element was found it returns the defalt value. **/ - static public function firstOrDefault(it : Iterable, defaultValue: T): T { + static public function firstOrDefault(it:Iterable, defaultValue:T):T { var iter = it.iterator(); - if (iter.hasNext()){ + if (iter.hasNext()) { return iter.next(); } diff --git a/src/util/MathI.hx b/src/util/MathI.hx index 166a4a2..e207afa 100644 --- a/src/util/MathI.hx +++ b/src/util/MathI.hx @@ -1,19 +1,19 @@ package util; class MathI { - public static function max(a: Int, b:Int): Int { - if (a > b){ - return a; - }else{ - return b; - } - } + public static function max(a:Int, b:Int):Int { + if (a > b) { + return a; + } else { + return b; + } + } - public static function min(a: Int,b:Int): Int { - if (a < b){ - return a; - }else{ - return b; - } - } + public static function min(a:Int, b:Int):Int { + if (a < b) { + return a; + } else { + return b; + } + } } diff --git a/src/util/Promise.hx b/src/util/Promise.hx index 329d60b..9745e7d 100644 --- a/src/util/Promise.hx +++ b/src/util/Promise.hx @@ -6,35 +6,34 @@ import haxe.Exception; JS-like promise class. **/ class Promise { - private var thenCB: T->Void; - private var errorCB: Exception -> Void; - - public function then(cb: (data: T)->Void): Promise { + private var thenCB:T->Void; + private var errorCB:Exception->Void; + + public function then(cb:(data:T) -> Void):Promise { thenCB = cb; return this; } - public function error(cb: (err: Exception)->Void) { + public function error(cb:(err:Exception) -> Void) { errorCB = cb; } - public function new(func:(resolve:(T)->Void,reject:(Exception)->Void)->Void) { + public function new(func:(resolve:(T) -> Void, reject:(Exception) -> Void)->Void) { try { func(data -> { - if (thenCB != null){ + if (thenCB != null) { thenCB(data); } - },e -> { - if (errorCB != null){ + }, e -> { + if (errorCB != null) { errorCB(e); } }); - }catch(e:Exception){ - if (errorCB != null){ + } catch (e:Exception) { + if (errorCB != null) { errorCB(e); } } - } -} \ No newline at end of file +} diff --git a/src/util/Vec.hx b/src/util/Vec.hx index c32ccca..16a3a61 100644 --- a/src/util/Vec.hx +++ b/src/util/Vec.hx @@ -1,13 +1,12 @@ package util; @:structInit class Vec2 { - public final x:T; - public final y:T; + public final x:T; + public final y:T; } - @:structInit class Vec3 { - public final x:T; - public final y:T; - public final z:T; + public final x:T; + public final y:T; + public final z:T; }