-
Notifications
You must be signed in to change notification settings - Fork 2.2k
/
Copy pathResourceUIScripting.cpp
570 lines (467 loc) · 14.1 KB
/
ResourceUIScripting.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
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
/*
* This file is part of the CitizenFX project - http://citizen.re/
*
* See LICENSE and MENTIONS in the root of the source tree for information
* regarding licensing.
*/
#include <StdInc.h>
#include <ResourceUI.h>
#include <fxScripting.h>
#include <ScriptEngine.h>
#include <rapidjson/document.h>
#include <rapidjson/writer.h>
#include <scrBind.h>
#include <IteratorView.h>
#include <CL2LaunchMode.h>
#include <HostSharedData.h>
#include <ReverseGameData.h>
#include <CrossBuildRuntime.h>
#include <sstream>
#include <string_view>
#include <Error.h>
#include <boost/algorithm/string/case_conv.hpp>
static std::string CleanURL(const std::string& url)
{
auto lowerURL = boost::algorithm::to_lower_copy(url);
if (lowerURL.find("file://") == 0)
{
// log an error so that we have insight as to any frequency of use
FatalError("file:// URI requests in DUI are not supported.\nRequested URL: %s", url);
}
if (lowerURL.find("http://") == 0 || lowerURL.find("https://") == 0 || lowerURL.find("nui://") == 0 || lowerURL.find("about:") == 0)
{
return url;
}
else
{
// unknown-ish url, prefix with https://
return fmt::sprintf("https://%s", url);
}
}
static InitFunction initFunction([] ()
{
static auto sendMessageToFrame = [](fx::ScriptContext& context, const char* native, auto& execFn)
{
// get the message as JSON and validate it by parsing/recreating (so we won't end up injecting malicious JS into the browser root)
const char* messageJson = context.GetArgument<const char*>(0);
rapidjson::Document document;
document.Parse(messageJson);
if (!document.HasParseError())
{
rapidjson::StringBuffer sb;
rapidjson::Writer<rapidjson::StringBuffer> writer(sb);
if (document.Accept(writer))
{
// execute in NUI
execFn(std::string_view(sb.GetString(), sb.GetSize()));
// and return 'true' to indicate to the script that we succeeded
context.SetResult(true);
return;
}
else
{
trace("%s: writing to JSON writer failed\n", native);
}
}
else
{
trace("%s: invalid JSON passed in frame (rapidjson error code %d)\n", native, document.GetParseError());
}
context.SetResult(false);
};
static auto getExecRootFrameFn = [](const std::string& frameName) -> std::function<void(std::string_view)>
{
return [frameName](std::string_view data)
{
// somewhat insane sanity check at the last minute
if (frameName.find('"') == std::string::npos)
{
// send to NUI
nui::PostFrameMessage(frameName, std::string(data));
}
};
};
fx::ScriptEngine::RegisterNativeHandler("SEND_NUI_MESSAGE", [=] (fx::ScriptContext& context)
{
fx::OMPtr<IScriptRuntime> runtime;
if (FX_SUCCEEDED(fx::GetCurrentScriptRuntime(&runtime)))
{
fx::Resource* resource = reinterpret_cast<fx::Resource*>(runtime->GetParentObject());
if (resource)
{
fwRefContainer<ResourceUI> resourceUI = resource->GetComponent<ResourceUI>();
if (resourceUI.GetRef())
{
if (resourceUI->HasFrame())
{
sendMessageToFrame(context, "SEND_NUI_MESSAGE", getExecRootFrameFn(resource->GetName()));
return;
}
else
{
trace("SEND_NUI_MESSAGE: resource %s has no UI frame\n", resource->GetName());
}
}
else
{
trace("SEND_NUI_MESSAGE: resource %s has no UI\n", resource->GetName());
}
}
else
{
trace("SEND_NUI_MESSAGE: no current resource\n");
}
}
else
{
trace("SEND_NUI_MESSAGE called from outside a scripting runtime\n");
}
context.SetResult(false);
});
fx::ScriptEngine::RegisterNativeHandler("SEND_LOADING_SCREEN_MESSAGE", [=](fx::ScriptContext& context)
{
if (nui::HasFrame("loadingScreen"))
{
return sendMessageToFrame(context, "SEND_LOADING_SCREEN_MESSAGE", getExecRootFrameFn("loadingScreen"));
}
else
{
trace("SEND_LOADING_SCREEN_MESSAGE called while the loading screen was shut down\n");
}
context.SetResult(false);
});
fx::ScriptEngine::RegisterNativeHandler("DOES_DUI_EXIST", [=](fx::ScriptContext& context)
{
auto duiHandle = context.CheckArgument<uint32_t>(0);
auto find = g_ScrBindPool.Handles.find(duiHandle);
context.SetResult(find != g_ScrBindPool.Handles.end());
});
class NUIWindowWrapper;
static std::multimap<std::string, std::string> resourcesToNuiWindows;
static std::map<std::string, NUIWindowWrapper*> nuiWindows;
static int nuiWindowIdx;
class NUIWindowWrapper
{
public:
NUIWindowWrapper(const char* urlArg, int width, int height)
: m_mouseX(0), m_mouseY(0)
{
fx::OMPtr<IScriptRuntime> runtime;
if (!FX_SUCCEEDED(fx::GetCurrentScriptRuntime(&runtime)))
{
return;
}
if (!urlArg)
{
return;
}
auto url = CleanURL(urlArg);
fx::Resource* resource = reinterpret_cast<fx::Resource*>(runtime->GetParentObject());
++nuiWindowIdx;
m_autogenHandle = fmt::sprintf("nui_resource_%d", nuiWindowIdx);
nui::CreateNUIWindow(m_autogenHandle, width, height, url);
nuiWindows.insert({ m_autogenHandle, this });
resourcesToNuiWindows.insert({ resource->GetName(), m_autogenHandle });
}
~NUIWindowWrapper()
{
Destroy();
}
void SetURL(const char* url)
{
if (!url)
{
return;
}
nui::SetNUIWindowURL(m_autogenHandle, CleanURL(url));
}
void Destroy()
{
if (m_autogenHandle.empty())
{
return;
}
nuiWindows.erase(m_autogenHandle);
nui::DestroyNUIWindow(m_autogenHandle);
m_autogenHandle.clear();
}
const char* GetHandle()
{
return m_autogenHandle.c_str();
}
bool SendMessage(const char* jsonString)
{
fx::ScriptContextBuffer fakeCxt;
fakeCxt.Push(jsonString);
sendMessageToFrame(fakeCxt, "SEND_DUI_MESSAGE", [this](std::string_view data)
{
std::stringstream stream;
stream << "window.postMessage(" << data << ", '*');";
nui::ExecuteWindowScript(m_autogenHandle, stream.str());
});
return fakeCxt.GetResult<bool>();
}
bool IsAvailable()
{
auto browser = nui::GetNUIWindowBrowser(m_autogenHandle);
return browser && browser->GetHost();
}
void InjectMouseMove(int x, int y)
{
auto browser = nui::GetNUIWindowBrowser(m_autogenHandle);
m_mouseX = x;
m_mouseY = y;
if (browser && browser->GetHost())
{
CefMouseEvent ev;
ev.x = x;
ev.y = y;
browser->GetHost()->SendMouseMoveEvent(ev, false);
}
}
void InjectMouseDown(const char* button)
{
auto browser = nui::GetNUIWindowBrowser(m_autogenHandle);
if (browser && browser->GetHost())
{
CefMouseEvent ev;
ev.x = m_mouseX;
ev.y = m_mouseY;
browser->GetHost()->SendMouseClickEvent(ev, GetButton(button), false, 1);
}
}
void InjectMouseUp(const char* button)
{
auto browser = nui::GetNUIWindowBrowser(m_autogenHandle);
if (browser && browser->GetHost())
{
CefMouseEvent ev;
ev.x = m_mouseX;
ev.y = m_mouseY;
browser->GetHost()->SendMouseClickEvent(ev, GetButton(button), true, 1);
}
}
void InjectMouseWheel(int dy, int dx)
{
auto browser = nui::GetNUIWindowBrowser(m_autogenHandle);
if (browser && browser->GetHost())
{
CefMouseEvent ev;
ev.x = m_mouseX;
ev.y = m_mouseY;
browser->GetHost()->SendMouseWheelEvent(ev, dx, dy);
}
}
private:
cef_mouse_button_type_t GetButton(const char* button)
{
if (_stricmp(button, "left") == 0)
{
return MBT_LEFT;
}
else if (_stricmp(button, "right") == 0)
{
return MBT_RIGHT;
}
else if (_stricmp(button, "middle") == 0)
{
return MBT_MIDDLE;
}
else
{
return MBT_MIDDLE;
}
}
private:
int m_mouseX;
int m_mouseY;
std::string m_autogenHandle;
};
scrBindClass<NUIWindowWrapper>()
.AddConstructor<const char*, int, int>("CREATE_DUI")
.AddDestructor("DESTROY_DUI")
.AddMethod("SET_DUI_URL", &NUIWindowWrapper::SetURL)
.AddMethod("SEND_DUI_MESSAGE", &NUIWindowWrapper::SendMessage)
.AddMethod("GET_DUI_HANDLE", &NUIWindowWrapper::GetHandle)
.AddMethod("IS_DUI_AVAILABLE", &NUIWindowWrapper::IsAvailable)
.AddMethod("SEND_DUI_MOUSE_MOVE", &NUIWindowWrapper::InjectMouseMove)
.AddMethod("SEND_DUI_MOUSE_DOWN", &NUIWindowWrapper::InjectMouseDown)
.AddMethod("SEND_DUI_MOUSE_UP", &NUIWindowWrapper::InjectMouseUp)
.AddMethod("SEND_DUI_MOUSE_WHEEL", &NUIWindowWrapper::InjectMouseWheel);
// this *was* a multiset before but some resources would not correctly pair set/unset and then be stuck in 'set' state
static std::unordered_set<std::string> focusVotes;
static std::unordered_set<std::string> focusCursorVotes;
static std::unordered_set<std::string> focusKeepInputVotes;
static bool lastFocus = false;
static bool lastFocusCursor = false;
static bool lastFocusKeepInput = false;
static auto updateFocus = []()
{
{
auto shouldFocus = !focusVotes.empty();
auto shouldCursor = !focusCursorVotes.empty();
if (shouldFocus != lastFocus || shouldCursor != lastFocusCursor)
{
nui::GiveFocus("", shouldFocus, shouldCursor);
lastFocus = shouldFocus;
lastFocusCursor = shouldCursor;
}
}
{
// find if the keep-input list overlaps with the general vote list
bool shouldKeepInput = false;
for (const auto& resource : focusKeepInputVotes)
{
if (focusVotes.find(resource) != focusVotes.end() ||
focusCursorVotes.find(resource) != focusCursorVotes.end())
{
shouldKeepInput = true;
break;
}
}
if (shouldKeepInput != lastFocusKeepInput)
{
nui::KeepInput(shouldKeepInput);
lastFocusKeepInput = shouldKeepInput;
}
}
};
fx::Resource::OnInitializeInstance.Connect([](fx::Resource* resource)
{
resource->OnStop.Connect([resource]()
{
auto resourceName = resource->GetName();
for (auto dui : fx::GetIteratorView(resourcesToNuiWindows.equal_range(resourceName)))
{
if (auto it = nuiWindows.find(dui.second); it != nuiWindows.end())
{
it->second->Destroy();
}
}
focusVotes.erase(resourceName);
focusKeepInputVotes.erase(resourceName);
focusCursorVotes.erase(resourceName);
updateFocus();
});
});
fx::ScriptEngine::RegisterNativeHandler("IS_NUI_FOCUSED", [] (fx::ScriptContext& context)
{
context.SetResult(nui::HasFocus());
});
fx::ScriptEngine::RegisterNativeHandler("IS_NUI_FOCUS_KEEPING_INPUT", [] (fx::ScriptContext& context)
{
context.SetResult(nui::HasFocusKeepInput());
});
fx::ScriptEngine::RegisterNativeHandler("SET_NUI_ZINDEX", [](fx::ScriptContext& context)
{
fx::OMPtr<IScriptRuntime> runtime;
if (FX_FAILED(fx::GetCurrentScriptRuntime(&runtime)))
{
return;
}
fx::Resource* resource = reinterpret_cast<fx::Resource*>(runtime->GetParentObject());
if (!resource)
{
return;
}
fwRefContainer<ResourceUI> resourceUI = resource->GetComponent<ResourceUI>();
if (!resourceUI.GetRef() || !resourceUI->HasFrame())
{
return;
}
if (resource->GetName().find('"') != std::string::npos)
{
return;
}
int zIndex = context.GetArgument<int>(0);
nui::PostRootMessage(fmt::sprintf(R"({ "type": "setZIndex", "frameName": "%s", "zIndex": "%d" })", resource->GetName(), zIndex));
});
fx::ScriptEngine::RegisterNativeHandler("SET_NUI_FOCUS", [] (fx::ScriptContext& context)
{
fx::OMPtr<IScriptRuntime> runtime;
if (FX_SUCCEEDED(fx::GetCurrentScriptRuntime(&runtime)))
{
fx::Resource* resource = reinterpret_cast<fx::Resource*>(runtime->GetParentObject());
if (resource)
{
fwRefContainer<ResourceUI> resourceUI = resource->GetComponent<ResourceUI>();
if (resourceUI.GetRef())
{
if (resourceUI->HasFrame())
{
if (resource->GetName().find('"') == std::string::npos)
{
bool hasFocus = context.GetArgument<bool>(0);
bool hasCursor = context.GetArgument<bool>(1);
const char* functionName = (hasFocus) ? "focusFrame" : "blurFrame";
nui::PostRootMessage(fmt::sprintf(R"({ "type": "%s", "frameName": "%s" } )", functionName, resource->GetName()));
if (hasFocus)
{
focusVotes.insert(resource->GetName());
}
else if (auto it = focusVotes.find(resource->GetName()); it != focusVotes.end())
{
focusVotes.erase(it);
}
if (hasCursor)
{
focusCursorVotes.insert(resource->GetName());
}
else if (auto it = focusCursorVotes.find(resource->GetName()); it != focusCursorVotes.end())
{
focusCursorVotes.erase(it);
}
updateFocus();
}
}
}
}
}
});
if (launch::IsSDKGuest())
{
fx::ScriptEngine::RegisterNativeHandler("GET_NUI_CURSOR_POSITION", [](fx::ScriptContext& context)
{
static HostSharedData<ReverseGameData> rgd("CfxReverseGameData");
*context.GetArgument<int*>(0) = rgd->mouseAbsX;
*context.GetArgument<int*>(1) = rgd->mouseAbsY;
});
}
else
{
fx::ScriptEngine::RegisterNativeHandler("GET_NUI_CURSOR_POSITION", [](fx::ScriptContext& context)
{
POINT cursorPos;
GetCursorPos(&cursorPos);
ScreenToClient(CoreGetGameWindow(), &cursorPos);
*context.GetArgument<int*>(0) = cursorPos.x;
*context.GetArgument<int*>(1) = cursorPos.y;
});
}
fx::ScriptEngine::RegisterNativeHandler("SET_NUI_FOCUS_KEEP_INPUT", [](fx::ScriptContext& context)
{
fx::OMPtr<IScriptRuntime> runtime;
if (FX_SUCCEEDED(fx::GetCurrentScriptRuntime(&runtime)))
{
fx::Resource* resource = reinterpret_cast<fx::Resource*>(runtime->GetParentObject());
if (resource)
{
bool shouldKeepInput = context.GetArgument<bool>(0);
auto& voteList = focusKeepInputVotes;
if (shouldKeepInput)
{
voteList.insert(resource->GetName());
}
else
{
// remove just one entry
if (auto it = voteList.find(resource->GetName()); it != voteList.end())
{
voteList.erase(it);
}
}
updateFocus();
}
}
});
});