kyy
2025-07-02 07558e32634314eec359ec8437d97bdc5def64f9
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
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
// 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;
 
namespace CefSharp.DevTools
{
    /// <summary>
    /// DevTool Client 
    /// </summary>
    public partial class DevToolsClient : IDevToolsMessageObserver, IDevToolsClient
    {
        private readonly ConcurrentDictionary<int, DevToolsMethodResponseContext> queuedCommandResults = new ConcurrentDictionary<int, DevToolsMethodResponseContext>();
        private readonly ConcurrentDictionary<string, IEventProxy> eventHandlers = new ConcurrentDictionary<string, IEventProxy>();
        private IBrowser browser;
        private IRegistration devToolsRegistration;
        private bool devToolsAttached;
        private SynchronizationContext syncContext;
        private int disposeCount;
 
        /// <inheritdoc/>
        public event EventHandler<DevToolsEventArgs> DevToolsEvent;
 
        /// <inheritdoc/>
        public event EventHandler<DevToolsErrorEventArgs> DevToolsEventError;
 
        /// <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;
 
            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;
        }
 
        /// <inheritdoc/>
        public void AddEventHandler<T>(string eventName, EventHandler<T> eventHandler) where T : EventArgs
        {
            var eventProxy = eventHandlers.GetOrAdd(eventName, _ => new EventProxy<T>(DeserializeJsonEvent<T>));
 
            var p = (EventProxy<T>)eventProxy;
 
            p.AddHandler(eventHandler);
        }
 
        /// <inheritdoc/>
        public bool RemoveEventHandler<T>(string eventName, EventHandler<T> eventHandler) where T : EventArgs
        {
            if (eventHandlers.TryGetValue(eventName, out IEventProxy eventProxy))
            {
                var p = ((EventProxy<T>)eventProxy);
 
                if (p.RemoveHandler(eventHandler))
                {
                    return !eventHandlers.TryRemove(eventName, out _);
                }
            }
 
            return true;
        }
 
        /// <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 Task<DevToolsMethodResponse> ExecuteDevToolsMethodAsync(string method, IDictionary<string, object> parameters = null)
        {
            return ExecuteDevToolsMethodAsync<DevToolsMethodResponse>(method, parameters);
        }
 
        /// <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>
        /// <typeparam name="T">The type into which the result will be deserialzed.</typeparam>
        /// <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 Task<T> ExecuteDevToolsMethodAsync<T>(string method, IDictionary<string, object> parameters = null) where T : DevToolsDomainResponseBase
        {
            if (browser == null || browser.IsDisposed)
            {
                //TODO: Queue up commands where possible
                throw new ObjectDisposedException(nameof(IBrowser));
            }
 
            var taskCompletionSource = new TaskCompletionSource<T>(TaskCreationOptions.RunContinuationsAsynchronously);
 
            var methodResultContext = new DevToolsMethodResponseContext(
                type: typeof(T),
                setResult: o => taskCompletionSource.TrySetResult((T)o),
                setException: taskCompletionSource.TrySetException,
                syncContext: CaptureSyncContext ? SynchronizationContext.Current : SyncContext
            );
 
            var browserHost = browser.GetHost();
 
            var messageId = browserHost.GetNextDevToolsMessageId();
 
            if (!queuedCommandResults.TryAdd(messageId, methodResultContext))
            {
                throw new DevToolsClientException(string.Format("Unable to add MessageId {0} to queuedCommandResults ConcurrentDictionary.", messageId));
            }
 
            //Currently on CEF UI Thread we can directly execute
            if (CefThread.CurrentlyOnUiThread)
            {
                ExecuteDevToolsMethod(browserHost, messageId, method, parameters, methodResultContext);
            }
            //ExecuteDevToolsMethod can only be called on the CEF UI Thread
            else if (CefThread.CanExecuteOnUiThread)
            {
                CefThread.ExecuteOnUiThread(() =>
                {
                    ExecuteDevToolsMethod(browserHost, messageId, method, parameters, methodResultContext);
                });
            }
            else
            {
                queuedCommandResults.TryRemove(messageId, out methodResultContext);
                throw new DevToolsClientException("Unable to invoke ExecuteDevToolsMethod on CEF UI Thread.");
            }
 
            return taskCompletionSource.Task;
        }
 
        private void ExecuteDevToolsMethod(IBrowserHost browserHost, int messageId, string method, IDictionary<string, object> parameters, DevToolsMethodResponseContext methodResultContext)
        {
            try
            {
                var returnedMessageId = browserHost.ExecuteDevToolsMethod(messageId, method, parameters);
                if (returnedMessageId == 0)
                {
                    throw new DevToolsClientException(string.Format("Failed to execute dev tools method {0}.", method));
                }
                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));
                }
            }
            catch (Exception ex)
            {
                queuedCommandResults.TryRemove(messageId, out _);
                methodResultContext.SetException(ex);
            }
        }
 
        /// <inheritdoc/>
        public void Dispose()
        {
            //Dispose can be called from different Threads
            //CEF maintains a reference and the user
            //maintains a reference, we in a rare case
            //we end up disposing of #3725 twice from different
            //threads. This will ensure our dispose only runs once.
            if (Interlocked.Increment(ref disposeCount) == 1)
            {
                DevToolsEvent = null;
                devToolsRegistration?.Dispose();
                devToolsRegistration = null;
                browser = null;
 
                var events = eventHandlers.Values;
                eventHandlers.Clear();
 
                foreach (var evt in events)
                {
                    evt.Dispose();
                }
            }
        }
 
        /// <inheritdoc/>
        void IDevToolsMessageObserver.OnDevToolsAgentAttached(IBrowser browser)
        {
            devToolsAttached = true;
        }
 
        /// <inheritdoc/>
        void IDevToolsMessageObserver.OnDevToolsAgentDetached(IBrowser browser)
        {
            devToolsAttached = false;
        }
 
        /// <inheritdoc/>
        void IDevToolsMessageObserver.OnDevToolsEvent(IBrowser browser, string method, Stream parameters)
        {
            try
            {
                var evt = DevToolsEvent;
 
                //Only parse the data if we have an event handler
                if (evt != null)
                {
                    var paramsAsJsonString = StreamToString(parameters, leaveOpen: true);
 
                    evt(this, new DevToolsEventArgs(method, paramsAsJsonString));
                }
 
                if (eventHandlers.TryGetValue(method, out IEventProxy eventProxy))
                {
                    eventProxy.Raise(this, method, parameters, SyncContext);
                }
            }
            catch (Exception ex)
            {
                var errorEvent = DevToolsEventError;
 
                var json = "";
 
                if (parameters.Length > 0)
                {
                    parameters.Position = 0;
 
                    try
                    {
                        json = StreamToString(parameters, leaveOpen: false);
                    }
                    catch (Exception)
                    {
                        //TODO: do we somehow pass this exception to the user?
                    }
                }
 
                var args = new DevToolsErrorEventArgs(method, json, ex);
 
                errorEvent?.Invoke(this, args);
            }
        }
 
        /// <inheritdoc/>
        bool IDevToolsMessageObserver.OnDevToolsMessage(IBrowser browser, Stream message)
        {
            return false;
        }
 
        /// <inheritdoc/>
        void IDevToolsMessageObserver.OnDevToolsMethodResult(IBrowser browser, int messageId, bool success, Stream result)
        {
            DevToolsMethodResponseContext context;
            if (queuedCommandResults.TryRemove(messageId, out context))
            {
                if (success)
                {
                    if (context.Type == typeof(DevToolsMethodResponse) || context.Type == typeof(DevToolsDomainResponseBase))
                    {
                        context.SetResult(new DevToolsMethodResponse
                        {
                            Success = success,
                            MessageId = messageId,
                            ResponseAsJsonString = StreamToString(result),
                        });
                    }
                    else
                    {
                        try
                        {
                            context.SetResult(DeserializeJson(context.Type, result));
                        }
                        catch (Exception ex)
                        {
                            context.SetException(ex);
                        }
                    }
                }
                else
                {
                    var errorObj = DeserializeJson<DevToolsDomainErrorResponse>(result);
                    errorObj.MessageId = messageId;
 
                    context.SetException(new DevToolsClientException("DevTools Client Error :" + errorObj.Message, errorObj));
                }
            }
        }
 
 
        /// <summary>
        /// Deserialize the JSON stream into a .Net object.
        /// For .Net Core/.Net 5.0 uses System.Text.Json
        /// for .Net 4.6.2 uses System.Runtime.Serialization.Json
        /// </summary>
        /// <typeparam name="T">Object type</typeparam>
        /// <param name="eventName">event Name</param>
        /// <param name="stream">JSON stream</param>
        /// <returns>object of type <typeparamref name="T"/></returns>
        private static T DeserializeJsonEvent<T>(string eventName, Stream stream) where T : EventArgs
        {
            if (typeof(T) == typeof(EventArgs))
            {
                return (T)EventArgs.Empty;
            }
 
            if (typeof(T) == typeof(DevToolsEventArgs))
            {
                var paramsAsJsonString = StreamToString(stream, leaveOpen: true);
                var args = new DevToolsEventArgs(eventName, paramsAsJsonString);
 
                return (T)(object)args;
            }
 
            return (T)DeserializeJson(typeof(T), stream);
        }
 
        /// <summary>
        /// Deserialize the JSON stream into a .Net object.
        /// For .Net Core/.Net 5.0 uses System.Text.Json
        /// for .Net 4.6.2 uses System.Runtime.Serialization.Json
        /// </summary>
        /// <typeparam name="T">Object type</typeparam>
        /// <param name="stream">JSON stream</param>
        /// <returns>object of type <typeparamref name="T"/></returns>
        private static T DeserializeJson<T>(Stream stream)
        {
            return (T)DeserializeJson(typeof(T), stream);
        }
 
#if NETCOREAPP
        private static readonly System.Text.Json.JsonSerializerOptions DefaultJsonSerializerOptions = new System.Text.Json.JsonSerializerOptions
        {
            PropertyNameCaseInsensitive = true,
            IgnoreNullValues = true,
            Converters = { new CefSharp.Internals.Json.JsonEnumConverterFactory() },
        };
#else
        private static readonly System.Runtime.Serialization.Json.DataContractJsonSerializerSettings DefaultJsonSerializerSettings = new System.Runtime.Serialization.Json.DataContractJsonSerializerSettings
        {
            UseSimpleDictionaryFormat = true,
        };
#endif
 
        /// <summary>
        /// Deserialize the JSON stream into a .Net object.
        /// For .Net Core/.Net 5.0 uses System.Text.Json
        /// for .Net 4.6.2 uses System.Runtime.Serialization.Json
        /// </summary>
        /// <param name="type">Object type</param>
        /// <param name="stream">JSON stream</param>
        /// <returns>object of type <paramref name="type"/></returns>
        private static object DeserializeJson(Type type, Stream stream)
        {
#if NETCOREAPP
            // TODO: use synchronus Deserialize<T>(Stream) when System.Text.Json gets updated
            var memoryStream = new MemoryStream((int)stream.Length);
            stream.CopyTo(memoryStream);
 
            return System.Text.Json.JsonSerializer.Deserialize(memoryStream.ToArray(), type, DefaultJsonSerializerOptions);
#else
            var dcs = new System.Runtime.Serialization.Json.DataContractJsonSerializer(type, DefaultJsonSerializerSettings);
            return dcs.ReadObject(stream);
#endif
        }
 
        private static string StreamToString(Stream stream, bool leaveOpen = false)
        {
            using (var streamReader = new StreamReader(stream, Encoding.UTF8, detectEncodingFromByteOrderMarks: false, bufferSize: 1024, leaveOpen: leaveOpen))
            {
                return streamReader.ReadToEnd();
            }
        }
    }
}