CEFInterfaceJSScripting.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368
  1. // Engine/Source/Runtime/WebBrowser/Private/CEF/CEFJSScripting.cpp
  2. #include "CEF/CEFInterfaceJSScripting.h"
  3. #if WITH_CEF3
  4. #include "WebInterfaceJSScripting.h"
  5. #include "WebInterfaceJSFunction.h"
  6. #include "CEFWebInterfaceBrowserWindow.h"
  7. #include "CEFInterfaceJSStructSerializerBackend.h"
  8. #include "CEFInterfaceJSStructDeserializerBackend.h"
  9. #include "StructSerializer.h"
  10. #include "StructDeserializer.h"
  11. // Internal utility function(s)
  12. namespace
  13. {
  14. template<typename DestContainerType, typename SrcContainerType, typename DestKeyType, typename SrcKeyType>
  15. bool CopyContainerValue(DestContainerType DestContainer, SrcContainerType SrcContainer, DestKeyType DestKey, SrcKeyType SrcKey )
  16. {
  17. switch (SrcContainer->GetType(SrcKey))
  18. {
  19. case VTYPE_NULL:
  20. return DestContainer->SetNull(DestKey);
  21. case VTYPE_BOOL:
  22. return DestContainer->SetBool(DestKey, SrcContainer->GetBool(SrcKey));
  23. case VTYPE_INT:
  24. return DestContainer->SetInt(DestKey, SrcContainer->GetInt(SrcKey));
  25. case VTYPE_DOUBLE:
  26. return DestContainer->SetDouble(DestKey, SrcContainer->GetDouble(SrcKey));
  27. case VTYPE_STRING:
  28. return DestContainer->SetString(DestKey, SrcContainer->GetString(SrcKey));
  29. case VTYPE_BINARY:
  30. return DestContainer->SetBinary(DestKey, SrcContainer->GetBinary(SrcKey));
  31. case VTYPE_DICTIONARY:
  32. return DestContainer->SetDictionary(DestKey, SrcContainer->GetDictionary(SrcKey));
  33. case VTYPE_LIST:
  34. return DestContainer->SetList(DestKey, SrcContainer->GetList(SrcKey));
  35. case VTYPE_INVALID:
  36. default:
  37. return false;
  38. }
  39. }
  40. }
  41. CefRefPtr<CefDictionaryValue> FCEFInterfaceJSScripting::ConvertStruct(UStruct* TypeInfo, const void* StructPtr)
  42. {
  43. FCEFInterfaceJSStructSerializerBackend Backend (SharedThis(this));
  44. FStructSerializer::Serialize(StructPtr, *TypeInfo, Backend);
  45. CefRefPtr<CefDictionaryValue> Result = CefDictionaryValue::Create();
  46. Result->SetString("$type", "struct");
  47. Result->SetString("$ue4Type", TCHAR_TO_WCHAR(*GetBindingName(TypeInfo)));
  48. Result->SetDictionary("$value", Backend.GetResult());
  49. return Result;
  50. }
  51. CefRefPtr<CefDictionaryValue> FCEFInterfaceJSScripting::ConvertObject(UObject* Object)
  52. {
  53. CefRefPtr<CefDictionaryValue> Result = CefDictionaryValue::Create();
  54. RetainBinding(Object);
  55. UClass* Class = Object->GetClass();
  56. CefRefPtr<CefListValue> MethodNames = CefListValue::Create();
  57. int32 MethodIndex = 0;
  58. for (TFieldIterator<UFunction> FunctionIt(Class, EFieldIteratorFlags::IncludeSuper); FunctionIt; ++FunctionIt)
  59. {
  60. UFunction* Function = *FunctionIt;
  61. MethodNames->SetString(MethodIndex++, TCHAR_TO_WCHAR(*GetBindingName(Function)));
  62. }
  63. Result->SetString("$type", "uobject");
  64. Result->SetString("$id", TCHAR_TO_WCHAR(*PtrToGuid(Object).ToString(EGuidFormats::Digits)));
  65. Result->SetList("$methods", MethodNames);
  66. return Result;
  67. }
  68. bool FCEFInterfaceJSScripting::OnProcessMessageReceived(CefRefPtr<CefBrowser> Browser, CefProcessId SourceProcess, CefRefPtr<CefProcessMessage> Message)
  69. {
  70. bool Result = false;
  71. FString MessageName = WCHAR_TO_TCHAR(Message->GetName().ToWString().c_str());
  72. if (MessageName == TEXT("UE::ExecuteUObjectMethod"))
  73. {
  74. Result = HandleExecuteUObjectMethodMessage(Message->GetArgumentList());
  75. }
  76. else if (MessageName == TEXT("UE::ReleaseUObject"))
  77. {
  78. Result = HandleReleaseUObjectMessage(Message->GetArgumentList());
  79. }
  80. return Result;
  81. }
  82. void FCEFInterfaceJSScripting::SendProcessMessage(CefRefPtr<CefProcessMessage> Message)
  83. {
  84. if (IsValid() && InternalCefBrowser->GetMainFrame())
  85. {
  86. InternalCefBrowser->GetMainFrame()->SendProcessMessage(PID_RENDERER, Message);
  87. }
  88. }
  89. CefRefPtr<CefDictionaryValue> FCEFInterfaceJSScripting::GetPermanentBindings()
  90. {
  91. CefRefPtr<CefDictionaryValue> Result = CefDictionaryValue::Create();
  92. TMap<FString, UObject*> CachedPermanentUObjectsByName = PermanentUObjectsByName;
  93. for(auto& Entry : CachedPermanentUObjectsByName)
  94. {
  95. Result->SetDictionary(TCHAR_TO_WCHAR(*Entry.Key), ConvertObject(Entry.Value));
  96. }
  97. return Result;
  98. }
  99. void FCEFInterfaceJSScripting::BindUObject(const FString& Name, UObject* Object, bool bIsPermanent)
  100. {
  101. const FString ExposedName = GetBindingName(Name, Object);
  102. CefRefPtr<CefDictionaryValue> Converted = ConvertObject(Object);
  103. if (bIsPermanent)
  104. {
  105. // Each object can only have one permanent binding
  106. if (BoundObjects[Object].bIsPermanent)
  107. {
  108. return;
  109. }
  110. // Existing permanent objects must be removed first
  111. if (PermanentUObjectsByName.Contains(ExposedName))
  112. {
  113. return;
  114. }
  115. BoundObjects[Object]={true, -1};
  116. PermanentUObjectsByName.Add(ExposedName, Object);
  117. }
  118. CefRefPtr<CefProcessMessage> SetValueMessage = CefProcessMessage::Create(TCHAR_TO_WCHAR(TEXT("UE::SetValue")));
  119. CefRefPtr<CefListValue>MessageArguments = SetValueMessage->GetArgumentList();
  120. CefRefPtr<CefDictionaryValue> Value = CefDictionaryValue::Create();
  121. Value->SetString("name", TCHAR_TO_WCHAR(*ExposedName));
  122. Value->SetDictionary("value", Converted);
  123. Value->SetBool("permanent", bIsPermanent);
  124. MessageArguments->SetDictionary(0, Value);
  125. SendProcessMessage(SetValueMessage);
  126. }
  127. void FCEFInterfaceJSScripting::UnbindUObject(const FString& Name, UObject* Object, bool bIsPermanent)
  128. {
  129. const FString ExposedName = GetBindingName(Name, Object);
  130. if (bIsPermanent)
  131. {
  132. // If overriding an existing permanent object, make it non-permanent
  133. if (PermanentUObjectsByName.Contains(ExposedName) && (Object == nullptr || PermanentUObjectsByName[ExposedName] == Object))
  134. {
  135. Object = PermanentUObjectsByName.FindAndRemoveChecked(ExposedName);
  136. BoundObjects.Remove(Object);
  137. return;
  138. }
  139. else
  140. {
  141. return;
  142. }
  143. }
  144. CefRefPtr<CefProcessMessage> DeleteValueMessage = CefProcessMessage::Create(TCHAR_TO_WCHAR(TEXT("UE::DeleteValue")));
  145. CefRefPtr<CefListValue>MessageArguments = DeleteValueMessage->GetArgumentList();
  146. CefRefPtr<CefDictionaryValue> Info = CefDictionaryValue::Create();
  147. Info->SetString("name", TCHAR_TO_WCHAR(*ExposedName));
  148. Info->SetString("id", TCHAR_TO_WCHAR(*PtrToGuid(Object).ToString(EGuidFormats::Digits)));
  149. Info->SetBool("permanent", bIsPermanent);
  150. MessageArguments->SetDictionary(0, Info);
  151. SendProcessMessage(DeleteValueMessage);
  152. }
  153. bool FCEFInterfaceJSScripting::HandleReleaseUObjectMessage(CefRefPtr<CefListValue> MessageArguments)
  154. {
  155. FGuid ObjectKey;
  156. // Message arguments are Name, Value, bGlobal
  157. if (MessageArguments->GetSize() != 1 || MessageArguments->GetType(0) != VTYPE_STRING)
  158. {
  159. // Wrong message argument types or count
  160. return false;
  161. }
  162. if (!FGuid::Parse(FString(WCHAR_TO_TCHAR(MessageArguments->GetString(0).ToWString().c_str())), ObjectKey))
  163. {
  164. // Invalid GUID
  165. return false;
  166. }
  167. UObject* Object = GuidToPtr(ObjectKey);
  168. if ( Object == nullptr )
  169. {
  170. // Invalid object
  171. return false;
  172. }
  173. ReleaseBinding(Object);
  174. return true;
  175. }
  176. bool FCEFInterfaceJSScripting::HandleExecuteUObjectMethodMessage(CefRefPtr<CefListValue> MessageArguments)
  177. {
  178. FGuid ObjectKey;
  179. // Message arguments are Name, Value, bGlobal
  180. if (MessageArguments->GetSize() != 4
  181. || MessageArguments->GetType(0) != VTYPE_STRING
  182. || MessageArguments->GetType(1) != VTYPE_STRING
  183. || MessageArguments->GetType(2) != VTYPE_STRING
  184. || MessageArguments->GetType(3) != VTYPE_LIST
  185. )
  186. {
  187. // Wrong message argument types or count
  188. return false;
  189. }
  190. if (!FGuid::Parse(FString(WCHAR_TO_TCHAR(MessageArguments->GetString(0).ToWString().c_str())), ObjectKey))
  191. {
  192. // Invalid GUID
  193. return false;
  194. }
  195. // Get the promise callback and use that to report any results from executing this function.
  196. FGuid ResultCallbackId;
  197. if (!FGuid::Parse(FString(WCHAR_TO_TCHAR(MessageArguments->GetString(2).ToWString().c_str())), ResultCallbackId))
  198. {
  199. // Invalid GUID
  200. return false;
  201. }
  202. UObject* Object = GuidToPtr(ObjectKey);
  203. if (Object == nullptr)
  204. {
  205. // Unknown uobject id
  206. InvokeJSErrorResult(ResultCallbackId, TEXT("Unknown UObject ID"));
  207. return true;
  208. }
  209. FName MethodName = WCHAR_TO_TCHAR(MessageArguments->GetString(1).ToWString().c_str());
  210. UFunction* Function = Object->FindFunction(MethodName);
  211. if (!Function)
  212. {
  213. InvokeJSErrorResult(ResultCallbackId, TEXT("Unknown UObject Function"));
  214. return true;
  215. }
  216. // Coerce arguments to function arguments.
  217. uint16 ParamsSize = Function->ParmsSize;
  218. uint8* Params = nullptr;
  219. FProperty* ReturnParam = nullptr;
  220. FProperty* PromiseParam = nullptr;
  221. if (ParamsSize > 0)
  222. {
  223. // Convert cef argument list to a dictionary, so we can use FStructDeserializer to convert it for us
  224. CefRefPtr<CefDictionaryValue> NamedArgs = CefDictionaryValue::Create();
  225. int32 CurrentArg = 0;
  226. CefRefPtr<CefListValue> CefArgs = MessageArguments->GetList(3);
  227. for ( TFieldIterator<FProperty> It(Function); It; ++It )
  228. {
  229. FProperty* Param = *It;
  230. if (Param->PropertyFlags & CPF_Parm)
  231. {
  232. if (Param->PropertyFlags & CPF_ReturnParm)
  233. {
  234. ReturnParam = Param;
  235. }
  236. else
  237. {
  238. FStructProperty *StructProperty = CastField<FStructProperty>(Param);
  239. if (StructProperty && StructProperty->Struct->IsChildOf(FWebInterfaceJSResponse::StaticStruct()))
  240. {
  241. PromiseParam = Param;
  242. }
  243. else
  244. {
  245. CopyContainerValue(NamedArgs, CefArgs, CefString(TCHAR_TO_WCHAR(*GetBindingName(Param))), CurrentArg);
  246. CurrentArg++;
  247. }
  248. }
  249. }
  250. }
  251. // UFunction is a subclass of UStruct, so we can treat the arguments as a struct for deserialization
  252. check(nullptr == Params);
  253. Params = (uint8*)FMemory::Malloc(Function->GetStructureSize());
  254. Function->InitializeStruct(Params);
  255. FCEFInterfaceJSStructDeserializerBackend Backend = FCEFInterfaceJSStructDeserializerBackend(SharedThis(this), NamedArgs);
  256. FStructDeserializer::Deserialize(Params, *Function, Backend);
  257. }
  258. if (PromiseParam)
  259. {
  260. FWebInterfaceJSResponse* PromisePtr = PromiseParam->ContainerPtrToValuePtr<FWebInterfaceJSResponse>(Params);
  261. if (PromisePtr)
  262. {
  263. *PromisePtr = FWebInterfaceJSResponse(SharedThis(this), ResultCallbackId);
  264. }
  265. }
  266. Object->ProcessEvent(Function, Params);
  267. CefRefPtr<CefListValue> Results = CefListValue::Create();
  268. if ( ! PromiseParam ) // If PromiseParam is set, we assume that the UFunction will ensure it is called with the result
  269. {
  270. if ( ReturnParam )
  271. {
  272. FStructSerializerPolicies ReturnPolicies;
  273. ReturnPolicies.PropertyFilter = [&](const FProperty* CandidateProperty, const FProperty* ParentProperty)
  274. {
  275. return ParentProperty != nullptr || CandidateProperty == ReturnParam;
  276. };
  277. FCEFInterfaceJSStructSerializerBackend ReturnBackend(SharedThis(this));
  278. FStructSerializer::Serialize(Params, *Function, ReturnBackend, ReturnPolicies);
  279. CefRefPtr<CefDictionaryValue> ResultDict = ReturnBackend.GetResult();
  280. // Extract the single return value from the serialized dictionary to an array
  281. CopyContainerValue(Results, ResultDict, 0, TCHAR_TO_WCHAR(*GetBindingName(ReturnParam)));
  282. }
  283. InvokeJSFunction(ResultCallbackId, Results, false);
  284. }
  285. if (Params)
  286. {
  287. Function->DestroyStruct(Params);
  288. FMemory::Free(Params);
  289. Params = nullptr;
  290. }
  291. return true;
  292. }
  293. void FCEFInterfaceJSScripting::UnbindCefBrowser()
  294. {
  295. InternalCefBrowser = nullptr;
  296. }
  297. void FCEFInterfaceJSScripting::InvokeJSErrorResult(FGuid FunctionId, const FString& Error)
  298. {
  299. CefRefPtr<CefListValue> FunctionArguments = CefListValue::Create();
  300. FunctionArguments->SetString(0, TCHAR_TO_WCHAR(*Error));
  301. InvokeJSFunction(FunctionId, FunctionArguments, true);
  302. }
  303. void FCEFInterfaceJSScripting::InvokeJSFunction(FGuid FunctionId, int32 ArgCount, FWebInterfaceJSParam Arguments[], bool bIsError)
  304. {
  305. CefRefPtr<CefListValue> FunctionArguments = CefListValue::Create();
  306. for ( int32 i=0; i<ArgCount; i++)
  307. {
  308. SetConverted(FunctionArguments, i, Arguments[i]);
  309. }
  310. InvokeJSFunction(FunctionId, FunctionArguments, bIsError);
  311. }
  312. void FCEFInterfaceJSScripting::InvokeJSFunction(FGuid FunctionId, const CefRefPtr<CefListValue>& FunctionArguments, bool bIsError)
  313. {
  314. CefRefPtr<CefProcessMessage> Message = CefProcessMessage::Create(TCHAR_TO_WCHAR(TEXT("UE::ExecuteJSFunction")));
  315. CefRefPtr<CefListValue> MessageArguments = Message->GetArgumentList();
  316. MessageArguments->SetString(0, TCHAR_TO_WCHAR(*FunctionId.ToString(EGuidFormats::Digits)));
  317. MessageArguments->SetList(1, FunctionArguments);
  318. MessageArguments->SetBool(2, bIsError);
  319. SendProcessMessage(Message);
  320. }
  321. #endif