JSB Add Caching

Bound object meta data is cached within a render process
CefSharp.IsObjectCached - JS method to test if object cached
CefSharp.RemoveObjectFromCache - JS method to remove object from cache

If a request is made for multiple objects with not all of them being cached then a IPC message is sent.
When all objects already bound return response object for consistency
FindBrowserWrapper signature change - it's really not safe to throw a managed exception in the middle of unmanaged code, changed to logging and null checking
JavascriptObjectRepository - Add All Constant - Used when All objects are requested for binding (objects can also be requested by name)

TODO: Add a JS library to improve user experience when dealing with cached objects
This commit is contained in:
amaitland
2018-01-29 15:48:54 +10:00
parent bd3f336bdc
commit 1b00c277b8
5 changed files with 198 additions and 66 deletions
@@ -5,17 +5,17 @@
#include "Stdafx.h"
#include "include\base\cef_logging.h"
#include "CefBrowserWrapper.h"
#include "CefAppUnmanagedWrapper.h"
#include "RegisterBoundObjectHandler.h"
#include "JavascriptRootObjectWrapper.h"
#include "Serialization\V8Serialization.h"
#include "Serialization\JsObjectsSerialization.h"
#include "Async/JavascriptAsyncMethodCallback.h"
#include "Async\JavascriptAsyncMethodCallback.h"
#include "..\CefSharp.Core\Internals\Messaging\Messages.h"
#include "..\CefSharp.Core\Internals\Serialization\Primitives.h"
using namespace System;
using namespace System::Diagnostics;
using namespace System::Collections::Generic;
using namespace CefSharp::Internals::Messaging;
@@ -75,21 +75,13 @@ namespace CefSharp
if (_legacyBindingEnabled)
{
auto browserWrapper = FindBrowserWrapper(browser->GetIdentifier(), true);
auto rootObjectWrappers = browserWrapper->JavascriptRootObjectWrappers;
auto frameId = frame->GetIdentifier();
if (_javascriptObjects->Count > 0)
{
JavascriptRootObjectWrapper^ rootObject;
if (!rootObjectWrappers->TryGetValue(frameId, rootObject))
auto rootObject = GetJsRootObjectWrapper(browser->GetIdentifier(), frame->GetIdentifier());
if (rootObject != nullptr)
{
rootObject = gcnew JavascriptRootObjectWrapper(browser->GetIdentifier(), browserWrapper->BrowserProcess);
rootObjectWrappers->TryAdd(frameId, rootObject);
rootObject->Bind(_javascriptObjects->Values, context->GetGlobal());
}
rootObject->Bind(_javascriptObjects->Values, context->GetGlobal());
}
}
@@ -98,15 +90,21 @@ namespace CefSharp
auto cefSharpObj = CefV8Value::CreateObject(NULL, NULL);
global->SetValue("CefSharp", cefSharpObj, CefV8Value::PropertyAttribute::V8_PROPERTY_ATTRIBUTE_READONLY);
auto bindObjAsyncFunction = CefV8Value::CreateFunction("BindObjectAsync", new RegisterBoundObjectHandler(_registerBoundObjectRegistry, _javascriptObjects));
auto browserWrapper = FindBrowserWrapper(browser->GetIdentifier());
//TODO: JSB: Split functions into their own classes
//Browser wrapper is only used for BindObjectAsync
auto bindObjAsyncFunction = CefV8Value::CreateFunction("BindObjectAsync", new RegisterBoundObjectHandler(_registerBoundObjectRegistry, _javascriptObjects, browserWrapper));
cefSharpObj->SetValue("BindObjectAsync", bindObjAsyncFunction, CefV8Value::PropertyAttribute::V8_PROPERTY_ATTRIBUTE_NONE);
auto unBindObFunction = CefV8Value::CreateFunction("DeleteBoundObject", new RegisterBoundObjectHandler(_registerBoundObjectRegistry, _javascriptObjects));
auto unBindObFunction = CefV8Value::CreateFunction("DeleteBoundObject", new RegisterBoundObjectHandler(_registerBoundObjectRegistry, _javascriptObjects, nullptr));
cefSharpObj->SetValue("DeleteBoundObject", unBindObFunction, CefV8Value::PropertyAttribute::V8_PROPERTY_ATTRIBUTE_NONE);
//TODO: JSB We could in theory auto bind all the cached objects which would resemble the original JSB behaviour, if
//the cache is empty which would be the case for any cross-site navigation request or the first request made to a browser instance
//then no objects would be bound by default
auto removeObjectFromCacheFunction = CefV8Value::CreateFunction("RemoveObjectFromCache", new RegisterBoundObjectHandler(_registerBoundObjectRegistry, _javascriptObjects, nullptr));
cefSharpObj->SetValue("RemoveObjectFromCache", removeObjectFromCacheFunction, CefV8Value::PropertyAttribute::V8_PROPERTY_ATTRIBUTE_NONE);
auto isObjectCachedFunction = CefV8Value::CreateFunction("IsObjectCached", new RegisterBoundObjectHandler(_registerBoundObjectRegistry, _javascriptObjects, nullptr));
cefSharpObj->SetValue("IsObjectCached", isObjectCachedFunction, CefV8Value::PropertyAttribute::V8_PROPERTY_ATTRIBUTE_NONE);
};
void CefAppUnmanagedWrapper::OnContextReleased(CefRefPtr<CefBrowser> browser, CefRefPtr<CefFrame> frame, CefRefPtr<CefV8Context> context)
@@ -123,7 +121,13 @@ namespace CefSharp
browser->SendProcessMessage(CefProcessId::PID_BROWSER, contextReleasedMessage);
}
auto browserWrapper = FindBrowserWrapper(browser->GetIdentifier(), true);
auto browserWrapper = FindBrowserWrapper(browser->GetIdentifier());
//If we no longer have a browser wrapper reference then there's nothing we can do
if (browserWrapper == nullptr)
{
return;
}
auto rootObjectWrappers = browserWrapper->JavascriptRootObjectWrappers;
@@ -177,15 +181,37 @@ namespace CefSharp
browser->SendProcessMessage(CefProcessId::PID_BROWSER, focusedNodeChangedMessage);
}
CefBrowserWrapper^ CefAppUnmanagedWrapper::FindBrowserWrapper(int browserId, bool mustExist)
JavascriptRootObjectWrapper^ CefAppUnmanagedWrapper::GetJsRootObjectWrapper(int browserId, int64 frameId)
{
auto browserWrapper = FindBrowserWrapper(browserId);
if (browserWrapper == nullptr)
{
return nullptr;
}
auto rootObjectWrappers = browserWrapper->JavascriptRootObjectWrappers;
JavascriptRootObjectWrapper^ rootObject;
if (!rootObjectWrappers->TryGetValue(frameId, rootObject))
{
rootObject = gcnew JavascriptRootObjectWrapper(browserId, browserWrapper->BrowserProcess);
rootObjectWrappers->TryAdd(frameId, rootObject);
}
return rootObject;
}
CefBrowserWrapper^ CefAppUnmanagedWrapper::FindBrowserWrapper(int browserId)
{
CefBrowserWrapper^ wrapper = nullptr;
_browserWrappers->TryGetValue(browserId, wrapper);
if (mustExist && wrapper == nullptr)
if (wrapper == nullptr)
{
throw gcnew InvalidOperationException(String::Format("Failed to identify BrowserWrapper in OnContextCreated. : {0}", browserId));
//TODO: Find the syntax for delcaring the native string directly
LOG(ERROR) << StringUtils::ToNative("Failed to identify BrowserWrapper in OnContextCreated BrowserId:" + browserId).ToString();
}
return wrapper;
@@ -197,7 +223,7 @@ namespace CefSharp
auto name = message->GetName();
auto argList = message->GetArgumentList();
auto browserWrapper = FindBrowserWrapper(browser->GetIdentifier(), false);
auto browserWrapper = FindBrowserWrapper(browser->GetIdentifier());
//Error handling for missing/closed browser
if (browserWrapper == nullptr)
{
@@ -434,28 +460,25 @@ namespace CefSharp
auto callbackId = GetInt64(argList, 3);
auto javascriptObjects = DeserializeJsObjects(argList, 4);
//TODO: JSB Implement Caching of JavascriptObjects
//Should caching be configurable? On a per object basis?
/*for each (JavascriptObject^ obj in Enumerable::OfType<JavascriptObject^>(javascriptObjects))
//Caching of JavascriptObjects
//TODO: JSB Should caching be configurable? On a per object basis?
for each (JavascriptObject^ obj in Enumerable::OfType<JavascriptObject^>(javascriptObjects))
{
if (_javascriptObjects->ContainsKey(obj->JavascriptName))
{
_javascriptObjects->Remove(obj->JavascriptName);
}
_javascriptObjects->Add(obj->JavascriptName, obj);
}*/
auto browserWrapper = FindBrowserWrapper(browser->GetIdentifier(), true);
}
auto rootObjectWrappers = browserWrapper->JavascriptRootObjectWrappers;
auto frame = browser->GetFrame(frameId);
if (frame.get())
{
JavascriptRootObjectWrapper^ rootObject;
if (!rootObjectWrappers->TryGetValue(frameId, rootObject))
auto rootObject = GetJsRootObjectWrapper(browser->GetIdentifier(), frameId);
if (rootObject == nullptr)
{
rootObject = gcnew JavascriptRootObjectWrapper(browser->GetIdentifier(), browserWrapper->BrowserProcess);
rootObjectWrappers->TryAdd(frameId, rootObject);
return false;
}
auto context = frame->GetV8Context();
@@ -472,6 +495,8 @@ namespace CefSharp
//Response object has no Accessor or Interceptor
auto response = CefV8Value::CreateObject(NULL, NULL);
response->SetValue("Count", CefV8Value::CreateInt(javascriptObjects->Count), CefV8Value::PropertyAttribute::V8_PROPERTY_ATTRIBUTE_READONLY);
if (javascriptObjects->Count > 0)
{
//TODO: JSB Should we include a list of successfully bound object names?
@@ -486,8 +511,6 @@ namespace CefSharp
callback->Success(response);
}
//TODO: JSB deal with failure - no object matching bound
//Send message notifying Browser Process of which objects were bound
//We do this after the objects have been created in the V8Context to gurantee
//they are accessible.
@@ -67,7 +67,8 @@ namespace CefSharp
delete _schemes;
}
CefBrowserWrapper^ FindBrowserWrapper(int browserId, bool mustExist);
CefBrowserWrapper^ FindBrowserWrapper(int browserId);
JavascriptRootObjectWrapper^ GetJsRootObjectWrapper(int browserId, int64 frameId);
virtual DECL CefRefPtr<CefRenderProcessHandler> GetRenderProcessHandler() OVERRIDE;
virtual DECL void OnBrowserCreated(CefRefPtr<CefBrowser> browser) OVERRIDE;
@@ -10,6 +10,7 @@
#include "..\CefSharp.Core\Internals\Messaging\Messages.h"
#include "..\CefSharp.Core\Internals\Serialization\Primitives.h"
using namespace System;
using namespace CefSharp::Internals::Messaging;
using namespace CefSharp::Internals::Serialization;
@@ -20,12 +21,14 @@ namespace CefSharp
private:
gcroot<RegisterBoundObjectRegistry^> _callbackRegistry;
gcroot<Dictionary<String^, JavascriptObject^>^> _javascriptObjects;
gcroot<CefBrowserWrapper^> _browserWrapper;
public:
RegisterBoundObjectHandler(RegisterBoundObjectRegistry^ callbackRegistery, Dictionary<String^, JavascriptObject^>^ javascriptObjects)
RegisterBoundObjectHandler(RegisterBoundObjectRegistry^ callbackRegistery, Dictionary<String^, JavascriptObject^>^ javascriptObjects, CefBrowserWrapper^ browserWrapper)
{
_callbackRegistry = callbackRegistery;
_javascriptObjects = javascriptObjects;
_browserWrapper = browserWrapper;
}
bool Execute(const CefString& name, CefRefPtr<CefV8Value> object, const CefV8ValueList& arguments, CefRefPtr<CefV8Value>& retval, CefString& exception) OVERRIDE
@@ -41,9 +44,48 @@ namespace CefSharp
{
auto global = context->GetGlobal();
if (name == "IsObjectCached")
{
if (arguments.size() == 0 || arguments.size() > 1)
{
//TODO: Improve error message
exception = "Must specify the name of a single bound object to check the cache for";
return true;
}
auto objectName = arguments[0]->GetStringValue();
auto managedObjectName = StringUtils::ToClr(objectName);
//Check to see if the object name is within the cache
retval = CefV8Value::CreateBool(_javascriptObjects->ContainsKey(managedObjectName));
}
else if (name == "RemoveObjectFromCache")
{
if (arguments.size() == 0 || arguments.size() > 1)
{
//TODO: Improve error message
exception = "Must specify the name of a single bound object to remove from cache";
return true;
}
auto objectName = arguments[0]->GetStringValue();
auto managedObjectName = StringUtils::ToClr(objectName);
if (_javascriptObjects->ContainsKey(managedObjectName))
{
//Remove object from cache
retval = CefV8Value::CreateBool(_javascriptObjects->Remove(managedObjectName));
}
else
{
retval = CefV8Value::CreateBool(false);
}
}
//TODO: Better name for this function
//TODO: Make this a const
if (name == "DeleteBoundObject")
else if (name == "DeleteBoundObject")
{
if (arguments.size() == 0 || arguments.size() > 1)
{
@@ -77,38 +119,33 @@ namespace CefSharp
auto callback = gcnew JavascriptAsyncMethodCallback(context, resolve, reject);
auto callbackId = _callbackRegistry->SaveMethodCallback(callback);
auto request = CefProcessMessage::Create(kJavascriptRootObjectRequest);
auto argList = request->GetArgumentList();
auto params = CefListValue::Create();
auto boundObjectRequired = false;
auto cachedObjects = gcnew List<JavascriptObject^>();
if (arguments.size() > 0)
{
for (auto i = 0; i < arguments.size(); i++)
{
auto objectName = arguments[i]->GetStringValue();
auto managedObjectName = StringUtils::ToClr(objectName);
//TODO: JSB Implement Caching of JavascriptObjects
//if (_javascriptObjects->ContainsKey(managedObjectName))
//{
// //We have a cached version of the required object so we won't request it again
// //We will still need to sent through a list of cached object names so they can be bound from cache
// //The problem with caching will be that we can only call Promise.Resolve once, so we'll need to gather
// //all our bound data before we return
//}
//else
//{
//}
//Check if the object has already been bound
if (!global->HasValue(objectName))
{
//If no matching object found then we'll add the object name to the list
boundObjectRequired = true;
params->SetString(i, objectName);
auto managedObjectName = StringUtils::ToClr(objectName);
JavascriptObject^ obj;
if (_javascriptObjects->TryGetValue(managedObjectName, obj))
{
cachedObjects->Add(obj);
}
}
}
}
@@ -118,21 +155,91 @@ namespace CefSharp
boundObjectRequired = true;
}
//If objects already exist then we'll just do nothing
if (boundObjectRequired)
{
argList->SetInt(0, browser->GetIdentifier());
SetInt64(argList, 1, context->GetFrame()->GetIdentifier());
SetInt64(argList, 2, callbackId);
argList->SetList(3, params);
//If the number of cached objects matches the number of args
//then we'll immediately bind the cached objects
if (cachedObjects->Count == (int)arguments.size())
{
auto frame = context->GetFrame();
if (frame.get())
{
if (Object::ReferenceEquals(_browserWrapper, nullptr))
{
callback->Fail("Browser wrapper is null and unable to bind objects");
}
else
{
//TODO: JSB This code is almost exactly duplicated in CefAppUnmangedWrapper
//Need to extract into a common method
auto rootObjectWrappers = _browserWrapper->JavascriptRootObjectWrappers;
browser->SendProcessMessage(CefProcessId::PID_BROWSER, request);
JavascriptRootObjectWrapper^ rootObject;
if (!rootObjectWrappers->TryGetValue(frame->GetIdentifier(), rootObject))
{
rootObject = gcnew JavascriptRootObjectWrapper(browser->GetIdentifier(), _browserWrapper->BrowserProcess);
rootObjectWrappers->TryAdd(frame->GetIdentifier(), rootObject);
}
rootObject->Bind(cachedObjects, context->GetGlobal());
//Response object has no Accessor or Interceptor
auto response = CefV8Value::CreateObject(NULL, NULL);
response->SetValue("Count", CefV8Value::CreateInt(cachedObjects->Count), CefV8Value::PropertyAttribute::V8_PROPERTY_ATTRIBUTE_READONLY);
response->SetValue("Success", CefV8Value::CreateBool(true), CefV8Value::PropertyAttribute::V8_PROPERTY_ATTRIBUTE_READONLY);
response->SetValue("Message", CefV8Value::CreateString("OK"), CefV8Value::PropertyAttribute::V8_PROPERTY_ATTRIBUTE_READONLY);
callback->Success(response);
//Send message notifying Browser Process of which objects were bound
//We do this after the objects have been created in the V8Context to gurantee
//they are accessible.
auto msg = CefProcessMessage::Create(kJavascriptObjectsBoundInJavascript);
auto args = msg->GetArgumentList();
auto names = CefListValue::Create();
for (auto i = 0; i < cachedObjects->Count; i++)
{
auto name = cachedObjects[i]->JavascriptName;
names->SetString(i, StringUtils::ToNative(name));
}
args->SetList(0, names);
browser->SendProcessMessage(CefProcessId::PID_BROWSER, msg);
}
}
}
else
{
//Obtain a callbackId then send off the Request
auto callbackId = _callbackRegistry->SaveMethodCallback(callback);
argList->SetInt(0, browser->GetIdentifier());
SetInt64(argList, 1, context->GetFrame()->GetIdentifier());
SetInt64(argList, 2, callbackId);
argList->SetList(3, params);
browser->SendProcessMessage(CefProcessId::PID_BROWSER, request);
}
}
else
{
//Response object has no Accessor or Interceptor
auto response = CefV8Value::CreateObject(NULL, NULL);
//Objects already bound so we immediately resolve the Promise
response->SetValue("Success", CefV8Value::CreateBool(false), CefV8Value::PropertyAttribute::V8_PROPERTY_ATTRIBUTE_READONLY);
response->SetValue("Count", CefV8Value::CreateInt(0), CefV8Value::PropertyAttribute::V8_PROPERTY_ATTRIBUTE_READONLY);
response->SetValue("Message", CefV8Value::CreateString("Object(s) already bound"), CefV8Value::PropertyAttribute::V8_PROPERTY_ATTRIBUTE_READONLY);
CefV8ValueList returnArgs;
returnArgs.push_back(CefV8Value::CreateBool(false));
//If all the requested objects are bound then we simply return false
returnArgs.push_back(response);
//If all the requested objects are bound then we immediately execute resolve
//with Success true and Count of 0
resolve->ExecuteFunctionWithContext(context, nullptr, returnArgs);
}
}
+1 -1
View File
@@ -31,7 +31,7 @@
let asyncCallback = assert.async();
CefSharp.BindObjectAsync("boundAsync", "bound").then(function(res)
{
assert.equal(false, res, "Second call to BindObjectAsync with already bound objects as params returned false.");
assert.equal(res.Success, false, "Second call to BindObjectAsync with already bound objects as params returned false.");
asyncCallback();
});
});
@@ -32,6 +32,8 @@ namespace CefSharp.Internals
/// </summary>
public class JavascriptObjectRepository : IJavascriptObjectRepository
{
public const string AllObjects = "All";
private static long lastId;
public event EventHandler<JavascriptBindingEventArgs> ResolveObject;
@@ -72,8 +74,7 @@ namespace CefSharp.Internals
var getAllObjects = names == null || names.Count == 0;
if (getAllObjects)
{
//TODO: JSB Declare Constant for All
RaiseResolveObjectEvent("All");
RaiseResolveObjectEvent(AllObjects);
return objects.Values.ToList();
}