2024-02-25 00:39:40 +01:00
|
|
|
// ignore_for_file: avoid_web_libraries_in_flutter
|
|
|
|
|
2024-02-23 18:58:31 +01:00
|
|
|
import 'dart:async';
|
2024-02-25 00:39:40 +01:00
|
|
|
import 'dart:js' as js;
|
|
|
|
import 'dart:html' as html;
|
2024-02-23 18:58:31 +01:00
|
|
|
|
2024-02-25 00:39:40 +01:00
|
|
|
import 'package:flutter/foundation.dart';
|
2024-02-23 18:58:31 +01:00
|
|
|
import 'package:flutter_stockfish_plugin/stockfish_bindings.dart';
|
|
|
|
|
|
|
|
class StockfishChessEngineBindings
|
|
|
|
extends StockfishChessEngineAbstractBindings {
|
2024-02-25 00:39:40 +01:00
|
|
|
Future<void>? loadJs;
|
|
|
|
StockfishChessEngineBindings() {
|
|
|
|
loadJs = loadJsFileIfNeeded();
|
|
|
|
}
|
|
|
|
|
2024-02-23 18:58:31 +01:00
|
|
|
@override
|
|
|
|
void cleanUp(int exitCode) {
|
2024-02-25 00:39:40 +01:00
|
|
|
stdoutController.close();
|
|
|
|
js.context.callMethod("stop_listening", []);
|
2024-02-23 18:58:31 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
@override
|
2024-02-25 00:39:40 +01:00
|
|
|
Future<int> stockfishMain(Function active) async {
|
|
|
|
if (loadJs != null) {
|
|
|
|
await loadJs;
|
|
|
|
loadJs = null;
|
|
|
|
}
|
2024-02-23 18:58:31 +01:00
|
|
|
final completer = Completer<int>();
|
2024-02-25 00:39:40 +01:00
|
|
|
js.context.callMethod("start_listening", [
|
|
|
|
(line) => stdoutController.sink.add(line),
|
|
|
|
(state) {
|
|
|
|
cleanUp(state is int ? state : 1);
|
|
|
|
completer.complete(state is int ? state : 1);
|
|
|
|
}
|
|
|
|
]);
|
2024-02-23 18:58:31 +01:00
|
|
|
active();
|
|
|
|
return completer.future;
|
|
|
|
}
|
|
|
|
|
|
|
|
@override
|
|
|
|
void write(String line) {
|
2024-02-25 00:39:40 +01:00
|
|
|
js.context.callMethod("write", [line]);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
bool _jsloaded = false;
|
|
|
|
|
|
|
|
Future<void> loadJsFileIfNeeded() async {
|
|
|
|
if (kIsWeb && !_jsloaded) {
|
|
|
|
final stockfishScript = html.document.createElement("script");
|
|
|
|
stockfishScript.setAttribute("src",
|
|
|
|
"assets/packages/flutter_stockfish_plugin/web/flutter_stockfish_plugin.js");
|
|
|
|
html.document.head?.append(stockfishScript);
|
|
|
|
|
|
|
|
await stockfishScript.onLoad.first;
|
|
|
|
|
|
|
|
final jsBindingsScript = html.document.createElement("script");
|
|
|
|
jsBindingsScript.setAttribute(
|
|
|
|
"src", "assets/packages/flutter_stockfish_plugin/web/js_bindings.js");
|
|
|
|
html.document.head?.append(jsBindingsScript);
|
|
|
|
|
|
|
|
await jsBindingsScript.onLoad.first;
|
|
|
|
|
|
|
|
await _stockfishWaitReady();
|
|
|
|
|
|
|
|
//js.context.callMethod("t_cb", [test]);
|
|
|
|
_jsloaded = true;
|
2024-02-23 18:58:31 +01:00
|
|
|
}
|
|
|
|
}
|
2024-02-25 00:39:40 +01:00
|
|
|
|
|
|
|
Future<dynamic> _stockfishWaitReady() {
|
|
|
|
final completer = Completer<dynamic>();
|
|
|
|
js.context.callMethod('wait_ready', [
|
|
|
|
completer.complete,
|
|
|
|
]);
|
|
|
|
return completer.future;
|
|
|
|
}
|