Compare commits

...

6 Commits

Author SHA1 Message Date
016063e3be formatting 2023-07-30 23:34:43 +02:00
0fc2d4d397 made SRSC a rpc thing 2023-07-30 23:34:35 +02:00
da3f00acb6 added precommit hook 2023-07-30 23:33:51 +02:00
db50a93512 improved RPC macro 2023-07-30 23:18:51 +02:00
f3a13e4247 rpc now can handle args 2023-07-30 19:02:59 +02:00
91972107eb BIG FORMATING COMMIT 2023-07-30 15:55:22 +02:00
109 changed files with 1695 additions and 1704 deletions

1
.gitignore vendored
View File

@@ -1,2 +1,3 @@
/build /build
/node_modules /node_modules
/dump

View File

@@ -55,3 +55,7 @@ emulator:
.PHONY: webconsole .PHONY: webconsole
webconsole: webconsole:
node console.js node console.js
.PHONY: format
format:
haxelib run formatter -s src

15
pre-commit.sh Executable file
View File

@@ -0,0 +1,15 @@
#!/usr/bin/env sh
# Run:
# ln -s ../../pre-commit.sh .git/hooks/pre-commit
set -e
# format
make format
# build
make build

View File

@@ -7,4 +7,3 @@ class Startup {
main.run(); main.run();
} }
} }

View File

@@ -7,7 +7,6 @@ import kernel.ps.Process;
using tink.CoreApi; using tink.CoreApi;
class HelloWorld implements Process { class HelloWorld implements Process {
public function new() {} public function new() {}
public function run(handle:ProcessHandle) { public function run(handle:ProcessHandle) {
@@ -15,7 +14,7 @@ class HelloWorld implements Process {
var c = new HelloWorldServiceRPC(0); var c = new HelloWorldServiceRPC(0);
c.getNumber().handle((res)->{ c.getNumber(2, 3).handle((res) -> {
Log.debug("Got number: " + res); Log.debug("Got number: " + res);
}); });

View File

@@ -1,5 +1,6 @@
package bin; package bin;
import kernel.log.Log;
import macros.rpc.RPC; import macros.rpc.RPC;
import kernel.ps.ProcessHandle; import kernel.ps.ProcessHandle;
import kernel.ps.Process; import kernel.ps.Process;
@@ -19,7 +20,9 @@ class HelloWorldService implements Process {
} }
@rpc @rpc
public function getNumber():Int{ public function getNumber(arg1:Int, arg2:Int):Int {
Log.debug(arg1);
Log.debug(arg2);
return 42; return 42;
} }
} }

View File

@@ -6,7 +6,8 @@ import lib.CLIAppBase;
class Perf extends CLIAppBase { class Perf extends CLIAppBase {
public function new() { public function new() {
registerSyncSubcommand("inspect", (args) -> { registerSyncSubcommand("inspect", (args) -> {
if (args.length < 1) return false; if (args.length < 1)
return false;
var result = Peripheral.inspect(args[0]); var result = Peripheral.inspect(args[0]);

View File

@@ -54,7 +54,6 @@ class Service extends CLIAppBase {
}, "<name>"); }, "<name>");
registerSyncSubcommand("list", (args) -> { registerSyncSubcommand("list", (args) -> {
var list = ServiceManager.listRunning(); var list = ServiceManager.listRunning();
for (name in list) { for (name in list) {

View File

@@ -38,7 +38,8 @@ class Terminal implements Process {
// Add input event handlers // Add input event handlers
handle.addCallbackLink(this.ctx.onChar.handle(char -> { handle.addCallbackLink(this.ctx.onChar.handle(char -> {
if (this.runningPID > 0) return; if (this.runningPID > 0)
return;
this.input += char; this.input += char;
this.requestRender(); this.requestRender();
})); }));
@@ -47,11 +48,13 @@ class Terminal implements Process {
handle.addCallbackLink(this.ctx.onKey.handle(e -> { handle.addCallbackLink(this.ctx.onKey.handle(e -> {
switch (e.keyCode) { switch (e.keyCode) {
case 259: // Backspace case 259: // Backspace
if (this.runningPID > 0) return; if (this.runningPID > 0)
return;
this.input = this.input.substr(0, this.input.length - 1); this.input = this.input.substr(0, this.input.length - 1);
this.requestRender(); this.requestRender();
case 257: // Enter case 257: // Enter
if (this.runningPID > 0) return; if (this.runningPID > 0)
return;
this.backlog.push("> " + this.input); this.backlog.push("> " + this.input);
var command = this.input; var command = this.input;
this.input = ""; this.input = "";

View File

@@ -40,5 +40,4 @@ class Turtle extends CLIAppBase {
return false; return false;
} }
} }
} }

View File

@@ -1,10 +1,10 @@
package bin.exporter; package bin.exporter;
import kernel.KernelSettings;
import kernel.peripherals.Peripherals.Peripheral; import kernel.peripherals.Peripherals.Peripheral;
import lib.KVStore; import lib.KVStore;
import lib.exporter.Request; import lib.exporter.Request;
import kernel.ps.ProcessHandle; import kernel.ps.ProcessHandle;
import lib.RessourceNames;
import lib.exporter.Export; import lib.exporter.Export;
import kernel.ps.Process; import kernel.ps.Process;
import kernel.net.Package; import kernel.net.Package;
@@ -53,14 +53,14 @@ class ResManager implements Process {
} }
private function registerName(id:String) { private function registerName(id:String) {
return RessourceNames.register(id, Net.networkID); var rpc = new SiteRessourceControllerRPC(KernelSettings.siteController);
return rpc.register(id, Net.networkID);
} }
private function persist() { private function persist() {
var store = new KVStore("export"); var store = new KVStore("export");
var saveExports: Array<{name: String, addr: String, type: String}> = var saveExports:Array<{name:String, addr:String, type:String}> = [for (k => v in this.exports) {name: k, addr: v.getAddr(), type: v.getType()}];
[for (k => v in this.exports) {name: k, addr: v.getAddr(), type: v.getType()}];
store.set("exports", saveExports); store.set("exports", saveExports);
@@ -86,6 +86,5 @@ class ResManager implements Process {
handle.writeLine('Loaded export: ${export.name} on ${export.addr}'); handle.writeLine('Loaded export: ${export.name} on ${export.addr}');
} }
} }
} }

View File

@@ -41,11 +41,16 @@ class PFClient implements Process {
var childre:Array<UIElement> = [ var childre:Array<UIElement> = [
new TextElement('Acc: ${acc}'), new TextElement('Acc: ${acc}'),
new TextElement('Pos: X:${pos.x} Y:${pos.y} Z:${pos.z}'), new TextElement('Pos: X:${pos.x} Y:${pos.y} Z:${pos.z}'),
new TextElement('UPDATE', { style: {bgColor: Gray}, uiEvents: {onClick: () -> { new TextElement('UPDATE', {
style: {bgColor: Gray},
uiEvents: {
onClick: () -> {
kernel.gps.GPS.locate().handle((pos) -> { kernel.gps.GPS.locate().handle((pos) -> {
this.requestRender(); this.requestRender();
}); });
}}}), }
}
}),
]; ];
this.root.setChildren(childre); this.root.setChildren(childre);

View File

@@ -1,7 +1,7 @@
package bin.srsc; package bin.srsc;
import kernel.KernelSettings;
import kernel.net.Package.NetworkID; import kernel.net.Package.NetworkID;
import lib.RessourceNames;
import lib.CLIAppBase; import lib.CLIAppBase;
using tink.CoreApi; using tink.CoreApi;
@@ -14,7 +14,9 @@ class CLI extends CLIAppBase {
return Future.sync(false); return Future.sync(false);
} }
return RessourceNames.get(args[0]).map((res) -> { var rpc = new SiteRessourceControllerRPC(KernelSettings.siteController);
return rpc.get(args[0]).map((res) -> {
switch (res) { switch (res) {
case Success(data): case Success(data):
if (data == null) { if (data == null) {
@@ -41,7 +43,9 @@ class CLI extends CLIAppBase {
return Future.sync(false); return Future.sync(false);
} }
return RessourceNames.register(args[0], id).map((res) -> { var rpc = new SiteRessourceControllerRPC(KernelSettings.siteController);
return rpc.register(args[0], id).map((res) -> {
switch (res) { switch (res) {
case Success(data): case Success(data):
handle.writeLine("Success"); handle.writeLine("Success");
@@ -59,20 +63,26 @@ class CLI extends CLIAppBase {
return Future.sync(false); return Future.sync(false);
} }
return RessourceNames.unregister(args[0]).map((res) -> { var rpc = new SiteRessourceControllerRPC(KernelSettings.siteController);
switch (res) {
case Success(data):
handle.writeLine("Success");
case Failure(error):
handle.writeLine("Error: " + error);
}
return true; // FIXME
}); return Future.sync(true);
// return rpc.unregister(args[0]).map((res) -> {
// switch (res) {
// case Success(_):
// handle.writeLine("Success");
// case Failure(error):
// handle.writeLine("Error: " + error);
// }
// return true;
// });
}, "<name>"); }, "<name>");
registerAsyncSubcommand("list", (args) -> { registerAsyncSubcommand("list", (args) -> {
return RessourceNames.list().map((res) -> { var rpc = new SiteRessourceControllerRPC(KernelSettings.siteController);
return rpc.list().map((res) -> {
switch (res) { switch (res) {
case Success(data): case Success(data):
for (name in data) { for (name in data) {

View File

@@ -1,36 +0,0 @@
package bin.srsc;
import kernel.net.Package.NetworkID;
typedef GetRequest = {
public var ?type:String;
public var name:String;
}
typedef GetResponse = {
public var success:Bool;
public var netID:NetworkID;
}
typedef RegisterRequest = {
public var ?type:String;
public var name:String;
public var netID:NetworkID;
}
typedef RegisterResponse = {
public var success:Bool;
}
typedef UnregisterRequest = {
public var ?type:String;
public var name:String;
}
typedef UnregisterResponse = {
public var success:Bool;
}
typedef ListRequest = {
public var ?type:String;
}

View File

@@ -1,19 +1,20 @@
package bin.srsc; package bin.srsc;
import macros.rpc.RPC;
import lib.KVStore; import lib.KVStore;
import bin.srsc.PackageTypes;
import kernel.net.Package; import kernel.net.Package;
import kernel.ps.ProcessHandle; import kernel.ps.ProcessHandle;
import kernel.ps.Process; import kernel.ps.Process;
using tink.CoreApi;
/** /**
The SiteRessourceController is responsible for the management of ressources on the site. The SiteRessourceController is responsible for the management of ressources on the site.
It makes sure that ressources are have a unique id and that they are not duplicated. It makes sure that ressources are have a unique id and that they are not duplicated.
It also keeps track of the responsible NetID for each ressource. Kinda like a DNS. It also keeps track of the responsible NetID for each ressource. Kinda like a DNS.
**/ **/
@:build(macros.rpc.RPC.buildRPC())
class SiteRessourceController implements Process { class SiteRessourceController implements Process {
public static inline final SITE_CONTROLLER_RESSOURCE_MANAGER_PROTO:String = "srsc";
private var handle:ProcessHandle; private var handle:ProcessHandle;
private var ressources:Map<String, NetworkID>; private var ressources:Map<String, NetworkID>;
@@ -24,47 +25,10 @@ class SiteRessourceController implements Process {
load(); load();
// Register proto RPC.generateRPCPackageHandle();
kernel.net.Net.registerProto(SITE_CONTROLLER_RESSOURCE_MANAGER_PROTO, this.handleMsg);
}
private function handleMsg(pkg:GenericPackage) {
/*
There are 3 types of messages:
- Register a new ressource name
- Unregister a ressource name
- Get the responsible NetID for a ressource name
*/
switch (pkg.data.type) {
case "register":
pkg.respond(handleRegister(cast pkg.data));
case "unregister":
pkg.respond(handleUnregister(cast pkg.data));
case "get":
pkg.respond(handleGet(cast pkg.data));
case "list":
pkg.respond(list());
default:
handle.writeLine("Unknown message type: " + pkg.data.type);
}
}
private function handleGet(data:GetRequest):GetResponse {
var res = get(data.name);
return {success: res != null, netID: res};
}
private function handleRegister(data:RegisterRequest):RegisterResponse {
var res = register(data.name, data.netID);
return {success: res};
}
private function handleUnregister(data:UnregisterRequest):UnregisterResponse {
unregister(data.name);
return {success: true};
} }
@rpc
public function register(name:String, netID:NetworkID):Bool { public function register(name:String, netID:NetworkID):Bool {
if (ressources.exists(name) && ressources.get(name) != netID) { if (ressources.exists(name) && ressources.get(name) != netID) {
return false; return false;
@@ -75,18 +39,21 @@ class SiteRessourceController implements Process {
return true; return true;
} }
public function unregister(name:String) { @rpc
public function unregister(name:String):Void {
if (ressources.exists(name)) { if (ressources.exists(name)) {
ressources.remove(name); ressources.remove(name);
} }
save(); save();
} }
@rpc
public function get(name:String):Null<NetworkID> { public function get(name:String):Null<NetworkID> {
return ressources.get(name); return ressources.get(name);
} }
private inline function list():Array<String> { @rpc
public function list():Array<String> {
return [for (k in ressources.keys()) k]; return [for (k in ressources.keys()) k];
} }

View File

@@ -12,12 +12,16 @@ class EndOfLoop {
public static function endOfLoop(func:Void->Void) { public static function endOfLoop(func:Void->Void) {
backlog.push(func); backlog.push(func);
if (!isQueued) { OS.queueEvent("endofloop", null); } if (!isQueued) {
OS.queueEvent("endofloop", null);
}
} }
@:allow(kernel.KernelEvents) @:allow(kernel.KernelEvents)
private static function run() { private static function run() {
for (func in backlog) { func(); } for (func in backlog) {
func();
}
backlog = []; backlog = [];
isQueued = false; isQueued = false;
} }

View File

@@ -14,11 +14,9 @@ import lib.Debug;
import kernel.ui.WindowManager; import kernel.ui.WindowManager;
import kernel.peripherals.Peripherals.Peripheral; import kernel.peripherals.Peripherals.Peripheral;
import kernel.net.Net; import kernel.net.Net;
import kernel.DCEHack; // Important for DCE hack import kernel.DCEHack; // Important for DCE hack
class Init { class Init {
@:allow(kernel.KernelEvents) @:allow(kernel.KernelEvents)
private static var mainEvent:MainEvent; private static var mainEvent:MainEvent;

View File

@@ -19,6 +19,7 @@ class KernelEvents {
Depends on: (Nothing) Depends on: (Nothing)
**/ **/
public static var onAlarm(default, null):Signal<Int>; public static var onAlarm(default, null):Signal<Int>;
public static var onChar(default, null):Signal<String>; public static var onChar(default, null):Signal<String>;
public static var onDisk(default, null):Signal<String>; public static var onDisk(default, null):Signal<String>;
public static var onDiskEject(default, null):Signal<String>; public static var onDiskEject(default, null):Signal<String>;
@@ -147,7 +148,6 @@ class KernelEvents {
} }
public static function shutdown() { public static function shutdown() {
// clearing screens // clearing screens
for (screen in Peripheral.getAllScreens()) { for (screen in Peripheral.getAllScreens()) {
screen.reset(); screen.reset();
@@ -253,35 +253,65 @@ class KernelEvents {
@:allow(lib.Debug) @:allow(lib.Debug)
private static function printListenerCount() { private static function printListenerCount() {
if (onAlarmTrigger.getLength() > 0) Log.debug("onAlarm: " + onAlarmTrigger.getLength()); if (onAlarmTrigger.getLength() > 0)
if (onCharTrigger.getLength() > 0) Log.debug("onChar: " + onCharTrigger.getLength()); Log.debug("onAlarm: " + onAlarmTrigger.getLength());
if (onDiskTrigger.getLength() > 0) Log.debug("onDisk: " + onDiskTrigger.getLength()); if (onCharTrigger.getLength() > 0)
if (onDiskEjectTrigger.getLength() > 0) Log.debug("onDiskEject: " + onDiskEjectTrigger.getLength()); Log.debug("onChar: " + onCharTrigger.getLength());
if (onHttpCheckTrigger.getLength() > 0) Log.debug("onHttpCheck: " + onHttpCheckTrigger.getLength()); if (onDiskTrigger.getLength() > 0)
if (onHttpFailureTrigger.getLength() > 0) Log.debug("onHttpFailure: " + onHttpFailureTrigger.getLength()); Log.debug("onDisk: " + onDiskTrigger.getLength());
if (onHttpSuccessTrigger.getLength() > 0) Log.debug("onHttpSuccess: " + onHttpSuccessTrigger.getLength()); if (onDiskEjectTrigger.getLength() > 0)
if (onKeyTrigger.getLength() > 0) Log.debug("onKey: " + onKeyTrigger.getLength()); Log.debug("onDiskEject: " + onDiskEjectTrigger.getLength());
if (onKeyUpTrigger.getLength() > 0) Log.debug("onKeyUp: " + onKeyUpTrigger.getLength()); if (onHttpCheckTrigger.getLength() > 0)
if (onModemMessageTrigger.getLength() > 0) Log.debug("onModemMessage: " + onModemMessageTrigger.getLength()); Log.debug("onHttpCheck: " + onHttpCheckTrigger.getLength());
if (onMonitorResizeTrigger.getLength() > 0) Log.debug("onMonitorResize: " + onMonitorResizeTrigger.getLength()); if (onHttpFailureTrigger.getLength() > 0)
if (onMonitorTouchTrigger.getLength() > 0) Log.debug("onMonitorTouch: " + onMonitorTouchTrigger.getLength()); Log.debug("onHttpFailure: " + onHttpFailureTrigger.getLength());
if (onMouseClickTrigger.getLength() > 0) Log.debug("onMouseClick: " + onMouseClickTrigger.getLength()); if (onHttpSuccessTrigger.getLength() > 0)
if (onMouseDragTrigger.getLength() > 0) Log.debug("onMouseDrag: " + onMouseDragTrigger.getLength()); Log.debug("onHttpSuccess: " + onHttpSuccessTrigger.getLength());
if (onMouseScrollTrigger.getLength() > 0) Log.debug("onMouseScroll: " + onMouseScrollTrigger.getLength()); if (onKeyTrigger.getLength() > 0)
if (onMouseUpTrigger.getLength() > 0) Log.debug("onMouseUp: " + onMouseUpTrigger.getLength()); Log.debug("onKey: " + onKeyTrigger.getLength());
if (onPasteTrigger.getLength() > 0) Log.debug("onPaste: " + onPasteTrigger.getLength()); if (onKeyUpTrigger.getLength() > 0)
if (onPeripheralTrigger.getLength() > 0) Log.debug("onPeripheral: " + onPeripheralTrigger.getLength()); Log.debug("onKeyUp: " + onKeyUpTrigger.getLength());
if (onPeripheralDetachTrigger.getLength() > 0) Log.debug("onPeripheralDetach: " + onPeripheralDetachTrigger.getLength()); if (onModemMessageTrigger.getLength() > 0)
if (onRedstoneTrigger.getLength() > 0) Log.debug("onRedstone: " + onRedstoneTrigger.getLength()); Log.debug("onModemMessage: " + onModemMessageTrigger.getLength());
if (onSpeakerAudioEmptyTrigger.getLength() > 0) Log.debug("onSpeakerAudioEmpty: " + onSpeakerAudioEmptyTrigger.getLength()); if (onMonitorResizeTrigger.getLength() > 0)
if (onTaskCompleteTrigger.getLength() > 0) Log.debug("onTaskComplete: " + onTaskCompleteTrigger.getLength()); Log.debug("onMonitorResize: " + onMonitorResizeTrigger.getLength());
if (onTermResizeTrigger.getLength() > 0) Log.debug("onTermResize: " + onTermResizeTrigger.getLength()); if (onMonitorTouchTrigger.getLength() > 0)
if (onTerminateTrigger.getLength() > 0) Log.debug("onTerminate: " + onTerminateTrigger.getLength()); Log.debug("onMonitorTouch: " + onMonitorTouchTrigger.getLength());
if (onTimerTrigger.getLength() > 0) Log.debug("onTimer: " + onTimerTrigger.getLength()); if (onMouseClickTrigger.getLength() > 0)
if (onTurtleInventoryTrigger.getLength() > 0) Log.debug("onTurtleInventory: " + onTurtleInventoryTrigger.getLength()); Log.debug("onMouseClick: " + onMouseClickTrigger.getLength());
if (onWebsocketCloseTrigger.getLength() > 0) Log.debug("onWebsocketClose: " + onWebsocketCloseTrigger.getLength()); if (onMouseDragTrigger.getLength() > 0)
if (onWebsocketFailureTrigger.getLength() > 0) Log.debug("onWebsocketFailure: " + onWebsocketFailureTrigger.getLength()); Log.debug("onMouseDrag: " + onMouseDragTrigger.getLength());
if (onWebsocketMessageTrigger.getLength() > 0) Log.debug("onWebsocketMessage: " + onWebsocketMessageTrigger.getLength()); if (onMouseScrollTrigger.getLength() > 0)
if (onWebsocketSuccessTrigger.getLength() > 0) Log.debug("onWebsocketSuccess: " + onWebsocketSuccessTrigger.getLength()); Log.debug("onMouseScroll: " + onMouseScrollTrigger.getLength());
if (onMouseUpTrigger.getLength() > 0)
Log.debug("onMouseUp: " + onMouseUpTrigger.getLength());
if (onPasteTrigger.getLength() > 0)
Log.debug("onPaste: " + onPasteTrigger.getLength());
if (onPeripheralTrigger.getLength() > 0)
Log.debug("onPeripheral: " + onPeripheralTrigger.getLength());
if (onPeripheralDetachTrigger.getLength() > 0)
Log.debug("onPeripheralDetach: " + onPeripheralDetachTrigger.getLength());
if (onRedstoneTrigger.getLength() > 0)
Log.debug("onRedstone: " + onRedstoneTrigger.getLength());
if (onSpeakerAudioEmptyTrigger.getLength() > 0)
Log.debug("onSpeakerAudioEmpty: " + onSpeakerAudioEmptyTrigger.getLength());
if (onTaskCompleteTrigger.getLength() > 0)
Log.debug("onTaskComplete: " + onTaskCompleteTrigger.getLength());
if (onTermResizeTrigger.getLength() > 0)
Log.debug("onTermResize: " + onTermResizeTrigger.getLength());
if (onTerminateTrigger.getLength() > 0)
Log.debug("onTerminate: " + onTerminateTrigger.getLength());
if (onTimerTrigger.getLength() > 0)
Log.debug("onTimer: " + onTimerTrigger.getLength());
if (onTurtleInventoryTrigger.getLength() > 0)
Log.debug("onTurtleInventory: " + onTurtleInventoryTrigger.getLength());
if (onWebsocketCloseTrigger.getLength() > 0)
Log.debug("onWebsocketClose: " + onWebsocketCloseTrigger.getLength());
if (onWebsocketFailureTrigger.getLength() > 0)
Log.debug("onWebsocketFailure: " + onWebsocketFailureTrigger.getLength());
if (onWebsocketMessageTrigger.getLength() > 0)
Log.debug("onWebsocketMessage: " + onWebsocketMessageTrigger.getLength());
if (onWebsocketSuccessTrigger.getLength() > 0)
Log.debug("onWebsocketSuccess: " + onWebsocketSuccessTrigger.getLength());
} }
} }

View File

@@ -27,6 +27,7 @@ class KernelSettings {
public static var hostname(get, set):String; public static var hostname(get, set):String;
private static var _hostname:String = get("hostname"); private static var _hostname:String = get("hostname");
private static inline function get_hostname():String { private static inline function get_hostname():String {
return _hostname; return _hostname;
} }
@@ -40,6 +41,7 @@ class KernelSettings {
public static var siteController(get, set):NetworkID; public static var siteController(get, set):NetworkID;
private static var _siteController:NetworkID = get("siteController"); private static var _siteController:NetworkID = get("siteController");
private static function get_siteController():NetworkID { private static function get_siteController():NetworkID {
return _siteController; return _siteController;
} }

View File

@@ -5,7 +5,6 @@ import cc.FileSystem.FileHandle;
using tink.CoreApi; using tink.CoreApi;
abstract ReadHandle(FileHandle) from FileHandle { abstract ReadHandle(FileHandle) from FileHandle {
public inline function new(handle:FileHandle) { public inline function new(handle:FileHandle) {
this = handle; this = handle;
} }
@@ -28,7 +27,6 @@ abstract ReadHandle(FileHandle) from FileHandle {
} }
abstract WriteHandle(FileHandle) from FileHandle { abstract WriteHandle(FileHandle) from FileHandle {
public inline function new(handle:FileHandle) { public inline function new(handle:FileHandle) {
this = handle; this = handle;
} }
@@ -51,7 +49,6 @@ abstract WriteHandle(FileHandle) from FileHandle {
} }
abstract ReadBinaryHandle(FileHandle) from FileHandle { abstract ReadBinaryHandle(FileHandle) from FileHandle {
public inline function new(handle:FileHandle) { public inline function new(handle:FileHandle) {
this = handle; this = handle;
} }
@@ -82,7 +79,6 @@ abstract ReadBinaryHandle(FileHandle) from FileHandle {
} }
abstract WriteBinaryHandle(FileHandle) from FileHandle { abstract WriteBinaryHandle(FileHandle) from FileHandle {
public inline function new(handle:FileHandle) { public inline function new(handle:FileHandle) {
this = handle; this = handle;
} }

View File

@@ -73,7 +73,8 @@ class GPS {
} }
private static function persistCachedPositon() { private static function persistCachedPositon() {
if (cachedPosition == null) return; if (cachedPosition == null)
return;
var kvstore = new KVStore("gps"); var kvstore = new KVStore("gps");
kvstore.set("cpos", cachedPosition); kvstore.set("cpos", cachedPosition);
@@ -114,7 +115,6 @@ class GPS {
posAccuracy = 2; posAccuracy = 2;
return; return;
} }
} }
private static function sendPositionRequest() { private static function sendPositionRequest() {
@@ -125,20 +125,25 @@ class GPS {
private static function handlePackage(pack:Package<Noise>, dist:Float, iface:INetworkInterface) { private static function handlePackage(pack:Package<Noise>, dist:Float, iface:INetworkInterface) {
switch (pack.type) { switch (pack.type) {
case GPSRequest: case GPSRequest:
if (!shouldRespond) return; if (!shouldRespond)
if (posAccuracy < 2) return; return;
if (cachedPosition == null) return; if (posAccuracy < 2)
return;
if (cachedPosition == null)
return;
var response = new Package(Net.networkID, pack.fromID, pack.msgID, GPSResponse(cachedPosition), null, 0); var response = new Package(Net.networkID, pack.fromID, pack.msgID, GPSResponse(cachedPosition), null, 0);
iface.send(pack.fromID, Net.networkID, response); iface.send(pack.fromID, Net.networkID, response);
case GPSResponse(pos): case GPSResponse(pos):
if (lastPositionResponse.contains({pos:pos,dist:dist})) return; // Ignore duplicate responses if (lastPositionResponse.contains({pos: pos, dist: dist}))
return; // Ignore duplicate responses
lastPositionResponse.push({pos: pos, dist: dist}); lastPositionResponse.push({pos: pos, dist: dist});
// TODO: wait for a few seconds before calculating the position, so we can get more responses // TODO: wait for a few seconds before calculating the position, so we can get more responses
if (lastPositionResponse.length < 4) return; // We need at least 3 responses to calculate the position if (lastPositionResponse.length < 4)
return; // We need at least 3 responses to calculate the position
var calculatedPosition = calculatePosition(); var calculatedPosition = calculatePosition();
@@ -148,7 +153,8 @@ class GPS {
lastPositionResponse = []; // Reset the response array lastPositionResponse = []; // Reset the response array
if (calculatedPosition == null) return; if (calculatedPosition == null)
return;
cachedPosition = calculatedPosition; cachedPosition = calculatedPosition;
posAccuracy = 3; posAccuracy = 3;
@@ -158,7 +164,8 @@ class GPS {
} }
private static function calculatePosition():Null<Pos3> { private static function calculatePosition():Null<Pos3> {
if (lastPositionResponse.length < 3) return null; if (lastPositionResponse.length < 3)
return null;
// do a simple trilateration with the last 3 responses for now // do a simple trilateration with the last 3 responses for now
var p1 = lastPositionResponse[0].pos; var p1 = lastPositionResponse[0].pos;
@@ -171,7 +178,8 @@ class GPS {
var result = trilateration(p1, p2, p3, r1, r2, r3); var result = trilateration(p1, p2, p3, r1, r2, r3);
if (result.a.close(result.b)) return result.a; if (result.a.close(result.b))
return result.a;
// If we have more than 3 responses, we can use the 4th response to determine which of the two positions is correct // If we have more than 3 responses, we can use the 4th response to determine which of the two positions is correct
// TODO: if this is a pocket computer we cant use this since it can move freely // TODO: if this is a pocket computer we cant use this since it can move freely
@@ -184,12 +192,15 @@ class GPS {
return null; // The two positions are essentially the same, so we cant determine which one is correct return null; // The two positions are essentially the same, so we cant determine which one is correct
} }
if (err1 < err2) return result.a; if (err1 < err2)
if (err2 < err1) return result.b; return result.a;
if (err2 < err1)
return result.b;
} }
// last resort, just use the position that is closest to a whole number (whithin a resonable margin of error) // last resort, just use the position that is closest to a whole number (whithin a resonable margin of error)
if (!shouldDoWholeNumberCheck) return null; if (!shouldDoWholeNumberCheck)
return null;
// TODO: mark the position as not so accurate if we use this method // TODO: mark the position as not so accurate if we use this method

View File

@@ -40,7 +40,8 @@ class INS {
@:allow(kernel.turtle.Turtle) @:allow(kernel.turtle.Turtle)
private static function turnLeft() { private static function turnLeft() {
if (heading == null) return; if (heading == null)
return;
if (heading.x == 0 && heading.z == -1) { if (heading.x == 0 && heading.z == -1) {
heading = {x: -1, y: 0, z: 0}; heading = {x: -1, y: 0, z: 0};
} else if (heading.x == -1 && heading.z == 0) { } else if (heading.x == -1 && heading.z == 0) {
@@ -54,7 +55,8 @@ class INS {
@:allow(kernel.turtle.Turtle) @:allow(kernel.turtle.Turtle)
private static function turnRight() { private static function turnRight() {
if (heading == null) return; if (heading == null)
return;
if (heading.x == 0 && heading.z == -1) { if (heading.x == 0 && heading.z == -1) {
heading = {x: 1, y: 0, z: 0}; heading = {x: 1, y: 0, z: 0};
} else if (heading.x == -1 && heading.z == 0) { } else if (heading.x == -1 && heading.z == 0) {
@@ -80,7 +82,6 @@ class INS {
public static function align():Promise<Noise> { public static function align():Promise<Noise> {
Log.info("Aligning INS"); Log.info("Aligning INS");
return new Promise<Noise>((resolve, reject) -> { return new Promise<Noise>((resolve, reject) -> {
if (Turtle.instance.getFuelLevel() < 2) { if (Turtle.instance.getFuelLevel() < 2) {
Log.warn("Not enough fuel to align"); Log.warn("Not enough fuel to align");
reject(new Error("Not enough fuel to align")); reject(new Error("Not enough fuel to align"));
@@ -124,7 +125,6 @@ class INS {
resolve(Noise); resolve(Noise);
}); });
}); });
return null; return null;
}); });
@@ -200,5 +200,4 @@ class INS {
private static function rotatePos3ToLeft(pos3:Pos3):Pos3 { private static function rotatePos3ToLeft(pos3:Pos3):Pos3 {
return rotatePos3ToRight(rotatePos3ToRight(rotatePos3ToRight(pos3))); return rotatePos3ToRight(rotatePos3ToRight(rotatePos3ToRight(pos3)));
} }
} }

View File

@@ -3,7 +3,6 @@ package kernel.http;
using lua.Table; using lua.Table;
class HTTPFailure { class HTTPFailure {
public final reason:String; public final reason:String;
public final statusCode:Null<StatusCode>; public final statusCode:Null<StatusCode>;
public final headers:Map<String, String>; public final headers:Map<String, String>;

View File

@@ -3,7 +3,6 @@ package kernel.http;
using lua.Table; using lua.Table;
class HTTPResponse { class HTTPResponse {
public final statusCode:StatusCode; public final statusCode:StatusCode;
public final headers:Map<String, String>; public final headers:Map<String, String>;
public final body:String; public final body:String;

View File

@@ -1,6 +1,7 @@
package kernel.net; package kernel.net;
import kernel.net.Package.GenericPackage; import kernel.net.Package.GenericPackage;
using tink.CoreApi; using tink.CoreApi;
/** /**

View File

@@ -2,6 +2,7 @@ package kernel.net;
import kernel.net.Package.GenericPackage; import kernel.net.Package.GenericPackage;
import kernel.log.Log; import kernel.log.Log;
using tink.CoreApi; using tink.CoreApi;
/** /**

View File

@@ -21,6 +21,7 @@ class Net {
Depends on: KernelEvents Depends on: KernelEvents
**/ **/
public static inline final BRODCAST_PORT:Int = 65533; public static inline final BRODCAST_PORT:Int = 65533;
public static inline final MESSAGE_TIMEOUT:Int = 3; public static inline final MESSAGE_TIMEOUT:Int = 3;
public static inline final DEFAULT_TTL:Int = 10; public static inline final DEFAULT_TTL:Int = 10;
@@ -120,7 +121,6 @@ class Net {
private static function forwardPackage(pack:GenericPackage) { private static function forwardPackage(pack:GenericPackage) {
if (pack.ttl == 0) { if (pack.ttl == 0) {
if (pack.type.match(Data(_))) { if (pack.type.match(Data(_))) {
// If the package is a data package and the ttl hits 0 // If the package is a data package and the ttl hits 0
// we send a "died" message to the sender // we send a "died" message to the sender
@@ -201,7 +201,6 @@ class Net {
var timeout:Timer = null; var timeout:Timer = null;
responseBus[pack.msgID] = ((reponse:Outcome<GenericPackage, Error>) -> { responseBus[pack.msgID] = ((reponse:Outcome<GenericPackage, Error>) -> {
switch reponse { switch reponse {
case Success(pack): case Success(pack):
resolve(pack); resolve(pack);
@@ -282,7 +281,8 @@ class Net {
}; };
for (modem in Peripheral.getAllModems()) { for (modem in Peripheral.getAllModems()) {
if (!modem.isWireless()) continue; if (!modem.isWireless())
continue;
modem.send(Net.BRODCAST_PORT, networkID, pack); modem.send(Net.BRODCAST_PORT, networkID, pack);
} }
} }

View File

@@ -20,7 +20,6 @@ class Routing {
/** /**
Depends on: Peripheral Depends on: Peripheral
**/ **/
public static inline final UPDATE_WAIT_TIME:Float = 1; public static inline final UPDATE_WAIT_TIME:Float = 1;
public static var onNewNeigbor(default, null):Signal<Int>; public static var onNewNeigbor(default, null):Signal<Int>;

View File

@@ -169,7 +169,6 @@ class BigReactor implements IPeripheral {
// getEnergyStats // getEnergyStats
// getCoolantFluidStats // getCoolantFluidStats
// getHotFluidStats // getHotFluidStats
// TODO: need research // TODO: need research
// isMethodAvailable(method: String): Bool // isMethodAvailable(method: String): Bool
// mbGetMaximumCoordinate(): Pos3 // mbGetMaximumCoordinate(): Pos3

View File

@@ -1,6 +1,7 @@
package kernel.peripherals; package kernel.peripherals;
import cc.Peripheral; import cc.Peripheral;
using tink.CoreApi; using tink.CoreApi;
class Drive implements IPeripheral { class Drive implements IPeripheral {

View File

@@ -90,18 +90,19 @@ class Peripheral {
public static function getScreen(addr:String):Null<Screen> { public static function getScreen(addr:String):Null<Screen> {
var addr = safeGetAddr(addr, Screen.TYPE_NAME); var addr = safeGetAddr(addr, Screen.TYPE_NAME);
if (addr == null) return null; if (addr == null)
return null;
return new Screen(addr); return new Screen(addr);
} }
public static function getAllScreens():Array<Screen> { public static function getAllScreens():Array<Screen> {
return [for (addr in findAddrByType(Screen.TYPE_NAME)) new Screen(addr)]; return [for (addr in findAddrByType(Screen.TYPE_NAME)) new Screen(addr)];
} }
public static function getModem(addr:String):Null<Modem> { public static function getModem(addr:String):Null<Modem> {
var addr = safeGetAddr(addr, Modem.TYPE_NAME); var addr = safeGetAddr(addr, Modem.TYPE_NAME);
if (addr == null) return null; if (addr == null)
return null;
return new Modem(addr); return new Modem(addr);
} }
@@ -111,7 +112,8 @@ class Peripheral {
public static function getDrive(addr:String):Null<Drive> { public static function getDrive(addr:String):Null<Drive> {
var addr = safeGetAddr(addr, Drive.TYPE_NAME); var addr = safeGetAddr(addr, Drive.TYPE_NAME);
if (addr == null) return null; if (addr == null)
return null;
return new Drive(addr); return new Drive(addr);
} }
@@ -126,7 +128,8 @@ class Peripheral {
public static function getPrinter(addr:String):Null<Printer> { public static function getPrinter(addr:String):Null<Printer> {
var addr = safeGetAddr(addr, Printer.TYPE_NAME); var addr = safeGetAddr(addr, Printer.TYPE_NAME);
if (addr == null) return null; if (addr == null)
return null;
return new Printer(addr); return new Printer(addr);
} }
@@ -136,7 +139,8 @@ class Peripheral {
public static function getEnergyStorage(addr:String):Null<EnergyStorage> { public static function getEnergyStorage(addr:String):Null<EnergyStorage> {
var addr = safeGetAddr(addr, EnergyStorage.TYPE_NAME); var addr = safeGetAddr(addr, EnergyStorage.TYPE_NAME);
if (addr == null) return null; if (addr == null)
return null;
return new EnergyStorage(addr); return new EnergyStorage(addr);
} }
@@ -146,7 +150,8 @@ class Peripheral {
public static function getComputer(addr:String):Null<Computer> { public static function getComputer(addr:String):Null<Computer> {
var addr = safeGetAddr(addr, Computer.TYPE_NAME); var addr = safeGetAddr(addr, Computer.TYPE_NAME);
if (addr == null) return null; if (addr == null)
return null;
return new Computer(addr); return new Computer(addr);
} }

View File

@@ -23,9 +23,7 @@ class Printer implements IPeripheral {
return TYPE_NAME; return TYPE_NAME;
} }
public function write(text: String){ public function write(text:String) {}
}
public function getCurserPos():Pos { public function getCurserPos():Pos {
return new Pos({x: 0, y: 0}); return new Pos({x: 0, y: 0});

View File

@@ -69,7 +69,6 @@ class Redstone implements IPeripheral implements IExportable {
this.onChangeTrigger.trigger(null); this.onChangeTrigger.trigger(null);
} }
}); });
} }
public function getAddr():String { public function getAddr():String {

View File

@@ -4,6 +4,7 @@ import kernel.ps.ProcessManager.PID;
import kernel.ui.WindowContext; import kernel.ui.WindowContext;
import kernel.ui.WindowManager; import kernel.ui.WindowManager;
import haxe.ds.ReadOnlyArray; import haxe.ds.ReadOnlyArray;
using tink.CoreApi; using tink.CoreApi;
typedef HandleConfig = { typedef HandleConfig = {
@@ -47,12 +48,15 @@ class ProcessHandle {
this.hasExited = true; this.hasExited = true;
this.dispose(); this.dispose();
EndOfLoop.endOfLoop(() ->{this.closeFutureResolev(success);}); EndOfLoop.endOfLoop(() -> {
this.closeFutureResolev(success);
});
ProcessManager.removeProcess(this.pid); ProcessManager.removeProcess(this.pid);
} }
public function write(message:String):Void { public function write(message:String):Void {
if (this.hasExited) return; if (this.hasExited)
return;
if (this.config.onWrite != null) { if (this.config.onWrite != null) {
this.config.onWrite.invoke(message); this.config.onWrite.invoke(message);
} }

View File

@@ -35,5 +35,4 @@ class Service {
public function stop() { public function stop() {
ProcessManager.kill(this.pid); ProcessManager.kill(this.pid);
} }
} }

View File

@@ -137,5 +137,4 @@ class ServiceManager {
var srv = services.get(name); var srv = services.get(name);
return srv.ps; return srv.ps;
} }
} }

View File

@@ -36,42 +36,48 @@ class Turtle {
public function forward():Outcome<Noise, String> { public function forward():Outcome<Noise, String> {
var r = cc.Turtle.forward(); var r = cc.Turtle.forward();
var r2 = conterToOutcome(r); var r2 = conterToOutcome(r);
if (r2.isSuccess()) INS.moveForward(); if (r2.isSuccess())
INS.moveForward();
return r2; return r2;
} }
public function back():Outcome<Noise, String> { public function back():Outcome<Noise, String> {
var r = cc.Turtle.back(); var r = cc.Turtle.back();
var r2 = conterToOutcome(r); var r2 = conterToOutcome(r);
if (r2.isSuccess()) INS.moveBackward(); if (r2.isSuccess())
INS.moveBackward();
return r2; return r2;
} }
public function up():Outcome<Noise, String> { public function up():Outcome<Noise, String> {
var r = cc.Turtle.up(); var r = cc.Turtle.up();
var r2 = conterToOutcome(r); var r2 = conterToOutcome(r);
if (r2.isSuccess()) INS.moveUp(); if (r2.isSuccess())
INS.moveUp();
return r2; return r2;
} }
public function down():Outcome<Noise, String> { public function down():Outcome<Noise, String> {
var r = cc.Turtle.down(); var r = cc.Turtle.down();
var r2 = conterToOutcome(r); var r2 = conterToOutcome(r);
if (r2.isSuccess()) INS.moveDown(); if (r2.isSuccess())
INS.moveDown();
return r2; return r2;
} }
public function turnLeft():Outcome<Noise, String> { public function turnLeft():Outcome<Noise, String> {
var r = cc.Turtle.turnLeft(); var r = cc.Turtle.turnLeft();
var r2 = conterToOutcome(r); var r2 = conterToOutcome(r);
if (r2.isSuccess()) INS.turnRight(); if (r2.isSuccess())
INS.turnRight();
return r2; return r2;
} }
public function turnRight():Outcome<Noise, String> { public function turnRight():Outcome<Noise, String> {
var r = cc.Turtle.turnRight(); var r = cc.Turtle.turnRight();
var r2 = conterToOutcome(r); var r2 = conterToOutcome(r);
if (r2.isSuccess()) INS.turnRight(); if (r2.isSuccess())
INS.turnRight();
return r2; return r2;
} }

View File

@@ -101,11 +101,13 @@ class StatelessVirtualTermWriter implements VirtualTermWriter {
// //
public inline function write(text:String) { public inline function write(text:String) {
if (enabled) target.write(text); if (enabled)
target.write(text);
} }
public inline function scroll(y:Int) { public inline function scroll(y:Int) {
if (enabled) target.scroll(y); if (enabled)
target.scroll(y);
} }
public inline function getCursorPos():Pos { public inline function getCursorPos():Pos {
@@ -113,7 +115,8 @@ class StatelessVirtualTermWriter implements VirtualTermWriter {
} }
public inline function setCursorPos(x:Int, y:Int) { public inline function setCursorPos(x:Int, y:Int) {
if (enabled) target.setCursorPos(x, y); if (enabled)
target.setCursorPos(x, y);
} }
public inline function getCursorBlink():Bool { public inline function getCursorBlink():Bool {
@@ -121,7 +124,8 @@ class StatelessVirtualTermWriter implements VirtualTermWriter {
} }
public inline function setCursorBlink(blink:Bool) { public inline function setCursorBlink(blink:Bool) {
if (enabled) target.setCursorBlink(blink); if (enabled)
target.setCursorBlink(blink);
} }
public inline function getSize():Vec2<Int> { public inline function getSize():Vec2<Int> {
@@ -129,11 +133,13 @@ class StatelessVirtualTermWriter implements VirtualTermWriter {
} }
public inline function clear() { public inline function clear() {
if (enabled) target.clear(); if (enabled)
target.clear();
} }
public inline function clearLine() { public inline function clearLine() {
if (enabled) target.clearLine(); if (enabled)
target.clearLine();
} }
public inline function getTextColor():Color { public inline function getTextColor():Color {
@@ -141,7 +147,8 @@ class StatelessVirtualTermWriter implements VirtualTermWriter {
} }
public inline function setTextColor(color:Color) { public inline function setTextColor(color:Color) {
if (enabled) target.setTextColor(color); if (enabled)
target.setTextColor(color);
} }
public inline function getBackgroundColor():Color { public inline function getBackgroundColor():Color {
@@ -149,7 +156,8 @@ class StatelessVirtualTermWriter implements VirtualTermWriter {
} }
public inline function setBackgroundColor(color:Color) { public inline function setBackgroundColor(color:Color) {
if (enabled) target.setBackgroundColor(color); if (enabled)
target.setBackgroundColor(color);
} }
public inline function isColor():Bool { public inline function isColor():Bool {
@@ -157,6 +165,7 @@ class StatelessVirtualTermWriter implements VirtualTermWriter {
} }
public inline function reset() { public inline function reset() {
if (enabled) target.reset(); if (enabled)
target.reset();
} }
} }

View File

@@ -35,6 +35,7 @@ interface TermWriteable {
public function getBackgroundColor():Color; public function getBackgroundColor():Color;
public function setBackgroundColor(color:Color):Void; public function setBackgroundColor(color:Color):Void;
public function isColor():Bool; public function isColor():Bool;
// public function setPaletteColor(...); // public function setPaletteColor(...);
// public function getPaletteColor(color); // public function getPaletteColor(color);

View File

@@ -15,6 +15,7 @@ class WindowManager {
Depends on: KernelEvents, Peripheral Depends on: KernelEvents, Peripheral
**/ **/
private static var currentMainContext:WindowContext; private static var currentMainContext:WindowContext;
private static final outputMap:Map<String, WindowContext> = new Map(); private static final outputMap:Map<String, WindowContext> = new Map();
@:allow(kernel.Init) @:allow(kernel.Init)

View File

@@ -35,7 +35,6 @@ abstract class CLIAppBase implements Process {
printHelp(); printHelp();
return handle.close(false); return handle.close(false);
} }
} }
private function registerSyncSubcommand(command:String, callback:(Array<String>) -> Bool, synopsis:String = null) { private function registerSyncSubcommand(command:String, callback:(Array<String>) -> Bool, synopsis:String = null) {

View File

@@ -31,11 +31,7 @@ class HomeContext {
private var selectedOutput:String = "main"; private var selectedOutput:String = "main";
private var selectedOutputIndex:Int = -1; private var selectedOutputIndex:Int = -1;
private final listedApps:Array<String> = [ private final listedApps:Array<String> = ["terminal", "log", "pfclient"];
"terminal",
"log",
"pfclient"
];
public function new() {} public function new() {}
@@ -154,14 +150,12 @@ class HomeContext {
workspaceIDs.sort((a, b) -> a - b); workspaceIDs.sort((a, b) -> a - b);
var children:Array<UIElement> = [ var children:Array<UIElement> = [
for (i in workspaceIDs) new TextElement('Switch to ${i + 1}', {uiEvents: {onClick: this.handleSelectContext.bind(i)}}) for (i in workspaceIDs)
new TextElement('Switch to ${i + 1}', {uiEvents: {onClick: this.handleSelectContext.bind(i)}})
]; ];
for (i in 0...listedApps.length) { for (i in 0...listedApps.length) {
children.push(new TextElement( children.push(new TextElement('Add ${BinStore.getNameByAlias(listedApps[i])}', {uiEvents: {onClick: this.spawnPs.bind(listedApps[i])}}));
'Add ${BinStore.getNameByAlias(listedApps[i])}',
{uiEvents: {onClick: this.spawnPs.bind(listedApps[i])}}
));
} }
children.push(new TextElement('Output: ${selectedOutput}', {uiEvents: {onClick: this.cycleOutput}})); children.push(new TextElement('Output: ${selectedOutput}', {uiEvents: {onClick: this.cycleOutput}}));

View File

@@ -4,7 +4,6 @@ package lib;
Represents an item in the game. Represents an item in the game.
**/ **/
abstract Item(String) to String { abstract Item(String) to String {
public inline function new(name:String) { public inline function new(name:String) {
// Check if the name is valid. in the format `mod:item_name` e.g. `minecraft:apple` // Check if the name is valid. in the format `mod:item_name` e.g. `minecraft:apple`
// TODO: implement // TODO: implement

View File

@@ -10,6 +10,7 @@ import haxe.ds.StringMap;
**/ **/
class KVStore { class KVStore {
private var kvStore:StringMap<Dynamic> = new StringMap(); private var kvStore:StringMap<Dynamic> = new StringMap();
public final namespace:String; public final namespace:String;
public function new(namespace:String) { public function new(namespace:String) {

View File

@@ -1,7 +1,6 @@
package lib; package lib;
class Rect { class Rect {
private final tl:Pos; private final tl:Pos;
private final br:Pos; private final br:Pos;

View File

@@ -1,84 +0,0 @@
package lib;
import bin.srsc.PackageTypes.ListRequest;
import kernel.KernelSettings;
import bin.srsc.PackageTypes.UnregisterRequest;
import bin.srsc.PackageTypes.RegisterRequest;
import bin.srsc.PackageTypes.GetRequest;
import bin.srsc.SiteRessourceController;
import kernel.net.Net;
import kernel.net.Package.NetworkID;
using tink.CoreApi;
class RessourceNames {
public static function get(name: String, controllerID: NetworkID = -1): Promise<Null<NetworkID>> {
if (controllerID == -1) controllerID = KernelSettings.siteController;
var payload: GetRequest = {name: name, type: "get"};
return Net.sendAndAwait(
controllerID,
SiteRessourceController.SITE_CONTROLLER_RESSOURCE_MANAGER_PROTO,
payload
).map((res)->{
switch (res){
case Success(pkg):
return Success(pkg.data.netID);
case Failure(error):
return Failure(error);
}
});
}
public static function register(name: String, netID: NetworkID, controllerID: NetworkID = -1): Promise<Bool> {
if (controllerID == -1) controllerID = KernelSettings.siteController;
var payload: RegisterRequest = {name: name, netID: netID, type: "register"};
return Net.sendAndAwait(
controllerID,
SiteRessourceController.SITE_CONTROLLER_RESSOURCE_MANAGER_PROTO,
payload
).map((res)->{
switch (res){
case Success(pkg):
return Success(pkg.data.success);
case Failure(error):
return Failure(error);
}
});
}
public static function unregister(name: String, controllerID: NetworkID = -1): Promise<Noise> {
if (controllerID == -1) controllerID = KernelSettings.siteController;
var payload: UnregisterRequest = {name: name, type: "unregister"};
return Net.sendAndAwait(
controllerID,
SiteRessourceController.SITE_CONTROLLER_RESSOURCE_MANAGER_PROTO,
payload
);
}
public static function list(controllerID: NetworkID = -1): Promise<Array<String>> {
if (controllerID == -1) controllerID = KernelSettings.siteController;
var payload: ListRequest = {type: "list"};
return Net.sendAndAwait(
controllerID,
SiteRessourceController.SITE_CONTROLLER_RESSOURCE_MANAGER_PROTO,
payload
).map(res->{
switch (res){
case Success(pkg):
return Success(pkg.data);
case Failure(error):
return Failure(error);
}
});
}
}

View File

@@ -1,5 +1,6 @@
package lib.exporter; package lib.exporter;
import kernel.KernelSettings;
import kernel.net.Net; import kernel.net.Net;
import kernel.net.Package.NetworkID; import kernel.net.Package.NetworkID;
@@ -8,8 +9,9 @@ using tink.CoreApi;
class Import { class Import {
public static function get(ressourceLocator:String):Promise<Response> { public static function get(ressourceLocator:String):Promise<Response> {
var request = Request.fromString(ressourceLocator); var request = Request.fromString(ressourceLocator);
var rpc = new SiteRessourceControllerRPC(KernelSettings.siteController);
return RessourceNames.get(request.id).next((response)->{ return rpc.get(request.id).next((response) -> {
return performRequest(response, request); return performRequest(response, request);
}); });
} }
@@ -23,6 +25,5 @@ class Import {
return Failure(error); return Failure(error);
} }
}); });
} }
} }

View File

@@ -16,7 +16,6 @@ class Request {
this.operation = operation; this.operation = operation;
} }
/** /**
Example: Example:
"myfield[2]@myid" "myfield[2]@myid"

View File

@@ -7,7 +7,6 @@ import kernel.turtle.Turtle;
using tink.CoreApi; using tink.CoreApi;
class TurtleExecuter { class TurtleExecuter {
private var instructions:Array<TurtleInstruction>; private var instructions:Array<TurtleInstruction>;
public function new(instructions:Array<TurtleInstruction>) { public function new(instructions:Array<TurtleInstruction>) {

View File

@@ -67,13 +67,11 @@ class TurtleExt {
var inv = getInventory(t); var inv = getInventory(t);
// For each item in the inventory // For each item in the inventory
for (k1 => v1 in inv) { for (k1 => v1 in inv) {
if (v1.free == 0 || v1.count == 0) { if (v1.free == 0 || v1.count == 0) {
continue; continue;
} }
for (k2 => v2 in inv) { for (k2 => v2 in inv) {
if (k2 == k1) { if (k2 == k1) {
continue; continue;
} }
@@ -88,11 +86,7 @@ class TurtleExt {
break; break;
} }
} }
} }
} }
} }
} }

View File

@@ -3,7 +3,6 @@ package lib.turtle;
// Check usage of NativeStringTools // Check usage of NativeStringTools
// here https://api.haxe.org/lua/NativeStringTools.html // here https://api.haxe.org/lua/NativeStringTools.html
// and here http://lua-users.org/wiki/StringLibraryTutorial // and here http://lua-users.org/wiki/StringLibraryTutorial
import kernel.turtle.Types.TurtleSlot; import kernel.turtle.Types.TurtleSlot;
import kernel.turtle.Turtle; import kernel.turtle.Turtle;
import lua.NativeStringTools; import lua.NativeStringTools;
@@ -14,10 +13,7 @@ using tink.CoreApi;
Save a set of turtle instructions to a string and execute them. Save a set of turtle instructions to a string and execute them.
**/ **/
class TurtleInstructionParser { class TurtleInstructionParser {
public function new() {}
public function new() {
}
public function encode(instructions:Array<TurtleInstruction>):String { public function encode(instructions:Array<TurtleInstruction>):String {
var s = ""; var s = "";
@@ -108,18 +104,7 @@ class TurtleInstructionParser {
} }
private var cmdMap:Map<String, TurtleInstruction> = [ private var cmdMap:Map<String, TurtleInstruction> = [
"a" => Forward, "a" => Forward, "b" => Back, "c" => TurnLeft, "d" => TurnRight, "e" => Up, "f" => Down, "g" => Dig(Front), "h" => Dig(Up), "i" => Dig(Down),
"b" => Back, "j" => Place(Front), "k" => Place(Up), "l" => Place(Down),
"c" => TurnLeft,
"d" => TurnRight,
"e" => Up,
"f" => Down,
"g" => Dig(Front),
"h" => Dig(Up),
"i" => Dig(Down),
"j" => Place(Front),
"k" => Place(Up),
"l" => Place(Down),
]; ];
} }

View File

@@ -191,7 +191,6 @@ class CanvasKeyValueIterator {
this.index = this.nextIndex; this.index = this.nextIndex;
this.nextIndex = nextValidPixel(); this.nextIndex = nextValidPixel();
return rtn; return rtn;
} }
} }

View File

@@ -2,11 +2,10 @@ package macros;
import haxe.macro.Context; import haxe.macro.Context;
import haxe.macro.Expr; import haxe.macro.Expr;
using Lambda; using Lambda;
class DCEHack { class DCEHack {
public static final classes:Array<haxe.macro.Type> = []; public static final classes:Array<haxe.macro.Type> = [];
macro static public function dceInclude():Array<Field> { macro static public function dceInclude():Array<Field> {

View File

@@ -2,6 +2,7 @@ package macros;
import haxe.macro.Context; import haxe.macro.Context;
import haxe.macro.Expr; import haxe.macro.Expr;
using Lambda; using Lambda;
class Exporter { class Exporter {
@@ -11,7 +12,8 @@ class Exporter {
var getExp = []; var getExp = [];
for (field in fields) { for (field in fields) {
if (field.meta == null) continue; if (field.meta == null)
continue;
var s = ""; var s = "";
for (meta in field.meta) { for (meta in field.meta) {
@@ -25,7 +27,8 @@ class Exporter {
} }
} }
if (s == "") continue; if (s == "")
continue;
switch (field.kind) { switch (field.kind) {
case FFun(f): case FFun(f):
@@ -74,4 +77,3 @@ class Exporter {
return fields; return fields;
} }
} }

43
src/macros/Helper.hx Normal file
View File

@@ -0,0 +1,43 @@
package macros;
#if macro
import haxe.macro.TypeTools;
import haxe.macro.Expr.Position;
import haxe.macro.Expr.ComplexType;
import haxe.macro.Context;
import haxe.macro.Type;
class Helper {
public static function resolveType(t:ComplexType, pos:Position):Null<ComplexType> {
if (t == null)
return null;
return TypeTools.toComplexType(Context.resolveType(t, pos));
}
public static function newPromise(t:ComplexType):ComplexType {
if (Helper.isVoidC(t)) {
return TPath({name: "Promise", params: [TPType(TPath({name: "Noise", pack: ["tink", "core"]}))], pack: ["tink", "core"]});
}
return TPath({name: "Promise", params: [TPType(t)], pack: ["tink", "core"]});
}
public static function isVoidC(t:ComplexType):Bool {
switch (t) {
case TPath(p):
return (p.name == "Void");
default:
return false;
}
}
public static function isVoid(t:Type) {
switch (t) {
case TAbstract(t, _):
return (t.get().name == "Void");
default:
return false;
}
}
}
#end

View File

@@ -2,6 +2,7 @@ package macros.rpc;
import haxe.macro.Context; import haxe.macro.Context;
import haxe.macro.Expr; import haxe.macro.Expr;
using Lambda; using Lambda;
class RPC { class RPC {
@@ -9,6 +10,7 @@ class RPC {
var fields = Context.getBuildFields(); var fields = Context.getBuildFields();
var className = Context.getLocalClass().get().name + "RPC"; var className = Context.getLocalClass().get().name + "RPC";
var imports = Context.getLocalImports();
var c = macro class $className extends macros.rpc.RPCBase { var c = macro class $className extends macros.rpc.RPCBase {
public function new(id:kernel.net.Package.NetworkID) { public function new(id:kernel.net.Package.NetworkID) {
@@ -17,20 +19,31 @@ class RPC {
} }
for (field in fields) { for (field in fields) {
if (field.meta == null) continue; if (field.meta == null)
if (field.meta.exists((i) -> i.name == "rpc") == false) continue; continue;
if (field.meta.exists((i) -> i.name == "rpc") == false)
continue;
switch (field.kind) { switch (field.kind) {
case FFun(f): case FFun(f):
var argsExprs:Array<Expr> = [for (a in f.args) macro $i{a.name}];
var convertedArgs = [];
for (a in f.args) {
a.type = Helper.resolveType(a.type, field.pos);
convertedArgs.push(a);
}
c.fields.push({ c.fields.push({
name: field.name, name: field.name,
pos: field.pos, pos: field.pos,
kind: FFun({ kind: FFun({
args: f.args, args: convertedArgs,
expr: macro { expr: macro {
return cast this._performRequest($v{field.name},[]); return cast this._performRequest($v{field.name}, $a{argsExprs});
}, },
ret: TPath({name: "Promise", params: [TPType(f.ret)], pack: ["tink","core"]}), ret: Helper.newPromise(Helper.resolveType(f.ret, field.pos)),
}), }),
access: [APublic], access: [APublic],
doc: null, doc: null,
@@ -42,7 +55,6 @@ class RPC {
} }
haxe.macro.Context.defineType(c); haxe.macro.Context.defineType(c);
return fields; return fields;
} }
@@ -53,18 +65,38 @@ class RPC {
var fields = Context.getLocalClass().get().fields.get(); var fields = Context.getLocalClass().get().fields.get();
for (field in fields) { for (field in fields) {
if (field.meta == null) continue; if (field.meta == null)
if (!field.meta.has("rpc")) continue; continue;
if (!field.meta.has("rpc"))
continue;
switch (field.kind) { switch (field.kind) {
case FMethod(k): case FMethod(k):
var funName = field.name; var funName = field.name;
var exprsType = field.expr().t;
switch (exprsType) {
case TFun(args, ret):
var callArgs = [for (k => v in args) macro pack.data.args[$v{k}]];
if (Helper.isVoid(ret)) {
exprs.push(macro { exprs.push(macro {
if (pack.data.func == $v{funName}) { if (pack.data.func == $v{funName}) {
pack.respond(this.$funName()); this.$funName($a{callArgs});
pack.respond(null);
} }
}); });
} else {
exprs.push(macro {
if (pack.data.func == $v{funName}) {
pack.respond(this.$funName($a{callArgs}));
}
});
}
default:
Context.error("Only functions can be used for rpc", field.pos);
}
default: default:
Context.error("Only functions can be used for rpc", field.pos); Context.error("Only functions can be used for rpc", field.pos);
} }

View File

@@ -7,7 +7,9 @@ using tink.CoreApi;
abstract class RPCBase { abstract class RPCBase {
public final id:NetworkID; public final id:NetworkID;
private final _proto:String; private final _proto:String;
public function new(id:NetworkID, proto:String) { public function new(id:NetworkID, proto:String) {
this.id = id; this.id = id;
this._proto = proto; this._proto = proto;
@@ -16,11 +18,11 @@ abstract class RPCBase {
private function _performRequest(func:String, args:Array<Dynamic>):Promise<Dynamic> { private function _performRequest(func:String, args:Array<Dynamic>):Promise<Dynamic> {
return Net.sendAndAwait(id, this._proto, { return Net.sendAndAwait(id, this._proto, {
func: func, func: func,
// args: args args: args
}).map((res) -> { }).map((res) -> {
switch (res) { switch (res) {
case Success(pack): case Success(pack):
return pack.data; return Success(pack.data);
case Failure(_): case Failure(_):
return res; return res;
} }