-
Notifications
You must be signed in to change notification settings - Fork 534
/
Copy pathweb_unity_widget_controller.dart
295 lines (256 loc) · 7.79 KB
/
web_unity_widget_controller.dart
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
import 'dart:async';
import 'dart:convert';
import 'dart:html' as html;
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;
}
class WebUnityWidgetController extends UnityWidgetController {
final WebUnityWidgetState _unityWidgetState;
static Registrar? webRegistrar;
late html.MessageEvent _unityFlutterBiding;
late html.MessageEvent _unityFlutterBidingFn;
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) {
html.window.addEventListener('message', (event) {
final raw = (event as html.MessageEvent).data.toString();
// ignore: unnecessary_null_comparison
if (raw == '' || raw == null) return;
if (raw == 'unityReady') {
unityReady = true;
unityPause = false;
_unityStreamController.add(UnityCreatedEvent(0, {}));
return;
}
_processEvents(UnityWebEvent(
name: event.data['name'],
data: event.data['data'],
));
});
}
}
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) {
_unityFlutterBidingFn = html.MessageEvent(
'unityFlutterBidingFnCal',
data: fnName,
);
html.window.dispatchEvent(_unityFlutterBidingFn);
}
}
void messageUnity({
required String gameObject,
required String methodName,
required String message,
}) {
if (kIsWeb) {
_unityFlutterBiding = html.MessageEvent(
'unityFlutterBiding',
data: json.encode({
"gameObject": gameObject,
"methodName": methodName,
"message": message,
}),
);
html.window.dispatchEvent(_unityFlutterBiding);
postProcess();
}
}
/// This method makes sure Unity has been refreshed and is ready to receive further messages.
void postProcess() {
html.Element? frame = html.document
.querySelector('flt-platform-view')
?.querySelector('iframe');
if (frame != null) {
(frame as html.IFrameElement).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) {
html.window.removeEventListener('message', (_) {});
html.window.removeEventListener('unityFlutterBiding', (event) {});
html.window.removeEventListener('unityFlutterBidingFnCal', (event) {});
}
}
}