forked from juicycleff/flutter-unity-view-widget
-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathweb_unity_widget_controller.dart
More file actions
331 lines (291 loc) · 9.02 KB
/
web_unity_widget_controller.dart
File metadata and controls
331 lines (291 loc) · 9.02 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
import 'dart:developer';
import 'dart:async';
import 'dart:convert';
import 'dart:js_interop';
import 'package:web/web.dart' as web;
import 'package:flutter/foundation.dart';
import 'package:flutter/services.dart';
import 'package:flutter_web_plugins/flutter_web_plugins.dart';
import 'package:stream_transform/stream_transform.dart';
import '../facade_controller.dart';
import '../helpers/events.dart';
import '../helpers/misc.dart';
import '../helpers/types.dart';
import 'unity_widget.dart';
class UnityWebEvent {
UnityWebEvent({
required this.name,
this.data,
});
final String name;
final dynamic data;
}
// use JSON.stringify to turn JS objects into strings which we can json decode.
@JS('JSON.stringify')
external JSString jsonStringify(JSAny value);
class WebUnityWidgetController extends UnityWidgetController {
final WebUnityWidgetState _unityWidgetState;
static Registrar? webRegistrar;
late JSFunction _messageListener;
bool unityReady = false;
bool unityPause = true;
MethodChannel? _channel;
/// used for cancel the subscription
StreamSubscription? _onUnityMessageSub,
_onUnitySceneLoadedSub,
_onUnityUnloadedSub;
// The controller we need to broadcast the different events coming
// from handleMethodCall.
//
// It is a `broadcast` because multiple controllers will connect to
// different stream views of this Controller.
final StreamController<UnityEvent> _unityStreamController =
StreamController<UnityEvent>.broadcast();
// Returns a filtered view of the events in the _controller, by unityId.
Stream<UnityEvent> get _events => _unityStreamController.stream;
WebUnityWidgetController._(this._unityWidgetState) {
_channel = ensureChannelInitialized();
_connectStreams();
_registerEvents();
}
/// Accesses the MethodChannel associated to the passed unityId.
MethodChannel get channel {
MethodChannel? channel = _channel;
if (channel == null) {
throw UnknownUnityIDError(0);
}
return channel;
}
// /// Initialize [UnityWidgetController] with [id]
// /// Mainly for internal use when instantiating a [UnityWidgetController] passed
// /// in [UnityWidget.onUnityCreated] callback.
static Future<WebUnityWidgetController> init(
int id, WebUnityWidgetState unityWidgetState) async {
return WebUnityWidgetController._(
unityWidgetState,
);
}
/// Method required for web initialization
static void registerWith(Registrar registrar) {
webRegistrar = registrar;
}
MethodChannel ensureChannelInitialized() {
MethodChannel? channel = _channel;
if (channel == null) {
channel = MethodChannel(
'plugin.xraph.com/unity_view',
const StandardMethodCodec(),
webRegistrar,
);
channel.setMethodCallHandler(_handleMessages);
_channel = channel;
}
return channel;
}
_registerEvents() {
if (kIsWeb) {
_messageListener = ((web.Event event) {
if (event is web.MessageEvent) {
final jsData = event.data;
String data = "";
// Handle a raw JS Object [Object object] instead of a json string.
if (jsData is JSObject) {
try {
data = jsonStringify(jsData).toDart;
} catch (e) {
log('Failed to stringify JS object', error: e);
return;
}
}
// this can be either a raw string like "unityReady" or a json string "{\"name\":\"\", ..}"
else if (jsData is JSString) {
data = jsData.toDart;
}
if (data.isNotEmpty) {
if (data == 'unityReady') {
unityReady = true;
unityPause = false;
_unityStreamController.add(UnityCreatedEvent(0, {}));
return;
} else {
try {
final decoded = json.decode(data);
if (decoded is Map<String, dynamic> &&
decoded.containsKey("name") &&
decoded.containsKey("data")) {
_processEvents(UnityWebEvent(
name: decoded['name'],
data: decoded['data'],
));
} else {
log('Unexpected json object', error: data);
}
} catch (e) {
log('Unexpected json object', error: e);
}
}
}
}
}).toJS;
web.window.addEventListener('message', _messageListener);
}
}
void _connectStreams() {
if (_unityWidgetState.widget.onUnityMessage != null) {
_onUnityMessageSub = _events.whereType<UnityMessageEvent>().listen(
(UnityMessageEvent e) =>
_unityWidgetState.widget.onUnityMessage!(e.value));
}
if (_unityWidgetState.widget.onUnitySceneLoaded != null) {
_onUnitySceneLoadedSub = _events
.whereType<UnitySceneLoadedEvent>()
.listen((UnitySceneLoadedEvent e) =>
_unityWidgetState.widget.onUnitySceneLoaded!(e.value));
}
if (_unityWidgetState.widget.onUnityUnloaded != null) {
_onUnityUnloadedSub = _events
.whereType<UnityLoadedEvent>()
.listen((_) => _unityWidgetState.widget.onUnityUnloaded!());
}
}
void _processEvents(UnityWebEvent e) {
switch (e.name) {
case 'onUnityMessage':
_unityStreamController.add(UnityMessageEvent(0, e.data));
break;
case 'onUnitySceneLoaded':
_unityStreamController
.add(UnitySceneLoadedEvent(0, SceneLoaded.fromMap(e.data)));
break;
}
}
Future<dynamic> _handleMessages(MethodCall call) {
switch (call.method) {
case "unity#waitForUnity":
return Future.value(null);
case "unity#dispose":
dispose();
return Future.value(null);
case "unity#postMessage":
messageUnity(
gameObject: call.arguments['gameObject'],
methodName: call.arguments['methodName'],
message: call.arguments['message'],
);
return Future.value(null);
case "unity#resumePlayer":
callUnityFn(fnName: 'resume');
return Future.value(null);
case "unity#pausePlayer":
callUnityFn(fnName: 'pause');
return Future.value(null);
case "unity#unloadPlayer":
callUnityFn(fnName: 'unload');
return Future.value(null);
case "unity#quitPlayer":
callUnityFn(fnName: 'quit');
return Future.value(null);
default:
throw UnimplementedError("Unimplemented ${call.method} method");
}
}
void callUnityFn({required String fnName}) {
if (kIsWeb) {
final web.MessageEvent _unityFlutterBidingFn = web.MessageEvent(
'unityFlutterBidingFnCal',
web.MessageEventInit(
data: fnName.toJS,
),
);
web.window.dispatchEvent(_unityFlutterBidingFn);
}
}
void messageUnity({
required String gameObject,
required String methodName,
required String message,
}) {
if (kIsWeb) {
final web.MessageEvent _unityFlutterBiding = web.MessageEvent(
'unityFlutterBiding',
web.MessageEventInit(
data: json.encode({
"gameObject": gameObject,
"methodName": methodName,
"message": message,
}).toJS,
),
);
web.window.dispatchEvent(_unityFlutterBiding);
postProcess();
}
}
/// This method makes sure Unity has been refreshed and is ready to receive further messages.
void postProcess() {
web.Element? frame = web.window.document
.querySelector('flt-platform-view')
?.querySelector('iframe');
if (frame != null && frame is web.HTMLIFrameElement) {
frame.focus();
}
}
@override
Future<void>? postMessage(
String gameObject,
dynamic methodName,
dynamic message,
) async {
messageUnity(
gameObject: gameObject,
methodName: methodName,
message: message,
);
}
@override
Future<void> postJsonMessage(
String gameObject,
String methodName,
Map<String, dynamic> message,
) async {
messageUnity(
gameObject: gameObject,
methodName: methodName,
message: json.encode(message),
);
}
@override
Future<void> pause() async {
callUnityFn(fnName: 'pause');
}
@override
Future<void> resume() async {
callUnityFn(fnName: 'resume');
}
@override
Future<void> openInNativeProcess() async {
await channel.invokeMethod('unity#openInNativeProcess');
}
@override
Future<void> unload() async {
callUnityFn(fnName: 'unload');
}
@override
Future<void> quit() async {
callUnityFn(fnName: 'quit');
}
/// cancel the subscriptions when dispose called
void _cancelSubscriptions() {
_onUnityMessageSub?.cancel();
_onUnitySceneLoadedSub?.cancel();
_onUnityUnloadedSub?.cancel();
_onUnityMessageSub = null;
_onUnitySceneLoadedSub = null;
_onUnityUnloadedSub = null;
}
void dispose() {
_cancelSubscriptions();
if (kIsWeb) {
web.window.removeEventListener('message', _messageListener);
}
}
}