2
0
mirror of https://github.com/esiur/esiur-dart.git synced 2025-05-06 12:02:57 +00:00
This commit is contained in:
Ahmed Zamil 2021-07-21 12:18:01 +03:00
parent 737397da11
commit 6be04c39ed
27 changed files with 659 additions and 513 deletions

View File

@ -1,19 +1,13 @@
import 'package:args/args.dart'; import 'dart:io';
void main(List<String> arguments) { import 'package:args/args.dart';
import 'package:pubspec_parse/pubspec_parse.dart';
import '../lib/src/Proxy/TemplateGenerator.dart';
void main(List<String> arguments) async {
if (arguments.length == 0) { if (arguments.length == 0) {
// print help printUsage();
print("Esiur package command line"); return;
print("");
print("Usage: <command> [arguments]");
print("");
print("Available commands:");
print("\tget-template\tGet a template from an IIP link.");
print("\tversion: print esiur version.");
print("");
print("Global options:");
print("\t-u, --username\tAuthentication username");
print("\t-p, --password\tAuthentication password");
} }
var cmd = arguments[0]; var cmd = arguments[0];
@ -27,15 +21,54 @@ void main(List<String> arguments) {
var link = arguments[1]; var link = arguments[1];
final parser = ArgParser() final parser = ArgParser()
..addFlag('username', abbr: 'u') ..addOption('username', abbr: 'u')
..addFlag('password', abbr: 'p'); ..addOption('password', abbr: 'p')
..addOption('dir', abbr: 'd');
var results = parser.parse(arguments.skip(2)); var results = parser.parse(arguments.skip(2));
var username = results['username']; var username = results['username'];
var password = results['password']; var password = results['password'];
var dir = results['dir'];
//print("Username ${username} password ${password} dir ${dir}");
// make template // make template
var destDir =
await TemplateGenerator.getTemplate(link, dir, username, password);
print("Generated directory `${destDir}`");
return;
} else if (cmd == "version") {
await printVersion();
} else {
printUsage();
} }
} }
printUsage() {
// print help
print("Esiur package command line");
print("");
print("Usage: <command> [arguments]");
print("");
print("Available commands:");
print("\tget-template\tGet a template from an IIP link.");
print("\tversion: print esiur version.");
print("");
print("Global options:");
print("\t-u, --username\tAuthentication username");
print("\t-p, --password\tAuthentication password");
print("\t-d, --dir\tName of the directory to generate model inside.");
}
printVersion() async {
var p = Platform.script.pathSegments;
var path = p.take(p.length - 2).join('/') + "/pubspec.yaml";
var yaml = await File(path).readAsString();
var pub = Pubspec.parse(yaml);
print("${pub.name} ${pub.version}");
print("\t${pub.description}");
print("\t${pub.homepage}");
}

View File

@ -2,9 +2,9 @@ import 'package:source_gen/source_gen.dart';
import 'package:build/build.dart'; import 'package:build/build.dart';
import 'package:yaml/yaml.dart'; import 'package:yaml/yaml.dart';
Builder iipService(BuilderOptions options) { //Builder iipService(BuilderOptions options) {
return LibraryBuilder(TemplateGenerator(), generatedExtension: '.info.dart'); //return LibraryBuilder(TemplateBuilder(), generatedExtension: '.info.dart');
} //}
class TemplateBuilder implements Builder { class TemplateBuilder implements Builder {
//BuilderOptions options; //BuilderOptions options;
@ -36,12 +36,12 @@ class TemplateBuilder implements Builder {
} }
} }
class TemplateGenerator extends Generator { // class TemplateBuilder extends Generator {
@override // @override
String generate(LibraryReader library, BuildStep buildStep) { // String generate(LibraryReader library, BuildStep buildStep) {
return ''' // return '''
// Source library: ${library.element.source.uri} // // Source library: ${library.element.source.uri}
const Testinggggg = 3; // const Testinggggg = 3;
'''; // ''';
} // }
} // }

View File

@ -14,6 +14,7 @@ export 'src/Resource/Template/MemberType.dart';
export 'src/Resource/Template/PropertyPermission.dart'; export 'src/Resource/Template/PropertyPermission.dart';
export 'src/Resource/Template/PropertyTemplate.dart'; export 'src/Resource/Template/PropertyTemplate.dart';
export 'src/Resource/Template/TypeTemplate.dart'; export 'src/Resource/Template/TypeTemplate.dart';
export 'src/Resource/Template/TemplateDescriber.dart';
// ----------------------------------------------------------------- // -----------------------------------------------------------------
// Core // Core

View File

@ -1,7 +1,9 @@
import 'AsyncReply.dart'; import 'AsyncReply.dart';
import '../Resource/Warehouse.dart';
class AsyncBag<T> extends AsyncReply<List<T>> { class AsyncBag<T> extends AsyncReply<List<T>> {
List<AsyncReply<T>> _replies = new List<AsyncReply<T>>(); List<AsyncReply<T>> _replies = <AsyncReply<T>>[];
List<T> _results = <T>[]; List<T> _results = <T>[];
int _count = 0; int _count = 0;
@ -16,7 +18,7 @@ class AsyncBag<T> extends AsyncReply<List<T>> {
_sealedBag = true; _sealedBag = true;
if (_results.length == 0) trigger(new List<T>()); if (_results.length == 0) trigger(<T>[]);
for (var i = 0; i < _results.length; i++) { for (var i = 0; i < _results.length; i++) {
var k = _replies[i]; var k = _replies[i];
@ -25,8 +27,15 @@ class AsyncBag<T> extends AsyncReply<List<T>> {
k.then<dynamic>((r) { k.then<dynamic>((r) {
_results[index] = r; _results[index] = r;
_count++; _count++;
//print("Seal ${_count}/${_results.length}"); if (_count == _results.length) {
if (_count == _results.length) trigger(_results); if (arrayType != null) {
var ar = Warehouse.createArray(arrayType);
_results.forEach(ar.add);
trigger(ar);
} else {
trigger(_results);
}
}
}).error((ex) { }).error((ex) {
triggerError(ex); triggerError(ex);
}); });

View File

@ -3,7 +3,7 @@ library esiur;
import 'AsyncReply.dart'; import 'AsyncReply.dart';
class AsyncQueue<T> extends AsyncReply<T> { class AsyncQueue<T> extends AsyncReply<T> {
List<AsyncReply<T>> _list = new List<AsyncReply<T>>(); List<AsyncReply<T>> _list = <AsyncReply<T>>[];
// object queueLock = new object(); // object queueLock = new object();

View File

@ -27,17 +27,16 @@ import 'AsyncException.dart';
import 'ProgressType.dart'; import 'ProgressType.dart';
class AsyncReply<T> implements Future<T> { class AsyncReply<T> implements Future<T> {
List<Function(T)> _callbacks = new List<Function(T)>(); List<Function(T)> _callbacks = <Function(T)>[];
T _result; T _result;
List<Function(AsyncException)> _errorCallbacks = List<Function(AsyncException)> _errorCallbacks = <Function(AsyncException)>[];
new List<Function(AsyncException)>();
List<Function(ProgressType, int, int)> _progressCallbacks = List<Function(ProgressType, int, int)> _progressCallbacks =
new List<Function(ProgressType, int, int)>(); <Function(ProgressType, int, int)>[];
List<Function(T)> _chunkCallbacks = new List<Function(T)>(); List<Function(T)> _chunkCallbacks = <Function(T)>[];
bool _resultReady = false; bool _resultReady = false;
AsyncException _exception; AsyncException _exception;

View File

@ -2,23 +2,18 @@ import '../Core/IDestructible.dart';
import 'Codec.dart'; import 'Codec.dart';
import 'dart:collection'; import 'dart:collection';
class AutoList<T, ST> extends IDestructible with IterableMixin class AutoList<T, ST> extends IDestructible with IterableMixin {
{ List<T> _list = <T>[];
List<T> _list = new List<T>();
ST _state; ST _state;
bool _removableList; bool _removableList;
sort(Function comparer) sort(Function comparer) {
{
_list.sort(comparer); _list.sort(comparer);
} }
Iterator<T> get iterator => _list.iterator; Iterator<T> get iterator => _list.iterator;
/// <summary> /// <summary>
/// Convert AutoList to array /// Convert AutoList to array
/// </summary> /// </summary>
@ -29,16 +24,13 @@ class AutoList<T, ST> extends IDestructible with IterableMixin
// return _list; // return _list;
//} //}
/// Create a new instance of AutoList /// Create a new instance of AutoList
/// <param name="state">State object to be included when an event is raised.</param> /// <param name="state">State object to be included when an event is raised.</param>
AutoList([ST state, List<T> values]) AutoList([ST state, List<T> values]) {
{
this._state = state; this._state = state;
this._removableList = Codec.implementsInterface<T, IDestructible>(); this._removableList = Codec.implementsInterface<T, IDestructible>();
if (values != null) if (values != null) addRange(values);
addRange(values);
register("modified"); register("modified");
register("added"); register("added");
@ -46,8 +38,6 @@ class AutoList<T, ST> extends IDestructible with IterableMixin
register("cleared"); register("cleared");
} }
/// <summary> /// <summary>
/// Synchronization lock of the list /// Synchronization lock of the list
/// </summary> /// </summary>
@ -67,21 +57,17 @@ class AutoList<T, ST> extends IDestructible with IterableMixin
// return _list.first; // return _list.first;
//} //}
operator [](index) operator [](index) {
{
return _list[index]; return _list[index];
} }
operator []=(index, value) operator []=(index, value) {
{
var oldValue = _list[index]; var oldValue = _list[index];
if (_removableList) if (_removableList) {
{
if (oldValue != null) if (oldValue != null)
(oldValue as IDestructible).off("destroy", _itemDestroyed); (oldValue as IDestructible).off("destroy", _itemDestroyed);
if (value != null) if (value != null) value.on("destroy", _itemDestroyed);
value.on("destroy", _itemDestroyed);
} }
//lock (syncRoot) //lock (syncRoot)
@ -93,39 +79,34 @@ class AutoList<T, ST> extends IDestructible with IterableMixin
/// <summary> /// <summary>
/// Add item to the list /// Add item to the list
/// </summary> /// </summary>
add(T value) add(T value) {
{ if (_removableList) if (value != null)
if (_removableList)
if (value != null)
(value as IDestructible).on("destroy", _itemDestroyed); (value as IDestructible).on("destroy", _itemDestroyed);
// lock (syncRoot) // lock (syncRoot)
_list.add(value); _list.add(value);
emitArgs("add",[_state, value]); emitArgs("add", [_state, value]);
} }
/// <summary> /// <summary>
/// Add an array of items to the list /// Add an array of items to the list
/// </summary> /// </summary>
addRange(List<T> values) addRange(List<T> values) {
{ values.forEach((x) => add(x));
values.forEach((x)=>add(x));
} }
_itemDestroyed(T sender) _itemDestroyed(T sender) {
{
remove(sender); remove(sender);
} }
/// <summary> /// <summary>
/// Clear the list /// Clear the list
/// </summary> /// </summary>
clear() clear() {
{
if (_removableList) if (_removableList)
_list.forEach((x)=>(x as IDestructible)?.off("destroy", _itemDestroyed)); _list
.forEach((x) => (x as IDestructible)?.off("destroy", _itemDestroyed));
// lock (syncRoot) // lock (syncRoot)
_list.clear(); _list.clear();
@ -137,13 +118,10 @@ class AutoList<T, ST> extends IDestructible with IterableMixin
/// Remove an item from the list /// Remove an item from the list
/// <param name="value">Item to remove</param> /// <param name="value">Item to remove</param>
/// </summary> /// </summary>
remove(T value) remove(T value) {
{ if (!_list.contains(value)) return;
if (!_list.contains(value))
return;
if (_removableList) if (_removableList) if (value != null)
if (value != null)
(value as IDestructible).off("destroy", _itemDestroyed); (value as IDestructible).off("destroy", _itemDestroyed);
//lock (syncRoot) //lock (syncRoot)
@ -158,7 +136,6 @@ class AutoList<T, ST> extends IDestructible with IterableMixin
get count => _list.length; get count => _list.length;
get length => _list.length; get length => _list.length;
/// <summary> /// <summary>
/// Check if an item exists in the list /// Check if an item exists in the list
/// </summary> /// </summary>
@ -169,24 +146,14 @@ class AutoList<T, ST> extends IDestructible with IterableMixin
/// Check if any item of the given array is in the list /// Check if any item of the given array is in the list
/// </summary> /// </summary>
/// <param name="values">Array of items</param> /// <param name="values">Array of items</param>
containsAny(values) containsAny(values) {
{ if (values is List<T>) {
for (var v in values) {
if (values is List<T>) if (_list.contains(v)) return true;
{
for(var v in values)
{
if (_list.contains(v))
return true;
} }
} } else if (values is AutoList<T, ST>) {
else if (values is AutoList<T, ST>) for (var v in values._list) {
{ if (_list.contains(v)) return true;
for(var v in values._list)
{
if (_list.contains(v))
return true;
} }
} }

View File

@ -21,7 +21,7 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE. SOFTWARE.
*/ */
import 'package:esiur/src/Resource/Template/TemplateType.dart'; import '../Resource/Template/TemplateType.dart';
import 'DataType.dart'; import 'DataType.dart';
import 'Guid.dart'; import 'Guid.dart';
@ -78,10 +78,11 @@ class Codec {
static List<int> getStructureDateTypes( static List<int> getStructureDateTypes(
Structure structure, DistributedConnection connection) { Structure structure, DistributedConnection connection) {
var keys = structure.getKeys(); var keys = structure.getKeys();
var types = new List<int>(keys.length); var types = new List<int>.generate(
keys.length, (i) => Codec.getDataType(structure[keys[i]], connection));
for (var i = 0; i < keys.length; i++) // for (var i = 0; i < keys.length; i++)
types[i] = Codec.getDataType(structure[keys[i]], connection); // types[i] = Codec.getDataType(structure[keys[i]], connection);
return types; return types;
} }
@ -325,7 +326,7 @@ class Codec {
record.deserialize(value); record.deserialize(value);
reply.trigger(null); reply.trigger(record);
} else { } else {
var record = new Record(); var record = new Record();
@ -336,8 +337,8 @@ class Codec {
} }
}); });
} else { } else {
connection.getTemplate(classId).then((tmp) { connection.getTemplate(classId).then<dynamic>((tmp) {
parseVarArray(data, offset, length, connection).then((ar) { parseVarArray(data, offset, length, connection).then<dynamic>((ar) {
var record = new Record(); var record = new Record();
for (var i = 0; i < tmp.properties.length; i++) for (var i = 0; i < tmp.properties.length; i++)
@ -619,8 +620,8 @@ class Codec {
{ {
var reply = new AsyncReply<Structure>(); var reply = new AsyncReply<Structure>();
var bag = new AsyncBag<dynamic>(); var bag = new AsyncBag<dynamic>();
var keylist = new List<String>(); var keylist = <String>[];
var typelist = new List<int>(); var typelist = <int>[];
var sizeObject = new SizeObject(); var sizeObject = new SizeObject();
if (keys == null) { if (keys == null) {
@ -888,10 +889,9 @@ class Codec {
/// <returns>True, if the resource owner is the given connection, otherwise False.</returns> /// <returns>True, if the resource owner is the given connection, otherwise False.</returns>
static bool isLocalResource( static bool isLocalResource(
IResource resource, DistributedConnection connection) { IResource resource, DistributedConnection connection) {
if (resource is DistributedResource) if ((resource as DistributedResource) if (resource is DistributedResource) {
.connection == if (resource.connection == connection) return true;
connection) return true; }
return false; return false;
} }
@ -1010,7 +1010,26 @@ class Codec {
var end = offset + length; var end = offset + length;
// //
var result = data[offset++];
// Is typed array ?
var type = (data[offset] & 0xF0);
var result = data[offset++] & 0xF;
if (type == ResourceArrayType.Wrapper) {
var classId = data.getGuid(offset);
offset += 16;
var tmp = Warehouse.getTemplateByClassId(classId, TemplateType.Resource);
// not mine, look if the type is elsewhere
if (tmp == null)
Warehouse.getTemplateByClassId(classId, TemplateType.Wrapper);
reply.arrayType = tmp?.definedType;
} else if (type == ResourceArrayType.Static) {
var classId = data.getGuid(offset);
offset += 16;
var tmp = Warehouse.getTemplateByClassId(classId, TemplateType.Wrapper);
reply.arrayType = tmp?.definedType;
}
AsyncReply<IResource> previous = null; AsyncReply<IResource> previous = null;
@ -1036,7 +1055,7 @@ class Codec {
} else if (result == ResourceComparisonResult.Same) { } else if (result == ResourceComparisonResult.Same) {
current = previous; current = previous;
} else if (result == ResourceComparisonResult.Local) { } else if (result == ResourceComparisonResult.Local) {
current = Warehouse.get(data.getUint32(offset)); current = Warehouse.getById(data.getUint32(offset));
offset += 4; offset += 4;
} else if (result == ResourceComparisonResult.Distributed) { } else if (result == ResourceComparisonResult.Distributed) {
current = connection.fetch(data.getUint32(offset)); current = connection.fetch(data.getUint32(offset));

View File

@ -9,7 +9,7 @@ class Guid {
DC get value => _data; DC get value => _data;
bool operator ==(Object other) { bool operator ==(other) {
if (other is Guid) if (other is Guid)
return _data.sequenceEqual(other._data); return _data.sequenceEqual(other._data);
else else
@ -20,4 +20,7 @@ class Guid {
String toString() { String toString() {
return _data.getString(0, _data.length); return _data.getString(0, _data.length);
} }
@override
int get hashCode => _data.toString().hashCode;
} }

View File

@ -27,9 +27,7 @@ import '../Core/IDestructible.dart';
import 'dart:collection'; import 'dart:collection';
import 'Codec.dart'; import 'Codec.dart';
class KeyList<KT, T> extends IEventHandler with MapMixin<KT, T> class KeyList<KT, T> extends IEventHandler with MapMixin<KT, T> {
{
dynamic owner; dynamic owner;
Map<KT, T> _map = new Map<KT, T>(); Map<KT, T> _map = new Map<KT, T>();
@ -39,78 +37,56 @@ class KeyList<KT, T> extends IEventHandler with MapMixin<KT, T>
Iterable<KT> get keys => _map.keys; Iterable<KT> get keys => _map.keys;
Iterable<T> get values => _map.values; Iterable<T> get values => _map.values;
operator [](index) => _map[index];
operator[](index) => _map[index]; operator []=(index, value) => add(index, value);
operator []= (index, value) => add(index, value);
at(int index) => _map.values.elementAt(index); at(int index) => _map.values.elementAt(index);
bool _removableList; bool _removableList;
T take(KT key) {
T take(KT key) if (_map.containsKey(key)) {
{
if (_map.containsKey(key))
{
var v = _map[key]; var v = _map[key];
remove(key); remove(key);
return v; return v;
} } else
else
return null; return null;
} }
List<T> toArray() => _map.values.toList(); List<T> toArray() => _map.values.toList();
void add(KT key, T value) void add(KT key, T value) {
{ if (_removableList) if (value != null)
if (_removableList)
if (value != null)
(value as IDestructible).on("destroy", _itemDestroyed); (value as IDestructible).on("destroy", _itemDestroyed);
if (_map.containsKey(key)) if (_map.containsKey(key)) {
{
var oldValue = _map[key]; var oldValue = _map[key];
if (_removableList) if (_removableList) if (oldValue != null)
if (oldValue != null)
(oldValue as IDestructible).off("destroy", _itemDestroyed); (oldValue as IDestructible).off("destroy", _itemDestroyed);
_map[key] = value; _map[key] = value;
emitArgs("modified", [key, oldValue, value, this]); emitArgs("modified", [key, oldValue, value, this]);
} } else {
else
{
_map[key] = value; _map[key] = value;
emitArgs("add", [value, this]); emitArgs("add", [value, this]);
}
} }
} _itemDestroyed(T sender) {
_itemDestroyed(T sender)
{
removeValue(sender); removeValue(sender);
} }
removeValue(T value) removeValue(T value) {
{ var toRemove = <KT>[];
var toRemove = new List<KT>(); for (var k in _map.keys) if (_map[k] == value) toRemove.add(k);
for (var k in _map.keys)
if (_map[k] == value)
toRemove.add(k);
for (var k in toRemove) for (var k in toRemove) remove(k);
remove(k);
} }
clear() clear() {
{
if (_removableList) if (_removableList)
for (var v in _map.values) for (var v in _map.values)
(v as IDestructible)?.off("destroy", _itemDestroyed); (v as IDestructible)?.off("destroy", _itemDestroyed);
@ -118,22 +94,16 @@ class KeyList<KT, T> extends IEventHandler with MapMixin<KT, T>
_map.clear(); _map.clear();
emitArgs("cleared", [this]); emitArgs("cleared", [this]);
} }
T remove(key) {
if (!_map.containsKey(key)) return null;
T remove(key)
{
if (!_map.containsKey(key))
return null;
var value = _map[key]; var value = _map[key];
if (_removableList) if (_removableList)
(value as IDestructible)?.off("destroy", _itemDestroyed); (value as IDestructible)?.off("destroy", _itemDestroyed);
_map.remove(key); _map.remove(key);
emitArgs("removed", [key, value, this]); emitArgs("removed", [key, value, this]);
@ -141,15 +111,11 @@ class KeyList<KT, T> extends IEventHandler with MapMixin<KT, T>
return value; return value;
} }
int get count => _map.length; int get count => _map.length;
bool contains(KT key) => _map.containsKey(key); bool contains(KT key) => _map.containsKey(key);
KeyList([owner = null]) {
KeyList([owner = null])
{
_removableList = Codec.implementsInterface<T, IDestructible>(); _removableList = Codec.implementsInterface<T, IDestructible>();
this.owner = owner; this.owner = owner;
} }

View File

@ -1,4 +1,4 @@
import 'package:esiur/src/Resource/Template/TemplateDescriber.dart'; import '../Resource/Template/TemplateDescriber.dart';
import 'IRecord.dart'; import 'IRecord.dart';
import 'KeyList.dart'; import 'KeyList.dart';

View File

@ -22,13 +22,10 @@ SOFTWARE.
*/ */
import 'dart:ffi';
import 'dart:typed_data';
import 'package:esiur/esiur.dart'; import '../../Resource/Template/TemplateDescriber.dart';
import 'package:esiur/src/Resource/Template/TemplateDescriber.dart'; import '../../Resource/Template/TemplateType.dart';
import 'package:esiur/src/Resource/Template/TemplateType.dart'; import '../../Security/Authority/AuthenticationMethod.dart';
import 'package:esiur/src/Security/Authority/AuthenticationMethod.dart';
import '../../Core/AsyncBag.dart'; import '../../Core/AsyncBag.dart';
@ -44,7 +41,7 @@ import '../../Core/ExceptionCode.dart';
import '../../Core/ErrorType.dart'; import '../../Core/ErrorType.dart';
import '../../Resource/Warehouse.dart'; import '../../Resource/Warehouse.dart';
import '../Sockets/SocketState.dart';
import 'dart:math'; import 'dart:math';
import '../../Resource/IStore.dart'; import '../../Resource/IStore.dart';
import '../../Resource/IResource.dart'; import '../../Resource/IResource.dart';
@ -434,9 +431,8 @@ class DistributedConnection extends NetworkConnection with IStore {
String link(IResource resource) { String link(IResource resource) {
if (resource is DistributedResource) { if (resource is DistributedResource) {
var r = resource as DistributedResource; if (resource.instance.store == this)
if (r.instance.store == this) return this.instance.name + "/" + resource.id.toString();
return this.instance.name + "/" + r.id.toString();
} }
return null; return null;
@ -445,9 +441,9 @@ class DistributedConnection extends NetworkConnection with IStore {
void init() { void init() {
_queue.then((x) { _queue.then((x) {
if (x.type == DistributedResourceQueueItemType.Event) if (x.type == DistributedResourceQueueItemType.Event)
x.resource.emitEventByIndex(x.index, x.value); x.resource.internal_emitEventByIndex(x.index, x.value);
else else
x.resource.updatePropertyByIndex(x.index, x.value); x.resource.internal_updatePropertyByIndex(x.index, x.value);
}); });
var r = new Random(); var r = new Random();
@ -663,8 +659,7 @@ class DistributedConnection extends NetworkConnection with IStore {
case IIPPacketAction.TemplateFromClassName: case IIPPacketAction.TemplateFromClassName:
case IIPPacketAction.TemplateFromClassId: case IIPPacketAction.TemplateFromClassId:
case IIPPacketAction.TemplateFromResourceId: case IIPPacketAction.TemplateFromResourceId:
iipReply( iipReply(packet.callbackId, [TypeTemplate.parse(packet.content)]);
packet.callbackId, [TypeTemplate.parse(packet.content)]);
break; break;
case IIPPacketAction.QueryLink: case IIPPacketAction.QueryLink:
@ -1285,7 +1280,7 @@ class DistributedConnection extends NetworkConnection with IStore {
.addUint16(link.length) .addUint16(link.length)
.addDC(link) .addDC(link)
.addDC(Codec.composePropertyValueArray( .addDC(Codec.composePropertyValueArray(
(r as DistributedResource).serialize(), this, true)) (r as DistributedResource).internal_serialize(), this, true))
.done(); .done();
} else { } else {
// reply ok // reply ok
@ -1883,7 +1878,7 @@ class DistributedConnection extends NetworkConnection with IStore {
if (ft != null) { if (ft != null) {
if (r is DistributedResource) { if (r is DistributedResource) {
var rt = (r as DistributedResource) var rt = (r as DistributedResource)
.invokeByArrayArguments(index, arguments); .internal_invokeByArrayArguments(index, arguments);
if (rt != null) { if (rt != null) {
rt.then((res) { rt.then((res) {
sendReply(IIPPacketAction.InvokeFunctionArrayArguments, sendReply(IIPPacketAction.InvokeFunctionArrayArguments,
@ -1922,7 +1917,7 @@ class DistributedConnection extends NetworkConnection with IStore {
if (ft != null) { if (ft != null) {
if (r is DistributedResource) { if (r is DistributedResource) {
var rt = (r as DistributedResource) var rt = (r as DistributedResource)
.invokeByNamedArguments(index, namedArgs); .internal_invokeByNamedArguments(index, namedArgs);
if (rt != null) { if (rt != null) {
rt.then((res) { rt.then((res) {
sendReply(IIPPacketAction.InvokeFunctionNamedArguments, sendReply(IIPPacketAction.InvokeFunctionNamedArguments,
@ -2215,8 +2210,7 @@ class DistributedConnection extends NetworkConnection with IStore {
.done() .done()
.then<dynamic>((rt) { .then<dynamic>((rt) {
_templateRequests.remove(classId); _templateRequests.remove(classId);
_templates[(rt[0] as TypeTemplate).classId] = _templates[(rt[0] as TypeTemplate).classId] = rt[0] as TypeTemplate;
rt[0] as TypeTemplate;
Warehouse.putTemplate(rt[0] as TypeTemplate); Warehouse.putTemplate(rt[0] as TypeTemplate);
reply.trigger(rt[0]); reply.trigger(rt[0]);
}).error((ex) { }).error((ex) {
@ -2316,12 +2310,14 @@ class DistributedConnection extends NetworkConnection with IStore {
DistributedResource dr; DistributedResource dr;
if (resource == null) { if (resource == null) {
var template = Warehouse.getTemplateByClassId(rt[0], TemplateType.Wrapper); var template =
Warehouse.getTemplateByClassId(rt[0], TemplateType.Wrapper);
if (template?.definedType != null) { if (template?.definedType != null) {
dr = Warehouse.createInstance(template?.definedType); dr = Warehouse.createInstance(template?.definedType);
dr.init(this, id, rt[1], rt[2]); dr.internal_init(this, id, rt[1], rt[2]);
} else { } else {
dr = new DistributedResource(this, id, rt[1], rt[2]); dr = new DistributedResource();
dr.internal_init(this, id, rt[1], rt[2]);
} }
} else } else
dr = resource; dr = resource;
@ -2338,7 +2334,7 @@ class DistributedConnection extends NetworkConnection with IStore {
Warehouse.put(id.toString(), dr, this, null, tmp).then<dynamic>((ok) { Warehouse.put(id.toString(), dr, this, null, tmp).then<dynamic>((ok) {
Codec.parsePropertyValueArray(d, 0, d.length, this).then((ar) { Codec.parsePropertyValueArray(d, 0, d.length, this).then((ar) {
//print("attached"); //print("attached");
dr.attach(ar); dr.internal_attach(ar);
_resourceRequests.remove(id); _resourceRequests.remove(id);
reply.trigger(dr); reply.trigger(dr);
}); });
@ -2346,7 +2342,7 @@ class DistributedConnection extends NetworkConnection with IStore {
} else { } else {
Codec.parsePropertyValueArray(d, 0, d.length, this).then((ar) { Codec.parsePropertyValueArray(d, 0, d.length, this).then((ar) {
//print("attached"); //print("attached");
dr.attach(ar); dr.internal_attach(ar);
_resourceRequests.remove(id); _resourceRequests.remove(id);
reply.trigger(dr); reply.trigger(dr);
}); });

View File

@ -22,8 +22,13 @@ SOFTWARE.
*/ */
import 'package:esiur/esiur.dart'; import '../../Core/AsyncException.dart';
import 'package:esiur/src/Data/KeyValuePair.dart'; import '../../Core/ErrorType.dart';
import '../../Core/ExceptionCode.dart';
import '../../Resource/ResourceTrigger.dart';
import '../../Data/KeyValuePair.dart';
import '../../Resource/IResource.dart'; import '../../Resource/IResource.dart';
import '../../Core/AsyncReply.dart'; import '../../Core/AsyncReply.dart';
@ -33,6 +38,9 @@ import '../../Data/Codec.dart';
import './DistributedConnection.dart'; import './DistributedConnection.dart';
import '../Packets/IIPPacketAction.dart'; import '../Packets/IIPPacketAction.dart';
import '../../Resource/Template/EventTemplate.dart';
class DistributedResource extends IResource { class DistributedResource extends IResource {
int _instanceId; int _instanceId;
DistributedConnection _connection; DistributedConnection _connection;
@ -107,32 +115,28 @@ class DistributedResource extends IResource {
/// <param name="template">Resource template.</param> /// <param name="template">Resource template.</param>
/// <param name="instanceId">Instance Id given by the other end.</param> /// <param name="instanceId">Instance Id given by the other end.</param>
/// <param name="age">Resource age.</param> /// <param name="age">Resource age.</param>
DistributedResource(
DistributedConnection connection, int instanceId, int age, String link) {
this._link = link;
this._connection = connection;
this._instanceId = instanceId;
this._age = age;
}
void init( // DistributedResource(
DistributedConnection connection, int instanceId, int age, String link) { // DistributedConnection connection, int instanceId, int age, String link) {
this._link = link; // this._link = link;
this._connection = connection; // this._connection = connection;
this._instanceId = instanceId; // this._instanceId = instanceId;
this._age = age; // this._age = age;
}
//void _ready()
//{
// _isReady = true;
// } // }
void internal_init(
DistributedConnection connection, int instanceId, int age, String link) {
this._link = link;
this._connection = connection;
this._instanceId = instanceId;
this._age = age;
}
/// <summary> /// <summary>
/// Export all properties with ResourceProperty attributed as bytes array. /// Export all properties with ResourceProperty attributed as bytes array.
/// </summary> /// </summary>
/// <returns></returns> /// <returns></returns>
List<PropertyValue> serialize() { List<PropertyValue> internal_serialize() {
var props = new List<PropertyValue>(_properties.length); var props = new List<PropertyValue>(_properties.length);
for (var i = 0; i < _properties.length; i++) for (var i = 0; i < _properties.length; i++)
@ -142,7 +146,7 @@ class DistributedResource extends IResource {
return props; return props;
} }
bool attach(List<PropertyValue> properties) { bool internal_attach(List<PropertyValue> properties) {
if (_attached) if (_attached)
return false; return false;
else { else {
@ -168,7 +172,7 @@ class DistributedResource extends IResource {
if (_queued_updates.length > 0) { if (_queued_updates.length > 0) {
_queued_updates _queued_updates
.forEach((kv) => updatePropertyByIndex(kv.key, kv.value)); .forEach((kv) => internal_updatePropertyByIndex(kv.key, kv.value));
_queued_updates.clear(); _queued_updates.clear();
} }
} }
@ -207,7 +211,7 @@ class DistributedResource extends IResource {
return connection.sendUnlistenRequest(_instanceId, et.index); return connection.sendUnlistenRequest(_instanceId, et.index);
} }
void emitEventByIndex(int index, dynamic args) { void internal_emitEventByIndex(int index, dynamic args) {
// neglect events when the object is not yet attached // neglect events when the object is not yet attached
if (!_attached) return; if (!_attached) return;
@ -217,7 +221,7 @@ class DistributedResource extends IResource {
instance.emitResourceEvent(null, null, et.name, args); instance.emitResourceEvent(null, null, et.name, args);
} }
AsyncReply<dynamic> invokeByNamedArguments(int index, Structure namedArgs) { AsyncReply<dynamic> internal_invokeByNamedArguments(int index, Structure namedArgs) {
if (_destroyed) throw new Exception("Trying to access destroyed object"); if (_destroyed) throw new Exception("Trying to access destroyed object");
if (_suspended) throw new Exception("Trying to access suspended object"); if (_suspended) throw new Exception("Trying to access suspended object");
@ -228,7 +232,7 @@ class DistributedResource extends IResource {
return connection.sendInvokeByNamedArguments(_instanceId, index, namedArgs); return connection.sendInvokeByNamedArguments(_instanceId, index, namedArgs);
} }
AsyncReply<dynamic> invokeByArrayArguments(int index, List<dynamic> args) { AsyncReply<dynamic> internal_invokeByArrayArguments(int index, List<dynamic> args) {
if (_destroyed) throw new Exception("Trying to access destroyed object"); if (_destroyed) throw new Exception("Trying to access destroyed object");
if (_suspended) throw new Exception("Trying to access suspended object"); if (_suspended) throw new Exception("Trying to access suspended object");
@ -270,9 +274,9 @@ class DistributedResource extends IResource {
for (var p in invocation.namedArguments.keys) for (var p in invocation.namedArguments.keys)
namedArgs[_getMemberName(p)] = invocation.namedArguments[p]; namedArgs[_getMemberName(p)] = invocation.namedArguments[p];
return invokeByNamedArguments(ft.index, namedArgs); return internal_invokeByNamedArguments(ft.index, namedArgs);
} else { } else {
return invokeByArrayArguments( return internal_invokeByArrayArguments(
ft.index, invocation.positionalArguments); ft.index, invocation.positionalArguments);
} }
} }
@ -304,7 +308,7 @@ class DistributedResource extends IResource {
return _properties[index]; return _properties[index];
} }
void updatePropertyByIndex(int index, dynamic value) { void internal_updatePropertyByIndex(int index, dynamic value) {
if (!_attached) { if (!_attached) {
_queued_updates.add(KeyValuePair(index, value)); _queued_updates.add(KeyValuePair(index, value));
} else { } else {

View File

@ -1,4 +1,4 @@
import 'package:esiur/src/Resource/Template/TemplateDescriber.dart'; import '../../Resource/Template/TemplateDescriber.dart';
import '../../Resource/IResource.dart'; import '../../Resource/IResource.dart';
import '../../Core/AsyncReply.dart'; import '../../Core/AsyncReply.dart';

View File

@ -23,7 +23,11 @@ SOFTWARE.
*/ */
import 'dart:io'; import 'dart:io';
import 'package:esiur/esiur.dart';
import '../../Core/ErrorType.dart';
import '../../Core/ExceptionCode.dart';
import '../../Core/AsyncException.dart';
import 'ISocket.dart'; import 'ISocket.dart';
import '../../Data/DC.dart'; import '../../Data/DC.dart';

View File

@ -10,19 +10,19 @@ import '../Resource/Template/TemplateDataType.dart';
import '../Resource/Template/TypeTemplate.dart'; import '../Resource/Template/TypeTemplate.dart';
class TemplateGenerator { class TemplateGenerator {
// static RegExp urlRegex = new RegExp("^(?:([\S]*)://([^/]*)/?)"); // static RegExp urlRegex = RegExp("^(?:([\S]*)://([^/]*)/?)");
static final _urlRegex = RegExp(r'^(?:([^\s|:]*):\/\/([^\/]*)\/?(.*))'); static final _urlRegex = RegExp(r'^(?:([^\s|:]*):\/\/([^\/]*)\/?(.*))');
static String generateRecord( static String generateRecord(
TypeTemplate template, List<TypeTemplate> templates) { TypeTemplate template, List<TypeTemplate> templates) {
var className = template.className.split('.').last; var className = template.className.split('.').last;
var rt = new StringBuffer(); var rt = StringBuffer();
rt.writeln("class ${className} extends IRecord {"); rt.writeln("class ${className} extends IRecord {");
template.properties.forEach((p) { template.properties.forEach((p) {
var ptTypeName = getTypeName(template, p.valueType, templates); var ptTypeName = getTypeName(template, p.valueType, templates);
rt.writeln("${ptTypeName} ${p.name};"); rt.writeln("${ptTypeName}? ${p.name};");
rt.writeln(); rt.writeln();
}); });
@ -48,40 +48,78 @@ class TemplateGenerator {
rt.writeln("return rt;"); rt.writeln("return rt;");
rt.writeln("}"); rt.writeln("}");
// add template
var descProps = template.properties.map((p) {
var isArray = p.valueType.type & 0x80 == 0x80;
var ptType = p.valueType.type & 0x7F;
var ptTypeName = getTypeName(
template, TemplateDataType(ptType, p.valueType.typeGuid), templates);
// return "Prop(\"${p.name}\", ${ptTypeName}, ${isArray})";
return "Prop('${p.name}', ${ptTypeName}, ${isArray}, ${_escape(p.readExpansion)}, ${_escape(p.writeExpansion)})";
}).join(', ');
rt.writeln("""@override
TemplateDescriber get template => TemplateDescriber('${template.className}', properties: [${descProps}]);""");
rt.writeln("\r\n}"); rt.writeln("\r\n}");
return rt.toString(); return rt.toString();
} }
static String _translateClassName(String className) {
var cls = className.split('.');
var nameSpace = cls.take(cls.length - 1).join('_').toLowerCase();
return "$nameSpace.${cls.last}";
}
static String getTypeName(TypeTemplate forTemplate, static String getTypeName(TypeTemplate forTemplate,
TemplateDataType templateDataType, List<TypeTemplate> templates) { TemplateDataType templateDataType, List<TypeTemplate> templates) {
if (templateDataType.type == DataType.Resource) { if (templateDataType.type == DataType.Resource) {
if (templateDataType.typeGuid == forTemplate.classId) if (templateDataType.typeGuid == forTemplate.classId)
return forTemplate.className.split('.').last; return forTemplate.className.split('.').last;
else { else {
var tmp = var tmp = templates.firstWhere((x) =>
templates.firstWhere((x) => x.classId == templateDataType.typeGuid); x.classId == templateDataType.typeGuid &&
(x.type == TemplateType.Resource ||
x.type == TemplateType.Wrapper));
if (tmp == null) return "dynamic"; // something went wrong if (tmp == null) return "dynamic"; // something went wrong
var cls = tmp.className.split('.'); return _translateClassName(tmp.className);
var nameSpace = cls.take(cls.length - 1).join('_');
return "$nameSpace.${cls.last}";
} }
} else if (templateDataType.type == DataType.ResourceArray) { } else if (templateDataType.type == DataType.ResourceArray) {
if (templateDataType.typeGuid == forTemplate.classId) if (templateDataType.typeGuid == forTemplate.classId)
return "List<${forTemplate.className.split('.').last}>"; return "List<${forTemplate.className.split('.').last}>";
else { else {
var tmp = var tmp = templates.firstWhere((x) =>
templates.firstWhere((x) => x.classId == templateDataType.typeGuid); x.classId == templateDataType.typeGuid &&
(x.type == TemplateType.Resource ||
x.type == TemplateType.Wrapper));
if (tmp == null) return "dynamic"; // something went wrong if (tmp == null) return "dynamic"; // something went wrong
var cls = tmp.className.split('.'); return "List<${_translateClassName(tmp.className)}>";
var nameSpace = cls.take(cls.length - 1).join('_'); }
} else if (templateDataType.type == DataType.Record) {
return "List<$nameSpace.${cls.last}>"; if (templateDataType.typeGuid == forTemplate.classId)
return forTemplate.className.split('.').last;
else {
var tmp = templates.firstWhere((x) =>
x.classId == templateDataType.typeGuid &&
x.type == TemplateType.Record);
if (tmp == null) return "dynamic"; // something went wrong
return _translateClassName(tmp.className);
}
} else if (templateDataType.type == DataType.RecordArray) {
if (templateDataType.typeGuid == forTemplate.classId)
return "List<${forTemplate.className.split('.').last}>";
else {
var tmp = templates.firstWhere((x) =>
x.classId == templateDataType.typeGuid &&
x.type == TemplateType.Record);
if (tmp == null) return "dynamic"; // something went wrong
return "List<${_translateClassName(tmp.className)}>";
} }
} }
@ -104,7 +142,7 @@ class TemplateGenerator {
case DataType.DecimalArray: case DataType.DecimalArray:
return "List<double>"; return "List<double>";
case DataType.Float32: case DataType.Float32:
return "List<double>"; return "double";
case DataType.Float32Array: case DataType.Float32Array:
return "List<double>"; return "List<double>";
case DataType.Float64: case DataType.Float64:
@ -172,7 +210,7 @@ class TemplateGenerator {
String username = null, String username = null,
String password = null]) async { String password = null]) async {
try { try {
if (!_urlRegex.hasMatch(url)) throw new Exception("Invalid IIP URL"); if (!_urlRegex.hasMatch(url)) throw Exception("Invalid IIP URL");
var path = _urlRegex.allMatches(url).first; var path = _urlRegex.allMatches(url).first;
var con = await Warehouse.get<DistributedConnection>( var con = await Warehouse.get<DistributedConnection>(
@ -181,12 +219,15 @@ class TemplateGenerator {
? {username: username, password: password} ? {username: username, password: password}
: null); : null);
if (con == null) throw new Exception("Can't connect to server"); if (con == null) throw Exception("Can't connect to server");
if (isNullOrEmpty(dir)) dir = path[2].replaceAll(":", "_"); if (isNullOrEmpty(dir)) dir = path[2].replaceAll(":", "_");
var templates = await con.getLinkTemplates(path[3]); var templates = await con.getLinkTemplates(path[3]);
// no longer needed
Warehouse.remove(con);
var dstDir = Directory("lib/$dir"); var dstDir = Directory("lib/$dir");
if (!dstDir.existsSync()) dstDir.createSync(); if (!dstDir.existsSync()) dstDir.createSync();
@ -201,9 +242,8 @@ class TemplateGenerator {
templates.forEach((tmp) { templates.forEach((tmp) {
if (tmp != skipTemplate) { if (tmp != skipTemplate) {
var cls = tmp.className.split('.'); var cls = tmp.className.split('.');
var nameSpace = cls.take(cls.length - 1).join('_'); var nameSpace = cls.take(cls.length - 1).join('_').toLowerCase();
imports.writeln( imports.writeln("import '${tmp.className}.g.dart' as $nameSpace;");
"import '${tmp.className}.Generated.dart' as $nameSpace;");
} }
}); });
@ -213,51 +253,61 @@ class TemplateGenerator {
// make sources // make sources
templates.forEach((tmp) { templates.forEach((tmp) {
print("Generating `${tmp.className}`.");
if (tmp.type == TemplateType.Resource) { if (tmp.type == TemplateType.Resource) {
var source = makeImports(tmp) + generateClass(tmp, templates); var source = makeImports(tmp) + generateClass(tmp, templates);
var f = File("${dstDir.path}/${tmp.className}.Generated.dart"); var f = File("${dstDir.path}/${tmp.className}.g.dart");
f.writeAsStringSync(source); f.writeAsStringSync(source);
} else if (tmp.type == TemplateType.Record) { } else if (tmp.type == TemplateType.Record) {
var source = makeImports(tmp) + generateRecord(tmp, templates); var source = makeImports(tmp) + generateRecord(tmp, templates);
var f = File("${dstDir.path}/${tmp.className}.Generated.dart"); var f = File("${dstDir.path}/${tmp.className}.g.dart");
f.writeAsStringSync(source); f.writeAsStringSync(source);
} }
}); });
// generate info class // generate info class
var typesFile =
"using System; \r\n namespace Esiur { public static class Generated { public static Type[] Resources {get;} = new Type[] { " +
templates
.where((x) => x.type == TemplateType.Resource)
.map((x) => "typeof(${x.className})")
.join(',') +
" }; \r\n public static Type[] Records { get; } = new Type[] { " +
templates
.where((x) => x.type == TemplateType.Record)
.map((x) => "typeof(${x.className})")
.join(',') +
" }; " +
"\r\n } \r\n}";
var f = File("${dstDir.path}/Esiur.Generated.cs"); var defineCreators = templates.map((tmp) {
// creator
var className = _translateClassName(tmp.className);
return "Warehouse.defineCreator(${className}, () => ${className}(), () => <${className}>[]);";
}).join("\r\n");
var putTemplates = templates.map((tmp) {
var className = _translateClassName(tmp.className);
return "Warehouse.putTemplate(TypeTemplate.fromType(${className}));";
}).join("\r\n");
var typesFile = makeImports(null) +
"\r\n void init_${dir}(){ ${defineCreators} \r\n ${putTemplates}}";
var f = File("${dstDir.path}/init.g.dart");
f.writeAsStringSync(typesFile); f.writeAsStringSync(typesFile);
return dstDir.path; return dstDir.path;
} catch (ex) { } catch (ex) {
//File.WriteAllText("C:\\gen\\gettemplate.err", ex.ToString());
throw ex; throw ex;
} }
} }
static String _escape(String str) {
if (str == null)
return "null";
else
return "r'$str'";
}
static String generateClass( static String generateClass(
TypeTemplate template, List<TypeTemplate> templates) { TypeTemplate template, List<TypeTemplate> templates) {
var className = template.className.split('.').last; var className = template.className.split('.').last;
var rt = new StringBuffer(); var rt = StringBuffer();
rt.writeln("class $className extends DistributedResource {"); rt.writeln("class $className extends DistributedResource {");
rt.writeln( rt.writeln(
"$className(DistributedConnection connection, int instanceId, int age, String link) : super(connection, instanceId, age, link) {"); // "$className(DistributedConnection connection, int instanceId, int age, String link) : super(connection, instanceId, age, link) {");
"$className() {");
template.events.forEach((e) { template.events.forEach((e) {
rt.writeln("on('${e.name}', (x) => _${e.name}Controller.add(x));"); rt.writeln("on('${e.name}', (x) => _${e.name}Controller.add(x));");
@ -273,9 +323,9 @@ class TemplateGenerator {
.join(",")); .join(","));
rt.writeln(") {"); rt.writeln(") {");
rt.writeln("var rt = new AsyncReply<$rtTypeName>();"); rt.writeln("var rt = AsyncReply<$rtTypeName>();");
rt.writeln( rt.writeln(
"invokeByArrayArguments(${f.index}, [${f.arguments.map((x) => x.name).join(',')}])"); "internal_invokeByArrayArguments(${f.index}, [${f.arguments.map((x) => x.name).join(',')}])");
rt.writeln(".then<dynamic>((x) => rt.trigger(x))"); rt.writeln(".then<dynamic>((x) => rt.trigger(x))");
rt.writeln(".error((x) => rt.triggerError(x))"); rt.writeln(".error((x) => rt.triggerError(x))");
rt.writeln(".chunk((x) => rt.triggerChunk(x));"); rt.writeln(".chunk((x) => rt.triggerChunk(x));");
@ -299,6 +349,43 @@ class TemplateGenerator {
rt.writeln("}"); rt.writeln("}");
}); });
// add template
var descProps = template.properties.map((p) {
var isArray = p.valueType.type & 0x80 == 0x80;
var ptType = p.valueType.type & 0x7F;
var ptTypeName = getTypeName(
template, TemplateDataType(ptType, p.valueType.typeGuid), templates);
return "Prop('${p.name}', ${ptTypeName}, ${isArray}, ${_escape(p.readExpansion)}, ${_escape(p.writeExpansion)})";
}).join(', ');
var descFuncs = template.functions.map((f) {
var isArray = f.returnType.type & 0x80 == 0x80;
var ftType = f.returnType.type & 0x7F;
var ftTypeName = getTypeName(
template, TemplateDataType(ftType, f.returnType.typeGuid), templates);
var args = f.arguments.map((a) {
var isArray = a.type.type & 0x80 == 0x80;
var atType = a.type.type & 0x7F;
var atTypeName = getTypeName(
template, TemplateDataType(atType, a.type.typeGuid), templates);
return "Arg('${a.name}', ${atTypeName}, ${isArray})";
}).join(', ');
return "Func('${f.name}', ${ftTypeName}, ${isArray}, [${args}], ${_escape(f.expansion)})";
}).join(', ');
var descEvents = template.events.map((e) {
var isArray = e.argumentType.type & 0x80 == 0x80;
var etType = e.argumentType.type & 0x7F;
var etTypeName = getTypeName(template,
TemplateDataType(etType, e.argumentType.typeGuid), templates);
return "Evt('${e.name}', ${etTypeName}, ${isArray}, ${e.listenable}, ${_escape(e.expansion)})";
}).join(', ');
rt.writeln(
"TemplateDescriber get template => TemplateDescriber('${template.className}', properties: [${descProps}], functions: [${descFuncs}], events: [$descEvents]);");
rt.writeln("\r\n}"); rt.writeln("\r\n}");
return rt.toString(); return rt.toString();

View File

@ -0,0 +1,7 @@
class FactoryEntry {
final Type type;
final Function() instanceCreator;
final Function() arrayCreator;
FactoryEntry(this.type, this.instanceCreator, this.arrayCreator);
}

View File

@ -22,7 +22,7 @@ SOFTWARE.
*/ */
import 'package:esiur/src/Resource/Template/TemplateDescriber.dart'; import './Template/TemplateDescriber.dart';
import '../Resource/Template/TemplateDescriber.dart'; import '../Resource/Template/TemplateDescriber.dart';
import '../Core/IDestructible.dart'; import '../Core/IDestructible.dart';

View File

@ -29,6 +29,6 @@ class MemberTemplate
DC compose() DC compose()
{ {
// return DC.ToBytes(Name); return DC.stringToBytes(_name);
} }
} }

View File

@ -10,7 +10,7 @@ import '../StorageMode.dart';
class PropertyTemplate extends MemberTemplate { class PropertyTemplate extends MemberTemplate {
TemplateDataType valueType; TemplateDataType valueType;
int permission; int permission = 0;
int storage; int storage;

View File

@ -26,7 +26,7 @@ class TemplateDataType {
TemplateDataType.fromType(type, bool isArray) { TemplateDataType.fromType(type, bool isArray) {
int dt; int dt;
if (type == null) if (type == null || type == dynamic)
dt = DataType.Void; dt = DataType.Void;
else if (type is int) { else if (type is int) {
dt = type; dt = type;
@ -50,7 +50,7 @@ class TemplateDataType {
dt = DataType.Int64; dt = DataType.Int64;
else if (type == Float) else if (type == Float)
dt = DataType.Float32; dt = DataType.Float32;
else if (type == Double) else if (type == Double || type == double)
dt = DataType.Float64; dt = DataType.Float64;
else if (type == String) else if (type == String)
dt = DataType.String; dt = DataType.String;

View File

@ -5,9 +5,10 @@ class TemplateDescriber {
final List<Evt> events; final List<Evt> events;
final List<Func> functions; final List<Func> functions;
final String nameSpace; final String nameSpace;
final int version;
TemplateDescriber(this.nameSpace, TemplateDescriber(this.nameSpace,
{this.properties, this.functions, this.events}); {this.properties, this.functions, this.events, this.version = 0});
} }
// class Property<T> { // class Property<T> {
@ -48,7 +49,8 @@ class Prop {
final bool isArray; final bool isArray;
final String readAnnotation; final String readAnnotation;
final String writeAnnotation; final String writeAnnotation;
Prop(this.name, this.type, this.isArray, [this.readAnnotation = null, this.writeAnnotation = null]); Prop(this.name, this.type, this.isArray,
[this.readAnnotation = null, this.writeAnnotation = null]);
} }
class Evt { class Evt {
@ -58,7 +60,8 @@ class Evt {
final bool isArray; final bool isArray;
final String annotation; final String annotation;
Evt(this.name, this.type, this.isArray, [this.listenable = false, this.annotation]); Evt(this.name, this.type, this.isArray,
[this.listenable = false, this.annotation]);
} }
class Func { class Func {
@ -68,7 +71,7 @@ class Func {
final bool isArray; final bool isArray;
final String annotation; final String annotation;
Func(this.name, this.returnType, this.argsType, this.isArray, Func(this.name, this.returnType, this.isArray, this.argsType,
[this.annotation = null]); [this.annotation = null]);
} }

View File

@ -1,5 +1,7 @@
import 'dart:ffi'; import 'dart:ffi';
import '../../Net/IIP/DistributedResource.dart';
import '../../Data/BinaryList.dart'; import '../../Data/BinaryList.dart';
import '../../Security/Integrity/SHA256.dart'; import '../../Security/Integrity/SHA256.dart';
@ -55,8 +57,7 @@ class TypeTemplate {
*/ */
//@TODO: implement //@TODO: implement
static List<TypeTemplate> getDependencies(TypeTemplate template) => static List<TypeTemplate> getDependencies(TypeTemplate template) => [];
[];
EventTemplate getEventTemplateByName(String eventName) { EventTemplate getEventTemplateByName(String eventName) {
for (var i in _events) if (i.name == eventName) return i; for (var i in _events) if (i.name == eventName) return i;
@ -106,15 +107,27 @@ class TypeTemplate {
List<PropertyTemplate> get properties => _properties; List<PropertyTemplate> get properties => _properties;
TypeTemplate.fromType(Type type, [bool addToWarehouse, bool isWrapper]) { TypeTemplate.fromType(Type type, [bool addToWarehouse = false]) {
// debugging print("FromType ${type.toString()}");
var instance = Warehouse.createInstance(type); var instance = Warehouse.createInstance(type);
if (instance is IRecord) if (instance is DistributedResource)
_templateType = TemplateType.Record; _templateType = TemplateType.Wrapper;
else if (instance is IResource) else if (instance is IResource)
_templateType = TemplateType.Resource; _templateType = TemplateType.Resource;
else if (instance is IRecord)
_templateType = TemplateType.Record;
else else
throw new Exception("Type is neither a resource nor a record."); throw new Exception(
"Type must implement IResource, IRecord or inherit from DistributedResource.");
// if (instance is IRecord)
// _templateType = TemplateType.Record;
// else if (instance is IResource)
// _templateType = TemplateType.Resource;
// else
// throw new Exception("Type is neither a resource nor a record.");
TemplateDescriber describer = instance.template; TemplateDescriber describer = instance.template;
@ -125,9 +138,12 @@ class TypeTemplate {
// set guid // set guid
_classId = getTypeGuid(_className); _classId = getTypeGuid(_className);
_version = describer.version;
if (addToWarehouse) Warehouse.putTemplate(this); if (addToWarehouse) Warehouse.putTemplate(this);
// _templates.add(template.classId, template); // _templates.add(template.classId, template);
if (describer.properties != null)
for (var i = 0; i < describer.properties.length; i++) { for (var i = 0; i < describer.properties.length; i++) {
var pi = describer.properties[i]; var pi = describer.properties[i];
var pt = PropertyTemplate( var pt = PropertyTemplate(
@ -141,18 +157,27 @@ class TypeTemplate {
properties.add(pt); properties.add(pt);
} }
if (describer.functions != null)
for (var i = 0; i < describer.functions.length; i++) { for (var i = 0; i < describer.functions.length; i++) {
var fi = describer.functions[i]; var fi = describer.functions[i];
List<ArgumentTemplate> args = fi.argsType.map((arg) => ArgumentTemplate( List<ArgumentTemplate> args = fi.argsType
arg.name, TemplateDataType.fromType(arg.type, arg.isArray))); .map((arg) => ArgumentTemplate(
arg.name, TemplateDataType.fromType(arg.type, arg.isArray)))
.toList();
var ft = FunctionTemplate(this, i, fi.name, args, var ft = FunctionTemplate(
TemplateDataType.fromType(fi.returnType, fi.isArray), fi.annotation); this,
i,
fi.name,
args,
TemplateDataType.fromType(fi.returnType, fi.isArray),
fi.annotation);
functions.add(ft); functions.add(ft);
} }
if (describer.events != null)
for (var i = 0; i < describer.events.length; i++) { for (var i = 0; i < describer.events.length; i++) {
var ei = describer.events[i]; var ei = describer.events[i];

View File

@ -23,6 +23,7 @@ SOFTWARE.
*/ */
import '../Data/AutoList.dart'; import '../Data/AutoList.dart';
import 'FactoryEntry.dart';
import 'Template/TemplateType.dart'; import 'Template/TemplateType.dart';
import 'Template/TypeTemplate.dart'; import 'Template/TypeTemplate.dart';
import '../Data/Guid.dart'; import '../Data/Guid.dart';
@ -45,7 +46,6 @@ class Warehouse {
static Map<int, IResource> _resources = new Map<int, IResource>(); static Map<int, IResource> _resources = new Map<int, IResource>();
static int resourceCounter = 0; static int resourceCounter = 0;
static KeyList<TemplateType, KeyList<Guid, TypeTemplate>> _templates = static KeyList<TemplateType, KeyList<Guid, TypeTemplate>> _templates =
_initTemplates(); // _initTemplates(); //
@ -60,13 +60,11 @@ class Warehouse {
return rt; return rt;
} }
static KeyList<Type, FactoryEntry> _factory = _getBuiltInTypes();
static KeyList<Type, Function()> _factory = _getBuiltInTypes();
static KeyList<String, AsyncReply<IStore> Function(String, dynamic)> static KeyList<String, AsyncReply<IStore> Function(String, dynamic)>
protocols = _getSupportedProtocols(); protocols = _getSupportedProtocols();
static bool _warehouseIsOpen = false; static bool _warehouseIsOpen = false;
static final _urlRegex = RegExp(r'^(?:([^\s|:]*):\/\/([^\/]*)\/?(.*))'); static final _urlRegex = RegExp(r'^(?:([^\s|:]*):\/\/([^\/]*)\/?(.*))');
@ -470,7 +468,11 @@ class Warehouse {
} }
static T createInstance<T>(Type T) { static T createInstance<T>(Type T) {
return _factory[T].call(); return _factory[T].instanceCreator.call();
}
static List<T> createArray<T>(Type T) {
return _factory[T].arrayCreator.call();
} }
static AsyncReply<T> newResource<T extends IResource>(String name, static AsyncReply<T> newResource<T extends IResource>(String name,
@ -479,7 +481,7 @@ class Warehouse {
IPermissionsManager manager = null, IPermissionsManager manager = null,
attributes = null, attributes = null,
properties = null]) { properties = null]) {
var resource = _factory[T].call(); var resource = _factory[T].instanceCreator.call();
if (properties != null) { if (properties != null) {
dynamic d = resource; dynamic d = resource;
@ -525,8 +527,9 @@ class Warehouse {
static TypeTemplate getTemplateByType(Type type) { static TypeTemplate getTemplateByType(Type type) {
// loaded ? // loaded ?
for (var tmps in _templates.values) for (var tmps in _templates.values)
for (var tmp in tmps.values) for (var tmp in tmps.values) if (tmp.definedType == type) return tmp;
if (tmp.className == type.toString()) return tmp;
//if (tmp.className == type.toString()) return tmp;
var template = new TypeTemplate.fromType(type, true); var template = new TypeTemplate.fromType(type, true);
@ -562,27 +565,30 @@ class Warehouse {
/// </summary> /// </summary>
/// <param name="className">Class name.</param> /// <param name="className">Class name.</param>
/// <returns>Resource template.</returns> /// <returns>Resource template.</returns>
static TypeTemplate getTemplateByClassName(String className, [TemplateType templateType = TemplateType.Unspecified]) { static TypeTemplate getTemplateByClassName(String className,
[TemplateType templateType = TemplateType.Unspecified]) {
if (templateType == TemplateType.Unspecified) if (templateType == TemplateType.Unspecified) {
{
// look in resources // look in resources
var template = _templates[TemplateType.Resource].values.firstWhere((x) => x.className == className); var template = _templates[TemplateType.Resource]
if (template != null) .values
return template; .firstWhere((x) => x.className == className);
if (template != null) return template;
// look in records // look in records
template = _templates[TemplateType.Record].values.firstWhere((x) => x.className == className); template = _templates[TemplateType.Record]
if (template != null) .values
return template; .firstWhere((x) => x.className == className);
if (template != null) return template;
// look in wrappers // look in wrappers
template = _templates[TemplateType.Wrapper].values.firstWhere((x) => x.className == className); template = _templates[TemplateType.Wrapper]
.values
.firstWhere((x) => x.className == className);
return template; return template;
} } else {
else return _templates[templateType]
{ .values
return _templates[templateType].values.firstWhere((x) => x.className == className); .firstWhere((x) => x.className == className);
} }
} }
@ -625,9 +631,17 @@ class Warehouse {
return rt; return rt;
} }
static KeyList<Type, Function()> _getBuiltInTypes() { static defineCreator(
var rt = KeyList<Type, Function()>(); Type type, Function instanceCreator, Function arrayCreator) {
rt.add(DistributedConnection, () => DistributedConnection()); _factory.add(type, FactoryEntry(type, instanceCreator, arrayCreator));
}
static KeyList<Type, FactoryEntry> _getBuiltInTypes() {
var rt = KeyList<Type, FactoryEntry>();
rt.add(
DistributedConnection,
FactoryEntry(DistributedConnection, () => DistributedConnection(),
() => DistributedConnection()));
return rt; return rt;
} }
} }

View File

@ -50,6 +50,13 @@ packages:
url: "https://pub.dartlang.org" url: "https://pub.dartlang.org"
source: hosted source: hosted
version: "1.3.1" version: "1.3.1"
checked_yaml:
dependency: transitive
description:
name: checked_yaml
url: "https://pub.dartlang.org"
source: hosted
version: "2.0.1"
cli_util: cli_util:
dependency: transitive dependency: transitive
description: description:
@ -134,6 +141,13 @@ packages:
url: "https://pub.dartlang.org" url: "https://pub.dartlang.org"
source: hosted source: hosted
version: "0.6.3" version: "0.6.3"
json_annotation:
dependency: transitive
description:
name: json_annotation
url: "https://pub.dartlang.org"
source: hosted
version: "4.0.1"
logging: logging:
dependency: transitive dependency: transitive
description: description:
@ -204,6 +218,13 @@ packages:
url: "https://pub.dartlang.org" url: "https://pub.dartlang.org"
source: hosted source: hosted
version: "2.0.0" version: "2.0.0"
pubspec_parse:
dependency: "direct main"
description:
name: pubspec_parse
url: "https://pub.dartlang.org"
source: hosted
version: "1.0.0"
shelf: shelf:
dependency: transitive dependency: transitive
description: description:

View File

@ -1,7 +1,7 @@
name: esiur name: esiur
description: Distributed Object Framework. description: Distributed Object Framework.
version: 1.3.0 version: 1.4.0
# author: Ahmed Zamil <ahmed@esiur.com> #author: Ahmed Zamil <ahmed@esiur.com>
homepage: https://github.com/esiur/esiur-dart homepage: https://github.com/esiur/esiur-dart
@ -11,6 +11,7 @@ environment:
dependencies: dependencies:
source_gen: ^1.0.2 source_gen: ^1.0.2
args: # args: #
pubspec_parse:
dev_dependencies: dev_dependencies:
test: ^1.14.2 test: ^1.14.2

View File

@ -1,22 +1,9 @@
import 'package:esiur/src/Proxy/TemplateGenerator.dart';
import "package:test/test.dart";
import 'package:esiur/esiur.dart'; import 'package:esiur/esiur.dart';
import 'dart:io';
import '../lib/localhost/Esiur.Generated.dart';
import 'TestResource.dart'; import 'TestResource.dart';
main() async { main() async {
try { try {
testMe();
var c = EsiurGenerated;
print(c);
print(Warehouse.protocols.length);
await TemplateGenerator.getTemplate("iip://localhost/sys/cp");
// var x = await Warehouse.get("iip://localhost/sys/cp",
// {"username": "guest", "password": "123456", "domain": "example.com"});
// print(x);
} catch (ex) { } catch (ex) {
print("Error occured"); print("Error occured");
print(ex); print(ex);