forked from obsproject/obs-browser
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbrowser-app.cpp
460 lines (365 loc) · 12.3 KB
/
browser-app.cpp
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
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
/******************************************************************************
Copyright (C) 2014 by John R. Bradley <[email protected]>
Copyright (C) 2018 by Hugh Bailey ("Jim") <[email protected]>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
******************************************************************************/
#include "browser-app.hpp"
#include "browser-version.h"
#include <json11/json11.hpp>
#ifdef _WIN32
#include <windows.h>
#endif
#ifdef USE_QT_LOOP
#include <util/base.h>
#include <util/platform.h>
#include <util/threading.h>
#include <QTimer>
#endif
#define UNUSED_PARAMETER(x) \
{ \
(void)x; \
}
using namespace json11;
CefRefPtr<CefRenderProcessHandler> BrowserApp::GetRenderProcessHandler()
{
return this;
}
CefRefPtr<CefBrowserProcessHandler> BrowserApp::GetBrowserProcessHandler()
{
return this;
}
void BrowserApp::OnRegisterCustomSchemes(CefRawPtr<CefSchemeRegistrar> registrar)
{
#if CHROME_VERSION_BUILD >= 3683
registrar->AddCustomScheme("http",
CEF_SCHEME_OPTION_STANDARD |
CEF_SCHEME_OPTION_CORS_ENABLED);
#elif CHROME_VERSION_BUILD >= 3029
registrar->AddCustomScheme("http", true, false, false, false, true,
false);
#else
registrar->AddCustomScheme("http", true, false, false, false, true);
#endif
}
void BrowserApp::OnBeforeChildProcessLaunch(
CefRefPtr<CefCommandLine> command_line)
{
#ifdef _WIN32
std::string pid = std::to_string(GetCurrentProcessId());
command_line->AppendSwitchWithValue("parent_pid", pid);
#else
(void)command_line;
#endif
}
void BrowserApp::OnBeforeCommandLineProcessing(
const CefString &, CefRefPtr<CefCommandLine> command_line)
{
if (!shared_texture_available) {
bool enableGPU = command_line->HasSwitch("enable-gpu");
CefString type = command_line->GetSwitchValue("type");
if (!enableGPU && type.empty()) {
command_line->AppendSwitch("disable-gpu-compositing");
}
}
if (command_line->HasSwitch("disable-features")) {
// Don't override existing, as this can break OSR
std::string disableFeatures =
command_line->GetSwitchValue("disable-features");
disableFeatures += ",HardwareMediaKeyHandling";
command_line->AppendSwitchWithValue("disable-features",
disableFeatures);
} else {
command_line->AppendSwitchWithValue("disable-features",
"HardwareMediaKeyHandling");
}
command_line->AppendSwitchWithValue("autoplay-policy",
"no-user-gesture-required");
#ifdef __APPLE__
command_line->AppendSwitch("use-mock-keychain");
#endif
}
void BrowserApp::OnContextCreated(CefRefPtr<CefBrowser> browser,
CefRefPtr<CefFrame>,
CefRefPtr<CefV8Context> context)
{
CefRefPtr<CefV8Value> globalObj = context->GetGlobal();
CefRefPtr<CefV8Value> obsStudioObj = CefV8Value::CreateObject(0, 0);
globalObj->SetValue("obsstudio", obsStudioObj,
V8_PROPERTY_ATTRIBUTE_NONE);
CefRefPtr<CefV8Value> pluginVersion =
CefV8Value::CreateString(OBS_BROWSER_VERSION_STRING);
obsStudioObj->SetValue("pluginVersion", pluginVersion,
V8_PROPERTY_ATTRIBUTE_NONE);
CefRefPtr<CefV8Value> getCurrentScene =
CefV8Value::CreateFunction("getCurrentScene", this);
obsStudioObj->SetValue("getCurrentScene", getCurrentScene,
V8_PROPERTY_ATTRIBUTE_NONE);
CefRefPtr<CefV8Value> getStatus =
CefV8Value::CreateFunction("getStatus", this);
obsStudioObj->SetValue("getStatus", getStatus,
V8_PROPERTY_ATTRIBUTE_NONE);
CefRefPtr<CefV8Value> saveReplayBuffer =
CefV8Value::CreateFunction("saveReplayBuffer", this);
obsStudioObj->SetValue("saveReplayBuffer", saveReplayBuffer,
V8_PROPERTY_ATTRIBUTE_NONE);
#if !ENABLE_WASHIDDEN
int id = browser->GetIdentifier();
if (browserVis.find(id) != browserVis.end()) {
SetDocumentVisibility(browser, browserVis[id]);
}
#endif
}
void BrowserApp::ExecuteJSFunction(CefRefPtr<CefBrowser> browser,
const char *functionName,
CefV8ValueList arguments)
{
CefRefPtr<CefV8Context> context =
browser->GetMainFrame()->GetV8Context();
context->Enter();
CefRefPtr<CefV8Value> globalObj = context->GetGlobal();
CefRefPtr<CefV8Value> obsStudioObj = globalObj->GetValue("obsstudio");
CefRefPtr<CefV8Value> jsFunction = obsStudioObj->GetValue(functionName);
if (jsFunction && jsFunction->IsFunction())
jsFunction->ExecuteFunction(NULL, arguments);
context->Exit();
}
#if !ENABLE_WASHIDDEN
void BrowserApp::SetFrameDocumentVisibility(CefRefPtr<CefBrowser> browser,
CefRefPtr<CefFrame> frame,
bool isVisible)
{
UNUSED_PARAMETER(browser);
CefRefPtr<CefV8Context> context = frame->GetV8Context();
context->Enter();
CefRefPtr<CefV8Value> globalObj = context->GetGlobal();
CefRefPtr<CefV8Value> documentObject = globalObj->GetValue("document");
if (!!documentObject) {
documentObject->SetValue("hidden",
CefV8Value::CreateBool(!isVisible),
V8_PROPERTY_ATTRIBUTE_READONLY);
documentObject->SetValue(
"visibilityState",
CefV8Value::CreateString(isVisible ? "visible"
: "hidden"),
V8_PROPERTY_ATTRIBUTE_READONLY);
std::string script = "new CustomEvent('visibilitychange', {});";
CefRefPtr<CefV8Value> returnValue;
CefRefPtr<CefV8Exception> exception;
/* Create the CustomEvent object
* We have to use eval to invoke the new operator */
bool success = context->Eval(script, frame->GetURL(), 0,
returnValue, exception);
if (success) {
CefV8ValueList arguments;
arguments.push_back(returnValue);
CefRefPtr<CefV8Value> dispatchEvent =
documentObject->GetValue("dispatchEvent");
/* Dispatch visibilitychange event on the document
* object */
dispatchEvent->ExecuteFunction(documentObject,
arguments);
}
}
context->Exit();
}
void BrowserApp::SetDocumentVisibility(CefRefPtr<CefBrowser> browser,
bool isVisible)
{
/* This method might be called before OnContextCreated
* call is made. We'll save the requested visibility
* state here, and use it later in OnContextCreated to
* set initial page visibility state. */
browserVis[browser->GetIdentifier()] = isVisible;
std::vector<int64> frameIdentifiers;
/* Set visibility state for every frame in the browser
*
* According to the Page Visibility API documentation:
* https://developer.mozilla.org/en-US/docs/Web/API/Page_Visibility_API
*
* "Visibility states of an <iframe> are the same as
* the parent document. Hiding an <iframe> using CSS
* properties (such as display: none;) doesn't trigger
* visibility events or change the state of the document
* contained within the frame."
*
* Thus, we set the same visibility state for every frame of the browser.
*/
browser->GetFrameIdentifiers(frameIdentifiers);
for (int64 frameId : frameIdentifiers) {
CefRefPtr<CefFrame> frame = browser->GetFrame(frameId);
SetFrameDocumentVisibility(browser, frame, isVisible);
}
}
#endif
bool BrowserApp::OnProcessMessageReceived(CefRefPtr<CefBrowser> browser,
#if CHROME_VERSION_BUILD >= 3770
CefRefPtr<CefFrame> frame,
#endif
CefProcessId source_process,
CefRefPtr<CefProcessMessage> message)
{
UNUSED_PARAMETER(frame);
DCHECK(source_process == PID_BROWSER);
CefRefPtr<CefListValue> args = message->GetArgumentList();
if (message->GetName() == "Visibility") {
CefV8ValueList arguments;
arguments.push_back(CefV8Value::CreateBool(args->GetBool(0)));
ExecuteJSFunction(browser, "onVisibilityChange", arguments);
#if !ENABLE_WASHIDDEN
SetDocumentVisibility(browser, args->GetBool(0));
#endif
} else if (message->GetName() == "Active") {
CefV8ValueList arguments;
arguments.push_back(CefV8Value::CreateBool(args->GetBool(0)));
ExecuteJSFunction(browser, "onActiveChange", arguments);
} else if (message->GetName() == "DispatchJSEvent") {
CefRefPtr<CefV8Context> context =
browser->GetMainFrame()->GetV8Context();
context->Enter();
CefRefPtr<CefV8Value> globalObj = context->GetGlobal();
std::string err;
auto payloadJson =
Json::parse(args->GetString(1).ToString(), err);
Json::object wrapperJson;
if (args->GetSize() > 1)
wrapperJson["detail"] = payloadJson;
std::string wrapperJsonString = Json(wrapperJson).dump();
std::string script;
script += "new CustomEvent('";
script += args->GetString(0).ToString();
script += "', ";
script += wrapperJsonString;
script += ");";
CefRefPtr<CefV8Value> returnValue;
CefRefPtr<CefV8Exception> exception;
/* Create the CustomEvent object
* We have to use eval to invoke the new operator */
context->Eval(script, browser->GetMainFrame()->GetURL(), 0,
returnValue, exception);
CefV8ValueList arguments;
arguments.push_back(returnValue);
CefRefPtr<CefV8Value> dispatchEvent =
globalObj->GetValue("dispatchEvent");
dispatchEvent->ExecuteFunction(NULL, arguments);
context->Exit();
} else if (message->GetName() == "executeCallback") {
CefRefPtr<CefV8Context> context =
browser->GetMainFrame()->GetV8Context();
CefRefPtr<CefV8Value> retval;
CefRefPtr<CefV8Exception> exception;
context->Enter();
CefRefPtr<CefListValue> arguments = message->GetArgumentList();
int callbackID = arguments->GetInt(0);
CefString jsonString = arguments->GetString(1);
std::string script;
script += "JSON.parse('";
script += arguments->GetString(1).ToString();
script += "');";
CefRefPtr<CefV8Value> callback = callbackMap[callbackID];
CefV8ValueList args;
context->Eval(script, browser->GetMainFrame()->GetURL(), 0,
retval, exception);
args.push_back(retval);
if (callback)
callback->ExecuteFunction(NULL, args);
context->Exit();
callbackMap.erase(callbackID);
} else {
return false;
}
return true;
}
bool BrowserApp::Execute(const CefString &name, CefRefPtr<CefV8Value>,
const CefV8ValueList &arguments,
CefRefPtr<CefV8Value> &, CefString &)
{
if (name == "getCurrentScene" || name == "getStatus" ||
name == "saveReplayBuffer") {
if (arguments.size() == 1 && arguments[0]->IsFunction()) {
callbackId++;
callbackMap[callbackId] = arguments[0];
}
CefRefPtr<CefProcessMessage> msg =
CefProcessMessage::Create(name);
CefRefPtr<CefListValue> args = msg->GetArgumentList();
args->SetInt(0, callbackId);
CefRefPtr<CefBrowser> browser =
CefV8Context::GetCurrentContext()->GetBrowser();
SendBrowserProcessMessage(browser, PID_BROWSER, msg);
} else {
/* Function does not exist. */
return false;
}
return true;
}
#ifdef USE_QT_LOOP
Q_DECLARE_METATYPE(MessageTask);
MessageObject messageObject;
void QueueBrowserTask(CefRefPtr<CefBrowser> browser, BrowserFunc func)
{
std::lock_guard<std::mutex> lock(messageObject.browserTaskMutex);
messageObject.browserTasks.emplace_back(browser, func);
QMetaObject::invokeMethod(&messageObject, "ExecuteNextBrowserTask",
Qt::QueuedConnection);
}
bool MessageObject::ExecuteNextBrowserTask()
{
Task nextTask;
{
std::lock_guard<std::mutex> lock(browserTaskMutex);
if (!browserTasks.size())
return false;
nextTask = browserTasks[0];
browserTasks.pop_front();
}
nextTask.func(nextTask.browser);
return true;
}
void MessageObject::ExecuteTask(MessageTask task)
{
task();
}
void MessageObject::DoCefMessageLoop(int ms)
{
if (ms)
QTimer::singleShot((int)ms + 2,
[]() { CefDoMessageLoopWork(); });
else
CefDoMessageLoopWork();
}
void MessageObject::Process()
{
CefDoMessageLoopWork();
}
void ProcessCef()
{
QMetaObject::invokeMethod(&messageObject, "DoCefMessageLoop",
Qt::QueuedConnection, Q_ARG(int, (int)0));
}
#define MAX_DELAY (1000 / 30)
void BrowserApp::OnScheduleMessagePumpWork(int64 delay_ms)
{
if (delay_ms < 0)
delay_ms = 0;
else if (delay_ms > MAX_DELAY)
delay_ms = MAX_DELAY;
if (!frameTimer.isActive()) {
QObject::connect(&frameTimer, &QTimer::timeout, &messageObject,
&MessageObject::Process);
frameTimer.setSingleShot(false);
frameTimer.start(33);
}
QMetaObject::invokeMethod(&messageObject, "DoCefMessageLoop",
Qt::QueuedConnection,
Q_ARG(int, (int)delay_ms));
}
#endif