-
Notifications
You must be signed in to change notification settings - Fork 390
Expand file tree
/
Copy pathextension_manager.dart
More file actions
324 lines (295 loc) · 11 KB
/
extension_manager.dart
File metadata and controls
324 lines (295 loc) · 11 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
// Copyright 2023 The Flutter Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file or at https://developers.google.com/open-source/licenses/bsd.
part of 'devtools_extension.dart';
final _log = Logger('devtools_extensions/extension_manager');
const _vmServiceQueryParameter = 'uri';
const _dtdQueryParameter = 'dtdUri';
class ExtensionManager {
final _registeredEventHandlers =
<DevToolsExtensionEventType, ExtensionEventHandler>{};
/// Whether dark theme is enabled for DevTools.
///
/// The DevTools extension will rebuild with the appropriate theme on
/// notifications from this notifier.
final darkThemeEnabled = ValueNotifier<bool>(useDarkThemeAsDefault);
/// The [IdeTheme] which has been parsed from the query parameters.
///
/// Ultimately, the theme is fetched from [globals], but this [ValueNotifier]
/// notifies listeners when it changes.
final theme = ValueNotifier<IdeTheme?>(null);
/// Registers an event handler for [DevToolsExtensionEvent]s of type [type].
///
/// When an event of type [type] is received by the extension, [handler] will
/// be called after any default event handling takes place for event [type].
/// See [_handleExtensionEvent].
void registerEventHandler(
DevToolsExtensionEventType type,
ExtensionEventHandler handler,
) {
_registeredEventHandlers[type] = handler;
}
/// Unregisters an event handler for [DevToolsExtensionEvent]s of type [type]
/// that was originally registered by calling [registerEventHandler].
void unregisterEventHandler(DevToolsExtensionEventType type) {
_registeredEventHandlers.remove(type);
}
/// The listener that is added to the extension iFrame to receive messages
/// from DevTools.
///
/// We need to store this in a variable so that the listener is properly
/// removed in [_dispose].
EventListener? _handleMessageListener;
Future<void> _init() async {
window.addEventListener(
'message',
_handleMessageListener = _handleMessage.toJS,
);
setGlobal(IdeTheme, getIdeTheme());
theme.value = ideTheme;
final queryParams = loadQueryParams();
final themeValue = queryParams[ExtensionEventParameters.theme];
_setThemeForValue(themeValue);
final dtdUri = queryParams[_dtdQueryParameter];
if (dtdUri != null) {
await _connectToDtd(dtdUri);
}
final vmServiceUri = queryParams[_vmServiceQueryParameter];
if (vmServiceUri == null && !_useSimulatedEnvironment) {
// Request the vm service uri for the connected app. DevTools will
// respond with a [DevToolsPluginEventType.connectedVmService] event
// containing the currently connected app's vm service URI.
postMessageToDevTools(
DevToolsExtensionEvent(
DevToolsExtensionEventType.vmServiceConnection,
),
);
} else {
unawaited(_connectToVmService(vmServiceUri));
}
}
void _dispose() {
_registeredEventHandlers.clear();
window.removeEventListener('message', _handleMessageListener);
_handleMessageListener = null;
}
void _handleMessage(Event e) {
final extensionEvent = tryParseExtensionEvent(e);
if (extensionEvent != null) {
_handleExtensionEvent(extensionEvent, e as MessageEvent);
}
}
void _handleExtensionEvent(
DevToolsExtensionEvent extensionEvent,
MessageEvent e,
) {
// Ignore events that come from the [ExtensionManager] itself.
if (extensionEvent.source == '$ExtensionManager') return;
// Ignore events that are not supported for the DevTools => Extension
// direction.
if (!extensionEvent.type
.supportedForDirection(ExtensionEventDirection.toExtension)) {
return;
}
switch (extensionEvent.type) {
case DevToolsExtensionEventType.ping:
postMessageToDevTools(
DevToolsExtensionEvent(DevToolsExtensionEventType.pong),
targetOrigin: e.origin,
);
break;
case DevToolsExtensionEventType.vmServiceConnection:
final vmServiceUri = extensionEvent
.data?[ExtensionEventParameters.vmServiceConnectionUri] as String?;
unawaited(_connectToVmService(vmServiceUri));
break;
case DevToolsExtensionEventType.themeUpdate:
final value =
extensionEvent.data?[ExtensionEventParameters.theme] as String?;
_setThemeForValue(value);
break;
case DevToolsExtensionEventType.forceReload:
window.location.reload();
default:
_log.warning(
'Unrecognized event received by extension: '
'(${extensionEvent.type} - ${e.data}',
);
}
_registeredEventHandlers[extensionEvent.type]?.call(extensionEvent);
}
/// Posts a [DevToolsExtensionEvent] to the DevTools extension host.
///
/// If [targetOrigin] is null, the message will be posed to [Window.origin].
///
/// When [_useSimulatedEnvironment] is true, this message will be posted to
/// the same [Window] that the extension is hosted in.
void postMessageToDevTools(
DevToolsExtensionEvent event, {
String? targetOrigin,
}) {
final postWindow = _useSimulatedEnvironment ? window : window.parent;
postWindow?.postMessage(
{
...event.toJson(),
DevToolsExtensionEvent.sourceKey: '$ExtensionManager',
}.jsify(),
(targetOrigin ?? window.origin).toJS,
);
}
Future<void> _connectToVmService(String? vmServiceUri) async {
// TODO(kenz): investigate. this is weird but `vmServiceUri` != null even
// when the `toString()` representation is 'null'.
if (vmServiceUri == null || vmServiceUri == 'null') {
if (serviceManager.connectedState.value.connected) {
await serviceManager.manuallyDisconnect();
}
if (loadQueryParams().containsKey(_vmServiceQueryParameter)) {
updateQueryParameter(_vmServiceQueryParameter, null);
}
return;
}
try {
final finishedCompleter = Completer<void>();
final normalizedUri = normalizeVmServiceUri(vmServiceUri);
if (normalizedUri == null) {
throw Exception('unable to normalize uri because it is not absolute');
}
final vmService = await connect<VmService>(
uri: normalizedUri,
finishedCompleter: finishedCompleter,
serviceFactory: VmService.defaultFactory,
);
await serviceManager.vmServiceOpened(
vmService,
onClosed: finishedCompleter.future,
);
updateQueryParameter(
_vmServiceQueryParameter,
serviceManager.serviceUri!,
);
} catch (e) {
final errorMessage =
'Unable to connect extension to VM service at $vmServiceUri: $e';
showNotification('Error: $errorMessage');
_log.shout(errorMessage);
}
}
Future<void> _connectToDtd(String? dtdUri) async {
// TODO(kenz): investigate. this is weird but `dtdUri` != null even
// when the `toString()` representation is 'null'.
if (dtdUri == null || dtdUri == 'null') {
if (dtdManager.hasConnection) {
await dtdManager.disconnect();
}
if (loadQueryParams().containsKey(_dtdQueryParameter)) {
updateQueryParameter(_dtdQueryParameter, null);
}
return;
}
try {
await dtdManager.connect(Uri.parse(dtdUri));
updateQueryParameter(
_dtdQueryParameter,
dtdManager.uri.toString(),
);
} catch (e) {
final errorMessage =
'Unable to connect extension to the Dart Tooling Daemon at $dtdUri: $e';
showNotification('Error: $errorMessage');
_log.shout(errorMessage);
}
}
void _setThemeForValue(String? themeValue) {
final useDarkTheme = (themeValue == null && useDarkThemeAsDefault) ||
themeValue == ExtensionEventParameters.themeValueDark;
darkThemeEnabled.value = useDarkTheme;
// Use a post frame callback so that we do not try to update this while a
// build is in progress.
WidgetsBinding.instance.addPostFrameCallback((_) {
updateQueryParameter(
'theme',
useDarkTheme
? ExtensionEventParameters.themeValueDark
: ExtensionEventParameters.themeValueLight,
);
});
}
/// Show a notification in DevTools.
///
/// This message will appear as a notification in the lower left corner of
/// DevTools and will be automatically dismissed after a short time period
/// (7 seconds).
///
/// [message] the content of this notification.
///
/// See also [ShowNotificationExtensionEvent].
void showNotification(String message) {
postMessageToDevTools(
ShowNotificationExtensionEvent(message: message),
);
}
/// Show a banner message in DevTools.
///
/// This message will float at the top of the DevTools on an extension's
/// screen until the user dismisses it.
///
/// [key] should be a unique identifier for this particular message. This is
/// how DevTools will determine whether this message has already been shown.
///
/// [type] should be one of 'warning' or 'error', which will determine the
/// styling of the banner message.
///
/// [message] the content of this banner message.
///
/// [extensionName] must match the 'name' field in your DevTools extension's
/// `config.yaml` file. This should also match the name of the extension's
/// parent package.
///
/// When [ignoreIfAlreadyDismissed] is true (the default case), this message
/// can only be shown and dismissed once. Any subsequent call to show the
/// same banner message will be ignored by DevTools. If you intend for a
/// banner message to be shown more than once, set this value to true or
/// consider using [showNotification] instead, which shows a notification in
/// DevTools that automatically dismisses after a short time period.
///
/// See also [ShowBannerMessageExtensionEvent].
void showBannerMessage({
required String key,
required String type,
required String message,
required String extensionName,
bool ignoreIfAlreadyDismissed = true,
}) {
postMessageToDevTools(
ShowBannerMessageExtensionEvent(
id: key,
bannerMessageType: type,
message: message,
extensionName: extensionName,
ignoreIfAlreadyDismissed: ignoreIfAlreadyDismissed,
),
);
}
/// Copy [content] to clipboard from DevTools.
///
/// [successMessage] is an optional message that DevTools will show as a
/// notification when [content] has been successfully copied to the clipboard.
/// Defaults to [CopyToClipboardExtensionEvent.defaultSuccessMessage].
///
/// This method of copying text is preferred over calling `Clipboard.setData`
/// directly because DevTools contains additional logic for copying text from
/// within an IDE-embedded web view. This scenario will occur when a user is
/// using a DevTools extension from within their IDE.
void copyToClipboard(
String content, {
String successMessage = CopyToClipboardExtensionEvent.defaultSuccessMessage,
}) {
postMessageToDevTools(
CopyToClipboardExtensionEvent(
content: content,
successMessage: successMessage,
),
);
}
}