-
-
Notifications
You must be signed in to change notification settings - Fork 2.9k
Expand file tree
/
Copy pathDevToolsClient.cs
More file actions
249 lines (215 loc) · 9.45 KB
/
DevToolsClient.cs
File metadata and controls
249 lines (215 loc) · 9.45 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
// Copyright © 2020 The CefSharp Authors. All rights reserved.
//
// Use of this source code is governed by a BSD-style license that can be found in the LICENSE file.
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using CefSharp.Callback;
using CefSharp.Internals;
using CefSharp.Internals.Tasks;
namespace CefSharp.DevTools
{
/// <summary>
/// DevTool Client
/// </summary>
public partial class DevToolsClient : IDevToolsMessageObserver, IDevToolsClient
{
private readonly ConcurrentDictionary<int, SyncContextTaskCompletionSource<DevToolsMethodResponse>> queuedCommandResults = new ConcurrentDictionary<int, SyncContextTaskCompletionSource<DevToolsMethodResponse>>();
private int lastMessageId;
private IBrowser browser;
private IRegistration devToolsRegistration;
private bool devToolsAttached;
private SynchronizationContext syncContext;
/// <summary>
/// DevToolsEvent
/// </summary>
public EventHandler<DevToolsEventArgs> DevToolsEvent;
/// <summary>
/// Capture the current <see cref="SynchronizationContext"/> so
/// continuation executes on the original calling thread. If
/// <see cref="SynchronizationContext.Current"/> is null for
/// <see cref="ExecuteDevToolsMethodAsync(string, IDictionary{string, object})"/>
/// then the continuation will be run on the CEF UI Thread (by default
/// this is not the same as the WPF/WinForms UI Thread).
/// </summary>
public bool CaptureSyncContext { get; set; }
/// <summary>
/// When not null provided <see cref="SynchronizationContext"/>
/// will be used to run the contination. Defaults to null
/// Setting this property will change <see cref="CaptureSyncContext"/>
/// to false.
/// </summary>
public SynchronizationContext SyncContext
{
get { return syncContext; }
set
{
CaptureSyncContext = false;
syncContext = value;
}
}
/// <summary>
/// DevToolsClient
/// </summary>
/// <param name="browser">Browser associated with this DevTools client</param>
public DevToolsClient(IBrowser browser)
{
this.browser = browser;
lastMessageId = browser.Identifier * 100000;
CaptureSyncContext = true;
}
/// <summary>
/// Store a reference to the IRegistration that's returned when
/// you register an observer.
/// </summary>
/// <param name="devToolsRegistration">registration</param>
public void SetDevToolsObserverRegistration(IRegistration devToolsRegistration)
{
this.devToolsRegistration = devToolsRegistration;
}
/// <summary>
/// Execute a method call over the DevTools protocol. This method can be called on any thread.
/// See the DevTools protocol documentation at https://chromedevtools.github.io/devtools-protocol/ for details
/// of supported methods and the expected <paramref name="parameters"/> dictionary contents.
/// </summary>
/// <param name="method">is the method name</param>
/// <param name="parameters">are the method parameters represented as a dictionary,
/// which may be empty.</param>
/// <returns>return a Task that can be awaited to obtain the method result</returns>
public async Task<DevToolsMethodResponse> ExecuteDevToolsMethodAsync(string method, IDictionary<string, object> parameters = null)
{
if (browser == null || browser.IsDisposed)
{
//TODO: Queue up commands where possible
return new DevToolsMethodResponse { Success = false };
}
var messageId = Interlocked.Increment(ref lastMessageId);
var taskCompletionSource = new SyncContextTaskCompletionSource<DevToolsMethodResponse>();
taskCompletionSource.SyncContext = CaptureSyncContext ? SynchronizationContext.Current : syncContext;
if (!queuedCommandResults.TryAdd(messageId, taskCompletionSource))
{
throw new DevToolsClientException(string.Format("Unable to add MessageId {0} to queuedCommandResults ConcurrentDictionary.", messageId));
}
var browserHost = browser.GetHost();
//Currently on CEF UI Thread we can directly execute
if (CefThread.CurrentlyOnUiThread)
{
var returnedMessageId = browserHost.ExecuteDevToolsMethod(messageId, method, parameters);
if (returnedMessageId == 0)
{
return new DevToolsMethodResponse { Success = false };
}
else if(returnedMessageId != messageId)
{
//For some reason our message Id's don't match
throw new DevToolsClientException(string.Format("Generated MessageId {0} doesn't match returned Message Id {1}", returnedMessageId, messageId));
}
}
//ExecuteDevToolsMethod can only be called on the CEF UI Thread
else if (CefThread.CanExecuteOnUiThread)
{
var returnedMessageId = await CefThread.ExecuteOnUiThread(() =>
{
return browserHost.ExecuteDevToolsMethod(messageId, method, parameters);
}).ConfigureAwait(false);
if (returnedMessageId == 0)
{
return new DevToolsMethodResponse { Success = false };
}
else if (returnedMessageId != messageId)
{
//For some reason our message Id's don't match
throw new DevToolsClientException(string.Format("Generated MessageId {0} doesn't match returned Message Id {1}", returnedMessageId, messageId));
}
}
else
{
throw new DevToolsClientException("Unable to invoke ExecuteDevToolsMethod on CEF UI Thread.");
}
return await taskCompletionSource.Task;
}
void IDisposable.Dispose()
{
DevToolsEvent = null;
devToolsRegistration?.Dispose();
devToolsRegistration = null;
browser = null;
}
void IDevToolsMessageObserver.OnDevToolsAgentAttached(IBrowser browser)
{
devToolsAttached = true;
}
void IDevToolsMessageObserver.OnDevToolsAgentDetached(IBrowser browser)
{
devToolsAttached = false;
}
void IDevToolsMessageObserver.OnDevToolsEvent(IBrowser browser, string method, Stream parameters)
{
var evt = DevToolsEvent;
//Only parse the data if we have an event handler
if (evt != null)
{
//TODO: Improve this
var memoryStream = new MemoryStream((int)parameters.Length);
parameters.CopyTo(memoryStream);
var paramsAsJsonString = Encoding.UTF8.GetString(memoryStream.ToArray());
evt(this, new DevToolsEventArgs(method, paramsAsJsonString));
}
}
bool IDevToolsMessageObserver.OnDevToolsMessage(IBrowser browser, Stream message)
{
return false;
}
void IDevToolsMessageObserver.OnDevToolsMethodResult(IBrowser browser, int messageId, bool success, Stream result)
{
var uiThread = CefThread.CurrentlyOnUiThread;
SyncContextTaskCompletionSource<DevToolsMethodResponse> taskCompletionSource = null;
if (queuedCommandResults.TryRemove(messageId, out taskCompletionSource))
{
var methodResult = new DevToolsMethodResponse
{
Success = success,
MessageId = messageId
};
//TODO: Improve this
var memoryStream = new MemoryStream((int)result.Length);
result.CopyTo(memoryStream);
methodResult.ResponseAsJsonString = Encoding.UTF8.GetString(memoryStream.ToArray());
Action execute = null;
if (success)
{
execute = () =>
{
taskCompletionSource.TrySetResult(methodResult);
};
}
else
{
execute = () =>
{
var errorObj = methodResult.DeserializeJson<DevToolsDomainErrorResponse>();
errorObj.MessageId = messageId;
//Make sure continuation runs on Thread Pool
taskCompletionSource.TrySetException(new DevToolsClientException("DevTools Client Error :" + errorObj.Message, errorObj));
};
}
var syncContext = taskCompletionSource.SyncContext;
if (syncContext == null)
{
execute();
}
else
{
syncContext.Post(new SendOrPostCallback((o) =>
{
execute();
}), null);
}
}
}
}
}